language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
ISO-8859-1
4,441
2.21875
2
[]
no_license
package br.com.gerenciamentoveterinario.domain; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.Size; import org.hibernate.annotations.Cascade; import org.hibernate.validator.constraints.NotEmpty; @Entity @Table(name = "tbl_vacina") @NamedQueries({ @NamedQuery(name = "Vacina.listar", query = "SELECT vacina FROM Vacina vacina"), @NamedQuery(name = "Vacina.buscarPorId", query = "SELECT vacina FROM Vacina vacina WHERE vacina.idVacina = :idVacina") }) public class Vacina { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id_vacina") private Long idVacina; @NotEmpty(message = "O campo nome da vacina Obrigatrio.") @Size(min = 1, max = 60, message = "Quanitidade de caracteres Invlido.") @Column(name = "nome_vaciana", length = 60, nullable = false) private String nomeVacina; @NotEmpty(message = "O campo descrio da vacina Obrigatrio.") @Size(min = 1, max = 60, message = "Quanitidade de caracteres Invlido.") @Column(name = "descricao_vaciana", length = 60, nullable = false) private String descricaoVacina; @NotEmpty(message = "O campo fabricante da vacina Obrigatrio.") @Size(min = 1, max = 60, message = "Quanitidade de caracteres Invlido.") @Column(name = "fabricante_vaciana", length = 60, nullable = false) private String fabricante; @NotEmpty(message = "O campo dosagem Obrigatrio.") @Size(min = 1, max = 6, message = "Quanitidade de caracteres Invlido.") @Column(name = "dosagem", length = 6, nullable = false) private String dosagem; @Column(name = "quantidade_doses", length = 10, nullable = true) private Long quantidadeDoses; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "tbl_usuario_id_usuario", referencedColumnName = "id_usuario") private Usuario usuario; @OneToMany(mappedBy = "vacina", fetch = FetchType.LAZY) @Cascade(org.hibernate.annotations.CascadeType.ALL) private List<CartaoDeVacina> cartaoDeVacina; public Long getIdVacina() { return idVacina; } public void setIdVacina(Long idVacina) { this.idVacina = idVacina; } public String getNomeVacina() { return nomeVacina; } public void setNomeVacina(String nomeVaciana) { this.nomeVacina = nomeVaciana; } public String getDescricaoVacina() { return descricaoVacina; } public void setDescricaoVacina(String descricaoVacina) { this.descricaoVacina = descricaoVacina; } public String getFabricante() { return fabricante; } public void setFabricante(String fabricante) { this.fabricante = fabricante; } public String getDosagem() { return dosagem; } public void setDosagem(String dosagem) { this.dosagem = dosagem; } public Long getQuantidadeDoses() { return quantidadeDoses; } public void setQuantidadeDoses(Long quantidadeDoses) { this.quantidadeDoses = quantidadeDoses; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public List<CartaoDeVacina> getCartaoDeVacina() { return cartaoDeVacina; } public void setCartaoDeVacina(List<CartaoDeVacina> cartaoDeVacina) { this.cartaoDeVacina = cartaoDeVacina; } @Override public String toString() { return "Vacina [idVacina=" + idVacina + ", nomeVacina=" + nomeVacina + ", descricaoVacina=" + descricaoVacina + ", fabricante=" + fabricante + ", dosagem=" + dosagem + ", quantidadeDoses=" + quantidadeDoses + ", usuario=" + usuario + ", cartaoDeVacina=" + cartaoDeVacina + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((idVacina == null) ? 0 : idVacina.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vacina other = (Vacina) obj; if (idVacina == null) { if (other.idVacina != null) return false; } else if (!idVacina.equals(other.idVacina)) return false; return true; } }
C#
UTF-8
493
3.015625
3
[ "MIT" ]
permissive
using _04.Recharge.Models; using System; namespace _04.Recharge { class Program { static void Main(string[] args) { Employee employee = new Employee("Ivan Ivanov"); Robot robot = new Robot("T1000", 100); RechargeStation rechargeStation = new RechargeStation(); rechargeStation.Recharge(robot); employee.Work(8); robot.Work(24); Console.WriteLine(robot.CurrentPower); } } }
C#
UTF-8
5,145
3.40625
3
[]
no_license
using Microsoft.Xna.Framework; using PacmanLibrary.Structure; using System; using System.Collections.Generic; namespace PacmanLibrary.Ghost_classes { /// <summary> /// The Chase class encapsulates the required behaviour /// when a Ghost is in Chase state. On every move, ghost /// will look at the available Tiles, and will choose the /// one that is closest to its target (Vector2 target which /// is relative to Pacman position) /// /// author: Daniel C /// version: Feb 2017 /// </summary> public class Chase : IGhostState { private Ghost ghost; private Maze maze; private Vector2 target; private Pacman pacman; private int relativeDistance; private int targetDirection; /// <summary> /// Four-parameter constructor to initialize the Chase state. /// It requires a handle to the Ghost who is chasing Pacman /// as well as the Maze to know which tiles are available, a /// target which is relative to Pacman position as well as /// Pacman. An exception will be thrown if the input ghost object is null, /// if the maze is null, if pacaman is null, if the target x and y values are /// negative. /// </summary> /// <param name="ghost">Ghost Object</param> /// <param name="maze">Maze Object</param> /// <param name="target">Vector2 target which is relative to /// Pacman position</param> /// <param name="pacman">Pacman Object</param> public Chase(Ghost ghost, Maze maze, Vector2 target, Pacman pacman) { if (Object.ReferenceEquals(null, ghost)) throw new ArgumentException("The input Ghost object to the Chase Constructor must not be null"); if (Object.ReferenceEquals(null, maze)) throw new ArgumentException("The input Maze object to the Chase Constructor must not be null"); if (Object.ReferenceEquals(null, pacman)) throw new ArgumentException("The input Pacman object to the Chase Constructor must not be null"); if(target.X < 0 || target.Y < 0) throw new ArgumentException("The input target X and Y positions to the Chase Constructor must not be negative"); this.ghost = ghost; this.maze = maze; this.target = target; this.pacman = pacman; //generate a random number between 1 to 3 as a distance relative to pacman Random rnd = new Random(); this.relativeDistance = rnd.Next(1, 6); this.targetDirection = rnd.Next(1, 3); } /// <summary> /// This method is invoked to move the Ghost while /// chasing Pacman to the closest available tile. /// Everytime a Ghost moves, we have to do two things: /// update the Ghost's Position and update the Ghosts's /// Direction. This indicates the direction in which it /// is moving, \ and it is required to make sure that /// the Ghosts doesn't turn back to it's previous /// position (i.e., to avoid 180 degree turns) (used /// by the Maze class's GetAvailableNeighbours /// method) /// </summary> public void Move() { float lowestDistance; List<Tile> tiles = maze.GetAvailableNeighbours(ghost.Position, ghost.Direction); int num = tiles.Count; if (num == 0) throw new Exception("Nowhere to go"); //update ghost's target depending on the new position of pacman if (this.targetDirection == 1) this.target = new Vector2(this.relativeDistance, 0) + this.pacman.Position; else this.target = this.pacman.Position - new Vector2(this.relativeDistance, 0); //set lowestDistance and closestTile as the first tile //in the list as a start lowestDistance = tiles[0].GetDistance(target); Tile closestTile = tiles[0]; //determine the closest Tile foreach (Tile element in tiles) { if(element.GetDistance(target) < lowestDistance) { lowestDistance = element.GetDistance(target); closestTile = element; } } //determine new direction if (closestTile.Position.X == ghost.Position.X + 1) ghost.Direction = Direction.Right; else if (closestTile.Position.X == ghost.Position.X - 1) ghost.Direction = Direction.Left; else if (closestTile.Position.Y == ghost.Position.Y - 1) ghost.Direction = Direction.Up; else ghost.Direction = Direction.Down; //set new position ghost.Position = closestTile.Position; } } }
Java
UTF-8
8,602
3.03125
3
[ "MIT" ]
permissive
// Description: This program maintains a list of customers. // It reads and writes from and to a // derby database. //*************************************************************************** package customermaintenancesql; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Scanner; import java.util.ArrayList; import java.util.Date; public class CustomerMaintApp implements CustomerConstants { private static CustomerDAO customerDAO = null; private static Scanner sc = null; public static void main(String[] args) { System.out.println("Welcome to the Customer Maintenance application\n"); customerDAO = DAOFactory.getCustomerDAO(); sc = new Scanner(System.in); displayMenu(); String userChoice = ""; //The Java compiler generates generally more efficient bytecode from switch statements //that use String objects than from chained if-then-else statements. //VIA https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html while (!userChoice.equalsIgnoreCase("exit")) { userChoice = Validator.getUserChoice(sc, "Enter a command: ", "Invalid choice"); System.out.println(); switch (userChoice) { case "LIST_CUSTOMERS": displayAllCustomers(); break; case "LIST_CUSTOMER_INVOICES": displayAllCustomerInvoices(); break; case "ADD": addCustomer(); break; /* case "ADD_CUSTOMER_INVOICE": addCustomerInvoice(); break; */ case "DEL": deleteCustomer(); break; case "HELP": displayMenu(); break; case "UPDATE": updateCustomer(); break; case "EXIT": System.out.println("Disconnecting from DB and exiting..."); customerDAO.disconnect(); break; default: System.out.println("Disconnecting from DB and exiting..."); customerDAO.disconnect(); System.exit(0); } } } public static void displayMenu() { System.out.println("COMMAND MENU\n list_customers - List all customers\n " + "list_customer_invoices - List Invoices of Customers\n " + "add - Add a customer\n " + "del - Delete a customer\n help - Show this menu\n" + " update - Update a customer\n exit - Exit this application\n"); } public static void displayAllCustomers() { System.out.println("CUSTOMER LIST\nEMAIL\t\t\t FIRSTNAME\t\t LASTNAME"); ArrayList<Customer> customers = customerDAO.getCustomers(); Customer c = null; StringBuilder sb = new StringBuilder(); for (int i = 0; i < customers.size(); i++) { c = customers.get(i); //index of customer email//firstname//lastname sb.append(StringUtils.addSpaces(c.getEmail(), NAME_SIZE + 2)); sb.append(StringUtils.addSpaces(c.getFirstName(), NAME_SIZE + 2)); sb.append(StringUtils.addSpaces(c.getLastName(), NAME_SIZE + 2)); sb.append("\n"); } System.out.println(sb.toString()); } public static void displayAllCustomerInvoices() { ArrayList<CustomerInvoice> customerInvoices = customerDAO.getCustomerInvoices();//gathers succesfully CustomerInvoice cInv = null; StringBuilder sb = new StringBuilder(); NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(); for (int i = 0; i < customerInvoices.size(); i++) { cInv = customerInvoices.get(i); //index of object to have values extracted / manipulated sb.append(StringUtils.addSpaces(cInv.getEmail(), NAME_SIZE + 2)); sb.append(StringUtils.addSpaces(cInv.getInvoiceCode(), INVOICE_CODE_SIZE + 2)); sb.append(StringUtils.addSpaces(cInv.getInvoiceDate(), DATE_SIZE + 2)); sb.append(defaultFormat.format(cInv.getInvoiceTotal())); sb.append("\n"); } System.out.println(sb.toString()); } public static void addCustomer() { String email = Validator.validateEmail(sc, "Enter customer email: "); Customer c = customerDAO.getCustomer(email);//check if already exists if (c != null) { //if email exists... System.out.println("You can't add the same customer twice!"); } else { String firstName = Validator.getString( sc, "Enter first name: "); String lastName = Validator.getString( sc, "Enter last name: "); Customer customer = new Customer(); //get highestCustomerID to increment for additional customers primary key ArrayList<Customer> customers = customerDAO.getCustomers(); Customer highestIdCustomer = customers.get(0); //these are pre-sorted by SQL when they come in int max = highestIdCustomer.getCustomerID(); //max is first entry's id for (Customer check : customers) { System.out.println("nth customer in arraylist is : " + check.toString()); if (max > check.getCustomerID()) { continue; } else { max = check.getCustomerID(); System.out.println("The Old highest ID was -> " + max); System.out.println("Additional customer will receive id of -> " + ++max); } } customer.setCustomerID(++max); //customerId is 1 higher than the highest now customer.setEmail(email); customer.setFirstName(firstName); customer.setLastName(lastName); customerDAO.addCustomer(customer); System.out.println(); System.out.println(firstName + " " + lastName + " has been added.\n"); } } public static void updateCustomer() { String emailToBeUpdated = Validator.getString(sc, "Enter email of customer to update: "); Customer c = customerDAO.getCustomer(emailToBeUpdated);//here's who we want to replace System.out.println(); if (c != null) { //if email exists... System.out.println("We found that customer."); int oldID = c.getCustomerID(); //hang on to their ID System.out.println("old id was -> " + oldID); customerDAO.deleteCustomer(c); //gather replacement info String firstName = Validator.getString( sc, "Enter a replacement first name: "); String lastName = Validator.getString( sc, "Enter a replacement last name: "); Customer updatedCustomer = new Customer(); //has ID of 0 //updatedCustomer needs to keep same ID updatedCustomer.setCustomerID(oldID); //has id of oldID updatedCustomer.setEmail(emailToBeUpdated); updatedCustomer.setFirstName(firstName); updatedCustomer.setLastName(lastName); customerDAO.addCustomer(updatedCustomer); customerDAO.updateCustomer(updatedCustomer); //send customer tied to entered email System.out.println(c.getName() + " has been updated to " + firstName + " " + lastName + ".\n"); } else { System.out.println("No customer matches that email. Can't update.\n"); } } public static void deleteCustomer() { //invoices are lost if customer is deleted! String email = Validator.getString(sc, "Enter email to delete: "); Customer c = customerDAO.getCustomer(email); System.out.println(); if (c != null) { customerDAO.deleteCustomer(c); System.out.println(c.getName() + " has been deleted.\n"); } else { System.out.println("No customer matches that email.\n"); } } }
C++
UTF-8
704
2.6875
3
[]
no_license
#pragma once #include "component.hpp" #include "mouse.hpp" #include "vector2d.hpp" #include "mouseElement.hpp" class Button : public Component { private: Transform* transform; MouseElement* mouseElement; public: Button() { mouseElement = new MouseElement(); } void setScene(string sceneName) { mouseElement->setScene(sceneName); } void onGetOtherComponent(Component* component) { storeIfIsInstance(&transform, component); } void onStart() { mouseElement->onStart(); mouseElement->connectTransform(transform); mouseElement->connectOwner(this); } void onDelete() { mouseElement->onDelete(); delete(mouseElement); } MouseElement* mouse() { return mouseElement; } };
SQL
UTF-8
407
3.140625
3
[ "MIT", "BSD-3-Clause", "GPL-1.0-or-later" ]
permissive
-- -- -- DELIMITER $$ DROP procedure IF EXISTS thread_notify $$ CREATE procedure thread_notify( in thread_wait_name varchar(128) character set ascii) DETERMINISTIC NO SQL SQL SECURITY INVOKER COMMENT '' begin insert into _waits (wait_name, wait_value) values (thread_wait_name, 1) on duplicate key update wait_value = wait_value + 1, last_entry_time = NOW() ; end $$ DELIMITER ;
Java
UTF-8
2,050
2.109375
2
[]
no_license
package www.ccb.com.common.utils; public class UrlFactory { /** * 数据类型: 福利 | Android | iOS | 休息视频 | 拓展资源 | 前端 | all * 请求个数: 数字,大于0 * 第几页:数字,大于0 */ public static String DataUrl = "http://gank.io/api/data"; //get 分类数据 /** * 获取最新一天的干货 */ public static String ToDayUrl = "http://gank.io/api/today"; //get 最新干货 /** * 数据类型:福利 | Android | iOS | 休息视频 | 拓展资源 | 前端 * 个数: 数字,大于0 */ public static String RandomDataUrl = "http://gank.io/api/random/data"; //get 随机数据 /** * 豆瓣 * start开始数据,count请求多少条; * https://api.douban.com/v2/movie/in_theaters?start=2&count=5 */ public static String DoubanDataIn_theatersUrl = "https://api.douban.com/v2/movie/in_theaters"; //get 豆瓣电影上映中 public static String DoubanDataTopUrl = "https://api.douban.com/v2/movie/top250"; //get 豆瓣电影排行榜 /** * 新闻API * http://c.m.163.com/nc/article/headline/T1348647853363/0-40.html  头条 * http://c.3g.163.com/nc/article/list/T1467284926140/0-20.html 精选 * http://c.3g.163.com/nc/article/list/T1348648517839/0-20.html   娱乐 * http://c.m.163.com/nc/auto/list/5bmz6aG25bGx/0-20.html 汽车 * http://c.m.163.com/nc/auto/list/6YOR5bee/0-20.html   * http://c.m.163.com/nc/auto/list/6YOR5bee/20-20.html    * http://c.3g.163.com/nc/article/list/T1348649079062/0-20.html  运动 * http://c.3g.163.com/nc/article/local/5bmz6aG25bGx/0-20.html 平顶山 * http://c.m.163.com/nc/article/list/T1444270454635/0-20.html 漫画 * http://c.m.163.com/nc/article/list/T1444270454635/20-20.html  更多 */ public static String NewsTopDataUrl = "http://c.m.163.com/nc/article/headline/T1348647853363/"; public static String NewsGossipDataUrl = "http://c.3g.163.com/nc/article/list/T1348648517839/"; }
Python
UTF-8
151
3.03125
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- print "#"*3 +" Operador ternario "+"#"*3 var1 = 'valor1' var2 = 'valor2' if var1 == 'valor1' else 'valor3' print "var2:",var2
Java
UTF-8
4,380
1.835938
2
[]
no_license
package com.example.roommanagementproject; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.RadioGroup; import android.widget.Toast; import com.example.roommanagementproject.databinding.ActivityGroupTransactionBinding; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.json.JSONException; import org.json.JSONObject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class GroupTransaction extends AppCompatActivity { ActivityGroupTransactionBinding activityGroupTransactionBinding; String reason,amount,date,phone,gid,card; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activityGroupTransactionBinding= DataBindingUtil.setContentView(GroupTransaction.this,R.layout.activity_group_transaction); Intent intent=getIntent(); final String adminum =intent.getStringExtra("groupadmin"); final String groupname=intent.getStringExtra("groupname"); gid=intent.getStringExtra("gid"); SharedPreferences preferences = getSharedPreferences("login", Context.MODE_PRIVATE); String num = preferences.getString("mobile", null); String pass = preferences.getString("pass", null); phone=num; reason=activityGroupTransactionBinding.groreason.getText().toString().trim(); amount=activityGroupTransactionBinding.amountg.getText().toString().trim(); date=activityGroupTransactionBinding.dateg.getText().toString(); activityGroupTransactionBinding.radiogroup.setOnCheckedChangeListener (new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged (RadioGroup group, int checkedId) { if(checkedId==R.id.creditcard){ card="C"; }else if(checkedId==R.id.debitcard){ card="D"; } } }); activityGroupTransactionBinding.buttong.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { JSONObject jsonObject=new JSONObject(); try { jsonObject.put("action","add_trans_as_personal"); jsonObject.put("mobile_no",phone); jsonObject.put("ttype","S"); jsonObject.put("gu_id",gid); jsonObject.put("reason",activityGroupTransactionBinding.groreason.getText().toString().trim()); jsonObject.put("bdate",activityGroupTransactionBinding.dateg.getText().toString()); jsonObject.put("cr_or_dr",card); jsonObject.put("amount",activityGroupTransactionBinding.amountg.getText().toString()); } catch (JSONException e) { e.printStackTrace(); } Retrofit retrofit=new Retrofit.Builder().baseUrl("http://androindian.com/apps/fm/").addConverterFactory(GsonConverterFactory.create()).build(); GroupTransactionInterface GTInterface=retrofit.create(GroupTransactionInterface.class); JsonObject object=new JsonParser().parse(jsonObject.toString()).getAsJsonObject(); Call<GroupTransactionPojo> groupTransactionPojoCall=GTInterface.GROUP_TRANSACTION_POJO_CALL(object); groupTransactionPojoCall.enqueue(new Callback<GroupTransactionPojo>() { @Override public void onResponse(Call<GroupTransactionPojo> call, Response<GroupTransactionPojo> response) { Toast.makeText(GroupTransaction.this, "transaction added to group", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<GroupTransactionPojo> call, Throwable t) { } }); } }); } }
C
UTF-8
470
3.828125
4
[]
no_license
#include<stdio.h> #include<math.h> double DegreesToRadians(double degrees); int main() { double x = 0; double results = 0; double radians = 0; printf("Assignment #1-3, Leonardo Gomez, email \n"); printf("Please input an integer: \n"); scanf("%lf", &x); radians = DegreesToRadians(x); results = cosh(radians); printf("%.3f", results); printf("\n"); return 0; } double DegreesToRadians(double degrees){ double radians = degrees*M_PI/180; return radians; }
C++
UTF-8
5,852
3.046875
3
[ "BSD-2-Clause" ]
permissive
// Distributed under the BSD 2-Clause License - Copyright 2012-2023 Robin Degen #pragma once #include <functional> #include <list> #include <mutex> #include <atomic> namespace aeon::common { template <class... Args> using signal_func = std::function<void(Args...)>; template <class... Args> class signal_connection { public: signal_connection() : handle_(0) , func_() , disconnect_() { } explicit signal_connection(int handle, signal_func<Args...> func, std::function<void()> disconnect) : handle_(handle) , func_(func) , disconnect_(disconnect) { } signal_connection(signal_connection<Args...> &&other) noexcept : handle_(other.handle_) , func_(std::move(other.func_)) , disconnect_(std::move(other.disconnect_)) { other.handle_ = 0; } ~signal_connection() = default; auto operator=(signal_connection<Args...> &&other) noexcept -> signal_connection & { handle_ = other.handle_; func_ = std::move(other.func_); disconnect_ = std::move(other.disconnect_); other.handle_ = 0; return *this; } signal_connection(const signal_connection<Args...> &) = default; auto operator=(const signal_connection<Args...> &) -> signal_connection & = default; [[nodiscard]] auto get_handle() const { return handle_; } void emit(Args... args) { func_(args...); } void disconnect() { if (disconnect_) disconnect_(); handle_ = 0; } explicit operator bool() const { return handle_ != 0; } private: int handle_; signal_func<Args...> func_; std::function<void()> disconnect_; }; template <class... Args> class [[nodiscard]] scoped_signal_connection { public: scoped_signal_connection() : signal_() { } scoped_signal_connection(signal_connection<Args...> &&signal) : signal_(std::move(signal)) { } ~scoped_signal_connection() { if (signal_) signal_.disconnect(); } scoped_signal_connection(scoped_signal_connection<Args...> &&other) : signal_(std::move(other.signal_)) { } scoped_signal_connection &operator=(scoped_signal_connection &&other) { signal_ = std::move(other.signal_); return *this; } scoped_signal_connection(const scoped_signal_connection<Args...> &other) = delete; scoped_signal_connection &operator=(const scoped_signal_connection &other) = delete; [[nodiscard]] auto get_handle() const { return signal_.get_handle(); } void emit(Args... args) { signal_.emit(args...); } void disconnect() const { signal_.disconnect(); } private: signal_connection<Args...> signal_; }; template <class... Args> class signal { public: signal() : last_handle_(0) , connections_() { } ~signal() = default; scoped_signal_connection<Args...> connect(signal_func<Args...> f) { auto handle = ++last_handle_; auto disconnect_func = [this, handle]() { disconnect(handle); }; auto connection = signal_connection<Args...>(handle, f, disconnect_func); connections_.push_back(connection); return connection; } void disconnect(const scoped_signal_connection<Args...> &c) { disconnect(c.get_handle()); } void disconnect(const int c) { connections_.remove_if([c](const signal_connection<Args...> &other) { return other.get_handle() == c; }); } void operator()(Args... args) { for (auto &c : connections_) { c.emit(args...); } } private: int last_handle_ = 0; std::list<signal_connection<Args...>> connections_; }; template <class... Args> class signal_mt { using mutex_type = std::mutex; using handle_type = std::atomic<int>; using list_type = std::list<signal_connection<Args...>>; public: signal_mt() = default; ~signal_mt() { /* \note This does not solve the 'destruction' while signal is executing problem. * Reasoning: * Thread a is the owner (he creates and destroys) and thread b executes the signal multiple times. Then * while the signal is being destroyed from thread a, thread b tries to execute the signal. Thread a will * acquire the mutex and execute the signal destructor. When the signal is destroyed it will release the * mutex and allow thread b to execute the signal that does not exist. Which will result in havoc. */ std::lock_guard<mutex_type> guard(lock_); connections_.clear(); } scoped_signal_connection<Args...> connect(signal_func<Args...> f) { int handle = ++last_handle_; auto disconnect_func = [this, handle]() { disconnect(handle); }; auto connection = signal_connection<Args...>(++last_handle_, f, disconnect_func); { std::lock_guard<mutex_type> guard(lock_); connections_.push_back(connection); } return connection; } void disconnect(const scoped_signal_connection<Args...> &c) { disconnect(c.get_handle()); } void disconnect(const int handle) { std::lock_guard<mutex_type> guard(lock_); connections_.remove_if([&handle](const signal_connection<Args...> &other) { return other.get_handle() == handle; }); } void operator()(Args... args) { std::lock_guard<mutex_type> guard(lock_); for (auto &c : connections_) c.emit(args...); } private: handle_type last_handle_{0}; list_type connections_; mutex_type lock_; }; } // namespace aeon::common
Python
UTF-8
4,027
2.546875
3
[]
no_license
import sys import threading import time import gc import shutil from datetime import timedelta from multiprocessing.pool import ThreadPool from multiprocessing import cpu_count from concurrent.futures import ThreadPoolExecutor from ddl_mongo import * from models.mongo_models import * #this script receives 5 parameters # 1 - filename # 2 - the csv delimiter: t - tab, c - coma, s - semicolon # 3 - integer: 1 csv has header, 0 csv does not have hearer # 4 - integer - nr of threads # 5 - lematizer/stemmer def getDates(): documents = Documents.objects.only("createdAt") no_docs = documents.count() last_docDate = None last_wordDate = None if no_docs > 0: last_docDate = documents[no_docs-1].createdAt words = Words.objects.only("createdAt") no_words = words.count() if no_words > 0: last_wordDate = words[no_words-1].createdAt return last_docDate, last_wordDate def populateDB(filename, csv_delimiter, header, language): start = time.time() h, lines = utils.readCSV(filename, csv_delimiter, header) for line in lines: populateDatabase(line, language) end = time.time() print "time_populate.append(", (end - start), ")" def clean(language, last_docDate): if not last_docDate: documents = Documents.objects.only("createdAt") else: documents = Documents.objects(Q(createdAt__gte = last_docDate)).only("createdAt") no_docs = documents.count() list_of_dates = [] idx = 0 for document in documents: if idx%100 == 0 or idx + 1 == no_docs: list_of_dates.append(document.createdAt) idx += 1 #add one second to the last date list_of_dates[-1] += timedelta(0,1) no_threads = cpu_count() start = time.time() #method 1 """ pool = ThreadPool(no_threads) for idx in xrange(0, len(list_of_dates)-1, 1) : #print list_of_dates[idx], list_of_dates[idx+1] #pool.apply_async(func = createCleanTextField_orig, args=(list_of_dates[idx], list_of_dates[idx+1], )) pool.apply_async(func = createCleanTextField, args=(list_of_dates[idx], list_of_dates[idx+1], idx+1, )) pool.close() pool.join() """ #method 2 with ThreadPoolExecutor(max_workers = no_threads) as e: for idx in xrange(0, len(list_of_dates)-1, 1) : e.submit(createCleanTextField, list_of_dates[idx], list_of_dates[idx+1], language) end = time.time() print "time_cleantext.append(", (end - start), ")" #TO_DO this is just a test, remove this line #createCleanTextField(list_of_dates[0], list_of_dates[1], language) #createCleanTextField(list_of_dates[1], list_of_dates[2], language) #delete documents without cleanText Documents.objects(cleanText__exists = False).delete(); def buildNamedEntities(): print "sunt in build entities" documents = Documents.objects.only("createdAt") no_docs = documents.count() list_of_dates = [] idx = 0 for document in documents: if idx%100 == 0 or idx + 1 == no_docs: list_of_dates.append(document.createdAt) idx += 1 #add one second to the last date list_of_dates[-1] += timedelta(0,1) no_threads = cpu_count() start = time.time() with ThreadPoolExecutor(max_workers = no_threads) as e: for idx in xrange(0, len(list_of_dates)-1, 1) : e.submit(createNamedEntitiesCollection, list_of_dates[idx], list_of_dates[idx+1]) end = time.time() print "time build named entities:", (end - start) def main(filename, csv_delimiter = '\t', header = True, dbname = 'ERICDB', language='EN'): connectDB(dbname) Documents.drop_collection() Words.drop_collection() last_docDate, last_wordDate = getDates() populateDB(filename, csv_delimiter, header, language) Documents.objects(intText__exists = False).delete() clean(language, last_docDate) print 'date for update indexes:', last_wordDate print 'last date doc:', last_docDate #NamedEntities.drop_collection() #buildNamedEntities() if __name__ == "__main__": filename = sys.argv[1] csv_delimiter = utils.determineDelimiter(sys.argv[2]) header = bool(sys.argv[3]) dbname = sys.argv[4] language = sys.argv[5] main(filename, csv_delimiter, header, dbname, language)
C#
UTF-8
1,790
2.734375
3
[]
no_license
using Rg.Plugins.Popup.Services; using System; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using WheelofFortune.Services; namespace WheelofFortune.ViewModels { /// <summary> /// Class - ViewModel - for the PopupTaskView /// </summary> public class PopupTaskViewModel : BaseViewModel { #region Properties public int Id { get; set; } int points; public int Points { get => points; set { SetProperty(ref points, value); } } DateTime datetime; public DateTime Datetime { get => datetime; set { SetProperty(ref datetime, value); } } #endregion #region Commands public ICommand AddPointsCommand { get; private set; } #endregion public PopupTaskViewModel(string number) { this.points = Int32.Parse(number); AddPointsCommand = new Command(async () => await AddPrizePoints()); } /// <summary> /// Async Method for Claíming the points /// and insert it into SQLite Database /// </summary> /// <returns></returns> async Task AddPrizePoints() { try { datetime = DateTime.Now; await PrizeService.AddPrize(points, datetime).ConfigureAwait(false); } catch (Exception ex) { Console.WriteLine($"ClaimPrize THREW: {ex.Message}"); } finally { await PopupNavigation.Instance.PopAsync(); } } } }
Java
UTF-8
638
1.898438
2
[]
no_license
package com.duo.user.service.impl; import org.springframework.stereotype.Component; import com.duo.user.entity.Menu; import com.duo.user.entity.User; import com.duo.user.service.IUserService; import com.duo.user.util.RespResult; @Component public class UserServiceImpl implements IUserService{ @Override public User queryUserById(String id) { System.out.println("接口不通 。。。。。。"); return null; } @Override public Menu queryUserInfoById(String userId) { // TODO Auto-generated method stub return null; } @Override public String test() { // TODO Auto-generated method stub return null; } }
JavaScript
UTF-8
2,628
2.609375
3
[]
no_license
var http = require('http'); var url = require('url'); var StringDecoder = require('string_decoder').StringDecoder; var cluster = require('cluster'); var os = require('os'); var childProcess = require('child_process'); var config = require('./config'); var httpServer; if(cluster.isMaster){ for(var i=0; i < os.cpus().length; i++){ cluster.fork(); } }else{ httpServer = http.createServer(function(req, res){ var parsedUrl = url.parse(req.url, true); var path = parsedUrl.pathname; var trimedPath = path.replace(/^\/+|\/+$/g, ''); var queryStringObj = parsedUrl.query; var method = req.method.toLocaleLowerCase(); var headers = req.headers; var decoder = new StringDecoder('utf-8'); var buffer = ''; req.on('data', function(data){ buffer += decoder.write(data); }); req.on('end', function(){ buffer += decoder.end(); var chosenHandler = typeof(router[trimedPath]) != 'undefined' ? router[trimedPath] : handlers.notFound; var data = { 'trimedPath': trimedPath, 'queryStringObj': queryStringObj, 'method': method, 'headers': headers, 'payload': buffer }; chosenHandler(data, function(statusCode, payload){ statusCode = typeof(statusCode) == 'number' ? statusCode : 200; payload = typeof(payload) == 'object' ? payload : {}; var payloadString = JSON.stringify(payload); // To return response as json res.setHeader('Content-Type', 'application/json'); res.writeHead(statusCode); res.end(payloadString); }); }); }); httpServer.listen(config.httpPort, function(){ console.log("server started at==>>", config.httpPort); }); } //request route handler var handlers = {}; // /hello request handler handlers.hello = function(data, callback){ var cat = childProcess.spawn('cat', ['./message.txt']); cat.stdout.on('data', function(dataObject){ var strData = dataObject.toString(); callback(200, {'assignment_number': 'Assignment 6', 'message': strData}); }); //To send data with status 200 } //handler Not Found handlers.notFound = function(data, callback){ callback(404); } //request router var router = { 'hello': handlers.hello };
Shell
UTF-8
568
3.34375
3
[]
no_license
#!/bin/bash card=1 toggle () { message=`amixer -c ${card} set Mic toggle \ | grep '\[on\]' > /dev/null \ && echo 'mic unmuted' \ || echo 'mic muted'`; notify-send "${message}"; espeak "${message}"; location=`dirname "$0"` } isMuted () { amixer -c ${card} get Mic | grep '\[off\]' > /dev/null } i3block () { isMuted if [[ $? -eq 0 ]]; then echo "" # full text echo "" # short text echo "#FF0000" # colour else echo "" # full text echo "" # short text echo "#00FF00" # colour fi } $1
Swift
UTF-8
1,052
3.09375
3
[]
no_license
// // PriceHistoryResponse.swift // CryptoPriceCore // // Created by Vitaliy Ampilogov on 6/8/19. // Copyright © 2019 Vitaliy Ampilogov. All rights reserved. // import Foundation struct PriceHistoryResponse { let history: [PriceHistoryItem] enum CodingKeys: String, CodingKey { case bpi } } extension PriceHistoryResponse: Decodable { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let historyDict = try container.decode([String: Double].self, forKey: .bpi) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let items = historyDict.enumerated().map({ PriceHistoryItem(date: $0.element.key, value: $0.element.value) }) history = items.sorted(by: { $0.date < $1.date }) } } public struct PriceHistoryItem: Equatable { public init(date: String, value: Double) { self.date = date self.value = value } public let date: String public let value: Double }
Java
UTF-8
7,438
2.96875
3
[]
no_license
/* Copyright (C) 2011 This file is part of BobConnect written by Max Bügler http://www.maxbuegler.eu/ BobConnect is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. BobConnect is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Main; /** * Converts between datatypes */ class BasisConversion{ /** * Frees a byte value to be used as terminator * @param data input data * @param b1 byte 1 * @param b2 byte 2 * @param free free byte * @return byte[] not using free byte */ public static byte[] freeByte(byte[] data, byte b1, byte b2, byte free){ byte[] temp=new byte[2*data.length]; int pointer=0; for (int x=0;x<data.length;x++){ if (data[x]==b1){ temp[pointer++]=b1; temp[pointer++]=b1; } else if (data[x]==b2){ temp[pointer++]=b1; temp[pointer++]=b2; } else if (data[x]==free){ temp[pointer++]=b2; temp[pointer++]=b1; } else{ temp[pointer++]=data[x]; } } byte[] out=new byte[pointer]; for (int x=0;x<pointer;x++){ out[x]=temp[x]; } return out; } /** * Frees a byte value to be used as terminator * @param data input data * @param b1 byte 1 * @param b2 byte 2 * @param term free byte * @return byte[] not using free byte and terminates */ public static byte[] freeByteAndTerminate(byte[] data, byte b1, byte b2, byte term){ byte[] temp=new byte[2*data.length+3]; int pointer=0; for (int x=0;x<data.length;x++){ if (data[x]==b1){ temp[pointer++]=b1; temp[pointer++]=b1; } else if (data[x]==b2){ temp[pointer++]=b1; temp[pointer++]=b2; } else if (data[x]==term){ temp[pointer++]=b2; temp[pointer++]=b1; } else{ temp[pointer++]=data[x]; } } temp[pointer++]=term; temp[pointer++]=term; temp[pointer++]=term; byte[] out=new byte[pointer]; for (int x=0;x<pointer;x++){ out[x]=temp[x]; } return out; } /** * Restore freed byte * @param data input * @param b1 byte 1 * @param b2 byte 2 * @param free free byte * @return restored byte[] */ public static byte[] restoreByte(byte[] data,byte b1, byte b2, byte free){ byte[] temp=new byte[data.length]; int pointer=0; for (int x=0;x<data.length;x++){ if (data[x]==b2){ x++; if (x<data.length&&data[x]==b1){ temp[pointer++]=free; } } else if (data[x]==b1){ x++; if (x<data.length&&data[x]==b1){ temp[pointer++]=b1; } else if (data[x]==b2){ temp[pointer++]=b2; } } else{ temp[pointer++]=data[x]; } } byte[] out=new byte[pointer]; for (int x=0;x<pointer;x++){ out[x]=temp[x]; } return out; } /** * Converts string to UTF8 * @param s input * @return byte[] */ public static byte[] stringToUTF8(String s){ try{ return s.getBytes("UTF8"); } catch(Exception ex){ex.printStackTrace();} return null; } /** * Converts UTF8 to string * @param b input * @return String */ public static String UTF8toString(byte[] b){ try{ return new String(b,"UTF8"); } catch(Exception ex){ex.printStackTrace();} return null; } private static final String HEX="0123456789abcdef"; public static String convertBytesToHex(byte[] bytes){ String out=""; for (int x=0;x<bytes.length;x++){ byte v=bytes[x]; out+=HEX.charAt((v+128)/16); out+=HEX.charAt((v+128)%16); } return out; } public static byte[] convertHexToBytes(String hex){ byte[] out=new byte[hex.length()/2]; for (int x=0;x<hex.length()-1;x+=2){ int res= 16*HEX.indexOf(hex.charAt( x ))+ HEX.indexOf(hex.charAt(x+1)); out[x/2]=(byte)(res-128); } return out; } /** * Converts a positive int to 3 bytes. * @param v small int value * @return byte[3] array */ /*public static byte[] intToBytes(int v){ //Create output array byte[] out=new byte[3]; //256^2 byte out[0]=(byte)((v/(256*256))-128); v=v%(256*256); //256 byte out[1]=(byte)((v/256)-128); v=v%256; //1 byte out[2]=(byte)(v-128); return out; } */ /** * Converts 3 bytes to an int * @param data byte[3] array * @return int */ /*public static int bytesToInt(byte[] v){ return (256*256*(v[0]+128))+(256*(v[1]+128))+v[2]+128; } */ public static byte[] intToBytes(int data) { return new byte[] { //(byte)( data >> 24 ), //(byte)( (data << 8) >> 24 ), //(byte)( (data << 16) >> 24 ), //(byte)( (data << 24) >> 24 ) (byte)((data >> 24) & 0xff), (byte)((data >> 16) & 0xff), (byte)((data >> 8) & 0xff), (byte)((data >> 0) & 0xff) }; } public static int bytesToInt(byte[] data) { if (data == null || data.length != 4) return 0x0; return ( (0xff & data[0]) << 24 | (0xff & data[1]) << 16 | (0xff & data[2]) << 8 | (0xff & data[3]) << 0 ); } public static byte[] longToBytes(long data) { return new byte[] { (byte)((data >> 56) & 0xff), (byte)((data >> 48) & 0xff), (byte)((data >> 40) & 0xff), (byte)((data >> 32) & 0xff), (byte)((data >> 24) & 0xff), (byte)((data >> 16) & 0xff), (byte)((data >> 8) & 0xff), (byte)((data >> 0) & 0xff) }; } public static long bytesToLong(byte[] data) { if (data == null || data.length != 8) return 0x0; return ( (long)(0xff & data[0]) << 56 | (long)(0xff & data[1]) << 48 | (long)(0xff & data[2]) << 40 | (long)(0xff & data[3]) << 32 | (long)(0xff & data[4]) << 24 | (long)(0xff & data[5]) << 16 | (long)(0xff & data[6]) << 8 | (long)(0xff & data[7]) << 0 ); } }
Markdown
UTF-8
2,411
3
3
[ "MIT" ]
permissive
# Урок 8 - База данных в FireBase, или запись легче считывания [World-Skills-Juniors](https://pavlenkodr.github.io/World-Skills-Juniors/) Необходимо установить Xamarin.Firebase.Fatabase. Делается это по аналогии с установкой Xamarin.Firebase.Auth из 7 урока. Усовершенствуем функцию регистрации ```RegsiterWithEmailPassword( ... )```. Теперь она заодно будет писать данные в базу. Функция находится в файле ```FirebaseAuthenticator.cs``` ```cs public async Task<string> RegsiterWithEmailPassword(string email, string password, string name, string secondName) { var user = await FirebaseAuth.Instance.CreateUserWithEmailAndPasswordAsync(email, password); var token = await user.User.GetIdTokenAsync(false); // Хранит в себе ссылку на базу FirebaseDatabase firebaseDatabase; // Хранит в себе ссылку на таблицу DatabaseReference databaseReference; // Будет использоваться для хранения промежуточных таблиц DatabaseReference child; try { // Получаем нашу базу firebaseDatabase = FirebaseDatabase.GetInstance("https://worldskills-f19d1.firebaseio.com/"); } catch { throw new ArgumentException("GetInstance error"); } try { // Получаем таблицу "worldskills-f19d1" databaseReference = firebaseDatabase.GetReference("worldskills-f19d1"); } catch { throw new ArgumentException("GetReference error"); } string tableName = ""; try { // Получаем таблицу нашего нового юзера tableName = email.Replace('@', 'a').Replace('.', 'b'); child = databaseReference.Child(tableName); // Записываем данные в базу await child.Child("Email").SetValueAsync(email); await child.Child("Name").SetValueAsync(name); await child.Child("SecondName").SetValueAsync(secondName); } catch { throw new ArgumentException("Add data error"); } return tableName; } ``` [World-Skills-Juniors](https://pavlenkodr.github.io/World-Skills-Juniors/)
Java
UTF-8
534
2.8125
3
[]
no_license
package org.practise.thread.synchronize; /** * @Description "可重入锁"是指自己可以再次获取自己的内部的锁 * @Author zhangshenming * @Date 2020/11/17 9:49 * @Version 1.0 * @See */ public class Practise021 extends Thread { @Override public void run() { super.run(); ServiceTest serviceTest = new ServiceTest(); serviceTest.service1(); } public static void main(String[] args) { Practise021 practise021 = new Practise021(); practise021.start(); } }
Python
UTF-8
451
3.28125
3
[]
no_license
#!/usr/bin/python # -*- coding:utf-8 -*- from types import MethodType def __len__(self): #必须要有self print('excute __len__') print(self) print(__len__.__name__) class Mine(object): def print_name(self): print(self) class Mine02(object): def print_name(self): print(self) a = Mine() b = Mine02() Mine02.len = MethodType(__len__, Mine02) #给类绑定实例 a.len = MethodType(__len__, a) c = Mine02() a.len() b.len() c.len()
C#
UTF-8
761
3.59375
4
[]
no_license
//Dice Rolling public void DiceRolling(List<string> readInList) { foreach (string s in readInList) { helperMethodDiceRolling(s); } } public void helperMethodDiceRolling(string valueFromList) { double tempVal = 0; double.TryParse(valueFromList, out tempVal); Random rnd = new Random(); int random1To6 = rnd.Next(1, 7); double multiplyBy = 0; multiplyBy = tempVal * random1To6; double flooredValue = Math.Floor(multiplyBy); double finalAnswer = 0; finalAnswer = flooredValue + 1; Console.WriteLine(finalAnswer); }
Java
UTF-8
2,954
2.296875
2
[ "MIT" ]
permissive
package the_gatherer.relics; import basemod.abstracts.CustomRelic; import basemod.abstracts.CustomSavable; import com.badlogic.gdx.graphics.Texture; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.helpers.CardLibrary; import com.megacrit.cardcrawl.helpers.PowerTip; import com.megacrit.cardcrawl.relics.AbstractRelic; import the_gatherer.GathererMod; import the_gatherer.cards.Helper.AbstractTaggedCard; import java.util.HashSet; public class FlyingFruit extends CustomRelic implements CustomSavable<HashSet<String>> { private static final String RelicID = "FlyingFruit"; public static final String ID = GathererMod.makeID(RelicID); public HashSet<String> exhaustedUniqueID = new HashSet<>(); private final int AMOUNT = 4; public FlyingFruit() { super(ID, new Texture(GathererMod.GetRelicPath(RelicID)), RelicTier.UNCOMMON, LandingSound.FLAT); this.counter = 0; } @Override public void onExhaust(AbstractCard card) { if (exhaustedUniqueID.size() < 10 && !exhaustedUniqueID.contains(GathererMod.getUniqueID(card))) { exhaustedUniqueID.add(GathererMod.getUniqueID(card)); switch (exhaustedUniqueID.size()) { case 1: case 3: case 6: case 10: this.flash(); AbstractDungeon.player.increaseMaxHp(AMOUNT, true); } this.counter = exhaustedUniqueID.size(); this.description = this.getUpdatedDescription(); this.tips.clear(); this.tips.add(new PowerTip(this.name, this.description)); this.initializeTips(); } } @Override public void onLoad(HashSet<String> data) { exhaustedUniqueID = data; this.description = this.getUpdatedDescription(); this.tips.clear(); this.tips.add(new PowerTip(this.name, this.description)); this.initializeTips(); } @Override public HashSet<String> onSave() { return exhaustedUniqueID; } @Override public String getUpdatedDescription() { if (exhaustedUniqueID == null || exhaustedUniqueID.isEmpty()) { return DESCRIPTIONS[0] + AMOUNT + DESCRIPTIONS[1]; } else { boolean first = true; StringBuilder result = new StringBuilder(DESCRIPTIONS[0] + AMOUNT + DESCRIPTIONS[1] + DESCRIPTIONS[2]); for (String id : exhaustedUniqueID) { if (!first) { result.append(", "); } else { first = false; } try { int index = id.indexOf("|Tag="); if (index >= 0) { AbstractCard c = CardLibrary.getCard(id.substring(0, index)).makeCopy(); AbstractTaggedCard atc = (AbstractTaggedCard) c; atc.setTag(Integer.parseInt(id.substring(index + 5))); result.append(atc.name); } else { AbstractCard c = CardLibrary.getCard(id); result.append(c.name); } } catch (Exception e) { e.printStackTrace(); result.append(GathererMod.stripPrefix(id)); } } return result.toString(); } } @Override public AbstractRelic makeCopy() { return new FlyingFruit(); } }
PHP
UTF-8
7,765
2.671875
3
[ "MIT" ]
permissive
<?php namespace Ojstr\UserBundle\Entity; use Symfony\Component\Security\Core\User\UserInterface; use Doctrine\Common\Collections\ArrayCollection; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Expose; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Validator\Constraints as Assert; use \Ojstr\JournalBundle\Entity\Subject; use \Ojstr\Common\Entity\GenericExtendedEntity; /** * User * @ExclusionPolicy("all") * @UniqueEntity(fields="username", message="That username is taken!") * @UniqueEntity(fields="email", message="That email is taken!") */ class User extends GenericExtendedEntity implements UserInterface, \Serializable { /** * @var integer * @Expose */ protected $id; /** * @var string * @Expose * @Assert\NotBlank(message="Username can't be blank") * @Assert\Length(min=3, minMessage="Username should be longer then 3 characters.") */ protected $username; /** * @var string * @Assert\NotBlank(message="Password can't be blank") */ protected $password = null; /** * @var string * @Expose * @Assert\NotBlank(message="Email can't be blank") * @Assert\Email */ protected $email; /** * @var string * @Assert\NotBlank(message="First name can't be blank") * @Expose */ protected $firstName; /** * @var string * @Assert\NotBlank(message="Last name can't be blank") * @Expose */ protected $lastName; /** * @var boolean * @Expose */ protected $isActive; /** * @var string * @Expose */ protected $token = null; /** * @var \DateTime */ protected $lastlogin; /** * @var string */ protected $avatar; /** * @var \Doctrine\Common\Collections\Collection * @Expose */ private $roles; /** * @var \Doctrine\Common\Collections\Collection * @Expose */ private $subjects; /** * @var integer */ protected $status = 1; public function __construct() { $this->isActive = true; $this->roles = new ArrayCollection(); $this->subjects = new ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * @param string $username * @return User */ public function setUsername($username) { $this->username = $username; return $this; } /** * @return string */ public function getUsername() { return $this->username; } /** * @param string $avatar * @return User */ public function setAvatar($avatar) { $this->avatar = $avatar; return $this; } /** * @return string */ public function getAvatar() { return $this->avatar; } /** * @param integer $status * @return User */ public function setStatus($status) { $this->status = $status; return $this; } /** * @return integer */ public function getStatus() { return $this->status; } /** * @param string $password * @return User */ public function setPassword($password) { $this->password = $password; return $this; } /** * @return string */ public function getPassword() { return $this->password; } /** * @param string $email * @return User */ public function setEmail($email) { $this->email = $email; return $this; } /** * @return string */ public function getEmail() { return $this->email; } /* * get * Set firstName * * @param string $firstName * @return User */ public function setFirstName($firstName) { $this->firstName = $firstName; return $this; } /** * @return string */ public function getFirstName() { return $this->firstName; } /** * @param String tr$lastName * @return $this */ public function setLastName($lastName) { $this->lastName = $lastName; return $this; } /** * @return string */ public function getLastName() { return $this->lastName; } /** * @param boolean $isActive * @return User */ public function setIsActive($isActive) { $this->isActive = $isActive; return $this; } /** * @return string */ public function getToken() { return $this->token; } /** * @param String $token * @return $this */ public function setToken($token) { $this->token = $token; return $this; } /** * @return boolean */ public function getIsActive() { return $this->isActive; } /** * @return \DateTime */ public function getLastlogin() { return $this->lastlogin; } /** * @param \DateTime $lastlogin */ public function setLastlogin(\DateTime $lastlogin) { $this->lastlogin = $lastlogin; } public function getSalt() { return null; } public function eraseCredentials() { //$this->setPassword(NULL); } /** * @see \Serializable::serialize() */ public function serialize() { return serialize(array( $this->id, $this->username, $this->password )); } /** * @see \Serializable::unserialize() */ public function unserialize($serialized) { list ( $this->id, $this->username, $this->password ) = unserialize($serialized); } /** * * @return \Doctrine\Common\Collections\Collection */ public function getRoles() { return $this->roles->toArray(); } /** * Add role * * @param \Ojstr\UserBundle\Entity\Role $role * @return User */ public function addRole(\Ojstr\UserBundle\Entity\Role $role) { $this->roles[] = $role; return $this; } /** * @param \Ojstr\UserBundle\Entity\Role $role */ public function removeRole(\Ojstr\UserBundle\Entity\Role $role) { $this->roles->removeElement($role); } /** * * @return \Doctrine\Common\Collections\Collection */ public function getSubjects() { return $this->subjects; } /** * @param Subject $subject * @return $this */ public function addSubject(Subject $subject) { $this->subjects[] = $subject; return $this; } /** * @param Subject $subject */ public function removeSubject(Subject $subject) { $this->subjects->removeElement($subject); } /** * * - fileName: The filename. * - fileExtension: The extension of the file (including the dot). Example: .jpg * - fileWithoutExt: The filename without the extension. * - filePath: The file path. Example: /my/path/filename.jpg * - fileMimeType: The mime-type of the file. Example: text/plain. * - fileSize: Size of the file in bytes. Example: 140000. * * @param array $info */ public function avatarFileCallback(array $info) { // noob } public function generateToken() { return md5($this->getEmail()) . md5(uniqid($this->getUsername(), true)); } }
C++
ISO-8859-1
8,111
2.765625
3
[]
no_license
/* ****************************************************************** FICHIER : Port.cpp AUTEUR : PhB DATE DE CREATION : 13/12/96 DERNIERE MODIFICATION : 14/02/97 VERSION : 1.0 ROLE : Implmentation de la classe CPort (gestion des port srie) *********************************************************************/ #include "stdafx.h" #include <stdio.h> #include "comm\Port.h" /* ********************************************************************** METHODE : CPort() TRAITEMENT: Constuit l'objet mais n'ouvre pas le port *********************************************************************** */ CPort::CPort() { ouverte = FALSE; } /* ********************************************************************** METHODE : ~CPort() TRAITEMENT: Destructeur de l'objet *********************************************************************** */ CPort::~CPort() { Fermeture(); } /* ********************************************************************** METHODE : PortOuvert() TRAITEMENT: Teste si le port a t ouvert *********************************************************************** */ BOOL CPort::PortOuvert() const { return ouverte; } /* ********************************************************************** METHODE : NumPort() TRAITEMENT: Retourne le numro de port utilis par l'objet *********************************************************************** */ int CPort::NumPort() const { return num_ligne; } /* ********************************************************************** METHODE : Ouverture() TRAITEMENT: Ouverture et initialisation du port * Dimensionne les buffers I/O * Parametre le format de transmission (vitesse, parit, controle de flux, ...) * Paramtrage des TimeOut criture/lecture * Purge des buffers I/O *********************************************************************** */ int CPort::Ouverture(const int numero,const int vitesse,const int nb_bit, const int stop_bit,const int parite) { char nom_port[14]; int iResult; DCB dcb; // structure de configuration du port COMMTIMEOUTS timeout; // Structure de gestion du time out num_ligne = numero; // numero du port utilis sprintf(nom_port,"\\\\.\\COM%d",num_ligne); // Ouverture du port hcom = CreateFile(nom_port, GENERIC_READ | GENERIC_WRITE, 0, // Accs exclusif NULL, // pas d'attribut de scurit OPEN_EXISTING, // Le port doit exister 0, // I/O limit dans le temps NULL); // NULL pour un pripherique COM /* hcom = CreateFile( nom_port, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL ); */ if (hcom == INVALID_HANDLE_VALUE) return ERR_OUVERT_HANDLE; ouverte = TRUE; // Dimensionnement des buffer I/O if (!SetupComm(hcom,1200,1200)) return ERR_OUVERTURE_PORT; // purge des buffer I/O iResult = Purge(); // Paramtrage du time out if (!GetCommTimeouts(hcom,&timeout)) // ancien timeout -> dcb return ERR_OUVERTURE_PORT; timeout.ReadIntervalTimeout = DELAI_TIME_OUT*4; // inter-caractere timeout.ReadTotalTimeoutMultiplier = DELAI_TIME_OUT_2*4; timeout.ReadTotalTimeoutConstant = DELAI_TIME_OUT_1*4;// timeout 1er car timeout.WriteTotalTimeoutMultiplier = DELAI_TIME_OUT*4; if (!SetCommTimeouts(hcom,&timeout)) // nouveau timout <- timeout return ERR_OUVERTURE_PORT; // Initialisation du port if (!GetCommState(hcom,&dcb)) // ancienne configuration -> dcb return ERR_OUVERTURE_PORT; dcb.BaudRate = vitesse; dcb.ByteSize = nb_bit; dcb.Parity = parite; dcb.StopBits = stop_bit; dcb.fDsrSensitivity = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fOutxCtsFlow = FALSE; dcb.fDtrControl = DTR_CONTROL_DISABLE; dcb.fRtsControl = RTS_CONTROL_DISABLE; dcb.fInX = dcb.fOutX = FALSE ; dcb.XonLim = 100 ; dcb.XoffLim = 100 ; dcb.fBinary = TRUE ; dcb.fParity = TRUE ; if (!SetCommState(hcom,&dcb)) { iResult = GetLastError(); // nouvelle config <- dcb return ERR_OUVERTURE_PORT; } // Force les etats RTS // if (!EscapeCommFunction(hcom,SETRTS)) if (!EscapeCommFunction(hcom,SETDTR)) return ERR_OUVERTURE_PORT; return 0; } /* ********************************************************************** METHODE : Fermeture() TRAITEMENT: Fermeture et libration du port *********************************************************************** */ int CPort::Fermeture() { if (!ouverte) return ERR_LIGNE_FERMEE; // Fermeture du port if (!CloseHandle(hcom)) return ERR_FERMETURE_PORT; ouverte = FALSE; return 0; } /* ********************************************************************** METHODE : Purge() TRAITEMENT: vide les buffers d' I/O associ au port *********************************************************************** */ int CPort::Purge() { OutputDebugString("Dans : CPort::Purge() !\n"); if (!ouverte) return ERR_LIGNE_FERMEE; if (!PurgeComm(hcom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR)) return ERR_PURGE_PORT; return 0; } /* ********************************************************************** METHODE : Ecrire() TRAITEMENT: Envoi d'un chaine de caractres sur le port srie. Si la procdure abouti, elle retourne le nombre de carac crit, sinon un code erreur ngatif *********************************************************************** */ int CPort::Ecrire(char *buf) { BOOL bResult; int nb_car_ecrit; if (!ouverte) return ERR_LIGNE_FERMEE; bResult = WriteFile(hcom,buf,strlen(buf),(DWORD*) &nb_car_ecrit,NULL); if (bResult && nb_car_ecrit) return nb_car_ecrit; else return ERR_ECRIRE_PORT; } /* ********************************************************************** METHODE : Ecrire() TRAITEMENT: Envoi d'un chaine de caractres sur le port srie. Si la procdure abouti, elle retourne le nombre de carac crit, sinon un code erreur ngatif *********************************************************************** */ int CPort::Ecrire(char *buf,int nbCar) { BOOL bResult; int nb_car_ecrit; if (!ouverte) return ERR_LIGNE_FERMEE; bResult = WriteFile(hcom,buf,nbCar,(DWORD*) &nb_car_ecrit,NULL); if (bResult && nb_car_ecrit) return nb_car_ecrit; else return ERR_ECRIRE_PORT; } /* ********************************************************************** METHODE : EcrireCar() TRAITEMENT: Envoi un caractres sur le port srie. Si la procdure abouti, elle retourne le nombre de caractre crit, sinon un code erreur ngatif *********************************************************************** */ int CPort::EcritCar(const char car) { BOOL bResult; int nb_car_ecrit; if (!ouverte) return ERR_LIGNE_FERMEE; bResult = WriteFile(hcom,&car,1,(DWORD*) &nb_car_ecrit,NULL); if (bResult && nb_car_ecrit) return nb_car_ecrit; else return ERR_ECRIRE_PORT; } /* ********************************************************************** METHODE : Lire() TRAITEMENT: Lecture des octets sur le port de communication selon le time out dfini dans Ouverture_port(). Les octets sont stocks dans buf, et le nombre d'octets lus est retourn par la fonction. En cas d'chec, un code ngatif est renvoy *********************************************************************** */ int CPort::Lire(char *buf,const int nb_car) { int nb_car_lu=0; if (!ouverte) return ERR_LIGNE_FERMEE; if (ReadFile(hcom,buf,nb_car,(DWORD*) &nb_car_lu,NULL)) { buf[nb_car_lu]=0; return nb_car_lu; } else return ERR_LIRE_PORT; } /* ********************************************************************** METHODE : Etat() TRAITEMENT: Compare l'etat du port avec celui pass en paramtre (CTS,DSR,RING, RLSD) *********************************************************************** */ int CPort::Etat(DWORD etat) { DWORD status; if (!ouverte) return ERR_LIGNE_FERMEE; if(GetCommModemStatus(hcom,&status)) { if (status & etat) return status; } return ERR_ETAT_PORT; }
Swift
UTF-8
1,990
4
4
[]
no_license
// Created on 2020/4/3 /* https://leetcode-cn.com/problems/count-and-say/ 38. Count and Say The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit. Note: Each term of the sequence of integers will be represented as a string. Example 1: Input: 1 Output: "1" Explanation: This is the base case. Example 2: Input: 4 Output: "1211" Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211". */ import XCTest class P38: XCTestCase { func countAndSay(_ n: Int) -> String { var seq = "1" for _ in 1..<n { let chars = Array(seq) var num = chars[0] var count = 1 var next = "" for i in stride(from: 1, to: chars.count, by: 1) { if chars[i] == chars[i - 1] { count += 1 } else { next += "\(count)\(num)" num = chars[i] count = 1 } } next += "\(count)\(num)" seq = next } return seq } func testCountAndSay() { let cases = ["", "1", "11", "21", "1211", "111221", "312211", "13112221", "1113213211", "31131211131221", "13211311123113112211"] for i in 1...10 { XCTAssert(countAndSay(i) == cases[i]) } } }
Python
UTF-8
378
3.1875
3
[]
no_license
# # @lc app=leetcode.cn id=1360 lang=python3 # # [1360] 日期之间隔几天 # # @lc code=start class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: import datetime date1 = datetime.datetime.strptime(date1,"%Y-%m-%d") date2 = datetime.datetime.strptime(date2,"%Y-%m-%d") return abs((date2-date1).days) # @lc code=end
C#
UTF-8
1,198
3.765625
4
[]
no_license
using System; class Program { static void Swap(ref int a, ref int b) { int t = a; a = b; b = t; } //static bool Div(int x, int y, ref int ret) //{ // if (y==0) // { // return true; // } // ret = x / y; // return false; //} //오류코드를 리턴, ret에 값을 저장. //ret는 out용 parameter 이다. //-> 새로운 키워드 제공. out 적고 메서드 종료 전에 값의 할당이 없으면 오류 static bool Div(int x, int y, out int ret) { if (y==0) { ret = 0; return true; } ret = x / y; return false; } static void Main1(string[] args) { int a = 10, b = 1000; //java에서는 swap이 어렵. 사실 C#도 포인터 없어서 C만큼 쉬운거같지는 않음. Swap(ref a, ref b); //몫을 구하는 메서드 구현하기. int ans=0; //if (Div(10, 0, ref ans)) Console.WriteLine("Div error"); //else Console.WriteLine(ans); if (Div(10, 0, out ans)) Console.WriteLine("Div error"); else Console.WriteLine(ans); } }
Python
UTF-8
2,445
2.625
3
[ "MIT" ]
permissive
#!/usr/bin/env python # # This library is free software, distributed under the terms of # the GNU Lesser General Public License Version 3, or any later version. # See the COPYING file included in this archive # # Thanks to Paul Cannon for IP-address resolution functions (taken from aspn.activestate.com) import os, sys, time, signal def destroyNetwork(nodes): print 'Destroying Kademlia network...' i = 0 for node in nodes: i += 1 hashAmount = i*50/amount hashbar = '#'*hashAmount output = '\r[%-50s] %d/%d' % (hashbar, i, amount) sys.stdout.write(output) time.sleep(0.15) os.kill(node, signal.SIGTERM) print if __name__ == '__main__': if len(sys.argv) < 2: print 'Usage:\n%s AMOUNT_OF_NODES [NIC_IP_ADDRESS]' % sys.argv[0] print '\nNIC_IP_ADDRESS should be the IP address of the network interface through' print 'which other systems will access these Kademlia nodes.\n' print 'If omitted, the script will attempt to determine the system\'s IP address' print 'automatically, but do note that this may result in 127.0.0.1 being used (i.e.' print 'the nodes will only be reachable from this system).\n' sys.exit(1) amount = int(sys.argv[1]) if len(sys.argv) >= 3: ipAddress = sys.argv[2] else: import socket ipAddress = socket.gethostbyname(socket.gethostname()) print 'Network interface IP address omitted; using %s...' % ipAddress startPort = 4000 port = startPort+1 nodes = [] print 'Creating Kademlia network...' try: nodes.append(os.spawnlp(os.P_NOWAIT, 'python', 'python', 'entangled/node.py', str(startPort))) for i in range(amount-1): time.sleep(0.15) hashAmount = i*50/amount hashbar = '#'*hashAmount output = '\r[%-50s] %d/%d' % (hashbar, i, amount) sys.stdout.write(output) nodes.append(os.spawnlp(os.P_NOWAIT, 'python', 'python', '../entangled/node.py', str(port), ipAddress, str(startPort))) port += 1 except KeyboardInterrupt: '\nNetwork creation cancelled.' destroyNetwork(nodes) sys.exit(1) print '\n\n---------------\nNetwork running\n---------------\n' try: while 1: time.sleep(1) except KeyboardInterrupt: pass finally: destroyNetwork(nodes)
Python
UTF-8
1,925
3.625
4
[]
no_license
#!/bin/python import random def solution(board): for i in range(3): if(board[i][0] == board[i][1] == board[i][2] != '_'): return board[i][0] if(board[0][i] == board[1][i] == board[2][i] != '_'): return board[0][i] if(board[0][0] == board[1][1] == board[2][2] != '_'): return board[0][0] if(board[2][0] == board[1][1] == board[0][2] != '_'): return board[2][0] return 0; def score(player, board): #score count; we will count the number of winning combinations this board position leads to, assuming that it is now the opponents turn sCount = 0 solut = solution(board) if(solut): return (solut == player) else: for i in range(3): for j in range(3): if(board[i][j] != '_'): board[i][j] = 'O' if(player == 'X') else 'X' temp = solution(board) if(temp): print "bad" return -1 * (temp != player) for x in range(3): for y in range(3): if(board[x][y] != '_'): board [x][y] = 'X' if(player == 'X') else 'O' sCount += score(player, board) board [x][y] = '_' board[i][j] = '_' return sCount # Complete the function below to print 2 integers separated by a single space which will be your next move def nextMove(player,board): #If player is X, I'm the first player. #If player is O, I'm the second player. player = raw_input() #Read the board now. The board is a 3x3 array filled with X, O or _. board = [] for i in xrange(0, 3): board.append(raw_input()) nextMove(player,board);
JavaScript
UTF-8
1,142
2.703125
3
[]
no_license
let menu = document.querySelector('#menu'); let nav = document.querySelector('.nav'); menu.onclick = () => { menu.classList.toggle('fa-times'); nav.classList.toggle('active'); } let scrollBar = document.querySelector('.scroll-bar'); function scrollIndicator(){ let maxHeight = window.document.body.scrollHeight - window.innerHeight; let percentage = ((window.scrollY) / maxHeight) *100; scrollBar.style.width = percentage + '%'; } window.onscroll = () =>{ scrollIndicator(); } var swiper = new Swiper(".banner-slider", { spaceBetween: 30, centeredSlides: true, autoplay: { delay: 2500, disableOnInteraction: false, }, pagination: { el: ".swiper-pagination", clickable: true, }, loop:true, }); /* Image Comparison Slider*/ const slider = document.querySelector('.slider input'); const img = document.querySelector('.images .img-2'); const dragLine = document.querySelector('.slider .drag-line'); slider.oninput = function(){ let sliderVal = slider.value; dragLine.style.left = sliderVal + '%'; img.style.width = sliderVal + '%'; }
Markdown
UTF-8
3,170
3.75
4
[]
no_license
# 变量的解构赋值 ES6允许按照一定模式,让变量从数组对象中提取值,这称为解构。 ### 数组的解构赋值 ES6允许从数组中提取值,按照对应关系赋值: var [a, b, c] = [1, 2, 4]; console.log(a); //1 console.log(b); //2 console.log(c); //4 还能使用一些嵌套的写法: var [a, [[b], c]] = [1, [[2], 4]]; var [, , m] = [1, 3, 5]; console.log(m); //5; var [head, ...tail] = [1, 3, 5, 7]; console.log(head); //1; console.log(tail); //[3, 5, 7]; 如果解构失败,变量的值为undefined: var [a] = []; var [a] = 1; var [a, b] = [1]; 解构允许指定默认值: var [a, b = 3] = [1]; console.log(a); //1 console.log(b); //3 var [a, b = 3] = [1, 4]; console.log(a); //1 console.log(b); //4 解构赋值同样适用于let和const命令。 ### 对象的解构赋值 解构也可以用对象。 var {a, b} = {a: '123', b: 'abc'}; console.log(a); //'123' console.log(b); //'abc' 与数组不同的是变量需要与对象属性同名才能取到值。 var {b, a} = {a: '123', b: 'abc'}; console.log(a); //'123' console.log(b); //'abc' var {c, a} = {a: '123', b: 'abc'}; console.log(a); //'123' console.log(c); //undefined 如果变量名不一致也能这样: var {a:c} = {a: '123', b: 'abc'}; console.log(c); //'123' 对象也能嵌套赋值: var obj = { word: 'hello', arr: [ 'world', { inner: '!' } ] }; var {word, arr: [world, {inner}]} = obj; console.log(word); //'hello' console.log(world); //'world' console.log(inner); //'!' ### 字符串的解构赋值 字符串被转换为类似数组的对象,也能解构赋值: var [a, b, c] = 'cat'; console.log(a); //'c' console.log(b); //'a' console.log(c); //'t' var {length: len} = 'hello'; console.log(len); //5 ### 函数参数的解构赋值 function add([x, y]){ return x + y; } add([1, 2]) // 3 ### 用途 1. 交换变量值 [x, y] = [y, x]; 2. 从函数返回多个值 方便的接收从函数返回的多个值: function foo() { return [1, 3, 5]; } var [a, b, c] = foo(); 3. 函数参数的定义 function foo({x, y, z}) {}; var obj = {x: 1, y: 2, z: 3}; foo(obj); 4. 提取JSON数据 var data = { 'id': 8, 'name': 'jack', 'friends': [ 'marry', 'tom' ] }; let {id, name, friends: [frd1, frd2]} = data; console.log(id); //8 console.log(name); //'jack' console.log(frd1); //'marry' console.log(frd2); //'tom' 5. 函数参数的默认值 function move({x, y} = { x: 0, y: 0 }) { return [x, y]; } 6. 遍历Map结构 var map = new Map(); map.set('first', 'hello'); map.set('second', 'world'); for (let [key, value] of map) { console.log(key + " is " + value); }
PHP
UTF-8
89
2.703125
3
[]
no_license
<?php $str = "<h1>Hello Poly</h1>"; echo $str; echo '<br>'; echo htmlentities($str);
Markdown
UTF-8
3,808
3.625
4
[]
no_license
# INTRODUCTION TO JAVA BASICS -ASSIGNMENT 1. Write a program to find the difference between sum of the squares and the square of the sums of n numbers? Output: Enter the value of n: 4 The 4 numbers are : 2 3 4 5 Sum of Squares of given 4 numbers is : 54 Squares of Sum of given 4 numbers is : 196 Difference between sum of the squares and the square of the sum of given 4 numbers is : 142 2. Develop a program that accepts the area of a square and will calculateits perimeter. Output: Enter the area: 23 Perimeter of the square is: 19.183326093250876 3. Develop the program calculate Cylinder Volume., which accepts radius of a cylinder's base disk and its height and computes the volume of the cylinder. Output: Enter the radius : 12 Enter the height : 13 Volume of the cylinder is : 5881.061447520093 4. Utopias tax accountants always use programs that compute income taxes even though the tax rate is a solid, never-changing 15%. Define theprogram calculateTax which determines the tax on the gross pay. DefinecalculateNetPay that determines the net pay of an employee from the number of hours worked. Assume an hourly rate of $12. Output: Days worked by employer in a year : 300 Enter the no. of working hours in a day : 6 Enter the no. of hours worked in over time : 1 Enter the no. of hours took leave : 1560 Gross Pay (in $) : 2892.0 Tax (in $) : 433.8 Net Pay (in $) : 2458.2 5. An old-style movie theater has a simple profit program. Each customer pays $5 per ticket. Every performance costs the theater $20, plus $.50 perattendee. Develop the program calculateTotalProfit that consumes the number of attendees (of a show) and calculates how much income the show earns. Output: Enter the no. of attendees per show : 50 Total Profit of the theater per show (in $) is : 205.0 6. Develop the program calculateCylinderArea, which accepts radius of the cylinder's base disk and its height and computes surface area of the cylinder. 2pi r h + 2 pi r square Enter the base radius : 12 Enter the height : 13 Surface Area of the cylinder is : 1884.9555921538758 7. Develop the program calculatePipeArea. It computes the surface areaof a pipe, which is an open cylinder. The program accpets three values: the pipes inner radius, its length, and the thickness of its wall. Output: Enter the inner radius : 13 Enter the length : 20 Enter the thickness : 5 Surface Area of the pipe is : 2261.946710584651 8. Develop the program calculateHeight, which computes the height that a rocket reaches in a given amount of time. If the rocket accelerates at a constant rate g, it reaches a speed of g • t in t time units and a height of 1/2 * v * t where v is the speed at t. Output: Enter the time (in seconds) : 300 Height reached (in meters) is : 441000.0 9. Develop a program that computes the distance a boat travels across a river, given the width of the river, the boat's speed perpendicular to the river, and the river's speed. Speed is distance/time, and the Pythagorean Theorem is c2 = a2 + b2. Solution: Output: Enter the width of the river (in meters) : 15 Enter the river's speed (in meter/sec) : 200 Enter the boat's speed (in meter/sec) : 250 The distance travelled by boat (in meters) is : 19.209372712298546 10. Develop a program that accepts an initial amount of money (called the principal), a simple annual interest rate, and a number of months will compute the balance at the end of that time. Assume that no additional deposits or withdrawals are made and that a month is 1/12 of a year. Total interest is the product of the principal, the annual interest rate expressed as a decimal, and the number of years. Output: Enter the principal amount : 15000 Enter the annual interest rate : 12 Enter the no. of months : 24 Balance after 24 month(s) is : 18600.0
Java
UTF-8
2,580
1.617188
2
[]
no_license
package com.move.etb.boot.model; import java.io.Serializable; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonInclude(Include.NON_NULL) public class UserInfoData implements Serializable { private static final long serialVersionUID = 3909957663978884279L; private List<LinkAccountData> linkAccountList; private CustomerProfileData restCustProfile; private String responseCode; private String responseMessage; private String userId; private String cifNo; private String productCustomerName; private String productCustomerEmail; private String tacPhoneNumber; private String sessionId; private String linkedAccountsString; public CustomerProfileData getRestCustProfile() { return restCustProfile; } public void setRestCustProfile(CustomerProfileData restCustProfile) { this.restCustProfile = restCustProfile; } public String getCifNo() { return cifNo; } public void setCifNo(String cifNo) { this.cifNo = cifNo; } public String getProductCustomerName() { return productCustomerName; } public void setProductCustomerName(String productCustomerName) { this.productCustomerName = productCustomerName; } public String getProductCustomerEmail() { return productCustomerEmail; } public void setProductCustomerEmail(String productCustomerEmail) { this.productCustomerEmail = productCustomerEmail; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String getResponseCode() { return responseCode; } public void setResponseCode(String responseCode) { this.responseCode = responseCode; } public String getResponseMessage() { return responseMessage; } public void setResponseMessage(String responseMessage) { this.responseMessage = responseMessage; } public List<LinkAccountData> getLinkAccountList() { return linkAccountList; } public void setLinkAccountList(List<LinkAccountData> linkAccountList) { this.linkAccountList = linkAccountList; } public String getLinkedAccountsString() { return linkedAccountsString; } public void setLinkedAccountsString(String linkedAccountsString) { this.linkedAccountsString = linkedAccountsString; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getTacPhoneNumber() { return tacPhoneNumber; } public void setTacPhoneNumber(String tacPhoneNumber) { this.tacPhoneNumber = tacPhoneNumber; } }
Shell
UTF-8
1,375
2.75
3
[ "MIT" ]
permissive
#!/bin/bash /bin/rm -rf /tmp/sileo/ /bin/rm -rf /tmp/org.coolstar.sileo_0.4b6_iphoneos-arm.deb /bin/rm -rf /tmp/sileo.deb /bin/rm -rf /tmp/install echo Downloading Sileo... /usr/bin/curl -o /tmp/org.coolstar.sileo_0.4b6_iphoneos-arm.deb https://raw.githubusercontent.com/coolstar/electratools/a5bc67fca462f06dd5c4a496d787ca41aa873d51/debs/org.coolstar.sileo_0.4b6_iphoneos-arm.deb sleep 1 set -e echo Extracting Sileo... /bin/mkdir /tmp/sileo/ /usr/bin/dpkg-deb -R /tmp/org.coolstar.sileo_0.4b6_iphoneos-arm.deb /tmp/sileo/ echo Preparing Sileo for install... /bin/rm /tmp/sileo/DEBIAN/control /bin/rm /tmp/sileo/DEBIAN/postinst /usr/bin/curl -o /tmp/sileo/DEBIAN/control https://raw.githubusercontent.com/Samgisaninja/sillyo-installer/master/control echo "" >> /tmp/sileo/DEBIAN/control /usr/bin/curl -o /tmp/sileo/DEBIAN/postinst https://raw.githubusercontent.com/Samgisaninja/sillyo-installer/master/postinst /bin/chmod 0755 /tmp/sileo/DEBIAN/postinst /usr/bin/dpkg-deb -b /tmp/sileo echo Installing Sileo... /usr/bin/dpkg -i /tmp/sileo.deb uicache echo Cleaning up... /bin/rm -rf /tmp/sileo/ /bin/rm -rf /tmp/org.coolstar.sileo_0.4b6_iphoneos-arm.deb /bin/rm -rf /tmp/sileo.deb /bin/rm -rf /tmp/install /bin/chown root:admin /Applications/Sileo.app/giveMeRoot /bin/chmod 4755 /Applications/Sileo.app/giveMeRoot /usr/bin/apt-get update echo All done!
C++
UTF-8
4,949
3.0625
3
[]
no_license
#include "HumanPlayerStrategy.h" void HumanPlayerStrategy::execute(Player* playerData, CardDeck* cardDeck) { cout << "HUMAN PLAYER EXECUTE()" << endl; node<Player*>* curr = Player::players->getHead(); // same list of players, but used for additional traversals while inside game loop node<Player*>* temp = curr; bool playersInManhatten = false; // check for whether any players are in any manhatten zones // 1. Roll the Dice (up to 3 times) playerData->rollDice(); // 2. Resolve the Dice playerData->resolveDice(); // CHECK IF PLAYER DIED WHILE RESOLVING THE DICE if (playerData->getHealth() == 0) return; // 3. Move (generally optional, sometimes mandatory) if (playerData) { // CHECK IF PLAYER IS ALREADY IN MANHATTEN // IF SO MOVE PLAYER UP TO NEXT ZONE int playerZone = playerData->getZone(); if (playerZone == 1) playerData->setZone(2); else if (playerZone == 2) playerData->setZone(3); else if (playerZone == 4) playerData->setZone(5); else if (playerZone == 5) playerData->setZone(6); else if (playerZone != 3 || playerZone != 6) { // PLAYER IS NOT IN MANHATTEN // FIRST CHECK IF MANHATTEN HAS ANY PLAYERS IN IT playersInManhatten = false; curr = Player::players->getHead(); while (curr) { playerZone = curr->getData()->getZone(); if (playerZone <= 6) { playersInManhatten = true; break; } curr = curr->getNext(); } // IF NO PLAYERS IN MANHATTEN, MOVE PLAYER THERE if (!playersInManhatten) { std::cout << "No one in Manhatten, you must move there." << std::endl; if (Player::getPlayerCount() < 5) playerData->setZone(1); else playerData->setZone(4); } else { // AT LEAST ONE PLAYER IN MANHATTEN, GIVE PLAYER CHOICE AS TO WHERE TO MOVE if (playerData->getZone() >= 7) { bool badInput = true; string answer; std::cout << "There is already one monster in Manhatten." << std::endl; std::cout << "Would you like to move(M) from or stay(S) in " << MapLoader::getMap()->getVertex(playerData->getZone())->getName() << "? (M/S): "; while (badInput) { try { std::cin >> answer; if (!(answer == "M" || answer == "S")) { throw answer; } badInput = false; } catch (string s) { std::cout << "The answer " << s << " is not valid. Please enter either M or S: "; } } if (answer == "M") playerData->move(); } } } // DEAL WITH ATTACK DICE // PLAYER IS NOT IN MANHATTEN, ALLOW MANHATTEN PLAYERS TO MOVE OUT bool attack = false; bool traversed = false; playerZone = playerData->getZone(); if (playerZone >= 7) { std::cout << "\n\nAllowing Manhatten players that were attacked to leave Manhattan\n"; for (int i = 0; i < 6; i++) { if (playerData->getDice()->getResult()[i] == Attack) { attack = true; curr = Player::players->getHead(); temp = curr; while (curr) { playerZone = curr->getData()->getZone(); if (playerZone <= 6) { if (curr->getData()->getName() == "Aggressive CPU" || curr->getData()->getName() == "Moderate CPU") { curr->getData()->cpuMove(); } else { if (curr->getData()->getHealth() == 0) { curr = curr->getNext(); traversed = true; playerData->removePlayer(temp->getData()->getCharacter()); temp = curr; } else { std::cout << "There is already one monster in Manhatten." << std::endl; std::cout << "Player " << curr->getData()->getName() << " you may move\n"; bool badInput = true; string answer; std::cout << "Would you like to move(M) from or stay(S) in " << MapLoader::getMap()->getVertex(curr->getData()->getZone())->getName() << "? (M/S): "; while (badInput) { try { std::cin >> answer; if (!(answer == "M" || answer == "S")) { throw answer; } badInput = false; } catch (string s) { std::cout << "The answer " << s << " is not valid. Please enter either M or S: "; } } if (answer == "M") curr->getData()->move(); } } } if(!traversed) curr = curr->getNext(); traversed = false; } } if (attack) break; } std::cout << "\n\nBack to " << playerData->getName() << "'s turn\n"; } // 4. Buy Cards (optional) playerData->buyCards(cardDeck); if(playerData -> getCards() -> getCount() > 0) { std::cout << "Now playing the cards for " << playerData -> getName() << "." << std::endl; node<Card*>* curr = playerData->getCards()->getHead(); while(curr != NULL) { curr -> getData() -> Play(playerData); curr = curr -> getNext(); } std::cout << playerData -> getName() << ", your cards have been played." << std::endl; system("pause"); } // 5. End Turn } }
Python
UTF-8
1,147
2.75
3
[]
no_license
import requests from bs4 import BeautifulSoup import time import csv url = 'https://s.weibo.com/top/summary' web_data = requests.get(url).content.decode('utf-8') soup = BeautifulSoup(web_data, 'lxml') tbody = soup.find(name='tbody') tr_list = tbody.find_all(name='tr') resou_lists = [] localtime = time.asctime( time.localtime(time.time()) ) for item in tr_list: if item.find(attrs={'class': 'td-01 ranktop'}): num = item.find(attrs={'class': 'td-01 ranktop'}).get_text() else: num = 'top' keyword = item.find(attrs={'class': 'td-02'}).a.get_text() if item.find(attrs={'class': 'td-02'}).span: hot = item.find(attrs={'class': 'td-02'}).span.get_text() else: hot = '' if item.find(attrs={'class': 'td-03'}).i: charac = item.find(attrs={'class': 'td-03'}).i.get_text() else: charac = ' ' resou_item = { 'time': localtime, 'number': num, 'keyword': keyword, 'hot': hot, 'character': charac } resou_lists.append(resou_item) headers = ['time', 'number', 'keyword', 'hot', 'character'] with open('resou.csv', 'a') as f: f_csv = csv.DictWriter(f, headers) # f_csv.writeheader() f_csv.writerows(resou_lists)
Python
UTF-8
1,186
3.6875
4
[]
no_license
""" Read file into texts and calls. It's ok if you don't understand how to read files """ import os __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) import csv with open(os.path.join(__location__, 'texts.csv'),'r') as f: reader = csv.reader(f) texts = list(reader) with open(os.path.join(__location__,'calls.csv'), 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 2: Which telephone number spent the longest time on the phone during the period? Don't forget that time spent answering a call is also time spent on the phone. Print a message: "<telephone number> spent the longest time, <total time> seconds, on the phone during September 2016.". """ maxDuration = 0 maxPhone1 = None maxPhone2 = None for i in range(len(calls)): if int(calls[i][3])> maxDuration: maxDuration = int(calls[i][3]) maxPhone1 = calls[i][0] maxPhone2 = calls[i][1] print(f"{maxPhone1} and {maxPhone2} spent the longest time, {maxDuration} seconds, on the phone during September 2016.") #"89071 50880 and (04546)388977 spent the longest time, 4617 seconds, on the phone during September 2016."
TypeScript
UTF-8
1,985
2.90625
3
[ "Apache-2.0" ]
permissive
abstract class HitboxBase { protected displayable : boolean; protected player : Player; protected element : HTMLCanvasElement; vectors : Vector2[]; protected constructor(displayable : boolean, player : Player) { this.player = player; this.displayable = displayable; if (displayable) { this.element = document.createElement("canvas"); this.element.style.background = "none"; player.appendChild(this.element); } } public flip(isFacingRight : boolean) : void { if (this.displayable) { if (isFacingRight) { this.element.style.transform = "scaleX(1)"; } else { this.element.style.transform = "scaleX(-1)"; } } } protected createPolygon() : any { const ctx = this.element.getContext("2d"); const game : HTMLElement = <HTMLElement>document.getElementsByTagName("game")[0]; const playerHeight : number = this.player.clientHeight; if (ctx !== null) { ctx.lineWidth = 2 ctx.strokeStyle = '#f00'; ctx.beginPath(); ctx.moveTo(this.vectors[0].x / 100 * game.offsetWidth, -this.vectors[0].y / 100 * game.offsetWidth + playerHeight); for(let i = 1 ; i < this.vectors.length ; i++) { ctx.lineTo(this.vectors[i].x / 100 * game.offsetWidth, -this.vectors[i].y / 100 * game.offsetWidth + playerHeight); } ctx.closePath(); ctx.stroke(); } } public removeElement() : void { // @ts-ignore this.element.parentNode.removeChild(this.element); } abstract display() : void; abstract get minX() : number; abstract get maxX() : number; abstract get minY() : number; abstract get maxY() : number; abstract getCurrentHitbox(currentPosition : Vector2) : HitboxBase; abstract get vectorAmount() : number; }
PHP
UTF-8
622
2.546875
3
[]
no_license
<?php class JobsHelper extends AppHelper { public $helpers = array( 'Html', 'Text' ); public function howToApply($email, $url) { if (!empty($email) && !empty($url)) { return "<hr />\n<p>Apply by email: ".$this->Text->autoLinkEmails($email)." or through: ".$this->Html->link($url, $url); } if (!empty($email)) { return "<hr />\n<p>Apply by email: ".$this->Text->autoLinkEmails($email); } if (!empty($url)) { return "<hr />\n<p>Apply through: ".$this->Html->link($url, $url); } } }
Java
UTF-8
423
2.28125
2
[]
no_license
package org.springboot.storelocator.model; import java.util.ArrayList; import java.util.List; public class StoreLocatorErrorResponse { public List<StoreLocatorError> error = new ArrayList<>(); public StoreLocatorErrorResponse() { } public void addError(String message, String code) { error.add(new StoreLocatorError(message, code)); } public List<StoreLocatorError> getError() { return error; } }
C++
UTF-8
403
2.65625
3
[]
no_license
#ifndef JUNK_H #define JUNK_H using namespace std; class Junk { private: int x, // data types y; public: Junk(); // constructor void setX(int); // function prototypes void setY(int); int getX(); int getY(); }; #endif // closes the ifndef so that resources won't keep checking to see if it's defined or not already // won't compile without this statement!
Python
UTF-8
3,672
2.71875
3
[]
no_license
from game import ResourceManager from .abstract_screen import AbstractScreen from game.gui import PlayButton, ExitButton, TextGUI, MainMenuButton class HighscoresScreen(AbstractScreen): def __init__(self, menu): AbstractScreen.__init__(self, menu, "backgrounds/main_menu.jpg") self._gui_elements.append(MainMenuButton(self, (self._x_total_half, self._y_total * 14 / 16))) white = (255, 255, 255) font_64 = ResourceManager.load_font_asset("8bit.ttf", 64) # font_32 = ResourceManager.load_font_asset("8bit.ttf", 32) font_24 = ResourceManager.load_font_asset("8bit.ttf", 24) # font_16 = ResourceManager.load_font_asset("8bit.ttf", 16) title = TextGUI(self, font_64, white, "Highscores", (self._x_total_half, self._y_total * 2 / 16)) hs_rect = HSBackground(self, (self._x_total_half, self._y_total>>1), 500, 325) self.hs1 = TextGUI(self, font_24, white, "None", (self._x_total_half, self._y_total * 5 / 16)) self.hs2 = TextGUI(self, font_24, white, "None", (self._x_total_half, self._y_total * 6.5 / 16)) self.hs3 = TextGUI(self, font_24, white, "None", (self._x_total_half, self._y_total * 8 / 16)) self.hs4 = TextGUI(self, font_24, white, "None", (self._x_total_half, self._y_total * 9.5 / 16)) self.hs5 = TextGUI(self, font_24, white, "None", (self._x_total_half, self._y_total * 11 / 16)) back_button = TextGUI(self, font_24, white, "Menú Principal", (self._x_total_half, self._y_total * 14 / 16)) self._gui_elements.append(title) self._gui_elements.append(hs_rect) self._gui_elements.append(self.hs1) self._gui_elements.append(self.hs2) self._gui_elements.append(self.hs3) self._gui_elements.append(self.hs4) self._gui_elements.append(self.hs5) self._gui_elements.append(back_button) def populate_hs_list(self, list): font_24 = ResourceManager.load_font_asset("8bit.ttf", 24) white = (255, 255, 255) self._gui_elements.remove(self.hs1) self._gui_elements.remove(self.hs2) self._gui_elements.remove(self.hs3) self._gui_elements.remove(self.hs4) self._gui_elements.remove(self.hs5) self.hs1 = TextGUI(self, font_24, white, f"{list[0][0]} - {list[0][1]} sec", (self._x_total_half, self._y_total * 5 / 16)) self.hs2 = TextGUI(self, font_24, white, f"{list[1][0]} - {list[1][1]} sec", (self._x_total_half, self._y_total * 6.5 / 16)) self.hs3 = TextGUI(self, font_24, white, f"{list[2][0]} - {list[2][1]} sec", (self._x_total_half, self._y_total * 8 / 16)) self.hs4 = TextGUI(self, font_24, white, f"{list[3][0]} - {list[3][1]} sec", (self._x_total_half, self._y_total * 9.5 / 16)) self.hs5 = TextGUI(self, font_24, white, f"{list[4][0]} - {list[4][1]} sec", (self._x_total_half, self._y_total * 11 / 16)) self._gui_elements.append(self.hs1) self._gui_elements.append(self.hs2) self._gui_elements.append(self.hs3) self._gui_elements.append(self.hs4) self._gui_elements.append(self.hs5) from ..gui.gui_element import GUIElement class HSBackground(GUIElement): def __init__(self, screen, pos, x_size, y_size): import pygame self.image = pygame.Surface((x_size, y_size)) self.image.fill((160, 160, 160)) self.rect = self.image.get_rect() self.rect.centerx = pos[0] self.rect.centery = pos[1] GUIElement.__init__(self, screen, self.rect) def draw(self, screen): screen.blit(self.image, self.rect) def callback(self): pass
Java
UTF-8
2,618
3.5
4
[]
no_license
package JavaDemo.MultiThreadTest; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * @Author MaoTian * @Classname ProducerConsumerBlockingQueue * @Description 使用阻塞队列,生产一个消费一个 * @Date 下午8:51 2019/8/8 * @Version 1.0 * @Created by mao<tianmao818@qq.com> */ class Resource{ private volatile boolean FLAG=true; //可见性 private AtomicInteger atomicInteger=new AtomicInteger();//原子类 BlockingQueue<String> blockingQueue=null;//阻塞队列 public Resource(BlockingQueue<String> blockingQueue){ this.blockingQueue=blockingQueue; System.out.println(blockingQueue.getClass().getName()); } public void myProd()throws Exception{ String data=null; boolean retvalue; while (FLAG){ data=atomicInteger.incrementAndGet()+""; retvalue=blockingQueue.offer(data,2L, TimeUnit.SECONDS); if(retvalue){ System.out.println(Thread.currentThread()+":insert ok "+data); }else{ System.out.println(Thread.currentThread()+":insert fail"); } // TimeUnit.SECONDS.sleep(1); } System.out.println(Thread.currentThread()+":producer stop"); } public void myCons()throws Exception{ String result; while (FLAG){ result=blockingQueue.poll(2L, TimeUnit.SECONDS); if(null==result||result.equalsIgnoreCase("")){ FLAG=false; System.out.println(Thread.currentThread()+":consumer stop"); return; } System.out.println(Thread.currentThread()+":consume ok "+result); } } public void stop(){ this.FLAG=false; } } public class ProducerConsumerBlockingQueue { public static void main(String[] args) throws InterruptedException { Resource resource=new Resource(new ArrayBlockingQueue<>(10)); new Thread(()->{ System.out.println(Thread.currentThread().getName()+" producer start"); try { resource.myProd(); }catch (Exception e){ } },"producer-3").start(); new Thread(()->{ System.out.println(Thread.currentThread().getName()+" consumer start"); try { resource.myCons(); }catch (Exception e){ } },"consumer-3").start(); TimeUnit.SECONDS.sleep(5); resource.stop(); } }
C#
UTF-8
1,338
2.609375
3
[]
no_license
using Google.Apis.Auth; using System; using System.Threading.Tasks; using Test.DTO; using static Google.Apis.Auth.GoogleJsonWebSignature; namespace Test { public class GoogleAuthService : IGoogleAuthService { GoogleAuthSettings googleAuthSettings; public GoogleAuthService(GoogleAuthSettings googleAuthSettings) { this.googleAuthSettings = googleAuthSettings; } public async Task<SocialUserDetails> getGoogleUserInfo(string token) { var payload = await validateToken(token); var googleUserDetails = new SocialUserDetails(); googleUserDetails.Email = payload.Email; googleUserDetails.FirstName = payload.GivenName; googleUserDetails.LastName = payload.FamilyName; googleUserDetails.Id = Guid.NewGuid().ToString(); return googleUserDetails; } public async Task<Payload> validateToken(string token) { var payload = await GoogleJsonWebSignature.ValidateAsync(token); if (payload.Audience.ToString() != googleAuthSettings.AppKey || (payload.Issuer != googleAuthSettings.Issuer)) { throw new Exception("Something Went wrong"); } return payload; } } }
JavaScript
UTF-8
624
3
3
[]
no_license
const canCross = stones => { const dp = Array.from({ length: stones.length }, _ => [] ) const stoneToIndex = {} const end = stones[ stones.length - 1 ] const jump = ( s, k ) => { if ( s === end ) return true let i = stoneToIndex[ s ] if ( k < 1 || end < s || isNaN( i ) ) return false if ( 'undefined' === typeof dp[ i ][ k ] ) { dp[ i ][ k ] = jump( s + k + 1, k + 1 ) || jump( s + k, k ) || jump( s + k - 1, k - 1 ) } return dp[ i ][ k ] } stones.forEach( ( s, i ) => stoneToIndex[ s ] = i ) return jump( 1, 1 ) }
C#
UTF-8
650
3.40625
3
[]
no_license
//using System; using TriangleServices.Exceptions; namespace TriangleServices { public class TriangleInit { public int A { get; private set; } public int B { get; private set; } public int C { get; private set; } public TriangleInit(int x, int y, int z) { if(x<0 || y<0 || z<0) throw new NegativeValueOfSideException("Negative side..."); A = x; B = y; C = z; } public bool IsPossibleTriangle() { if(A+B>C && A+C>B && B+C>A) return true; else return false; } } }
Go
UTF-8
235
2.625
3
[]
no_license
package race import ( "sync" "testing" ) func TestRace(t *testing.T) { var wg sync.WaitGroup defer wg.Wait() wg.Add(2) var i int go func() { defer wg.Done() i = 0 }() go func() { defer wg.Done() i = 1 }() _ = i }
Java
UTF-8
769
3.9375
4
[]
no_license
package Chapter2; /*Exercise 12: (3) Start with a number that is all binary ones. Left shift it, then use the unsigned right-shift operator to right shift through all of its binary positions, each time displaying the result using Integer.toBinaryString( ).*/ public class Task12 { public static void main(String[] args) { int a = Integer.parseInt("111111",2); System.out.println(Integer.toBinaryString(a)); int steps = Integer.toBinaryString(a).length() -1; a <<=steps; System.out.println(Integer.toBinaryString(a)); steps = Integer.toBinaryString(a).length() -1; for (int i=0; i<steps; i++) { a >>=1; System.out.println(Integer.toBinaryString(a)); } } }
Java
UTF-8
368
2.265625
2
[ "Apache-2.0" ]
permissive
package org.erp_microservices.model; import java.util.UUID; /** * A synthetic entity is an entity who does not have a real representation in storage, and is made of 1 or more entities. */ public abstract class AggregateEntity<E extends Entity> implements Entity { public UUID getId() { return rootAggregate().getId(); } public abstract E rootAggregate(); }
Python
UTF-8
543
2.828125
3
[]
no_license
import time from ok import * print time.strftime("%H:%M:%S\n") @ok def _ok(): assert 9 == 3 @ok def _ok1(): assert 1==1 @ok def _ok2(): assert 2==1 @ok def _ok3(): assert 3==3 @ok def _ok4(): assert unittest.tries==4 assert unittest.fails==1 print unittest.score() @ok def _okRegular(): assert 0 == False assert 1 == True @ok def _okFunFact(): # Fun fact: boolean is a subclass of int in Python 2.7 # Python 3 changed it to a keyword to avoid this problem False = True assert 0 == False assert 1 == True
Java
UTF-8
1,091
2.859375
3
[ "Apache-2.0" ]
permissive
package dataset.transformation; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.tuple.Tuple2; /** * Created by yidxue on 2018/2/8 */ public class FlinkMapDemo { public class IntAdder implements MapFunction<Tuple2<Integer, Integer>, Integer> { @Override public Integer map(Tuple2<Integer, Integer> in) { return in.f0 + in.f1; } } public static void main(String[] args) throws Exception { final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<Tuple2<Integer, Integer>> inData = env.fromElements( Tuple2.of(2, 6), Tuple2.of(2, 4), Tuple2.of(1, 3), Tuple2.of(1, 5), Tuple2.of(6, 7), Tuple2.of(6, 7), Tuple2.of(1, 17), Tuple2.of(1, 2)); DataSet<Integer> intSums = inData.map(new FlinkMapDemo().new IntAdder()); intSums.print(); } }
TypeScript
UTF-8
1,195
2.71875
3
[]
no_license
import { hash } from "../services/hashManage"; import { Request, Response } from "express"; import insertUser from "../data/insertUser"; import { generateToken } from "../services/authenticator"; import { generatedId } from "../services/idGenerator"; export default async function createUser(req: Request, res: Response) { try { if ( !req.body.name || !req.body.nickname || !req.body.email || !req.body.senha || !req.body.role ) { throw new Error('Preencha os campos "name","nickname", "email" e "senha"') } const id: string = generatedId() const cypherPassword = await hash(req.body.senha) await insertUser( id, req.body.name, req.body.nickname, req.body.email, cypherPassword, req.body.role ) const token : string = generateToken({id, role: req.body.role}) res.status(201).send({message: "Usuário criado", token }) } catch (error) { res.status(400).send({ message: error.message || error.sqlMessage }) } }
Rust
UTF-8
3,247
3
3
[]
no_license
use std::net::{UdpSocket, SocketAddr}; use std::io::{Read, Result}; use std::thread::{self}; use std::sync::{Arc}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver, TryRecvError, Sender}; use super::reader::{self}; use super::message::{SSDPMessage}; // Should Be Enough To Hold All SSDP Packets. const DEFAULT_MSG_LEN: usize = 600; /// Provides a non-blocking interface for retrieving SSDPMessages off of some /// UdpSocket that is receiving messages from one or more entities. pub struct SSDPReceiver { udp_sock: UdpSocket, udp_addr: SocketAddr, msg_recv: Receiver<SSDPMessage>, kill_flag: Arc<AtomicBool> } impl SSDPReceiver { /// Spawns a worker thread that listens for SSDPMessages and forwards them /// back to the SSDPReceiver object that is returned from this method. pub fn spawn(udp: UdpSocket) -> Result<SSDPReceiver> { let local_addr = try!(udp.local_addr()); let kill_flag = Arc::new(AtomicBool::new(false)); let (msg_send, msg_recv) = mpsc::channel(); let udp_clone = try!(udp.try_clone()); let kill_clone = kill_flag.clone(); thread::spawn(move || { receive_messages(udp_clone, msg_send, kill_clone); }); Ok(SSDPReceiver{ udp_sock: udp, udp_addr: local_addr, msg_recv: msg_recv, kill_flag: kill_flag }) } pub fn recv(&mut self) -> SSDPMessage { self.msg_recv.recv().unwrap() } } impl Drop for SSDPReceiver { fn drop(&mut self) { // TODO: Add Logging For If Kill Flag Is Already Set -> Packet Receiver Failed // SeqCst, Keep Write To UdpSocket Below Us self.kill_flag.store(true, Ordering::SeqCst); // Don't Care About Return Value, If It Fails Nothing We Can Do... self.udp_sock.send_to(&[0], self.udp_addr); } } // TODO: Add Logging /// Listens for packets coming off of the given UdpSocket and sends each packet /// to a worker thread that builds the SSDPMessage which is sent back to the /// SSDPReceiver. fn receive_messages(udp: UdpSocket, msg_send: Sender<SSDPMessage>, kill: Arc<AtomicBool>) { let (pckt_send, pckt_recv) = mpsc::channel(); // Spawn Message Reader Thread thread::spawn(move || { reader::read_messages(pckt_recv, msg_send); }); // Receive Packets On The UdpSocket loop { let mut pckt_buf = vec![0u8; DEFAULT_MSG_LEN]; // Receive A Packet From The UdpSocket let mut result = udp.recv_from(&mut pckt_buf[..]); while result.is_err() { result = udp.recv_from(&mut pckt_buf[..]); } // Check If We Received A Kill Order if kill.load(Ordering::SeqCst) { break; } let (pckt_len, pckt_src) = result.unwrap(); // Check The Length Returned By The UdpSocket if pckt_len > pckt_buf.len() { kill.store(true, Ordering::SeqCst); panic!("Something Is Wrong With UdpSocket Recv Length") } unsafe{ pckt_buf.set_len(pckt_len) }; // Send The Packet To The Reader Thread pckt_send.send((pckt_buf, pckt_src)).unwrap(); } }
Python
UTF-8
246
4
4
[]
no_license
b = float(input('Oi, vamos calcular a área de um triângulo, informe em metros a medida de base: ')) a = float(input('Agora preciso da medida em metros, da altura do triângulo: ')) area = (a*b)/2 print('A área é de {:.2f} m².'.format(area))
Python
UTF-8
1,787
2.703125
3
[]
no_license
from flask import Flask, render_template import data app = Flask(__name__) city = {'ekb':'Из Екатеринбурга','msk':'Из Москвы','spb':'Из Петербурга','kazan':'Из Казани','nsk':'Из Новосибирска'} @app.route("/") def start_index(): dic={} i=0 for k,v in data.tours.items(): if i == 6: break i+=1 dic[k]=v return render_template('index.html',d=dic) @app.route('/departures/') def start_depart(): return render_template('departure.html') @app.route('/departures/<departure>/') def post_depart(departure): S = [] n = [] for k,v in data.tours.items(): if v["departure"]==departure: S.append(int(v["price"])) n.append(int(v["nights"])) S.sort() n.sort() if len(S) in [1,21]: t='тур' elif len(S) in [2,3,4]: t='тура' else: t = 'туров' return render_template('departure.html',d=data.tours,dep=departure,kol=len(S),min_n=n[0],max_n=n[-1],min_S=S[0],max_S=S[-1],gorod=city[departure],text=t) @app.route('/tours/') def start_tour(): return render_template('tour.html') @app.route('/tours/<id>/') def post_tour(id): id=int(id) d=data.tours[id] return render_template('tour.html',title=d['title'],country=d['country'],dep=city[d['departure']],n=d['nights'],desc=d['description'],sum=d['price'],picture=d['picture']) #@app.errorhandler(404) #def render_not_found(error): # return "Что-то не так, но мы все починим:\n{}".format(error), 404 #@app.errorhandler(500) #def render_server_error(error): # return "Что-то не так, но мы все починим" #app.run(debug=True) if __name__ == '__main___': app.run()
Python
UTF-8
11,094
3.0625
3
[]
no_license
import time from threading import Thread import _thread import pygame # Define some colors WHITE = (255, 255, 255) RED = (255,0,0) GREEN = (0,255,0) BROWN = (165, 42, 42) list = [0,1,2,3,4,5,6,7,8] current_list = [2,6,5,1,8,3,0,7,4] OG_List = [2,6,5,1,8,3,0,7,4] current_blank = current_list[8] OG_Blank = current_list[8] # Defining possible movements plus_one = 0,1,3,4,6,7 minus_one = 1,2,4,5,7,8 plus_three = 0,1,2,3,4,5 minus_three = 3,4,5,6,7,8 # Defining the coordinates one = (50, 50) two = (150, 50) three = (250, 50) four = (50, 150) five = (150, 150) six = (250, 150) seven = (50, 250) eight = (150, 250) nine = (250, 250) # Defining the piece and where variables piece = 9 where=9 # Number of movements movements = 0 # ----------------------------------------------------------------------- # Pre Game # initialized the game engine pygame.init() # Import whole image preview WholeParrot = pygame.image.load("WholeParrot.png") WholeFlower = pygame.image.load("WholeFlower.png") WholeFlower = pygame.transform.scale(WholeFlower, (300, 300)) WholeParrot = pygame.transform.scale(WholeParrot, (300, 300)) # Initialize font myfont = pygame.font.SysFont("Times New Roman", 15) # Creating Window size = (500, 500) screen = pygame.display.set_mode(size) screen.fill(WHITE) pygame.display.update() def text_objects(text, font): textSurface = font.render(text, True, (0,0,0)) return textSurface , textSurface.get_rect() def game_intro(WholePicture, pic_Choosen): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() screen.fill(WHITE) mouse = pygame.mouse.get_pos() if 150 + 100 > mouse[0] > 150 and 400 + 50 > mouse[1] > 400: pygame.draw.rect(screen, GREEN, (150, 400, 100, 50)) return pic_Choosen, WholePicture else: pygame.draw.rect(screen, RED, (150, 400, 100, 50)) if 365 + 75 > mouse[0] > 365 and 125 + 50 > mouse[1] > 125: pygame.draw.rect(screen, GREEN, (365, 125, 75, 50)) WholePicture = WholeParrot pic_Choosen =2 else: pygame.draw.rect(screen, RED, (365, 125, 75, 50)) if 365 + 75 > mouse[0] > 365 and 225 + 50 > mouse[1] > 225: pygame.draw.rect(screen, GREEN, (365, 225, 75, 50)) WholePicture = WholeFlower pic_Choosen =1 else: pygame.draw.rect(screen, RED, (365, 225, 75, 50)) textSurf, textRect = text_objects("---------->", myfont) textRect.center = ((350 + (100 / 2)), (125 + (50 / 2))) screen.blit(textSurf, textRect) textSurf, textRect = text_objects("<----------", myfont) textRect.center = ((350 + (100 / 2)), (225 + (50 / 2))) screen.blit(textSurf, textRect) textSurf, textRect = text_objects("Start the game", myfont) textRect.center = ((150 + (100 / 2)), (400 + (50 / 2))) screen.blit(textSurf, textRect) screen.blit(WholePicture, (50, 50)) pygame.display.update() WholePicture = WholeFlower pic_Choosen, WholePicture = game_intro(WholePicture, pic_Choosen =1) # ----------------------------------------------------------------------- # Methods def check_Whole_Image(): mouse = pygame.mouse.get_pos() while 275 + 125 > mouse[0] > 275 and 400 + 50 > mouse[1] > 400: for event in pygame.event.get(): if event.type == pygame.QUIT: quit() mouse = pygame.mouse.get_pos() screen.blit(WholePicture, (50, 50)) pygame.draw.rect(screen, GREEN, (275, 400, 125, 50)) textSurf, textRect = text_objects("Back to game", myfont) textRect.center = ((290 + (100 / 2)), (400 + (50 / 2))) screen.blit(textSurf, textRect) pygame.display.update() def reset(movements, current_list, current_blank): mouse = pygame.mouse.get_pos() if 375+70 >mouse[0]>375 and 200+50> mouse[1]>200: movements = 0 current_list = [2,6,5,1,8,3,0,7,4] current_blank = OG_Blank showImages(screen, current_list, BROWN, flowers) return movements, current_list, current_blank def drawSquare(screen, BROWN): # First row pygame.draw.rect(screen, BROWN, [50, 50, 100, 100], 2) pygame.draw.rect(screen, BROWN, [150, 50, 100, 100], 2) pygame.draw.rect(screen, BROWN, [250, 50, 100, 100], 2) # Second row pygame.draw.rect(screen, BROWN, [50, 150, 100, 100], 2) pygame.draw.rect(screen, BROWN, [150, 150, 100, 100], 2) pygame.draw.rect(screen, BROWN, [250, 150, 100, 100], 2) # Third row pygame.draw.rect(screen, BROWN, [50, 250, 100, 100], 2) pygame.draw.rect(screen, BROWN, [150, 250, 100, 100], 2) pygame.draw.rect(screen, BROWN, [250, 250, 100, 100], 2) def set_Images(screen, pic_Choosen): # Import Images # fuck = input("what the fuch u want") # fuck = int(fuck) if pic_Choosen ==1: flower0 = pygame.image.load("Flower#0.png") flower1 = pygame.image.load("Flower#1.png") flower2 = pygame.image.load("Flower#2.png") flower3 = pygame.image.load("Flower#3.png") flower4 = pygame.image.load("Flower#4.png") flower5 = pygame.image.load("Flower#5.png") flower6 = pygame.image.load("Flower#6.png") flower7 = pygame.image.load("Flower#7.png") flower8 = pygame.image.load("Blank.png") elif pic_Choosen ==2: flower0 = pygame.image.load("Parrot#0.png") flower1 = pygame.image.load("Parrot#1.png") flower2 = pygame.image.load("Parrot#2.png") flower3 = pygame.image.load("Parrot#3.png") flower4 = pygame.image.load("Parrot#4.png") flower5 = pygame.image.load("Parrot#5.png") flower6 = pygame.image.load("Parrot#6.png") flower7 = pygame.image.load("Parrot#7.png") flower8 = pygame.image.load("Blank.png") flower0 = pygame.transform.scale(flower0, (100, 100)) flower1 = pygame.transform.scale(flower1, (100, 100)) flower2 = pygame.transform.scale(flower2, (100, 100)) flower3 = pygame.transform.scale(flower3, (100, 100)) flower4 = pygame.transform.scale(flower4, (100, 100)) flower5 = pygame.transform.scale(flower5, (100, 100)) flower6 = pygame.transform.scale(flower6, (100, 100)) flower7 = pygame.transform.scale(flower7, (100, 100)) flower8 = pygame.transform.scale(flower8, (100, 100)) flowers = [flower0, flower1, flower2, flower3, flower4, flower5, flower6, flower7, flower8] return flowers def showImages(screen,current_list, BROWN, flowers): screen.fill(WHITE) screen.blit(flowers[current_list[0]], one) screen.blit(flowers[current_list[1]], two) screen.blit(flowers[current_list[2]], three) screen.blit(flowers[current_list[3]], four) screen.blit(flowers[current_list[4]], five) screen.blit(flowers[current_list[5]], six) screen.blit(flowers[current_list[6]], seven) screen.blit(flowers[current_list[7]], eight) screen.blit(flowers[current_list[8]], nine) pygame.draw.rect(screen, BROWN, (80, 400, 75, 50)) textSurf, textRect = text_objects("Moves: " +(str(movements)), myfont) textRect.center = ((65 + (100 / 2)), (400 + (50 / 2))) screen.blit(textSurf, textRect) textSurf, textRect = text_objects("Reset", myfont) textRect.center = ((360 + (100 / 2)), (200 + (50 / 2))) pygame.draw.rect(screen, RED, (375, 200, 70, 50)) screen.blit(textSurf, textRect) textSurf, textRect = text_objects("Show Whole Image", myfont) textRect.center = ((290 + (100 / 2)), (400 + (50 / 2))) pygame.draw.rect(screen, RED, (275, 400, 125, 50)) screen.blit(textSurf, textRect) drawSquare(screen, BROWN) pygame.display.update() # Set up method def setUp(): # Set screen screen.fill(WHITE) flowers = set_Images(screen, pic_Choosen) showImages(screen, current_list, BROWN, flowers) pygame.display.update() return screen, flowers # Start the Set-Up screen, flowers = setUp() def get_Coord(posX, posY): if posY<150: if posX<150: pos = 0 return pos elif posX>150 and posX<250: pos = 1 return pos elif posX>250 and posX<350: pos = 2 return pos elif posY<250 and posY>150: if posX<150: pos = 3 return pos elif posX>150 and posX<250: pos = 4 return pos elif posX>250 and posX<350: pos = 5 return pos elif posY<350 and posY>250: if posX<150: pos = 6 return pos elif posX>150 and posX<250: pos = 7 return pos elif posX>250 and posX<350: pos = 8 return pos return 9 #---------------------------------------------------------------------------- # Getting the input from user and calling the methods above start = time.time() while True: for event in pygame.event.get(): check_Whole_Image() movements, current_list, current_blank = reset(movements, current_list, current_blank) if event.type == pygame.MOUSEBUTTONDOWN: pieceX, pieceY = event.pos piece = int(get_Coord(pieceX, pieceY)) elif event.type == pygame.MOUSEBUTTONUP: # or MOUSEBUTTONDOWN depending on what you want. whereX, whereY = event.pos where = int(get_Coord(whereX, whereY)) elif event.type == pygame.QUIT: quit() if piece in plus_one and piece + 1 == where and where == current_blank : movements += 1 current_list[piece], current_list[where] = current_list[where], current_list[piece] current_blank = piece #showImages(screen, current_list, BROWN, flowers) if piece in minus_one and piece - 1 == where and where == current_blank: movements += 1 current_list[piece], current_list[where] = current_list[where], current_list[piece] current_blank = piece #showImages(screen, current_list, BROWN, flowers) if piece in plus_three and piece + 3 == where and where == current_blank: movements += 1 current_list[piece], current_list[where] = current_list[where], current_list[piece] current_blank = piece #showImages(screen, current_list, BROWN, flowers) if piece in minus_three and piece - 3 == where and where == current_blank: movements += 1 current_list[piece], current_list[where] = current_list[where], current_list[piece] current_blank = piece showImages(screen, current_list, BROWN, flowers)
TypeScript
UTF-8
459
2.65625
3
[]
no_license
export const slugify = (url: string | null | undefined) => url?.replace(/(\s)/g, '-') export const removeSlashesAndEmptySpaces = (url: string | null | undefined) => slugify(url)?.replace(/-/g, '') export const removeAccents = (url: string | null | undefined) => url?.normalize('NFD').replace(/[\u0300-\u036f]/g, '') export const dateFormatter = (date: string | null | undefined) => new Intl.DateTimeFormat('pt-br').format(new Date(date as string))
JavaScript
UTF-8
2,419
2.796875
3
[]
no_license
import React, { useState } from 'react'; const FormData = () => { const [inputtext,setname] = useState({ fname:"", password:"", email:"", phone:"" }); const InputChange = (index) =>{ // console.log(index.target.value); // console.log(index.target.name); var {name,value} = index.target; setname((prev) => { // console.log(...prev); return { ...prev, [name]:value, }; // if(name === 'fName'){ // return{ // fname:value, // password:prev.password, // email:prev.email, // number:prev.number // }; // }else if(name === 'passWord'){ // return{ // fname:prev.fname, // password:value, // email:prev.email, // number:prev.number // }; // }else if(name === 'eMail'){ // return{ // fname:prev.fname, // password:prev.password, // email:value, // number:prev.number // }; // }else if(name === 'nuMber'){ // return{ // fname:prev.fname, // password:prev.password, // email:prev.email, // number:value // }; // } }); } const onSubmits = (e) =>{ e.preventDefault(); } return( <> <div className="form1"> <form onSubmit={onSubmits} method="post"> <h1>Hello {inputtext.fname} {inputtext.password} {inputtext.email} {inputtext.phone}</h1> <input type="text" name="fname" onChange={InputChange} value={inputtext.fname}/> <input type="password" name="password" onChange={InputChange} value={inputtext.password}/> <input type="email" name="email" onChange={InputChange} value={inputtext.email}/> <input type="number" name="phone" onChange={InputChange} value={inputtext.phone}/> <button type="submit">Submit</button> </form> </div> </> ); } export default FormData;
Java
UTF-8
1,929
2.421875
2
[]
no_license
package com.example.sujoy.citi1.UI; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.TextView; import com.example.sujoy.citi1.R; import com.example.sujoy.citi1.technical_classes.Agent; import java.util.ArrayList; public class AgentListActivity extends Activity { private RecyclerView recyclerView; private RecyclerView.LayoutManager layoutManager; private RecyclerView.Adapter adapter; private String service; private TextView txtCaption; ArrayList<Agent> agents; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_agent_list); recyclerView = (RecyclerView) findViewById(R.id.agRecycler); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); Intent intent = getIntent(); agents = intent.getBundleExtra("agent").getParcelableArrayList("agents"); service = intent.getStringExtra("service"); txtCaption = (TextView) findViewById(R.id.txtAgListCaption); if(!service.equals("")){ txtCaption.setText(txtCaption.getText().toString() + " (" + service + ")"); } FragmentManager fm = getFragmentManager(); FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.add(R.id.frmTitleAgentList, new TitleFragment()); fragmentTransaction.commit(); System.out.println(agents); showData(); } public void showData(){ adapter = new AgentCard(agents, this); recyclerView.setAdapter(adapter); } }
Python
UTF-8
95
3.09375
3
[]
no_license
n = int(input()) ss = [ input() for _ in range(n) ] for s in reversed(ss): print(s)
C#
UTF-8
254
2.921875
3
[]
no_license
foreach (DictionaryEntry item in od) { if (item.Value is string[]) { foreach (string str in (string[])item.Value) { Console.WriteLine("A string item: " + str); } } }
Java
UTF-8
2,233
2.953125
3
[]
no_license
package com.encima.filedeleter; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.util.Vector; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; public class FileDeleterFrame extends JFrame{ JPanel chooseDir = new JPanel(); JPanel showDir = new JPanel(); JTextField dirTextField = new JTextField(); JButton dirButton = new JButton("Find Deleted Files"); static JList sameFileList = new JList(); static JList similarFileList = new JList(); static JScrollPane sameScroll = new JScrollPane(sameFileList); static JScrollPane similarScroll = new JScrollPane(similarFileList); public FileDeleterFrame() { setTitle("File Deleter"); setSize(600, 600); addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent arg0) { System.exit(0); } }); setLayout(new BorderLayout()); chooseDir.setLayout(new GridLayout(1,2)); showDir.setLayout(new GridLayout(1,2)); chooseDir.add(dirTextField); dirTextField.setText("Enter File Dir"); chooseDir.add(dirButton); showDir.add(sameScroll); showDir.add(similarScroll); add(chooseDir, BorderLayout.NORTH); add(showDir, BorderLayout.CENTER); setVisible(true); dirButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { File file = new File(dirTextField.getText()); if(file.isDirectory()) { FileFinder f = new FileFinder(file); f.start(); }else{ System.out.println("Error: " + file); System.out.println("Not a directory, try again"); } } }); } /** * @param args */ public static void main(String[] args) { FileDeleterFrame fdf = new FileDeleterFrame(); } public static void updateList(Vector<File> sameName, Vector<File> similarName) { sameFileList.setListData(sameName); similarFileList.setListData(similarName); } }
PHP
UTF-8
2,754
3.109375
3
[ "CC-BY-3.0", "MIT" ]
permissive
<?php namespace Bonzer\Inputs\fields\utils; use Bonzer\Exceptions\Method_Call_Sequence_Exception, Bonzer\Exceptions\Invalid_Param_Exception; class Regex implements \Bonzer\Inputs\contracts\interfaces\Regex{ /** * Filepath * * @var string */ protected $_filepath; /** * Regex Matches * * @var array */ protected $_matches; /** * -------------------------------------------------------------------------- * Set the file to be read * -------------------------------------------------------------------------- * * @param string $filepath * * @Return Regex * */ public function set_filepath( $filepath ) { if ( !file_exists( $filepath ) ) { throw new Invalid_Param_Exception( "file {$filepath} does not exists!" ); } $this->_filepath = $filepath; return $this; } /** * -------------------------------------------------------------------------- * Reads file by regex * -------------------------------------------------------------------------- * * @param string $regex * * @Return void * */ public function read( $regex ) { // Unset previous matches that was built by previous call to this method unset( $this->_matches ); if ( !$this->_filepath ) { throw new Method_Call_Sequence_Exception( 'file is not set. Set it first before calling this method!' ); } $file_content = file_get_contents( $this->_filepath, 'r' ); // Generate numeric indexed array preg_match_all( $regex, $file_content, $matches ); $this->_matches = $matches; return $this; } /** * -------------------------------------------------------------------------- * All Matches * -------------------------------------------------------------------------- * * @param int $index * * @Return array * */ public function get( $index = NULL ) { if ( is_null( $index ) ) { return $this->_matches; } if ( isset( $this->_matches[ $index ] ) ) { return $this->_matches[ $index ]; } return NULL; } /** * -------------------------------------------------------------------------- * Builds Associative Array of matches * -------------------------------------------------------------------------- * * @Return Regex * */ public function associate() { $numeric_matches = $this->_matches; unset( $this->_matches ); for ( $i = 0; $i < count( $numeric_matches ) - 1; $i++ ) { $index = 0; array_walk( $numeric_matches[ $i ], function( $match ) use ($numeric_matches, &$index, $i) { $this->_matches[ $i ][ $match ] = $numeric_matches[ $i + 1 ][ $index ]; $index++; } ); } return $this; } }
Ruby
UTF-8
197
3
3
[]
no_license
class TodoList def initialize(x) @x = x end def get_items @x end def add_item(y) @x << y end def delete_item(z) @x.delete(z) end def get_item(index) @x[index] end end
C++
UTF-8
877
3.625
4
[]
no_license
// reference : https://austingwalters.com/multithreading-semaphores // 그냥 mtx.lock, mtx.unlock 으로 구현... #include <thread> #include <mutex> #include <iostream> using namespace std; mutex mtx; bool ready = false; int balance = 0; void depo(int cnt) { mtx.lock(); balance += 1000; cout << cnt << " 번째 1000원 입금, 잔액 : " << balance << endl; ready = true; mtx.unlock(); } void draw(int cnt) { mtx.lock(); if (balance >= 1000) { balance -= 1000; cout << cnt << " 번째 1000원 출금, 잔액 : " << balance << endl; } else cout << cnt << " 잔액이 없습니다.\n"; mtx.unlock(); } int main() { thread threads[20]; for (int id = 0; id < 20; id++) { if (id < 10) threads[id] = thread(depo, id); else threads[id] = thread(draw, id); } for (int id = 0; id < 20; id++) threads[id].join(); cout << "잔액 : " << balance << endl; }
Python
UTF-8
762
2.828125
3
[]
no_license
from collections import Counter def solution(a): if len(a) <= 1: return 0 answer = [0] N = len(a) def check_star(arr): cntt = Counter(arr) num = cntt.most_common()[0][0] for i in range(len(arr)): if i % 2 == 0: if arr[i] == arr[i + 1]: return False if arr[i] == num or arr[i + 1] == num: continue else: return False return True def dfs(i, arr): if len(arr) > answer[0] and len(arr) % 2 == 0: if check_star(arr): answer[0] = len(arr) for j in range(i, N): dfs(j + 1, arr + [a[j]]) dfs(0, []) return answer[0]
Markdown
UTF-8
2,876
2.609375
3
[ "MIT", "BSD-3-Clause" ]
permissive
gisid ===== Efficiently check for unique identifiers using C plugins. This is a fast option to Stata's isid. It checks whether a set of variables uniquely identifies observations in a dataset. It can additionally take `if` and `in` but it cannot check an external data set or sort the data. !!! tip "Important" Run `gtools, upgrade` to update `gtools` to the latest stable version. Syntax ------ <p><span class="codespan"><b>gisid</b> varlist [if] [in] [, missok ] </span></p> Options ------- missok indicates that missing values are permitted in varlist. ### Gtools options (Note: These are common to every gtools command.) - `compress` Try to compress strL to str#. The Stata Plugin Interface has only limited support for strL variables. In Stata 13 and earlier (version 2.0) there is no support, and in Stata 14 and later (version 3.0) there is read-only support. The user can try to compress strL variables using this option. - `forcestrl` Skip binary variable check and force gtools to read strL variables (14 and above only). __Gtools gives incorrect results when there is binary data in strL variables__. This option was included because on some windows systems Stata detects binary data even when there is none. Only use this option if you are sure you do not have binary data in your strL variables. - `verbose` prints some useful debugging info to the console. - `benchmark` or `bench(level)` prints how long in seconds various parts of the program take to execute. Level 1 is the same as `benchmark`. Levels 2 and 3 additionally prints benchmarks for internal plugin steps. - `hashmethod(str)` Hash method to use. `default` automagically chooses the algorithm. `biject` tries to biject the inputs into the natural numbers. `spooky` hashes the data and then uses the hash. - `oncollision(str)` How to handle collisions. A collision should never happen but just in case it does `gtools` will try to use native commands. The user can specify it throw an error instead by passing `oncollision(error)`. Examples -------- You can download the raw code for the examples below [here <img src="https://upload.wikimedia.org/wikipedia/commons/6/64/Icon_External_Link.png" width="13px"/>](https://raw.githubusercontent.com/mcaceresb/stata-gtools/master/docs/examples/gisid.do) ```stata . sysuse auto, clear (1978 Automobile Data) . gisid mpg variable mpg does not uniquely identify the observations r(459); . gisid make . replace make = "" in 1 (1 real change made) . gisid make variable make should never be missing r(459); . gisid make, missok ``` gisid can also take a range, that is ``` . gisid mpg in 1 . gisid mpg if _n == 1 ```
JavaScript
UTF-8
293
3.046875
3
[]
no_license
//https://blog.csdn.net/Dailoge/article/details/84874503 const arr = Array.from({length: 10}, (item, index) => index + 1) // 测试 i++,++i for (let i = 0; i < arr.length; i++) { console.log(i, arr[i], 'i++') } for (let i = 0; i < arr.length; ++i) { console.log(i, arr[i], '++i') }
PHP
UTF-8
1,504
2.609375
3
[]
no_license
<?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class UserController extends ApiController { /** * Create a new AuthController instance. * * @return void */ public function __construct() { $this->middleware('auth:api', ['except' => ['login', 'signup', 'rewind']]); } /** * Fonction de login qui génère un token JWT * @param Request $request * @return mixed */ public function login(Request $request) { $validation = $this->validateInputs($request, [ 'login' => 'required', 'password' => 'required', ]); if(!empty($validation) && !is_array($validation)) { // traitement classique $credentials = [ 'username' => $request->input('login'), 'password' => $request->input('password'), ]; if(! $token = Auth::guard('api')->attempt($credentials) ) { return $this->response(null, false, $this->error('USER_NOT_FOUND','Utilisateur introuvable'), 400 ); } $user = Auth::guard('api')->user(); return $this->response([ 'token' => $token, ]); } return $this->response( null, false, $validation, 400 ); // erreur liée aux inputs } public function logout() { auth()->logout(); return $this->response(null, false, null, 400); } }
C
UTF-8
392
3.296875
3
[]
no_license
#include <stdio.h> /*Дефинирайте и инициализирайте int променлива = 34 и пойнтер към нея. Опитайте да ги разместите, като поредност (първо да е пойнтерът, после променливата).*/ int main(void) { int value = 34; int *valuePtr = &value; return 0; }
Shell
UTF-8
734
2.75
3
[]
no_license
pkgname=thc-ipv6 pkgver=2.3 groups=(blackarch blackarch-exploitation blackarch-intel blackarch-stress-testing) pkgrel=2 pkgdesc="A complete tool set to attack the inherent protocol weaknesses of IPv6 and ICMP6, and includes an easy to use packet factory library." url='http://thc.org/thc-ipv6/' depends=(libpcap openssl) arch=(i686 x86_64) license=(GPL) source=(http://www.thc.org/releases/$pkgname-$pkgver.tar.gz) md5sums=('4771be6aa69cc3ab57c9b9672651df6f') prepare() { cd $srcdir/$pkgname-$pkgver sed -i 's|+=|=|' Makefile } build() { cd $srcdir/$pkgname-$pkgver make clean all } package() { cd $srcdir/$pkgname-$pkgver install -d "$pkgdir/usr/bin" find . -type f -perm /o+x | xargs install -t "$pkgdir/usr/bin" }
PHP
UTF-8
2,550
2.65625
3
[ "MIT" ]
permissive
<?php use App\Models\Product; use App\Models\Size; use Gloudemans\Shoppingcart\Facades\Cart; function quantity($product_id, $color_id = null, $size_id = null){ $product = Product::find($product_id); if($size_id){ $size = Size::find($size_id); $quantity = $size->colors->find($color_id)->pivot->quantity; }elseif($color_id){ $quantity = $product->colors->find($color_id)->pivot->quantity; }else{ $quantity = $product->quantity; } return $quantity; } function qty_added($product_id, $color_id = null, $size_id = null){ $cart = Cart::content(); $item = $cart->where('id', $product_id) ->where('options.color_id', $color_id) ->where('options.size_id', $size_id) ->first(); if($item){ return $item->qty; }else{ return 0; } } function qty_available($product_id, $color_id = null, $size_id = null){ return quantity($product_id, $color_id, $size_id) - qty_added($product_id, $color_id, $size_id); } function discount($item){ $product = Product::find($item->id); $qty_available = qty_available($item->id, $item->options->color_id, $item->options->size_id); if ($item->options->size_id) { // actualiza existencias con medida y color $size = Size::find($item->options->size_id); $size->colors()->updateExistingPivot( $item->options->color_id , ['quantity'=> $qty_available] ); }elseif($item->options->color_id){ // actualiza existencias con color $product->colors()->updateExistingPivot( $item->options->color_id , ['quantity'=> $qty_available] ); }else{ $product->quantity = $qty_available; $product->save(); } } function increase($item){ $product = Product::find($item->id); $quantity = quantity($item->id, $item->options->color_id, $item->options->size_id) + $item->qty; if ($item->options->size_id) { // actualiza existencias con medida y color $size = Size::find($item->options->size_id); $size->colors()->updateExistingPivot( $item->options->color_id , ['quantity'=> $quantity] ); }elseif($item->options->color_id){ // actualiza existencias con color $product->colors()->updateExistingPivot( $item->options->color_id , ['quantity'=> $quantity] ); }else{ $product->quantity = $quantity; $product->save(); } }
Java
UTF-8
673
2.28125
2
[]
no_license
package eu.rekawek.radioblock.standalone; import eu.rekawek.radioblock.MutingPipe; import eu.rekawek.radioblock.Rate; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.net.URL; public class MainCli { public static void main(String[] args) throws IOException { PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(pis); IceStreamReader reader = new IceStreamReader(new URL(Player.URL), 96000, pos); new Thread(reader).start(); MutingPipe pipe = new MutingPipe(Rate.RATE_44_1); pipe.copyStream(pis, System.out); } }
Ruby
UTF-8
2,027
4.34375
4
[ "MIT" ]
permissive
# Write a method that takes in an integer `offset` and a string. # Produce a new string, where each letter is shifted by `offset`. You # may assume that the string contains only lowercase letters and # spaces. # # When shifting "z" by three letters, wrap around to the front of the # alphabet to produce the letter "c". # # You'll want to use String's `ord` method and Integer's `chr` method. # `ord` converts a letter to an ASCII number code. `chr` converts an # ASCII number code to a letter. # # You may look at the ASCII printable characters chart: # # http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters # # Notice that the letter 'a' has code 97, 'b' has code 98, etc., up to # 'z' having code 122. # # You may also want to use the `%` modulo operation to handle wrapping # of "z" to the front of the alphabet. # # Difficulty: hard. Because this problem relies on outside # information, we would not give it to you on the timed challenge. :-) def caesar_cipher(offset, string) alpha = ("a".."z").to_a + ("a".."z").to_a #so it "loops" back to the beginning newString = "" #answer string = string.split(" ") string.each do |i| #loop through array of string(s) i.chars.each do |j| #loop through each letter in the string newString << alpha[alpha.index(j).to_i+offset] #shift the letter by the offset end newString += " " #add an empty space so you it's not all one string. This is for conditions than > 1 word. end return newString.strip #remove whitespace at the end of the string end # These are tests to check that your code is working. After writing # your solution, they should all print true. puts( 'caesar_cipher(3, "abc") == "def": ' + (caesar_cipher(3, 'abc') == 'def').to_s ) puts( 'caesar_cipher(3, "abc xyz") == "def abc": ' + (caesar_cipher(3, 'abc xyz') == 'def abc').to_s ) # "defdabcc"
Java
UTF-8
553
1.984375
2
[]
no_license
package de.ascendro.f4m.service.tombola.model.get; import de.ascendro.f4m.service.json.model.JsonMessageContent; import de.ascendro.f4m.service.tombola.model.TombolaDrawing; public class TombolaWinnerListResponse implements JsonMessageContent { private TombolaDrawing drawing; public TombolaWinnerListResponse(TombolaDrawing drawing) { this.drawing = drawing; } public TombolaDrawing getDrawing() { return drawing; } public void setDrawing(TombolaDrawing drawing) { this.drawing = drawing; } }
Shell
UTF-8
537
2.84375
3
[ "MIT" ]
permissive
# t120_awk.test -*- sh -*- . $srcdir/Init.sh # ${PROG} input 1> out 2> err # where # input -- the input file # out -- stdout # out-ok -- expected stdout # err -- stderr # err-ok -- expected stderr # Files are compared by diff with $DIFF_OPTS options. # # Generate input, out-ok and err-ok. # Then invoke the program as above. cat <<EOF > input abc<?awk 1 + 2?>def abc<?awk:d 1 + 2?>def EOF cat <<EOF > out-ok abcdef abc3def EOF ${PROG} -l ${srcdir}/../src/lang/awk input 1> out 2> err . $srcdir/Finish.sh # end
PHP
UTF-8
2,196
2.59375
3
[]
no_license
<? namespace { ini_set('xdebug.var_display_max_depth', 4); $debug_display=['display', 'generic', 'engine', 'form', 'query', /* 'Data', */ 'Task', 'EntityType']; // $debug_display=['query']; $debug_count=array_fill_keys($debug_display, 0); $debug_log=[]; function debug ($s, $domain='generic') { global $debug, $debug_display, $debug_log, $debug_count; if (!$debug) return; if (!in_array($domain, $debug_display)) return; $debug_count[$domain]++; $entry="<small style=\"color:#EEE\">$domain</small> $s<br>"; $debug_log[]=$entry; //echo_anyway($entry); } function echo_anyway($s) { $buffer=ob_get_contents(); ob_end_clean(); echo $s; ob_start(); echo $buffer; } function vdump(...$args) { if (count($args)>1) { foreach ($args as $arg) vdump($arg); return; } $v=$args[0]; $ob_level=ob_get_level(); if ($ob_level>0) { $buffer=ob_get_contents(); ob_end_clean(); } // xdebug_print_function_stack(); var_dump($v); if ($ob_level>0) { ob_start(); echo $buffer; } /* if (!is_object($v)) var_dump($v); else var_dump($v->intro()); */ } function debug_value ($v) { if ($v===true) $result='TRUE'; elseif ($v===false) $result='FALSE'; elseif (is_null($v)) $result='NULL'; elseif (is_string($v)) $result='"'.$v.'"'; elseif ( (is_array($v)) || (is_object($v)) ) { ob_start(); var_dump($v); $result=ob_get_contents(); ob_end_clean(); //$result=htmlspecialchars($result); } else $result=$v; return $result; } function debug_dump() { vdump('debug dump'); global $debug, $debug_log, $debug_count; if (!$debug) return; foreach ($debug_log as $msg) { echo $msg; } vdump($debug_count); $debug_log=[]; } function debug_clear() { global $debug, $debug_log, $debug_count; if (!$debug) return; $debug_log=[]; } function load_debug_concern($dir, $base) { include_once($dir.'/'.$base.'_debug.php'); } } namespace Pokeliga\Entlink { trait Logger { public abstract function log_domain(); public function debug($s, $domain=null) { if ($domain===null) { if (!empty($this->log_domain)) $domain=$this->log_domain(); else $domain='generic'; } debug($s, $domain); } public abstract function log($msg_id, $details=[]); } } ?>
Markdown
UTF-8
2,845
2.703125
3
[]
no_license
--- layout: post title: SpringBoot无法启动问题排查 date: 2017-08-19 tags: Java, --- ## 背景 在维护的项目使用了 SpringBoot,常规本地运行都是直接用 main 方法去跑。有一个需求需要在 Spring 容器启动前增加一些操作,因为测试和线上环境其实都是打 war 包去部署到 tomcat 中去的,和 main 方法稍微有些不同。所以就去尝试本地也用 tomcat war 包部署的方式去启动,但是碰到了一个麻烦的问题。在运行的时候会运行很长时间,而且进程占满了一个 cpu。 <!-- more --> ## 解决 包依赖包的日志级别调整的 debug ```Xml <logger name="org" level="debug" /> ``` 然后在跑,能看到非常多的 debug 信息,启动以后很长的一段时间 debug 信息都在疯狂的刷,找到一些错误信息(这里出现了明显的不可逆错误居然没有往外抛异常也是醉了,还在让程序瞎跑) ``` Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.weidai.cf.rdc.dao.ApiEventConfigMapper.BaseResultMap ``` 这个是 MyBatis 在解析 Mapper 配置的时候报错。另外还看到这个信息。 ``` Find JAR URL: jar:file:/Users/zhangli/Work/idea_workspace/******/rule-data-center-webapp/target/*****/WEB-INF/lib/******-dao-2.0.3-SNAPSHOT.jar!/com/******/dao/handler ``` 之前有从 SpringBoot 的启动的地方一步一步 debug 进去看过,最终发现其实是在 scan compotent 的地方运行进去就出不来了。这条信息说明是扫描到了匹配的 jar 包并准备处理。但是这个 jar 包的版本是旧的,记得已经把 SNAPSHOT 去掉了,那为什么还能扫描到这个版本?然后去检查部署的 war 包。 ``` *****-dao-2.0.3-SNAPSHOT.jar *****-dao-2.0.4.jar ``` 在 IDEA 的 target 目录下的 lib 文件夹能找到这两个 jar 包。问题很明显是重复的 jar 包导致的 MyBatis 初始化失败,然而 MyBatis 初始化出现错误居然不往外抛异常也是醉了,还什么 error 信息也不打印。解决办法很简单,mvn clean,然后重新打包就可以了。 但是为什么会出现多个版本包呢?去重试在 IDEA 内切分支到旧的分支里去,在旧分支打包,最终发现打包以后,target 的 lib 包内能重现出重复的 jar 包。所以 IDEA 在自动打包时候,是不会自己去做 clean 的(应该有什么地方进行配置)。 但是为什么用 main 方法执行就又可以呢?那是因为 main 执行 classpath 不是使用的打包结果,当切换分支以后,IDEA 回去刷新依赖,这个时候是不会出现重复的 jar 的,从 IDEA 的 Maven Projects 视图的 dependencies 标签里就能看到。 ## 总结 框架运行处问题的时候去打开 debug 日志很有用。
Java
UTF-8
532
3.1875
3
[]
no_license
package Part_17; import java.util.Arrays; public class Methods_with_Arrays1_Merge_Arrays_178 { public static void main(String[] args) { int [] ar1= {1,2,3}; int [] ar2= {4,5,6}; System.out.println(Arrays.toString(mergR(ar1, ar2))); } public static int[] mergR(int[] a, int[] b) { int [] arr=new int[a.length+b.length]; for(int i=0; i<a.length; i++) { arr[i]=a[i]; } for(int i=0; i<b.length; i++) { arr[a.length+i]=b[i]; } return arr; } }
Markdown
UTF-8
3,201
3.28125
3
[ "Apache-2.0" ]
permissive
# 10 articles to sharpen your command line skills The command line interface (also known as the CLI) is probably the most powerful and yet itimidating aspect of Linux as it gives you unparalleled power and complete access to what the operating system can do for you. Linux inherited UNIX design and its ability to compose more complex commands from simple tools. For the sake of example, you can combine the disk usage (du) tool and the sort tool (sort) to get the size of the items on the current directory: ``` du -s *|sort -r -n ``` You get the picure (or the command in this case). With that in mind I want to recommend a group of articles for you, hopefully you will learn a thing of two after reading them, and even better you will put them in practice. So let's dive in with the list and get ready to have fun while learning: 1. David Both [Adding arguments and options to your Bash scripts](http://www.redhat.com/sysadmin/arguments-options-bash-scripts ): Adding arguments and options to your Bash scripts will make them more easy to use and less complex. 2. Jeff Warnica [5 Linux commands I'm going to start using](http://www.redhat.com/sysadmin/5-linux-commands). You will be surprised how these 5 not so common commands can save your time. 3. [Ken Hess 5 Linux commands I never use](http://www.redhat.com/sysadmin/5-never-use-linux-commands): Another point of view on the same 5 commands and why you should use them. Being a sysadmin or DevOps means you have to choose your tools carefully too! 4. Bryant Son [Exploring the differences between sudo and su](http://www.redhat.com/sysadmin/difference-between-sudo-su) commands in Linux: If want to elevate your privileges on Linux or want to control how your users can do the same then you must understand the differences between these two commands. 5. Roberto Nozaki [3 must-know Linux commands for text manipulation](http://www.redhat.com/sysadmin/linux-text-manipulation-tools). Sooner or later you will use one of these or all of them. Time to get ready and have some fun. 6. Evans Amoany [7 Linux networking commands that every sysadmin should know](http://www.redhat.com/sysadmin/7-great-network-commands). If tcpdump or mtr doesn't sound familiar then you should read about them (and some more). You can thank me later. 7. Ken Hess [How to capture terminal sessions and output with the Linux script command](http://www.redhat.com/sysadmin/linux-script-command). You have an interactive shell session. You need to capture the output (for troubleshooting). You can read this article and learn how to do just that. 8. Anthony Critelli [6 OpenSSL command options that every sysadmin should know](http://www.redhat.com/sysadmin/6-openssl-commands). OpenSSL is well know for its power, functionality and very complex options. This article demistifies some of these and will make you more productive 9. Nathan Lager [Introduction to Linux Bash programming: 5 `for` loop tips](http://www.redhat.com/sysadmin/bash-scripting-loops). Get ready to learn a few tricks and very useful shortcuts. 10. Evans Amoany [Managing Linux users with the passwd command](http://www.redhat.com/sysadmin/managing-users-passwd). It is a critical skill if you want to make sure your system is secure.
Java
UTF-8
344
2.265625
2
[]
no_license
package interfaces; import model.Entity; import validators.ValidatorException; import java.util.List; public interface ICrudRepo<ID,E extends Entity> { public E add(E e) throws ValidatorException; public E remove(E e); public E findOne(ID id); public E update(E e) throws ValidatorException; public List<E> findAll(); }
Python
UTF-8
1,676
2.625
3
[ "MIT" ]
permissive
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : word_embedding.py # Author : Jiayuan Mao # Email : maojiayuan@gmail.com # Date : 06/15/2018 # # This file is part of Jacinle. # Distributed under terms of the MIT license. import torch import torch.nn as nn import torch.nn.functional as F __all__ = ['WordEmbedding'] class WordEmbedding(nn.Module): def __init__(self, word_embeddings, nr_extra_words, fake=False): super().__init__() self.nr_words = word_embeddings.shape[0] self.nr_extra_words = nr_extra_words self.nr_tot_words = self.nr_words + self.nr_extra_words self.embedding_dim = word_embeddings.shape[1] self.fake = fake self.impl = nn.Embedding(self.nr_tot_words, self.embedding_dim, padding_idx=0) if not fake: self.word_embeddings = nn.Parameter(torch.tensor(word_embeddings)) self.word_embeddings.requires_grad = False self.extra_word_embeddings = nn.Parameter(torch.zeros(nr_extra_words, self.embedding_dim, dtype=self.word_embeddings.dtype, device=self.word_embeddings.device)) self.extra_word_embeddings.requires_grad = True self.impl.weight = nn.Parameter(torch.cat((self.word_embeddings, self.extra_word_embeddings), dim=0)) self.reset_parameters() def reset_parameters(self): if not self.fake: self.extra_word_embeddings.data.normal_( self.word_embeddings.data.mean(), self.word_embeddings.data.std() ) @property def weight(self): return self.impl.weight def forward(self, words): return self.impl(words)
Python
UTF-8
1,013
2.796875
3
[]
no_license
from scipy import stats import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns column_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV'] data = pd.read_csv('/home/maybeabhishek/Documents/Projects/ML-Lab/Datasets/boston-house-prices/housing.csv', header=None, delimiter=r"\s+", names=column_names) print(data.head(5)) # Dimension of the dataset print(np.shape(data)) # Dimension of the dataset print(np.shape(data)) #Histogram data.hist(figsize=(15,10),grid=False) plt.show() # outlier percentage for k, v in data.items(): q1 = v.quantile(0.25) q3 = v.quantile(0.75) irq = q3 - q1 v_col = v[(v <= q1 - 1.5 * irq) | (v >= q3 + 1.5 * irq)] perc = np.shape(v_col)[0] * 100.0 / np.shape(data)[0] print("Column %s outliers = %.2f%%" % (k, perc)) #correlation Heat Map plt.figure(figsize=(20, 10)) sns.heatmap(data.corr().abs(), annot=True) plt.show()
Shell
UTF-8
16,032
3.75
4
[ "MIT" ]
permissive
#!/bin/bash # -*-mode: Shell-script; indent-tabs-mode: nil; sh-basic-offset: 2 -*- # Find the base directory while avoiding subtle variations in $0: dollar0=`which $0`; PACKAGE_DIR=$(cd $(dirname $dollar0); pwd) # NEVER export PACKAGE_DIR # Set defaults for BUILD_DIR and INSTALL_DIR environment variables and # utility functions such as BuildDependentPackage: . $PACKAGE_DIR/../../../support-files/build_platform_util.bash . $PACKAGE_DIR/../../../support-files/pkg_config_util.bash CLEAN=0 while [ $# -gt 0 ] do if [ "$1" = "-builddir" ] then BUILD_DIR="$2" shift elif [ "$1" = "-installdir" ] then INSTALL_DIR="$2" shift elif [ "$1" = "-clean" ] then CLEAN=1 elif [ "$1" = "-h" ] then EmitStandardUsage exit 0 else echo "Undefined parameter $1" exit 1 fi shift done # -------------------------------------------------------------------------------- # Dependent packages will be installed into $INSTALL_DIR/bin so add # that directory to the PATH: # -------------------------------------------------------------------------------- SetupBasicEnvironment # -------------------------------------------------------------------------------- # Verify the system-supplied prerequisites: # -------------------------------------------------------------------------------- # For RHEL6, I think I need these packages installed which I now have # to ask the admins to do: # # librsvg2-devel # dbus # atk-devel # cairo-devel # libXi-devel # pango-devel # gtk2-devel # ncurses-devel # libXpm-devel # giflib-devel # libtiff-devel # bitstream-vera-fonts <-- not any more; see git controlled .fonts directory # # But here is what the admins actually found on 2012-10-19: # # All of the packages below were on the RHEL6 system by default, except for: # # giflib-devel # libtiff-devel # bitstream-vera-fonts # # libtiff-devel is part of the distribution, the admin will have to # add that to the system. # # giflib-devel is no longer part of the ISO distribution but RedHat # does carry it in one of the repositories on their site, so the # admin will have to install it on the system. # # bitstream-vera-fonts is not available for RHEL6, but my hackaround # was to just copy them from a Debian wheezy/sid release and store # them under git under ~/.fonts (they are platform-independent files # anyhow, and I could not find the right CentOS RPM to scavenge them # from!). # # Sun Apr 23 09:58:08 PDT 2017: libpng is not on RHEL 6.8 by default # so it is now added as a build dependency below. if ! which git >/dev/null then echo "ERROR: git executable not found in the PATH." fi if [ ! -f /usr/include/X11/X.h ] then echo "ERROR: You must install development headers for X" echo " On Debian, maybe the package is libx11-dev" echo " On Ubuntu, maybe the package is x11proto-core-dev" fi # Disabled svg_config_options code for now as it does not seem to adversely impact the build: # svg_config_options="--without-rsvg" # if [ "$DO_SVG" = 1 ] # then # svg_config_options="" # # From http://linux.derkeiler.com/Mailing-Lists/Debian/2008-12/msg02185.html # # we see: # # # # Assuming that you have a suitable deb-src line in your sources.list, you # # can simply use "apt-get build-dep emacs22" to install the needed # # packages. You also may want to install librsvg2-dev and libdbus-1-dev # # for SVG and Dbus support that is new in Emacs 23. # files=`ls -d /usr/include/librsvg*/librsvg/rsvg.h 2>/dev/null` # if [ -z "$files" ] # then # echo "ERROR: rsvg.h header is missing from the system." # echo " On Debian, maybe the package is librsvg2-dev" # echo " On RHEL, maybe the package is librsvg2-devel" # exit 1 # fi # fi if [ ! -f /usr/include/dbus-1.0/dbus/dbus.h ] then echo "ERROR: dbus.h is missing from the system." echo " On Debian, maybe the package is libdbus-1-dev" echo " On RHEL, maybe the package is dbus" exit 1 fi # About this error that can occur: # # configure: error: No package 'gtk+-3.0' found # No package 'glib-2.0' found # # See later on where we include both system and locally built # directories into the value of PKG_CONFIG_PATH that pkg-config sees # during ./configure execution. # # Therefore, test for the existence of GTK headers. Here, we are using # either GTK2 or GTK3 headers. Note ./configure searches for GTK3 # headers first, then GTK2 headers, when --with-x-toolkit is specified # (versus us specifying --with-x-toolkit=gtk3). we look for both GTK2 # and GTK3 because ideally we would not have to request admins to # install gtk3 on RHEL6 systems if we can avoid it (and it is not # apparent if gtk3 is needed on RHEL6 for Emacs). if [ -z "$(ls -d /usr/include/gtk-[23].0/gtk/gtk.h 2>/dev/null)" ] then echo "ERROR: gtk.h is missing from the system." echo " On Debian, maybe the package is libgtk-3-dev" echo " On RHEL, maybe the packages to install are: atk-devel cairo-devel libXi-devel pango-devel gtk3-devel" exit 1 fi if [ ! -f /usr/include/ncurses.h ] then echo "ERROR: ncurses.h is missing from the system." echo " On Debian, maybe the package is ncurses-devel" echo " On RHEL, maybe the package to install is libncurses5-dev" exit 1 fi if [ ! -f /usr/include/X11/xpm.h ] then echo "ERROR: xpm.h is missing from the system." echo " On Debian, maybe the package is libxpm-dev" echo " On RHEL, maybe the package to install is libXpm-devel" exit 1 fi gif_config_options="" if [ "$WITH_GIF" = 1 ] then if [ ! -e /usr/lib64/libungif.so -a ! -e /usr/lib/libungif.so ] then echo "ERROR: gif libraries are missing from the system." echo " On Debian, maybe the package is libgif-dev" echo " On RHEL, maybe the package to install is giflib-devel" exit 1 fi else # I added --without-gif because on RHEL6.4 gif is not there. Temporary # hack until we decide we need to build it from source. gif_config_options="--without-gif" fi tiff_config_options="" if [ "$WITH_TIFF" = 1 ] then files=`ls -d /usr/lib/x86_64-linux-gnu/libtiff.so /usr/lib64/libtiff.so 2>/dev/null` if [ -z "$files" ] then echo "ERROR: libtiff headers are missing from the system." echo " On Debian, maybe the package is libtiff4-dev" echo " On RHEL, maybe the package to install is libtiff-devel" exit 1 # rpm -q --whatprovides libtiff-devel # rpm -q -l libtiff-devel-3.9.4-1.el6_0.3.x86_64 fi else # I added --with-tiff=no because on RHEL6.4 tiff is not there. Temporary # hack until we decide we need to build it from source. # # Sun Apr 23 12:22:53 PDT 2017: The INSTALL file in the emacs # distribution has a path to a URL that is dead so we will continue # to just not have tiff support if they are going to maintaining it # on a solid server, like GitHub. # tiff_config_options="--with-tiff=no" fi # The xft stuff may have problems on older Linux systems but require # it since this is primarily geared for building an X11 version of # Emacs: xft_option="--with-xft" # -------------------------------------------------------------------------------- # Build required dependent packages: # -------------------------------------------------------------------------------- BuildDependentPackage autoconf bin/autoconf BuildDependentPackage automake bin/automake BuildDependentPackage texinfo bin/makeinfo BuildDependentPackage pkg-config bin/pkg-config BuildDependentPackage zlib include/zlib.h BuildDependentPackage libpng lib/pkgconfig/libpng\*.pc BuildDependentPackage make bin/make # because GNU make 3.80 that is default in RHEL6 has a buggy (or ...) operator # Try building with gtk now that I'm running RHEL 6.8 which should have the gtk headers: ###echo "TODO: build gtk as a dependency: BuildDependentPackage gtk bin/fixmeforgtk"; exit 1 # -------------------------------------------------------------------------------- # Dependent packages will be installed into $INSTALL_DIR/bin so add # that directory to the PATH: # -------------------------------------------------------------------------------- SetupBasicEnvironment # -------------------------------------------------------------------------------- # Create build directory structure: # -------------------------------------------------------------------------------- CreateAndChdirIntoBuildDir emacs # -------------------------------------------------------------------------------- # Download and build tarball into the build directory: # -------------------------------------------------------------------------------- # The V variable referenced by the Emacs configure script to enable # verbose output of compile lines, which we need in order to debug # compile failures: export V=1 # zlib.h is still not found when compiling decompress.c, so I have to hack with this CFLAGS setting: export CFLAGS="-I$INSTALL_DIR/include" # Hack in the -L options from libpng which are not recognized by the configure script (bug?): libpng_ldflags="$(libpng-config --L_opts)" # But libraries like libpng###.so will not be found at runtime unless you use an RPATH: # # The reason Linux distributions do not use an RPATH is that they # instead use ld.conf.so. You can see this via # # objdump -x path_to_some_executable | grep RPATH # # Emacs on those distributions thus do not have an RPATH. See # https://gcc.gnu.org/ml/gcc-help/2005-12/msg00017.html for details. # rpath_options="-Wl,-rpath=$INSTALL_DIR/lib" # Sigh. You cannot pass LDFLAGS to the ./configure command line. It # does some weird expansion and trips up on it. So we HAVE to export # it as an environment variable: export LDFLAGS="$libpng_ldflags $rpath_options" # Disable libgif for now (why it is listed as an "X" for X11 in the # INSTALL file I don't know). Are playing gifs inside Emacs really # necessary? libgif_config_options="--with-gif=no" # Add system-defined directories to PKG_CONFIG_PATH: # # This is needed in order to find xft and fontconfig packages (maybe # more than that): # Add_System_Defined_PKG_CONFIG_PATH DownloadExtractBuildGnuPackage emacs "$libgif_config_options;$tiff_config_options;$xft_option" # Experiment with: # bash -c ' # export BUILD_DIR=$HOME/build/RHEL.6.8.x86_64.for_emacs; # export INSTALL_DIR=$HOME/install/RHEL.6.8.x86_64.for_emacs; # $HOME/bgoodr/build-locally/packages/emacs/linux/build.bash -clean # ' # Skip code I plan on deleting eventually: if false then # -------------------------------------------------------------------------------- # OLD STUFF BELOW: # My intent is to just get the latest stable release downloaded and not work from top of trunk. # The reason is that there is no way to check out a tag from a git repo without downloading all of it (e.g., without using --depth 1). # -------------------------------------------------------------------------------- # -------------------------------------------------------------------------------- # Check out the source for emacs into the build directory: # -------------------------------------------------------------------------------- packageSubDir=emacs echo "TODO: find the latest stable release via some heuristic here" DownloadPackageFromGitRepo git://git.savannah.gnu.org/emacs.git $packageSubDir fullcheckout PrintRun cd $packageSubDir # -------------------------------------------------------------------------------- # Configure # -------------------------------------------------------------------------------- echo "Configuring ..." # Disable some code I would like to delete to see if it is still an issue on RHEL 6.8: if false then cat <<EOF TODO: Rip out the following code that tries to use system supplied gtk libraries as they no longer work on RHEL6 because of this error configure: error: Package 'gobject-2.0', required by 'gdk-pixbuf-2.0', not found EOF exit 1 # Allow system supplied gtk libraries to also be found by pkg-config # versus our locally built pkg-config that does not also read from the # system-supplied .pc files. This may also solve problems finding # other system-supplied packages that I am choosing not to build in # the near term: # Our local pkg-config PKG_CONFIG_PATH value: local_pkg_config_path=$(pkg-config --variable pc_path pkg-config) echo "local_pkg_config_path==\"${local_pkg_config_path}\"" # The system-supplied pkg-config PKG_CONFIG_PATH value: system_pkg_config_path=$(PATH=$(echo "$PATH" | sed 's%'"$INSTALL_DIR/bin":'%%g'); pkg-config --variable pc_path pkg-config) if [ -z "$system_pkg_config_path" ] then # pkg-config on RHEL6 does not return anything. Hack in something that might work and pray: system_pkg_config_path=/usr/lib/pkgconfig:/usr/share/pkgconfig echo "WARNING: System-supplied buggy pkg-config that returns nothing for 'pkg-config --variable pc_path pkg-config'. Hacking around it with: $system_pkg_config_path" fi echo "system_pkg_config_path==\"${system_pkg_config_path}\"" export PKG_CONFIG_PATH="$local_pkg_config_path:$system_pkg_config_path" echo PKG_CONFIG_PATH now is ... echo "${PKG_CONFIG_PATH}" | tr : '\012' fi echo debug exit; exit 0 # The distclean command will fail if there the top-level Makefile has not yet been generated: if [ -f Makefile ] then PrintRun make distclean fi # Per the GNUmakefile which takes precedence over the Makefile: # "This GNUmakefile is for GNU Make. It is for convenience, so # that one can run 'make' in an unconfigured source tree. In such # a tree, ....". Therefore, build the configure script using that # GNUmakefile first: PrintRun make configure # Run configure: PrintRun ./configure --prefix="$INSTALL_DIR" --with-x-toolkit $xft_option $svg_config_options $gif_config_options $tiff_config_options # -------------------------------------------------------------------------------- # Build: # -------------------------------------------------------------------------------- echo "Building ..." PrintRun make # -------------------------------------------------------------------------------- # Install: # -------------------------------------------------------------------------------- echo "Installing ..." PrintRun make install fi # -------------------------------------------------------------------------------- # Testing: # -------------------------------------------------------------------------------- echo "Testing ..." emacsExe="$INSTALL_DIR/bin/emacs" if [ ! -f "$emacsExe" ] then echo "ERROR: Could not find expected executable at: $emacsExe" exit 1 fi # Determine the expected version from the ./configure file: expected_emacs_version=$(sed -n "s%^ *PACKAGE_VERSION='\\([^']*\\)'.*\$%\\1%gp" < configure); if [ -z "$expected_emacs_version" ] then echo "ASSERTION FAILED: Could not determine expected emacs version." exit 1 fi # Determine the actual version we built: actual_emacs_version=$($emacsExe --batch --quick --eval '(prin1 emacs-version t)') # Use the first two numbers of the version. The 3rd and subsequent numbers gets added by # something in the build (how? the makefiles are obfuscated) and we # don't care about that. And if you run make then make install, that # number gets bumped again. echo "Original actual_emacs_version is \"${actual_emacs_version}\"." actual_emacs_version=$(echo "$actual_emacs_version" | sed -e 's/"//g' -e 's%^\([0-9]*\.[0-9]*\).*$%\1%g' ) echo "Trimmed actual_emacs_version is \"${actual_emacs_version}\"." # Now compare: if [ "$expected_emacs_version" != "$actual_emacs_version" ] then echo "ERROR: Failed to build expected emacs version: $expected_emacs_version" echo " actual emacs version: $actual_emacs_version" exit 1 fi echo "Note: All installation tests passed. Emacs version $actual_emacs_version was built and installed." exit 0
Swift
UTF-8
1,245
3.3125
3
[]
no_license
// // Player.swift // Reversi_Trial // // Created by Bartosz on 13/01/2019. // Copyright © 2019 Bartosz Bilski. All rights reserved. // //import Foundation import GameplayKit enum StoneColor: Int { case none = 0 case white case black } class Player: NSObject, GKGameModelPlayer { var stone: StoneColor var color: String //var color: UIImage var name: String // Required by GKGameModelPlayer var playerId: Int // Array with all players static var allPlayers = [ Player(stone: .white), Player(stone: .black) ] // Return opposite player var opponent: Player { if stone == .white { return Player.allPlayers[1] } else { return Player.allPlayers[0] } } // Init method init(stone: StoneColor) { self.stone = stone // MARK: - GamePlayKit required properties self.playerId = stone.rawValue if stone == .white { color = "w" //color = UIImage(named: "White")! name = "White Stone" } else { color = "b" //color = UIImage(named: "Black")! name = "Black Stone" } } }
Go
UTF-8
2,213
2.9375
3
[]
no_license
package indexer import ( "context" "io/ioutil" "net/http" "net/url" "strings" "google.golang.org/appengine/log" "google.golang.org/appengine/urlfetch" ) type Renderer struct { BaseUrl string ctx context.Context } func NewRenderer(ctx context.Context, baseUrl string) *Renderer { return &Renderer{ BaseUrl: baseUrl, ctx: ctx, } } func (r *Renderer) RenderSvg(source string) (string, error) { umlId, err := r.getUmlId(source) if err != nil { return "", err } svgBytes, err := r.doRequest("/svg/" + umlId) if err != nil { return "", err } return string(svgBytes), err } func (r *Renderer) RenderPng(source string) ([]byte, error) { umlId, err := r.getUmlId(source) if err != nil { return nil, err } return r.doRequest("/png/" + umlId) } func (r *Renderer) RenderAscii(source string) (string, error) { umlId, err := r.getUmlId(source) if err != nil { return "", err } asciiBytes, err := r.doRequest("/txt/" + umlId) if err != nil { return "", err } return string(asciiBytes), err } func (r *Renderer) getUmlId(source string) (string, error) { values := url.Values{} values.Add("text", source) req, _ := http.NewRequest("POST", r.BaseUrl+"/form", strings.NewReader(values.Encode())) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") client := urlfetch.Client(r.ctx) client.CheckRedirect = func(req *http.Request, via []*http.Request) error { // no follow redirect return http.ErrUseLastResponse } resp, err := client.Do(req) if err != nil { log.Criticalf(r.ctx, "Failed to request to renderer /form: %s", err) return "", err } defer resp.Body.Close() locationUrl, err := resp.Location() if err != nil { log.Criticalf(r.ctx, "Failed to get location header: %s", err) return "", err } umlId := strings.TrimPrefix(locationUrl.Path, "/uml/") return umlId, nil } func (r *Renderer) doRequest(path string) ([]byte, error) { req, _ := http.NewRequest("GET", r.BaseUrl+path, nil) client := urlfetch.Client(r.ctx) resp, err := client.Do(req) if err != nil { log.Criticalf(r.ctx, "Failed to request to %s: err=%s", path, err) return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) }
Java
UTF-8
21,499
2.03125
2
[]
no_license
package com.example.ikozompolis.myapplication.FacebookPackage; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.example.ikozompolis.myapplication.Mysingleton; import com.facebook.AccessToken; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import static com.example.ikozompolis.myapplication.CentralActivity.username; import static com.example.ikozompolis.myapplication.Usefullmethods.configuration.URL_SAVE_EDUCATION_INFO; import static com.example.ikozompolis.myapplication.Usefullmethods.configuration.URL_SAVE_FB_BOOK; import static com.example.ikozompolis.myapplication.Usefullmethods.configuration.URL_SAVE_FB_EVENT; import static com.example.ikozompolis.myapplication.Usefullmethods.configuration.URL_SAVE_FB_FAVORITE_TEAM; import static com.example.ikozompolis.myapplication.Usefullmethods.configuration.URL_SAVE_FB_INTEREST_PAGE; import static com.example.ikozompolis.myapplication.Usefullmethods.configuration.URL_SAVE_FB_MUSIC; import static com.example.ikozompolis.myapplication.Usefullmethods.configuration.URL_SAVE_WORK_INFO; import static com.example.ikozompolis.myapplication.Usefullmethods.configuration.methodGET; /** * Created by user on 9/12/2017. */ public class facebookFunctions { public facebookFunctions() { } public void saveUserWorkInfo(AccessToken accessToken, final Context context) { GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted( JSONObject object, GraphResponse response) { try { String employer, position, URL; if (object.has("work")) { JSONArray jsonArray = object.getJSONArray("work"); JSONObject empl= new JSONObject(); JSONObject pos=new JSONObject(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject obj = jsonArray.getJSONObject(i); if(obj.has("employer")) { empl = obj.getJSONObject("employer"); }else{ empl.put("name", ""); } if(obj.has("position")) { pos = obj.getJSONObject("position"); } else{ pos.put("name",""); } if(empl.getString("name")!="") { employer = URLEncoder.encode(empl.getString("name"),"utf-8"); } else { employer =null; } if (pos.getString("name")!="") { position = URLEncoder.encode(pos.getString("name"),"utf-8"); }else{ position = null; } URL = URL_SAVE_WORK_INFO + "?i_username=" + username + "&i_work_employer=" + employer + "&i_work_position=" + position; saveData(URL,methodGET,context,"The work experience saved successfully...","Something went wrong on saving work experience..."); } }else { Log.v("FACEBOOK_FUNCTIONS", "No work info found from facebook..."); } } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "work"); request.setParameters(parameters); request.executeAsync(); } public void saveUserEducationInfo(AccessToken accessToken, final Context context) { GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted( JSONObject object, GraphResponse response) { try { String degree, school, type , year, URL; if (object.has("education")) { JSONObject deg, sch, yr,obj; JSONArray jsonArray = object.getJSONArray("education"); for (int i = 0; i < jsonArray.length(); i++) { obj = jsonArray.getJSONObject(i); if (obj.has("degree")) { deg = obj.getJSONObject("degree"); }else{ deg = null; } if (obj.has("school")) { sch = obj.getJSONObject("school"); }else { sch = null; } if (obj.has("year")){ yr = obj.getJSONObject("year"); }else { yr = null; } if (obj.has("type")) { type = URLEncoder.encode(obj.getString("type"),"utf-8"); }else { type = null; } if(deg!=null){ degree = URLEncoder.encode(deg.getString("name"),"utf-8"); }else{ degree = null; } if(sch!=null) { school = URLEncoder.encode(sch.getString("name"),"utf-8"); }else{ school = null; } if(yr!=null) { year = URLEncoder.encode(yr.getString("name"),"utf-8"); }else{ year=null; } URL = URL_SAVE_EDUCATION_INFO + "?i_username=" + username + "&i_edu_degree=" + degree + "&i_edu_school=" + school + "&i_edu_type=" + type + "&i_edu_year=" + year; saveData(URL,methodGET,context,"The Education Info saved successfully...","Something went wrong on saving Education Info..."); } }else { Log.v("FACEBOOK_FUNCTIONS", "No Education Info found from facebook...."); } } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "education"); request.setParameters(parameters); request.executeAsync(); } public void saveFbMusicInfo(AccessToken accessToken, final Context context) { GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted( JSONObject object, GraphResponse response) { String i_music_title,URL; try { if (object.has("music")) { JSONObject music = object.getJSONObject("music"); JSONArray jsonArray = music.getJSONArray("data"); JSONObject obj; for (int i = 0; i < jsonArray.length(); i++) { obj = jsonArray.getJSONObject(i); if(obj.has("name")) { i_music_title = URLEncoder.encode(obj.getString("name"),"utf-8"); }else{ i_music_title = null; } URL = URL_SAVE_FB_MUSIC + "?i_username=" + username + "&i_music_title=" + i_music_title; saveData(URL,methodGET,context,"The FB Music Info saved successfully...","Something went wrong on saving FB Music Info..."); } }else { Log.v("FACEBOOK_FUNCTIONS", "No music info found from facebook..."); } } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "music"); request.setParameters(parameters); request.executeAsync(); } public void saveFbEvents(AccessToken accessToken, final Context context) { GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted( JSONObject object, GraphResponse response) { String URL,i_event_name, i_event_description, i_event_start_date; try { if (object.getString("events") != null) { JSONObject music = object.getJSONObject("events"); JSONArray jsonArray = music.getJSONArray("data"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject obj = jsonArray.getJSONObject(i); if(obj.has("name")){ i_event_name = URLEncoder.encode(obj.getString("name"),"utf-8"); } else { i_event_name = null; } if (obj.has("description")) { i_event_description =URLEncoder.encode(obj.getString("description"),"utf-8"); }else{ i_event_description=null; } if(obj.has("start_time")) { i_event_start_date = URLEncoder.encode(obj.getString("start_time"), "utf-8"); } else { i_event_start_date = null; } URL = URL_SAVE_FB_EVENT + "?username=" + username + "&i_event_name=" + i_event_name + "&i_event_description=" + i_event_description + "&i_event_start_date=" + i_event_start_date; saveData(URL,methodGET,context,"The FB Event Info saved successfully...","Something went wrong on saving FB Event Info..."); } }else { Log.v("FACEBOOK_FUNCTIONS", "No FB Events found..."); } } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "events"); request.setParameters(parameters); request.executeAsync(); } public void saveFbFavoriteTeams(AccessToken accessToken, final Context context) { GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback(){ @Override public void onCompleted(JSONObject object, GraphResponse response) { String i_team_name,URL; try { if (object.has("favorite_teams")) { JSONArray data = object.getJSONArray("favorite_teams"); JSONObject name; for (int i = 0; i < data.length(); i++) { name = data.getJSONObject(i); i_team_name = URLEncoder.encode(name.getString("name"), "utf-8"); URL = URL_SAVE_FB_FAVORITE_TEAM + "?i_username=" + username + "&i_team_name=" + i_team_name; saveData(URL,methodGET,context,"The FB Favorite Team Info saved successfully...","Something went wrong on saving FB Favorite Team Info..."); } }else { Log.v("FACEBOOK_FUNCTIONS", "No FB Favorite Team Info experience found.."); } } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "favorite_teams"); request.setParameters(parameters); request.executeAsync(); } public void saveFbBooksInfo(AccessToken accessToken, final Context context) { GraphRequest request = GraphRequest.newGraphPathRequest( accessToken,"me?fields=books{name,description}", new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse response) { JSONObject jsonObject = response.getJSONObject(); String name,description, URL; try { if (jsonObject.has("books")){ JSONObject book = jsonObject.getJSONObject("books"); JSONArray data = book.getJSONArray("data"); JSONObject obj; for (int i = 0; i<data.length();i++){ obj = data.getJSONObject(i); if(obj.has("name")) { name = URLEncoder.encode(obj.getString("name"),"utf-8"); }else { name = null; } if( obj.has("description")) { description = URLEncoder.encode(obj.getString("description"), "utf-8"); } else { description = null; } URL = URL_SAVE_FB_BOOK + "?username=" + username + "&name=" + name + "&description=" + description; saveData(URL,methodGET,context,"The FB Books Info saved successfully...","Something went wrong on saving FB Books Info..."); } }else{ Log.v("FACEBOOK_FUNCTIONS", "No FB Events Info found..."); } } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }); request.executeAsync(); } public void saveFbLastPageLikes(AccessToken accessToken, final Context context) { GraphRequest request = GraphRequest.newGraphPathRequest( accessToken,"me?fields=likes{about,name}", new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse response) { JSONObject jsonObject = response.getJSONObject(); String name,about, URL; try { if (jsonObject.getString("likes")!=null){ JSONObject book = jsonObject.getJSONObject("likes"); JSONArray data = book.getJSONArray("data"); for (int i = 0; i<data.length();i++){ JSONObject obj = data.getJSONObject(i); if(obj.has("name")) { name = URLEncoder.encode(obj.getString("name"),"utf-8"); }else { name = null; } if( obj.has("about")) { about = URLEncoder.encode(obj.getString("about"),"utf-8"); } else { about = null; } URL = URL_SAVE_FB_INTEREST_PAGE + "?i_username=" + username + "&i_page_name=" + name + "&i_page_description=" + about; saveData(URL,methodGET,context,"The Info saved successfully...","Something went wrong on saving FB Info..."); } }else{ Log.v("FACEBOOK_FUNCTIONS", "No FB Interest Pages Info experience found..."); } } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }); request.executeAsync(); } public void saveData(String URL, int method, final Context context, final String successMessage, final String failMessage) { JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(method, URL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { String status = response.getString("status"); if (status.equals("success")){ Log.v("FACEBOOK_FUNCTIONS", successMessage); }else { Log.v("FACEBOOK_FUNCTIONS", failMessage); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.v("ON_RESPONSE_VOLLEY: ", "Something went wrong on response... please try again.."); } }); Mysingleton.getInstance(context).addToRequestque(jsonObjectRequest); } }
PHP
UTF-8
1,245
3.125
3
[]
no_license
<?php namespace dataProviders; use models\Lead; use generators\LeadGenerator; /** * Class GeneratedLeadDataProvider * @package dataProviders */ class GeneratedLeadDataProvider extends \Threaded implements DataProvider { /** * @var int Сколько лидов всего */ private $total = 0; /** * @var int Сколько лидов было обработано */ private $processed = 0; /** * @var Lead[] */ private $data; public function __construct(int $count) { $this->data = $this->fetchData($count); $this->total = count($this->data); } /** * получаем данные из источника * @param int $count */ protected function fetchData(int $count): ?array { $generator = new LeadGenerator(); return $generator->generateLeads($count); } /** * Получаем лида для обработки * @return Lead|null */ public function getNext(): ?Lead { if ($this->processed >= $this->total || empty($this->data)) { return null; } $lead = $this->data->shift(); $this->processed++; return $lead; } }
C
UTF-8
2,336
2.625
3
[]
no_license
#include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define perror_if(a, b) do{if(a){perror(b);exit(1);}}while(0) void handle(char* name, int rtype, void* opaque); int write_record(void* opaque, int ptr, int type, void* data, int l) { char* ptr0 = ((void**)opaque)[0]; char* wptr = ((void**)opaque)[1]; ptr = 0xc000|(ptr+12); *wptr++ = ptr >> 8; *wptr++ = ptr; *wptr++ = type >> 8; *wptr++ = type; memcpy(wptr, "\0\1\0\0\0;", 6); wptr += 6; *wptr++ = l >> 8; *wptr++ = l; int ans = wptr - ptr0; memcpy(wptr, data, l); wptr += l; int nq = ((ptr0[6] & 255) << 8) | (ptr0[7] & 255); nq++; ptr0[6] = nq >> 8; ptr0[7] = nq; ((void**)opaque)[1] = wptr; return ans - 12; } int main() { int sock = socket(AF_INET6, SOCK_DGRAM, 0); perror_if(sock < 0, "socket"); struct sockaddr_in6 addr; addr.sin6_family = AF_INET6; memset(addr.sin6_addr.s6_addr, 0, 16); addr.sin6_port = ntohs(53); perror_if(bind(sock, (struct sockaddr*)&addr, sizeof(addr)), "bind"); char buf[1048576]; for(;;) { socklen_t addrlen = sizeof(addr); ssize_t sz = recvfrom(sock, buf, 1048575, 0, (struct sockaddr*)&addr, &addrlen); perror_if(sz <= 0 || addrlen != sizeof(addr), "recvfrom"); buf[1048575] = 0; int l = strlen(buf + 12); if(l >= sz - 15) { fprintf(stderr, "invalid DNS packet received"); continue; } int idx = 12; while(buf[idx]) { int c = buf[idx]; buf[idx] = '.'; idx += c + 1; } int record_type = ((buf[idx + 1] & 255) << 8) | (buf[idx + 2] & 255); memcpy(buf+2, "\x81\x80\0\1\0\0\0\0\0\1", 10); buf[idx+3] = 0; buf[idx+4] = 1; char* ptr[2] = {buf, buf+idx+5}; handle(buf+13, record_type, ptr); char* p = buf + 12; char* q; while((q = strchr(p+1, '.'))) { p[0] = q - p - 1; p = q; } p[0] = strlen(p+1); memcpy(ptr[1], "\0\0)\2\0\0\0\0\0\0\0", 11); l = ptr[1]-ptr[0]+11; perror_if(sendto(sock, buf, l, 0, (struct sockaddr*)&addr, sizeof(addr)) != l, "sendto"); } return 0; }
Markdown
UTF-8
1,106
3.359375
3
[ "MIT" ]
permissive
--- layout: post title: "Unicode System" date: 2015-10-02 08:55:00 categories: Design permalink: blog/unicode-system --- Unicode is a universal international standard character encoding that is capable of representing most of the world's written languages. <h3>Why Java uses Unicode System?</h3> Before Unicode, there were many language standards: * <b>ASCII</b> (American Standard Code for Information Interchange) for the United States.<br> * <b>ISO 8859-1</b> for Western European Language.<br> * <b>KOI-8</b> for Russian.<br> * <b>GB18030</b> and <b>BIG-5</b> for chinese, and so on. This caused two problems: 1. A particular code value corresponds to different letters in the various language standards. 2. The encodings for languages with large character sets have variable length.Some common characters are encoded as single bytes, other require two or more byte. To solve these problems, a new language standard was developed i.e. Unicode System.<br> In unicode, character holds 2 byte, so java also uses 2 byte for characters. <b>lowest value:\u0000</b><br> <b>highest value:\uFFFF</b>
Python
UTF-8
126
2.921875
3
[]
no_license
n=int(input()) l=list(map(int,input().split())) s=0 for i in range(n): for j in range(n):s+=abs(l[i]-l[j]) print(s)
Java
UTF-8
2,227
2.953125
3
[]
no_license
package codeforces.gyms.gym102646; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import static java.lang.Long.max; public class TeamSelection implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { n = in.ni(); k = in.ni(); a = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.nl(); } b = new long[k]; for (int i = 0; i < k; i++) { b[i] = in.nl(); } dp = new long[n][k]; for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { dp[i][j] = -1; } } out.println(recurse(0, 0)); } private int n, k; private long[] a, b; private long[][] dp; private long recurse(int i, int j) { if (j == k) return 0; if (i == n) return (long) -1e15; if (dp[i][j] != -1) return dp[i][j]; long skip = recurse(i + 1, j), take = 0; if (j < k) { take = a[i] * b[j] + recurse(i + 1, j + 1); } return dp[i][j] = max(take, skip); } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (TeamSelection instance = new TeamSelection()) { instance.solve(); } } }
Java
UTF-8
475
2.40625
2
[]
no_license
package com.cognizant.spring.batch.processor; import org.springframework.batch.item.ItemProcessor; import com.cognizant.spring.batch.model.XmlToCsvModel; //run before writing public class XmlToCsvProcessor implements ItemProcessor<XmlToCsvModel, XmlToCsvModel> { @Override public XmlToCsvModel process(XmlToCsvModel item) throws Exception { //filter object which age = 30 if(item.getAge()==30){ return null; // null = ignore this object } return item; } }
Python
UTF-8
693
3.34375
3
[]
no_license
"""Tests for Problem 1. """ from ..problems import multiples_of_3_and_5 def test_1(): """multiples_of_3_and_5(10) should return a number.""" assert isinstance(multiples_of_3_and_5(10), int) def test_2(): """multiples_of_3_and_5(49) should return 543.""" assert multiples_of_3_and_5(49) == 543 def test_3(): """multiples_of_3_and_5(1000) should return 233168.""" assert multiples_of_3_and_5(1000) == 233168 def test_4(): """multiples_of_3_and_5(8456) should return 16687353.""" assert multiples_of_3_and_5(8456) == 16687353 def test_5(): """multiples_of_3_and_5(19564) should return 89301183.""" assert multiples_of_3_and_5(19564) == 89301183
Java
UTF-8
2,025
2.765625
3
[]
no_license
package com.example.demo; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; import javax.validation.constraints.AssertFalse; import javax.validation.constraints.Digits; import javax.validation.constraints.Max; import javax.validation.constraints.Min; /** * Created by Daniel on 2017. 7. 8.. */ @Entity @DynamicUpdate public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @NotBlank(message = "이름은 최소 2글자에서 최대 10글자입니다.") @Length(min = 2, max = 10) private String name; private int age; @NotBlank(message = "주소는 필수 값입니다.") private String address; @NotBlank private String gender; @Min(value = 0, message = "최소 1회 이상입니다.") @Max(value= 1000, message = "최대 1000회 이하입니다.") private int countSex; private boolean isMoSol; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getCountSex() { return countSex; } public void setCountSex(int countSex) { this.countSex = countSex; } public boolean isMoSol() { return isMoSol; } public void setMoSol(boolean moSol) { isMoSol = moSol; } }
Markdown
UTF-8
3,475
2.65625
3
[]
no_license
#项目说明 演示站点:http://blog.ydemo.cn/ 原作者项目:http://git.oschina.net/biezhi/tale 作者的项目看着挺简单的,做起来却不是那么一回事了。好多细节的处理让我感觉到和作者之间的差距巨大。于是,让自己的能力和项目对等,就简化了很多功能。也便于大家一起学习吧,毕竟我也是新手。现在项目整体的运行和原作者的基本一致。 1.开发的功能: 1. 用户管理:只面向个人用户,不提供对用户的CRUD,可以扩展。 1. 角色管理:安全框架必须,用户角色关联对应,可以进行扩展。 1. 文章发布:发布博文。 1. 友链管理:对网站挂载友情链接的管理。 1. 分类、标签管理:主要是给文章发布提供便捷。 1. 附件管理:使用七牛云对文章中要用到的图片文件统一进行管理。 由于选择的框架不同,对于原作者提供的一些功能暂时没有实现,一切从简,主要面对初学者。具体的我去掉的功能:评论这一块,系统设置中的站点设置,清除缓存,导出sql,配置插件,扩展主题模板。其余基本一致,可打包为jar war等多种形式直接运行。 2.项目框架 - 主框架:spring boot 1.5.2+ spring security4+jpa - 缓存:ehcache - 后台管理模板:H-UI admin - 前台主题模板:pingshu - 数据库:mysql - 模板引擎:thymeleaf - 图片存储:七牛 - 前端框架在此不做说明,基本都用的差不多。 这里我感觉做的最有意义的事就是整合springboot 和security,扩展了JPA数据库访问,以及展示了如何通过七牛实现的云存储。 3.快速开始 码云地址:https://git.oschina.net/aper/base/ 开发工具:idea。 运行环境:jdk1.8 maven3.0+ 从码云导入项目至idea,修改resources文件下application.yml中mysql的配置信息,然后直接运行DemoApplication.java的main()方法。 如图所示: ![输入图片说明](http://on74nfn25.bkt.clouddn.com/peizhi.png "在这里输入图片标题") ![输入图片说明](http://on74nfn25.bkt.clouddn.com/b_run.png "在这里输入图片标题") 4.项目结构 ![输入图片说明](http://on74nfn25.bkt.clouddn.com/b_jiegou.png "在这里输入图片标题") Java源码在 src/main/java 中, - 其中app包下的代码是业务开发中需求的bean dao controller等存放的地方。 - 其中core是系统核心包,里头包括整合框架的一些配置信息,默认不要做任何改动。如进行开发从APP包开发即可。 src/main/resouces 文件夹中存放了框架配置文件和页面文件。 - 其中static文件下存放了系统所需的静态资源文件。 - 其中templates文件夹下存放本系统所有的页面信息。 #来几张开发后的美图 主页: ![输入图片说明](http://on74nfn25.bkt.clouddn.com/b_index.png "在这里输入图片标题") 详情页 ![输入图片说明](http://on74nfn25.bkt.clouddn.com/b_detail.png "在这里输入图片标题") 后台主页: ![输入图片说明](http://on74nfn25.bkt.clouddn.com/b_admin_index.png "在这里输入图片标题") 友链 ![输入图片说明](http://on74nfn25.bkt.clouddn.com/b_youlian.png "在这里输入图片标题") 附件: ![输入图片说明](http://on74nfn25.bkt.clouddn.com/b_attach.png?a=1 "在这里输入图片标题") 标签: ![输入图片说明](http://on74nfn25.bkt.clouddn.com/b-tags.png "在这里输入图片标题")
C++
UTF-8
5,053
2.65625
3
[]
no_license
/* ------------------------------------------------------------------------------------------ Copyright (c) 2014 Vinyl Games Studio Author: Mikhail Kutuzov Date: 7/23/2014 3:35:20 PM ------------------------------------------------------------------------------------------ */ #include "SoundModule.h" #include "CachedResourceLoader.h" #include "SoundResource.h" #include "Sound.h" #include "Engine.h" #include "EngineModule.h" #include <iostream> #define MAX_VOLUME 100.0f #define VOLUME_DROP_PACE 100.0f // volume for all sounds drops by VOLUME_DROP_RATE, #define VOLUME_DROP_RATE 8.5f; // when the source sound moves away from the sound listener by a distance of VOLUME_DROP_PACE using namespace vgs; // // default constructor // SoundModule::SoundModule() {} // // destructor // SoundModule::~SoundModule() { for (auto sound : m_combatSounds) { delete sound.second; } m_combatSounds.clear(); m_soundPtrs.clear(); } // // plays a sound once with the specified volume and stops it after the specified time // void SoundModule::PlaySound(const char* fileName, const float volume, const float duration) { // find out if that sound was already created sf::SoundBuffer* buffer = FindSoundBufferByName(fileName); // if this sound has already been played, but "free" right now, play it std::pair<SoundMap::iterator, SoundMap::iterator> equalRange = m_combatSounds.equal_range(buffer); for (SoundMap::iterator soundsItr = equalRange.first; soundsItr != equalRange.second; ++soundsItr) { Sound* sound = soundsItr->second; if (sound->GetStatus() != sf::Sound::Playing) { sound->SetVolume(volume); sound->SetDuration(duration); sound->Play(); return; } } // otherwise, create a new sound from the same buffer Sound* sound = new Sound(new sf::Sound(*buffer), duration); sound->SetVolume(volume); sound->Play(); m_combatSounds.insert(std::pair<sf::SoundBuffer*, Sound*>(buffer, sound)); } // // only plays the sound if no sound with the same SoundBuffer is being played at the moment // void SoundModule::PlayUniqueSound(const char* fileName, const float volume, const float duration) { // find out if that sound was already created sf::SoundBuffer* buffer = FindSoundBufferByName(fileName); SoundMap::iterator soundItr = m_combatSounds.find(buffer); if (soundItr != m_combatSounds.end()) { Sound* sound = soundItr->second; // play the sound if it is not already being played if (sound->GetStatus() != sf::Sound::Playing) { sound->SetDuration(duration); sound->SetVolume(volume); sound->Play(); } } // this sound was never played before, create it, play, and store for future use else { Sound* sound = new Sound(new sf::Sound(*buffer), duration); sound->SetVolume(volume); sound->Play(); m_combatSounds.insert(std::pair<sf::SoundBuffer*, Sound*>(buffer, sound)); } } // // finds a sound and tries to pause it // void SoundModule::PauseUniqueSound(const char* fileName) { sf::SoundBuffer* buffer = FindSoundBufferByName(fileName); SoundMap::iterator soundItr = m_combatSounds.find(buffer); if (soundItr != m_combatSounds.end()) { soundItr->second->Pause(); } } // // finds a sound and tries to resume it // void SoundModule::ResumeUniqueSound(const char* fileName) { sf::SoundBuffer* buffer = FindSoundBufferByName(fileName); SoundMap::iterator soundItr = m_combatSounds.find(buffer); if (soundItr != m_combatSounds.end()) { soundItr->second->Resume(); } } // // finds a sound and tries to stop it // void SoundModule::StopUniqueSound(const char* fileName) { sf::SoundBuffer* buffer = FindSoundBufferByName(fileName); SoundMap::iterator soundItr = m_combatSounds.find(buffer); if (soundItr != m_combatSounds.end()) { soundItr->second->Stop(); } } // // calculates volume for a sound based on the distance between its source and the listener // const float SoundModule::CalculateVolume(const float distanceToSound) { float result = distanceToSound / VOLUME_DROP_PACE * VOLUME_DROP_RATE; return std::max(MAX_VOLUME - result, 0.0f); } // // starts up // void SoundModule::Startup(void) { } // // manages currently played sounds // void SoundModule::Update(float dt) { // let each sound update itself for (SoundMap::iterator soundsItr = m_combatSounds.begin(); soundsItr != m_combatSounds.end();) { if ((*soundsItr).second->Update(dt)) { soundsItr = m_combatSounds.erase(soundsItr); } else { ++soundsItr; } } } // // shuts down // void SoundModule::Shutdown(void) { } // // queries the ResourceLoader for a SoundResource with a passed name and returns a SoundBuffer from that SoundResource // sf::SoundBuffer* SoundModule::FindSoundBufferByName(const char* fileName) { // load and save a sound resource CachedResourceLoader* loader = Engine::GetInstance()->GetModuleByType<CachedResourceLoader>(EngineModuleType::RESOURCELOADER); std::shared_ptr<SoundResource> srPtr = loader->LoadResource<SoundResource>(fileName); m_soundPtrs.insert(srPtr); return srPtr.get()->GetSoundBuffer(); }
Java
UTF-8
1,004
2.328125
2
[]
no_license
package org.springframework.web.servlet.mvc.method; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy; public class RequestMappingInfoHandlerMethodMappingNamingStrategy implements HandlerMethodMappingNamingStrategy<RequestMappingInfo> { public static final String SEPARATOR = "#"; @Override public String getName(HandlerMethod handlerMethod, RequestMappingInfo mapping) { if (mapping.getName() != null) { return mapping.getName(); } StringBuilder sb = new StringBuilder(); String simpleTypeName = handlerMethod.getBeanType().getSimpleName(); for (int i = 0; i < simpleTypeName.length(); i++) { if (Character.isUpperCase(simpleTypeName.charAt(i))) { sb.append(simpleTypeName.charAt(i)); } } sb.append(SEPARATOR).append(handlerMethod.getMethod().getName()); return sb.toString(); } }