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
UTF-8
3,594
2.453125
2
[ "MIT" ]
permissive
/* * MIT LICENSE * Copyright 2000-2023 Simplified Logic, Inc * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: The above copyright * notice and this permission notice shall be included in all copies or * substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", * WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.simplifiedlogic.nitro.util; import com.ptc.cipjava.jxthrowable; import com.simplifiedlogic.nitro.jlink.calls.base.CallPoint2D; import com.simplifiedlogic.nitro.jlink.calls.base.CallPoint3D; import com.simplifiedlogic.nitro.jlink.calls.base.CallVector3D; import com.simplifiedlogic.nitro.jlink.data.JLPoint; import com.simplifiedlogic.nitro.jlink.impl.JlinkUtils; import com.simplifiedlogic.nitro.rpc.JLIException; /** * Utility class for creating JLPoint objects * * @author Adam Andrews * */ public class JLPointMaker { /** * Create a JLPoint from a Creo Point3D object * @param point The Creo point * @return The resulting JShell point * @throws JLIException */ public static JLPoint create(CallPoint3D point) throws JLIException { try { JLPoint pt = new JLPoint(); pt.setX(point.get(0)); pt.setY(point.get(1)); pt.setZ(point.get(2)); return pt; } catch (jxthrowable e) { throw JlinkUtils.createException(e); } } /** * Create a JLPoint from a Creo Poitn2D object * @param point The Creo point * @return The resulting JShell point * @throws JLIException */ public static JLPoint create(CallPoint2D point) throws JLIException { try { JLPoint pt = new JLPoint(); pt.setX(point.get(0)); pt.setY(point.get(1)); pt.setZ(0.0); return pt; } catch (jxthrowable e) { throw JlinkUtils.createException(e); } } /** * Create a Creo Point3D object from a JLPoint * @param point The JShell point * @return The Creo point * @throws jxthrowable */ public static CallPoint3D create3D(JLPoint point) throws jxthrowable { CallPoint3D pt = CallPoint3D.create(); pt.set(0, point.getX()); pt.set(1, point.getY()); pt.set(2, point.getZ()); return pt; } /** * Convert a Creo Point3D to a string, for debugging purposes * @param point The Creo point * @return The string value of the point * @throws jxthrowable */ public static String toString(CallPoint3D point) throws jxthrowable { return point.get(0) + " " + point.get(1) + " " + point.get(2); } /** * Convert a Creo Vector3D to a string, for debugging purposes * @param vec The Creo vector * @return The string value of the vector * @throws jxthrowable */ public static String toString(CallVector3D vec) throws jxthrowable { return vec.get(0) + " " + vec.get(1) + " " + vec.get(2); } }
Go
UTF-8
4,954
3.109375
3
[ "MIT" ]
permissive
package trade import ( "trading-bot/pkg/domain/model" ) func MaxRate(rates []float64) (float64, int) { max := rates[0] maxIndex := 0 for i := 0; i < len(rates); i++ { rate := rates[i] if rate > max { max = rate maxIndex = i } } return max, maxIndex } func MinRate(rates []float64) (float64, int) { min := rates[0] minIndex := 0 for i := 0; i < len(rates); i++ { rate := rates[i] if rate < min { min = rate minIndex = i } } return min, minIndex } // func SupportLine(rates []float64, term1, term2 int) ([]float64, float64) { // term1End := len(rates) - 1 // term1Begin := term1End - (term1 - 1) // term1Min, term1MinIdx := MinRate(rates[term1Begin : term1End-1]) // term1MinIdx = term1MinIdx + term1Begin // // term2End := term1Begin - 1 // term2Begin := term2End - (term2 - 1) // term2Min, term2MinIdx := MinRate(rates[term2Begin : term2End-1]) // term2MinIdx = term2MinIdx + term2Begin // // a := (term1Min - term2Min) / float64(term1MinIdx-term2MinIdx) // b := term1Min - float64(term1MinIdx)*a // // supportLine := []float64{} // for x := range rates { // supportLine = append(supportLine, float64(x)*a+b) // } // // return supportLine, a // } func SupportLine(rates []float64, period, periodInterval int) ([]float64, float64) { term1End := len(rates) - 1 term1Begin := term1End - (period - 1) term1Min, term1MinIdx := MinRate(rates[term1Begin:term1End]) term1MinIdx = term1MinIdx + term1Begin term2End := term1MinIdx - 1 - periodInterval term2Begin := term2End - (period - 1) term2Min, term2MinIdx := MinRate(rates[term2Begin : term2End-1]) term2MinIdx = term2MinIdx + term2Begin a := (term1Min - term2Min) / float64(term1MinIdx-term2MinIdx) b := term1Min - float64(term1MinIdx)*a supportLine := []float64{} for x := range rates { supportLine = append(supportLine, float64(x)*a+b) } return supportLine, a } func ResistanceLine(rates []float64, period, periodInterval int) ([]float64, float64) { term1End := len(rates) - 1 term1Begin := term1End - (period - 1) term1Max, term1MaxIdx := MaxRate(rates[term1Begin:term1End]) term1MaxIdx = term1MaxIdx + term1Begin term2End := term1MaxIdx - 1 - periodInterval term2Begin := term2End - (period - 1) term2Max, term2MaxIdx := MaxRate(rates[term2Begin : term2End-1]) term2MaxIdx = term2MaxIdx + term2Begin a := (term1Max - term2Max) / float64(term1MaxIdx-term2MaxIdx) b := term1Max - float64(term1MaxIdx)*a supportLine := []float64{} for x := range rates { supportLine = append(supportLine, float64(x)*a+b) } return supportLine, a } func SupportLine2(rates []float64, beginIdx, endIdx int) (a, b float64) { begin := true for { x := []float64{} y := []float64{} for i, rate := range rates { if i < beginIdx || i > endIdx { continue } if begin || rate <= a*float64(i)+b { x = append(x, float64(i)) y = append(y, rate) } } if len(x) <= 3 { return } a, b = LinFit(x, y) begin = false } } func ResistanceLine2(rates []float64, beginIdx, endIdx int) (a, b float64) { begin := true for { x := []float64{} y := []float64{} for i, rate := range rates { if i < beginIdx || i > endIdx { continue } if begin || rate >= a*float64(i)+b { x = append(x, float64(i)) y = append(y, rate) } } if len(x) <= 3 { return } a, b = LinFit(x, y) begin = false } } func MakeLine(a, b float64, size int) []float64 { line := []float64{} for i := 0; i < size; i++ { line = append(line, a*float64(i)+b) } return line } func GetLastBuyContracts(pair *model.CurrencyPair, cc []model.Contract) []model.Contract { buyContracts := []model.Contract{} for i := 0; i < len(cc); i++ { c := cc[i] if c.Side != model.BuySide { break } if c.IncreaseCurrency == pair.Key && c.DecreaseCurrency == pair.Settlement { buyContracts = append(buyContracts, c) } } return buyContracts } // CalcAmount 未決済分の購入金額を算出 func CalcAmount(pair *model.CurrencyPair, cc []model.Contract, keyAmount, fraction float64) (usedJPY float64, obtainedCurrency float64) { tmp := keyAmount for _, c := range cc { if tmp < fraction { break } if c.DecreaseCurrency == pair.Settlement && c.IncreaseCurrency == pair.Key { // 買い注文 usedJPY -= c.DecreaseAmount obtainedCurrency += c.IncreaseAmount tmp -= c.IncreaseAmount continue } if c.DecreaseCurrency == pair.Settlement && c.IncreaseCurrency == pair.Key { // 売り注文 usedJPY -= c.IncreaseAmount obtainedCurrency += c.DecreaseAmount tmp -= c.DecreaseAmount continue } } return } func LinFit(x, y []float64) (a, b float64) { var sx, sy, t, st2 float64 ndata := len(x) if ndata < 2 { return } for i := 0; i < ndata; i++ { sx += x[i] sy += y[i] } ss := float64(ndata) sxoss := sx / ss for i := 0; i < ndata; i++ { t = x[i] - sxoss st2 += t * t a += t * y[i] } a /= st2 b = (sy - sx*a) / ss return }
C++
UTF-8
931
2.515625
3
[ "MIT" ]
permissive
#pragma once #include "Particle.h" #include <vector> #include <SFML/Graphics.hpp> #include <thread> #include "Algorithms.h" class ParticleSystem { public: ParticleSystem(sf::Vector2f pos,sf::Vector2f systemS, std::string texturePath); ~ParticleSystem(); void addParticle(); //void draw(sf::RenderWindow& window); void draw(sf::RenderTexture& texture); void update(); void init(); void setMousePos(const sf::Vector2i& mP); void doFrame(sf::RenderTexture& window); //function for threading sf::Vector2f getPosition(); void setMouseGravity(const float& newGravity); float getMouseGravity(); private: std::vector <Particle*> particles; sf::CircleShape particle; std::vector<sf::Vertex> vertices; sf::Vector2f origin; int emmitanceRate; int numParticles; int currentIndex; sf::Vector2f systemForce; sf::Vector2i mousePos; sf::Texture texture; sf::Vertex tmp; sf::Vector2f systemSize; float mouseGravity; };
JavaScript
UTF-8
5,145
3.71875
4
[]
no_license
import Card from '../UI/Card'; import React, { useState } from 'react'; import classes from './AddUser.module.css'; import Button from '../UI/Button'; import ErrorModal from '../UI/ErrorModal'; const AddUser = (props) => { // this can be also done using useRef() // const nameInputRef = useRef(); // const ageInputRef = useRef(); const [enteredUsername, setEnteredUsername] = useState(''); const [enteredAge, setEnteredAge]= useState(''); const [error, setError] = useState(); const addUserHandler = (event) => { event.preventDefault(); // const enteredName = nameInputRef.current.value; // const enteredUserAge = ageInputRef.current.value; if(enteredUsername.trim().length === 0 || enteredAge.trim().length ===0){ setError({ title: 'Invalid input', message: 'Please enter a valid name and age (non-empty values).' }); return; // if(enteredName.trim().length ===0 || entereUserdAge.trim().length ===0){ // setError({ // title: 'Invalid input', // message: 'Please enter a valid name and age (non-empty values).' // }); // return; } //since the user input is a string and should be converted into number. if(+enteredAge < 1){ setError({ title: 'Invalid age', message: 'Please enter a valid age (> 0).' }); return; } // lifting the state up: This sendes the user inputs up to the parent component i.e, App comp and the // the comp saves the incoming user in the users array and then sendes down to its child UserList via props props.onAddUser(enteredUsername, enteredAge); setEnteredUsername(''); setEnteredAge(''); }; const usernameChangeHandler = (event) => { setEnteredUsername(event.target.value); }; const ageChangeHandler = (event) => { setEnteredAge(event.target.value); }; const errorHandler = () => { setError(null); }; return ( <div> { error && <ErrorModal title= {error.title} message={error.message} onConfirm= {errorHandler}/>} <Card className= {classes.input}> <form onSubmit={addUserHandler} > <label htmlFor="username">Username</label> <input id="username" type ="text" value={enteredUsername} onChange={usernameChangeHandler} // ref={nameInputRef} /> <label htmlFor="age">Age(Years)</label> <input id="age" type ="number" value={enteredAge} onChange={ageChangeHandler} // ref={ageInputRef} /> <Button type="submit"> Add user </Button> </form> </Card> </div> ); // How TO USE useRef() TO READ THE CURRENT VALUE OF THE USER INPUT // -------------------------------------------------------------------------- // // we can also get access to the value of the input fields using useRef() react hook // const nameInputRef = useRef(); // const ageInputRef = useRef(); // // and in the input fields // <input id= "username" type= "text" ref= {nameInputRef} /> // <input id="age" type="number" ref= {ageInputRef} /> // useRef has a 'current' property and, using this current propery we access the // value of the user input // when the form is submitted // const addUserHandler = (event) => { // event.preventDefault(); // const enteredName = nameInputRef.current.value(); // const enteredUserAge = ageInputRef.current.value(); // // check if the inputs are valid // if (enteredName.trim().length === 0 || enteredUserAge.trim().length === 0){ // setError({ // title: 'Invlaid input', // message: 'Please enter a valid name and age (non-empty values.)', // }); // return; // } // if(+enteredUserAge < 1){ // setError({ // title: 'Invalid age', // message: 'Please enter a valid age (>0)', // }); // return; // } // props.onAddUser(enteredName, enteredUserAge); // // Thought it is not recommended to manipulate the DOM using Refs, but it can // // be resett the values of the input fields as following // nameInputRef.current.value = ''; // ageInputRef.current.value=''; // useRef vs useState // ---------------------------- // if your target is to read the value of the user input, but not to change it , // better to use useRef() react hook. // if you want to get acces and at the same time to change the value of the input fields, better // to use useState() react hook // controlled and un-controlled controls // ------------------------------------------- // input fields which we have access using useRef are un-controlled. since we can't change // the values of the fields. // input filds which have access to using useState are controlled since we can change the // values of the input fields. // } }; export default AddUser;
Go
UTF-8
2,119
2.609375
3
[ "BSD-3-Clause" ]
permissive
package verifier import ( "archive/zip" "io/ioutil" "os/exec" "path" "path/filepath" "strings" "github.com/rocketsoftware/open-web-launch/settings" "github.com/rocketsoftware/open-web-launch/utils" "github.com/rocketsoftware/open-web-launch/utils/log" "github.com/pkg/errors" ) const ( verboseMessage = "Re-run jarsigner with the -verbose option for more details." ) func VerifyWithJARSigner(jar string, verbose bool) error { jarSignerExecutable := settings.JARSigner() if jarSignerExecutable == "" { return nil } var cmd *exec.Cmd if verbose { cmd = exec.Command(jarSignerExecutable, "-verify", "-verbose", jar) } else { cmd = exec.Command(jarSignerExecutable, "-verify", jar) } utils.HideWindow(cmd) stdoutStderr, err := cmd.CombinedOutput() if err != nil { return errors.Wrap(err, "unable to run jarsigner") } output := string(stdoutStderr) if !strings.Contains(output, "jar verified.") { if !verbose && strings.Contains(output, verboseMessage) { output = strings.Replace(output, verboseMessage, " See log file for more details", 1) err := VerifyWithJARSigner(jar, true) log.Println(err) } return errors.New(output) } return nil } func GetJARCertificate(jar string) ([]byte, error) { reader, err := zip.OpenReader(jar) if err != nil { return nil, err } defer reader.Close() var certificate []byte for _, file := range reader.File { if strings.HasPrefix(file.Name, "META-INF/") { dir, filename := path.Split(file.Name) if dir != "META-INF/" { continue } ext := path.Ext(filename) if ext == ".RSA" || ext == ".DSA" { data, err := getFileContent(file) if err != nil { return nil, errors.Wrapf(err, "unable to read certificate file %s", filename) } certificate = data } } } if certificate == nil { return nil, errors.Errorf("unable to find certificate in JAR file %s", filepath.Base(jar)) } return certificate, nil } func getFileContent(file *zip.File) ([]byte, error) { fileReader, err := file.Open() if err != nil { return nil, err } defer fileReader.Close() return ioutil.ReadAll(fileReader) }
C
UTF-8
502
3.578125
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "binary_trees.h" /** * binary_tree_node - insert node in binary tree * @parent: pointer to head tree * @value: value of node * Return: tree with node new */ binary_tree_t *binary_tree_node(binary_tree_t *parent, int value) { binary_tree_t *newNode; newNode = malloc(sizeof(binary_tree_t)); if (newNode == NULL) return (NULL); newNode->parent = parent; newNode->n = value; newNode->left = NULL; newNode->right = NULL; return (newNode); }
Java
UTF-8
1,630
3.25
3
[]
no_license
package interview.amazon; import java.util.*; class CriticalConnections { List<List<Integer>> bridges; ArrayList<Integer>[] graph; int[] ids, low; int id; public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) { //1. initialize global variables; bridges = new ArrayList<>(); graph = new ArrayList[n]; ids = new int[n]; low = new int[n]; id = 0; //2. build graph; buildGraph(connections); //3. find bridges; boolean[] visited = new boolean[n]; dfs(visited, -1, 0); return bridges; } private void dfs(boolean[] visited, int parent, int i) { visited[i] = true; ids[i] = low[i] = id++; for (int node : graph[i]) { if (node == parent) continue; if (!visited[node]) { dfs(visited, i, node); //things below happen during backtracking low[i] = Math.min(low[i], low[node]); if (ids[i] < low[node]) bridges.add(Arrays.asList(i, node)); } else { low[i] = Math.min(low[i], ids[node]); } } } private void buildGraph(List<List<Integer>> connections) { for (int i = 0; i < graph.length; i++) graph[i] = new ArrayList<>(); for (int i = 0; i < connections.size(); i++) { int a = connections.get(i).get(0), b = connections.get(i).get(1); graph[a].add(b); graph[b].add(a); } } }
C++
UTF-8
948
2.734375
3
[]
no_license
#include "../include/scheduler.h" #include <unistd.h> Scheduler::Scheduler( int num_threads ): num_threads( num_threads ) { cout << "Scheduler: \t\tStarted!" << std::endl; done_ = false; pool_ = new ThreadPool( num_threads ); pool_ -> init(); quit_token = std::bind(&Scheduler::doDone, this); thd_ = std::thread(&Scheduler::dispatch, this); } void Scheduler::doDone( ) { done_ = true; } void Scheduler::dispatch( ) { while(!this->done_) { if( (this->mq_).empty( ) ) { continue; } Callback func; (this->mq_).wait_and_pop(func); cout << "Scheduler: \t\tsubmits a task to the pool" << std::endl; pool_->submit(func); } } Scheduler::~Scheduler( ) { //cout << "4" << endl; mq_.push(quit_token); thd_.join(); pool_->shutdown(); cout << "Sheduler: \t\tShut down" << std::endl; // std::cout<<"thd joined"<<std::endl; }
C++
UTF-8
2,146
2.90625
3
[]
no_license
/** * @file SunStation.h * * Helper class that stores the state and * functions used to interact with the SunStation. */ #ifndef SunStation_h #define SunStation_h #include "Arduino.h" /** Interface for SunStation helper class */ class SunStation { public: void begin(); bool isButtonPressed(); bool isUsbOn(); void turnUsbOn(); void turnUsbOff(); void turnBleOn(); void turnBleOff(); void turnLightsOn(); void turnLightsOff(); byte getBatteryLevel(); float getRawBatteryLevel(); float getBatteryCurrent(); float getCumulativeCurrent(); float getCarbonSaved(); unsigned long getEnergyProduced(); void measureBatteryCurrent(); void updateCumulativeCurrent(); void resetCumulativeCurrent(); void computeBatteryLevels(); void computeCarbonSaved(); void computeEnergyProduced(); void saveEnergyProduced(); void recoverEnergyProduced(); template <typename T> void sendBlePacket(char *name, T value); private: bool mIsUsbOn = false; //!< whether or not usb port is delivering power byte batteryLevel = 0; //!< battery level in percentage (0-100) float rawBatteryLevel = 0.0; //!< battey level in range (0-maxCapacity) float batteryCurrent = 0.0; //!< battery's amperage output (amps) float cumulativeCurrent = 0.0; //!< current accumulated by battery in 1 hour float carbonSaved = 0.0; //!< carbon emissions saved by station in its lifetime (kg of CO2) unsigned long energyProduced = 0L; //!< energy produced by station in its lifetime (Wh) static const float batteryIdleDraw; //!< battery's amperage draw when station is idle (amps / 300 ms) static const float batteryChargeRate; //!< battery's charge rate (amps) static const float batteryDischargeRate; //!< battery's discharge rate (amps) static const float batteryMaxCapacity; //!< battery's maximum usable capacity (cummulative amps till full) static const float currentMeasurementNoise; //!< values in range -measurementNoise to +measurementNoise are unrealiable void computeRawBatteryLevel(); void computeBatteryLevel(); }; #endif
Java
UTF-8
1,619
2.0625
2
[]
no_license
package homeSwitchHome; import java.time.LocalDate; public final class HomeSwitchHome { private static Usuario usuarioActual; private static Propiedad propiedadActual; private static LocalDate fechaInicioBuscada; private static LocalDate fechaFinBuscada; private static Reserva reservaActual; // private static ArrayList<Usuario> usuarios; // private static ArrayList<UsuarioAdministrador> administradores; // private static ArrayList<Reserva> reservas; // private static ArrayList<Propiedad> propiedades; public HomeSwitchHome() { } public static Usuario getUsuarioActual() { return usuarioActual; } public static void setUsuarioActual(Usuario usuarioActual) { HomeSwitchHome.usuarioActual = usuarioActual; } public static Propiedad getPropiedadActual() { return propiedadActual; } public static void setPropiedadActual(Propiedad propiedadActual) { HomeSwitchHome.propiedadActual = propiedadActual; } public static LocalDate getFechaInicioBuscada() { return fechaInicioBuscada; } public static void setFechaInicioBuscada(LocalDate fechaInicioBuscada) { HomeSwitchHome.fechaInicioBuscada = fechaInicioBuscada; } public static LocalDate getFechaFinBuscada() { return fechaFinBuscada; } public static void setFechaFinBuscada(LocalDate fechaFinBuscada) { HomeSwitchHome.fechaFinBuscada = fechaFinBuscada; } public static Reserva getReservaActual() { return reservaActual; } public static void setReservaActual(Reserva reservaActual) { HomeSwitchHome.reservaActual = reservaActual; } }
C#
UTF-8
332
2.90625
3
[]
no_license
using System.Collections.Generic; using JetBrains.Annotations; namespace RepetitionDetection.Commons { public class CharGreaterComparer : IComparer<char> { public int Compare(char x, char y) => comparer.Compare(y, x); [NotNull] private readonly IComparer<char> comparer = Comparer<char>.Default; } }
Java
UTF-8
712
2.421875
2
[]
no_license
package com.dale.net.exception; /** * create by Dale * create on 2019/7/12 * description: */ public class ErrorMessage { /** * 错误状态码,http状态码 或者 服务器返回的状态码 */ private int code; /** * 错误的信息 可能为空 */ private String message; public ErrorMessage(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
Markdown
UTF-8
1,084
3.328125
3
[]
no_license
# ajv-validator-keywords Demonstration repository on how to add Keywords to AJV which map to validator functions. ```typescript import Ajv from "ajv"; import validator from "validator" export const addValidatorKeywords = (ajv: Ajv) => { ajv.addKeyword({ keyword: "isPort", validate: ((schema, data) => validator.isPort(data + '')) }) } ``` ## Usage Example usage using a YAML schema to validate an application configuration on startup ```yaml # config-schema.yml $schema: http://json-schema.org/draft-07/schema title: Root Application Schema type: object properties: server: type: object required: [] properties: port: { type: integer, isPort } required: [ server ] ``` ```typescript // validate-something.ts import { addValidatorKeywords } from "ajv-validator-keywords" const schema = // Import/load using yaml library const config = { server: { port: 123455678 }} const ajv = new Ajv(); addValidatorKeywords(ajv); const validator = ajv.compile(schema); validator(config); // Will Return False and contain validator.errors ```
Markdown
UTF-8
1,538
3.921875
4
[]
no_license
# 42-H2S-OOP_Introduction Ex00: Make your first class with a constructor that says "Hello World". You must instanciate your first class only in a main Ex01: Make your second class that will inherit from the first class and call the first class constructor that says "Hello World". You must instanciate the second class only in your main. Ex02: You now need your second class to take a parameter "name" (which will be your login name) and pass it into the first class which will display "Hello ". You must instanciate the second class only in your main. Ex03: You now need to create a method inside your first class called Hello which will take the name from the constructor and print out "Hello ". When the method is call put some sort of output for identification. You must instanciate the second class only in your main. Ex04: You now need to create a method inside your second class called number which will randomly generate a number from 1 to 6. It than will pass it to Hello method in first class which will print out "Hello , your number is ". When any method is called it must put some sort of output for itself. You must instanciate the second class only in your main. Ex05: Your second class will now take a second parameter called hobby and it must be stored as a variable. You will write a method called getHobby in your second class that returns this variable. In your main you need to print out "Your hobby is " where must be returned from the getHobby method. You must instanciate the second class only in your main.
Python
UTF-8
3,035
4.15625
4
[]
no_license
# ------------------------------ # 457. Circular Array Loop # # Description: # You are given a circular array nums of positive and negative integers. If a number k at an # index is positive, then move forward k steps. Conversely, if it's negative (-k), move # backward k steps. Since the array is circular, you may assume that the last element's next # element is the first element, and the first element's previous element is the last element. # # Determine if there is a loop (or a cycle) in nums. A cycle must start and end at the same # index and the cycle's length > 1. Furthermore, movements in a cycle must all follow a # single direction. In other words, a cycle must not consist of both forward and backward movements. # # Example 1: # Input: [2,-1,1,2,2] # Output: true # Explanation: There is a cycle, from index 0 -> 2 -> 3 -> 0. The cycle's length is 3. # # Example 2: # Input: [-1,2] # Output: false # Explanation: The movement from index 1 -> 1 -> 1 ... is not a cycle, because the cycle's # length is 1. By definition the cycle's length must be greater than 1. # # Example 3: # Input: [-2,1,-1,-2,-2] # Output: false # Explanation: The movement from index 1 -> 2 -> 1 -> ... is not a cycle, because movement # from index 1 -> 2 is a forward movement, but movement from index 2 -> 1 is a backward # movement. All movements in a cycle must follow a single direction. # # Note: # # -1000 ≤ nums[i] ≤ 1000 # nums[i] ≠ 0 # 1 ≤ nums.length ≤ 5000 # # Follow up: # Could you solve it in O(n) time complexity and O(1) extra space complexity? # # Version: 1.0 # 10/15/19 by Jianfa # ------------------------------ class Solution: def circularArrayLoop(self, nums: List[int]) -> bool: if not nums: return False size = len(nums) def getIndex(i): return (i + nums[i]) % size for i in range(size): if nums[i] == 0: continue # slow and fast pointers slow = i fast = getIndex(i) while nums[slow] * nums[fast] > 0 and nums[slow] * nums[getIndex(fast)] > 0: if slow == fast: if slow == getIndex(slow): # the loop with only one element break return True slow = getIndex(slow) fast = getIndex(getIndex(fast)) # loop not found, set all elements along the way to 0 slow = i val = nums[i] while nums[slow] * val > 0: nextIdx = getIndex(slow) nums[slow] = 0 slow = nextIdx return False # Used for testing if __name__ == "__main__": test = Solution() # ------------------------------ # Summary: # Slow/fast pointers solution from: https://leetcode.com/problems/circular-array-loop/discuss/94148/Java-SlowFast-Pointer-Solution # # O(n) time and O(1) space
Python
UTF-8
1,026
4.5625
5
[ "Unlicense" ]
permissive
""" Chooses a random integer in [0, 100]. Asks user to enter a guess, terminates only when user guesses correctly """ import random def guessing_game(): number = random.randint(1, 5) while True: guess = int( input("Please enter a number between 1 and 5 (inclusive) ")) if guess == number: return "correct!" # print(guessing_game()) """ implement sum function sum(a, b, c, d, ... m, n) = a+b+c+d+...+m+n """ def mysum(*numbers): total = 0 for number in numbers: total += number return total #print(mysum(1, 2, 3, 4, 5)) def get_avg(): # taking number from user enter number through string message # stores them in an array and then averages values in array5 total = 0 count = 0 while True: user_input = input("enter a number: ") try: n = int(user_input) count += 1 except: break total += n if count > 0: print(total/count) return get_avg()
Shell
UTF-8
1,172
3.71875
4
[]
no_license
#!bin/bash #Global variable declaration difficulty=" " numfloors=" " numcoins=12 #Functionfor the menu interface menu_interface(){ clear echo "======================" echo "New Game" echo "Quit" read -p "Selection: " select if [[ $select == "Quit" ]] || [[ $select == "quit" ]] then exit 1 elif [[ $select == "New Game" ]] || [[ $select == "new game" ]] then #Difficulty choosing echo "==================================================" echo "Choose difficulty: Normal Intermediate Insane" read dif if [[ $dif == "Normal" ]] || [[ $dif == "normal" ]] then difficulty=1 elif [[ $dif == "Intermediate" ]] || [[ $dif == "intermediate" ]] then difficulty=1.5 elif [[ $dif == "Insane" ]] || [[ $dif == "insane" ]] then difficulty=2 else echo "Please choose a valid command." read menu_interface fi #Choosing the number of floors to go through echo "==================================================" echo -e "Choose the number of floors you wish to go through:\n10 20 50 100" read numfl numfloors=$numfl else echo "Please choose a valid command." read menu_interface fi }
C++
UTF-8
824
2.796875
3
[]
no_license
/** * \file LeftDistrict.h * \author RPGteam * \date 23.06.2016 * \version 1.0 * \brief File contains the definition of LeftDistrict class */ // ------------------------------------------------------------------------- #ifndef LEFTDISTRICT_H #define LEFTDISTRICT_H // ------------------------------------------------------------------------- #include "../GameStep.h" // ------------------------------------------------------------------------- /** * \class LeftDistrict * \author RPGteam * \date 23.06.2016 * \brief LeftDistrict class, which represents staying in the Left District of the City */ class LeftDistrict : public GameStep { public: /// \brief TBD! /// /// \param subject - TBD! void play(Heroe& subject); /// \brief TBD! /// /// \return TBD! GameStep* getNext(); }; #endif
JavaScript
UTF-8
902
3.3125
3
[]
no_license
function solve(arguments) { var result = new Array(); let headers = arguments[0].split("|").map(item => item.trim()).filter(i => i != ""); let town = headers[0]; let latitude = headers[1]; let longitude = headers[2]; for (let i = 1; i < arguments.length; i++) { let values = arguments[i].split("|").map(item => item.trim()).filter(i => i != ""); let townName = values[0]; let latitudeValue = Number(values[1]) == 0 ? 0 : Number(values[1]).toFixed(2) * 1; let longitudeValue = Number(values[2]) == 0 ? 0 : Number(values[2]).toFixed(2) * 1; result.push(`{\"${town}\":\"${townName}\",\"${latitude}\":${latitudeValue},\"${longitude}\":${longitudeValue}}`) } console.log(`[${result.join(",")}]`); } solve(['| Town | Latitude | Longitude |', '| Sofia | 42.696552 | 23.32601 |', '| Beijing | 39.913818 | 116.363625 |'] );
C++
UTF-8
283
2.734375
3
[]
no_license
#include<iostream> using namespace std; int main() { int i,j,n,m; cout<<"Enter two numbers"; cin>>n>>m; while(m!=n) { if(m>n) m=m-n; else { n=n-m; } } cout<<m; return 0; }
Python
UTF-8
772
2.703125
3
[]
no_license
''' Created on Sep 11, 2013 @author: johannes @review: johannes, benjamin ''' from MouseInput import MouseInput from CalculateAngle import Calculations import thread class Pid(object): ''' classdocs ''' def __init__(self): self.calculator=Calculations() self.mice = MouseInput(self.calculator) ''' Constructor ''' #miceSensors.update() thread.start_new_thread( miceSensor.update(), ("Thread-1", 2, ) ) # self.initMouseThread() pass def computeAngle(self): pass def initMiceThread(self): self.mice.start() def main(): pid=Pid() pid.initMiceThread() while(1): pass if __name__== '__main__': main()
Java
UTF-8
1,397
2.21875
2
[]
no_license
package org.aliu.springboot.model.four.domain.dto; import lombok.Data; import org.aliu.springboot.model.four.utils.InsertValidationGroup; import javax.validation.constraints.Email; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; /** * 分页参数DTO * * @author liusheng * @date 2021/9/27 */ @Data public class UserQueryDTO implements Serializable { private static final long serialVersionUID = 3033532065421245483L; /** * 用户姓名 */ @NotBlank(message = "用户名不能为空", groups = {InsertValidationGroup.class}) private String username; /** * 邮箱 */ @NotBlank(message = "邮箱不能为空", groups = {InsertValidationGroup.class}) @Email(message = "必须为有效的邮箱格式") private String email; /** * 年龄 */ @NotNull(message = "年龄不能为空", groups = {InsertValidationGroup.class}) @Max(value = 60, message = "年龄不能大于60") @Min(value = 18, message = "年龄不能小于18") private Integer age; /** * 手机号码 */ @NotBlank(message = "手机号码不能为空", groups = {InsertValidationGroup.class}) private String phone; }
TypeScript
UTF-8
3,322
2.921875
3
[]
no_license
class Yoshi { private game: Game; private vehicleCloud : VehicleCloud; private _behavior : Behavior public speed: number; public div: HTMLElement; public x: number; public y: number; public height : number; public width : number; public jumpDirection: number; public get behavior(): Behavior { return this._behavior; } public set behavior(b: Behavior) { this._behavior = b; } constructor(parent: HTMLElement, g: Game) { this.div = document.createElement("yoshi"); parent.appendChild(this.div); this.game = g; this.speed = 0; this.jumpDirection = -3; this.x = 18; this.y = 340; this.height = 70; this.width = 70; let vehicleCloud = new VehicleCloud(this.div, -18, 50); this._behavior = new MoveHorizontal(this); window.addEventListener("keydown", (e: KeyboardEvent) => this.onKeyDown(e)); window.addEventListener("keyup", (e: KeyboardEvent) => this.onKeyUp(e)); } private onKeyDown(e: KeyboardEvent): void { console.log(e.key); if(e.key == 'w' && Game.getInstance().running == true) { this._behavior = new MoveVertical(this); this.onGoUp(); } if(e.key == 's' && Game.getInstance().running == true) { this._behavior = new MoveVertical(this); this.onGoDown(); } if(e.key == 'd' && Game.getInstance().running == true) { // this.div.style.backgroundImage = "url(' ')"; this._behavior = new MoveHorizontal(this); this.onGoForward(); } if(e.key == 'a' && Game.getInstance().running == true){ // this.div.style.backgroundImage = "url('http://static.tumblr.com/4ea070e8e27105fc99069d5e21456305/ofhymms/XYMon1apq/tumblr_static_6cy45y7o5i0wocsgo0k4ks4gc.gif')"; this._behavior = new MoveHorizontal(this); this.onGoBack(); } if(e.key == ' ' && Game.getInstance().running == true){ // this._behavior = new Shoot(); // this.onShoot(); //SCHIETEN!!! } } private onKeyUp(e: KeyboardEvent){ if(e.key == ' ' || e.key == 'd' || e.key == 'a' ){ this.speed = 0; } } public update():void { this._behavior.performBehavior(); this.onCollision(); if(this.speed == 0 && Game.getInstance().collision == false){ this.onIdle(); } } public onCollision(){ if(Game.getInstance().collision == true){ this._behavior = new Dead(this); this.onDead(); } } public onGoUp():void { // console.log("Jumping!"); this._behavior.onGoUp(); } public onGoDown():void { // console.log("Jumping!"); this._behavior.onGoDown(); } public onGoForward():void{ console.log("Running!"); this._behavior.onGoForward(); } public onGoBack() : void{ console.log("Running back!"); this._behavior.onGoBack(); } public onIdle(){ this._behavior.onIdle(); } public onDead(){ this._behavior.onDead(); } public onShoot(){ this._behavior.onShoot(); } }
Java
UTF-8
2,413
1.78125
2
[]
no_license
package com.appCore.personnel.Core.Controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.Resource; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.apache.commons.fileupload.FileUpload; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.util.Streams; import org.apache.log4j.Logger; import com.appCore.personnel.Core.Helpers.CoreConstants; import com.appCore.personnel.Core.Helpers.FileContentHelper; import com.appCore.Mvc.Controller.AppCoreController; import com.appCore.Requests.RequestStatus; import com.appCore.personnel.Core.Entity.Branch; import com.appCore.personnel.Core.Entity.BranchSummary; import com.appCore.personnel.Core.Entity.FileUploadContent; import com.appCore.personnel.Core.Entity.UnitSummary; import com.appCore.personnel.Core.Helpers.RequestStatusHelper; import com.appCore.personnel.Core.Job.Entity.AssociationMembershipType; import com.appCore.personnel.Core.Service.BranchService; @Controller @RequestMapping("/Core") public class FileUploadController { protected static Logger logger = Logger.getLogger("controller"); @RequestMapping(value = "/create/upload", method = RequestMethod.POST, consumes = "multipart/form-data", produces = "application/json") @ResponseBody() public String handleImageUpload(MultipartFile file, @RequestParam(value = "fileName") String name) throws IOException, FileUploadException { if (file.getSize() > 0 && !name.isEmpty()) { String contentType = file.getContentType(); File targetFileName = new java.io.File(CoreConstants.fileUploadEmployeePixPath + name + FileContentHelper.getFileExtByContent(contentType)); file.transferTo(targetFileName); return "{\"success\": true}"; } else { return "{\"success\": false}"; } } }
Java
UTF-8
1,032
1.796875
2
[]
no_license
package cn.mooc.app.module.cms.model; import java.io.Serializable; public class DiscoverServerItem implements Serializable { /** * */ private static final long serialVersionUID = -7465117607734383942L; private String name; private Integer linkType; private String image; private String url; private String enabled; private String range; public String getRange() { return range; } public void setRange(String range) { this.range = range; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getLinkType() { return linkType; } public void setLinkType(Integer linkType) { this.linkType = linkType; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getEnabled() { return enabled; } public void setEnabled(String enabled) { this.enabled = enabled; } }
Markdown
UTF-8
5,418
3.3125
3
[ "MIT" ]
permissive
#co-stream [Streams](http://nodejs.org/api/stream.html "Stream") are node's best and most misunderstood idea, and _<em>co-stream</em>_ is a toolkit to make creating and working with streams <em>easy</em>. This package is very similar to [event-stream](https://github.com/dominictarr/event-stream), the difference is this package is in [co](https://github.com/tj/co) style, so we can write async stream processing code in a nice way. ## Installation ``` npm install co-stream ``` ## wait(stream) Wait for stream 'end'/'finish' event; ``` co(function *() { // blabla yield* cs.wait(your_stream); }); ``` ## through (write?, end?) Re-emits data synchronously. Easy way to create synchronous through streams. Pass in optional `write` and `end` methods. They will be called in the context of the stream. Use `this.pause()` and `this.resume()` to manage flow. Check `this.paused` to see current flow state. (write always returns `!this.paused`) this function is the basis for most of the synchronous streams in `event-stream`. ```js cs.through(function write(data) { this.emit('data', data) //this.pause() }, function end () { //optional this.emit('end') }) ``` ## fromEmitter(eventEmitter, opt) Create a stream from an event emitter. ```js var cs = require('co-stream'); var es = cs.fromEmitter(evt, { objectMode: true, data: 'message', // event name for data, default 'data' end: 'finish', // event name for end, default 'end' pause: evt.stop, // method to pause event emitter, default evt.pause || function () {} resume: evt.start });// method to resume event emiiter, default evt.resume || function () {} es.pipe(process.stdout); // cs.object.fromEmitter (cs.fromEmitter with default opt { objectMode: true }) // cs.string.fromEmitter (cs.fromEmitter with default opt { encoding: 'utf8' }) ``` ## fromIterable(iterable) Create a stream from an iterable object. ```js var cs = require('co-stream'); cs.fromIterable([1, 2, 3, 4, 5, 6, 7, 8]).pipe(cs.object.each(console.log)); // Promise is also supported. const promise = new Promise(resolve => setTimeout(() => resolve(['a', 'b', 'c']), 1000)); cs.fromIterable(promise).pipe(cs.object.each(console.log)); ``` ## map Create a map stream from a function(can be generator / async function). ```js var cs = require('co-stream') var ms = cs.map(function *(data) { //transform data return transformed_data; }, { objectMode: true, parallel: 3 }); your_source_stream.pipe(ms).pipe(your_dest_stream); // parallel param will allow you to process data parallelly, but the sequence of data may be changed if you have async call in the processor. // cs.object.map (cs.map with default opt { objectMode: true }) // cs.string.map (cs.map with default opt { encoding: 'utf8' }) ``` ## filter Create a filter stream from a function(can be generator / async function). ```js var cs = require('co-stream') var fs = cs.filter(async (data) => { // async data processing. return processingResult; }, { objectMode: true, parallel: 3 }); your_source_stream.pipe(fs).pipe(your_dest_stream); // parallel param will allow you to process data parallelly, but the sequence of data may be changed if you have async call in the processor. // cs.object.filter (cs.filter with default opt { objectMode: true }) // cs.string.filter (cs.filter with default opt { encoding: 'utf8' }) ``` ## each If you just want to process data without any data to output, use this. ```js var cs = require('co-stream') var ms = cs.each(function *(data) { // process data }, { objectMode: true, parallel: 3 }); your_source_stream.pipe(ms); // NOTE: ms.pipe is invalid. // parallel param will allow you to process data parallelly. // cs.object.each (cs.each with default opt { objectMode: true }) // cs.string.each (cs.each with default opt { encoding: 'utf8' }) ``` ## split (matcher) Break up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp` Example, read every line in a file ... ```js fs.createReadStream(file, {flags: 'r'}) .pipe(cs.split()) .pipe(cs.object.each(function *(line) { //do something with the line console.log('line: ', line); })) ``` ## duplex (writeStream, readStream) Takes a writable stream and a readable stream and makes them appear as a readable writable stream. It is assumed that the two streams are connected to each other in some way. (This is used by `pipeline` and `child`.) ```js var grep = cp.exec('grep Stream') cs.duplex(grep.stdin, grep.stdout) ``` ## Legacy API ```js var cs = require('co-stream'), co = require('co'), fs = require('fs'); co(function *() { var input = fs.createReadStream('test.in'), output = fs.createWriteStream('test.out'); var cin = new (cs.Reader)(input), // new (cs.LineReader)(input) will create a line reader. cout = new (cs.Writer)(output); var txt; while (txt = yield cin.read('utf8')) { yield cout.write(txt); // or: yield cout.writeLine(txt) } })(); // Object mode can process object streams such as mongodb stream. co(function *() { var objstream = collection.find({ age: { $gte: 10, $lt: 15 } }).stream(), reader = new (cs.Reader)(objstream, { objectMode: true }); var obj; while (obj = (yield reader.read())) { // blabla.... } })(); ```
Markdown
UTF-8
2,064
3.234375
3
[]
no_license
# Data-Mining-CW2 PowerShell scripts for performing some of the steps in Coursework 2. In order to run these scripts, the file paths must be changed, as they were the directories on my personal machine. These file paths are often denoted by "input_path" or "output_path" or something similar. Also, the destinations of the result text files will need changing too, to suit your own machine. Within each .ps1 script, I have placed console outputs which act both to track the position the script is at and also to make the code easier to understand. step2&3.ps1 randomizes the dataset and performs naive Bayes classification on the resulting file. step4&5.ps1 is slightly more complicated. For each optN file it: Splits the data set into two equal folds, saves the first fold. Performs CorrelationAttributeEval with a Ranker search method, and outputs the result to a text file. Reads this file, extracts the top 2/3/5 attributes and saves them to variables. Removes these selected attributes from optN, and produces subtracted data sets only including the class attribute and the top 2/3/5 attributes. Performs naive Bayes on these 2/3/5reduced data sets as well as the original optN set and saves these results for analysis. step7.ps1 utilises SimpleKMeans clustering. For each optN and optall file: Produces a new data set based on the file with normalized attribute values (minus the class attribute). Removes the class attribute from this set (eg opt0 - normalised), saves it as a new dataset (eg opt0 - normalised(no class)) and clusters, saving the output. Produces a .arff file for the clustered instances (for visualisation). Clusters the normalised .arff set with the class attribute, saving the output. step8.ps1 is functionally similar to step7.ps1, however instead of SimpleKMeans clustering it uses EM clustering. This script has variables to chaneg the parameters of the EM clustering, which is needed to compare and analyse the effects of different parameters.
Java
UTF-8
1,672
3.03125
3
[]
no_license
package main; import org.junit.Test; import org.junit.Assert; import java.util.concurrent.ThreadLocalRandom; import static org.junit.Assert.*; public class MainTest { public static int rnd(int min, int max) { return ThreadLocalRandom.current().nextInt(min, max); } @Test public void getLetterFromBase() { char c = 'a'; int i = 11; for (; i < 36 + 1; ++i, ++c) { Assert.assertEquals(c, Main.getLetterFromBase(i)); } } private String generateNumber(int radix) { StringBuilder result = new StringBuilder(); if (radix <= 10) { for (int i = 0; i < rnd(1, 10); ++i) { result.append(String.valueOf(rnd(0, radix))); } } else for (int i = 0; i < rnd(1, 5); ++i) { result.append(rnd(0, 1) % 2 == 0 ? (char) ('a' + rnd(0, radix - 10)) : String.valueOf(rnd(0, radix))); } if (result.indexOf("0") == 0) result.insert(0, 1); return result.toString(); } @Test public void convert() { for (int i = 0; i < 100; ++i) { int radixFrom = rnd(2, 36); int radixTo = rnd(2, 36); //генерируем число в сс radixFrom String number = generateNumber(radixFrom); System.out.print("from : " + radixFrom + " to : " + radixTo + " " + number); String temp = Main.convert(number, radixFrom, radixTo); System.out.println(" -> " + temp); Assert.assertEquals(Integer.parseInt(number, radixFrom), Integer.parseInt(temp, radixTo)); } } }
Python
UTF-8
1,564
2.671875
3
[]
no_license
from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class LoadDimensionOperator(BaseOperator): ui_color = '#80BD9E' truncate_sql_stmt = """ TRUNCATE TABLE {} """ insert_into_stmt = """ INSERT INTO {} {} """ @apply_defaults def __init__(self, # Define your operators params (with defaults) here # Example: # conn_id = your-connection-name redshift_conn_id = "", table = "", select_query = "", truncate_table_sql_stmt = False, *args, **kwargs): super(LoadDimensionOperator, self).__init__(*args, **kwargs) self.redshift_conn_id = redshift_conn_id self.table = table self.select_query = select_query self.truncate_table = truncate_table def execute(self, context): # connect to redshift cluster to run sql statements redshift = PostgresHook(postgres_conn_id = self.redshift_conn_id) if self.truncate_table : self.log.info("Will truncate table {} before inserting new data".format(self.table)) redshift.run(LoadDimensionOperator.truncate_sql_stmt.format( self.table )) self.log.info("Inserting dimension table data to {}".format(self.table)) redshift.run(LoadDimensionOperator.insert_into_stmt.format( self.table, self.select_query ))
Java
UTF-8
2,906
2.09375
2
[]
no_license
package com.skynet.spms.action.supplierSupport.consignment; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.skynet.spms.client.gui.supplierSupport.common.DSKey; import com.skynet.spms.datasource.DataSourceAction; import com.skynet.spms.manager.ListGridFilterManager; import com.skynet.spms.manager.supplierSupport.consignment.ConsignmentContract.IConsignProtocolManager; import com.skynet.spms.persistence.entity.contractManagement.template.supplierContactTemplate.consignmentAgreementTemplate.ConsignmentAgreementTemplate; /** * * 描述:寄售协议 * * @author 付磊 * @version 1.0 * @Date 2011-7-12 */ @Component public class ConsignProtocolAction implements DataSourceAction<ConsignmentAgreementTemplate> { @Autowired private IConsignProtocolManager manager; @Autowired private ListGridFilterManager<ConsignmentAgreementTemplate> filterManager; @Override public String[] getBindDsName() { return new String[] { DSKey.S_CONSIGNPROTOCOL_DS }; } /** * * 描述:添加一条记录 * * @param item * 寄售协议实体 */ @Override public void insert(ConsignmentAgreementTemplate item) { manager.addSheet(item); } /** * * 描述: 修改 * * @param newValues * 待修改的值集合 * @param itemID * 被修改的实体的uuid * @return 返回修改后的实体 */ @Override public ConsignmentAgreementTemplate update(Map<String, Object> newValues, String itemID) { return manager.update(newValues, itemID); } /** * 描述: 删除一条记录,这里的删除实际上只是更新操作 * * @param itemID * 被删除记录的UUID */ @Override public void delete(String itemID) { manager.delete(itemID); } /** * 描述: 分页查询 * * @param values * 查询条件集合,各个条件为and的关系 * @param startRow * 开始行 * @param endRow * 结束行 * @return 返回查询结果集合 */ @Override public List<ConsignmentAgreementTemplate> doQuery( Map<String, Object> values, int startRow, int endRow) { List criteria = (List) values.remove("criteria"); if (criteria != null) { return filterManager.doQueryFilter( ConsignmentAgreementTemplate.class, criteria, startRow, endRow); } return manager.doQuery(values, startRow, endRow); } /** * 描述: 分页查询 * * @param startRow * 开始行 * @param endRow * 结束行 * @return 返回查询的结果集合 */ @Override public List<ConsignmentAgreementTemplate> getList(int startRow, int endRow) { return manager.getList(startRow, endRow); } }
Shell
UTF-8
1,950
3.796875
4
[ "CC0-1.0" ]
permissive
#!/bin/bash BRIDGE="${1}" SCRIPT=$(readlink -f $0) SCRIPTPATH=$(dirname ${SCRIPT}) CFG_FILE="${SCRIPTPATH}/../etc/of-flows.txt" cd ${SCRIPTPATH}/../etc if [[ ! -d .git ]]; then echo "Initializing the Openflow configuration repository" [ -f /tmp/openflow.lastcommitted ] && rm /tmp/openflow.lastcommitted git init git config user.name "System" git config user.email "me@foo.org" echo "foo.sh" > .gitignore git add .gitignore fi git add ${CFG_FILE} git commit -m "fix" CURRENT=$(git log -1 --pretty=format:"%h") if [[ ! -f /tmp/openflow.lastcommitted ]]; then echo "Performing a full load ..." ovs-ofctl del-flows --protocols=OpenFlow10,OpenFlow13 ${BRIDGE} while IFS= read -r line do [[ "$line" =~ ^#.*$ ]] && continue COMMAND=$(echo $line | sed "s/^\"/ovs-ofctl add-flow ${BRIDGE} --protocols=OpenFlow10,OpenFlow13 \"/g") [ -n "${COMMAND}" ] && echo "Executing '${COMMAND}'" eval ${COMMAND} done < ${CFG_FILE} else PREVIOUS=$(cat /tmp/openflow.lastcommitted) #echo PREVIOUIS=$PREVIOUS #=$(git log -2 --pretty=format:"%h"|tail -n 1) if [[ "${CURRENT}" == "$PREVIOUS" ]]; then echo "We are alread at $PREVIOUS, so there's nothing to do, ... exiting" exit 0 fi ADD=$(git diff $PREVIOUS..$CURRENT |grep -- '+"') REMOVE=$(git diff $PREVIOUS..$CURRENT |grep -- '-"') #echo CURRENT=$CURRENT #echo PREVIOUS=$PREVIOUS while IFS= read -r line do COMMAND=$(echo $line| sed "s+^-\"\(cookie=0x[0-9]*\).*+ovs-ofctl del-flows ${BRIDGE} --protocols=OpenFlow10,OpenFlow13 \"\1/-1\"+") [ -n "${COMMAND}" ] && echo "Executing '${COMMAND}'" eval ${COMMAND} done <<< "$REMOVE" while IFS= read -r line do #echo $line COMMAND=$(echo $line | sed "s/^+\"/ovs-ofctl add-flow ${BRIDGE} --protocols=OpenFlow10,OpenFlow13 \"/g") [ -n "${COMMAND}" ] && echo "Executing '${COMMAND}'" eval ${COMMAND} done <<< "$ADD" fi echo ${CURRENT} > /tmp/openflow.lastcommitted
Java
UTF-8
7,958
2.46875
2
[]
no_license
package de.ees.group1.cs.controller; import java.util.ListIterator; import de.ees.group1.bt.BT_manager; import de.ees.group1.com.IControlStation; import de.ees.group1.cs.gui.IConnectionController; import de.ees.group1.cs.gui.IOrderController; import de.ees.group1.cs.gui.MainWindow; import de.ees.group1.model.OrderList; import de.ees.group1.model.ProductionOrder; import de.ees.group1.model.ProductionStep; import de.ees.group1.model.WorkstationType; public class ControlStation implements IOrderController, IControlStation, IConnectionController{ private ProductionOrder currentOrder; private ProductionStep currentStep; private int currentStepNumber; private OrderList list; private int statusNXT; private BT_manager btManager; private WorkingStationAll workingStation; private MainWindow mainWindow; private boolean isInWaitingPosition; private WorkingStation currentWorkStation; public ControlStation(MainWindow mainWindow){ this.mainWindow=mainWindow; mainWindow.registerConnectionController(this); btManager=new BT_manager(); btManager.register(this); //Erzeugt die vier Arbeitsstationen workingStation=new WorkingStationAll(); for (int i = 0; i < 4; i++) { new WorkingStation(btManager, i+1, workingStation); } //Erzeugt OrderList list=new OrderList(); btManager.connectWithDevice("00:16:53:05:65:FD"); //Test currentOrder = new ProductionOrder(0); currentStep=new ProductionStep(WorkstationType.DRILL, 1,2); currentOrder.add(currentStep); currentStep=new ProductionStep(WorkstationType.LATHE, 3,2); currentOrder.add(1,currentStep); currentStep=new ProductionStep(WorkstationType.DRILL, 1,3); currentOrder.add(2,currentStep); list.setProductionOrder(currentOrder); currentOrder = new ProductionOrder(3); currentStep=new ProductionStep(WorkstationType.DRILL, 1,2); currentOrder.add(currentStep); currentStep=new ProductionStep(WorkstationType.LATHE, 4,2); currentOrder.add(1,currentStep); currentStep=new ProductionStep(WorkstationType.DRILL, 1,3); currentOrder.add(2,currentStep); list.setProductionOrder(currentOrder); currentOrder=new ProductionOrder(45); currentStep=new ProductionStep(WorkstationType.DRILL,3,4); currentOrder.add(currentStep); currentStep=new ProductionStep(WorkstationType.LATHE,2,3); currentOrder.add(currentStep); list.setProductionOrder(currentOrder); workingStation.workstationQualityUpdatedAction(1, 1); workingStation.workstationQualityUpdatedAction(2, 1); workingStation.workstationQualityUpdatedAction(3, 3); workingStation.workstationQualityUpdatedAction(4, 3); workingStation.workstationTypeUpdatedAction(1, WorkstationType.DRILL); workingStation.workstationTypeUpdatedAction(2, WorkstationType.LATHE); workingStation.workstationTypeUpdatedAction(3, WorkstationType.DRILL); workingStation.workstationTypeUpdatedAction(4, WorkstationType.LATHE); reachedParkingPositionInd(21); //btManager.transmitProductionOrder(currentOrder); //*/ } public BT_manager getManager(){ return this.btManager; } /* * �bergibt den gerade an den NXT �bermittleten Auftrag an die ControlStation */ public void setCurrentOrder(){ currentOrder=list.getFirstOrder(); currentStepNumber=0; } /* * F�gt der Liste mit den ProductionOrder einen neuen Auftrag zu. */ public void addProductionOrder(ProductionOrder order){ list.setProductionOrder(order); } public int getStatusNXT(){ return statusNXT; } public void evaluateStatusNXT(){ int status=getStatusNXT(); if ((0<status) & (status<=22)){ switch (status){ case 1: case 5: case 9: case 13: case 17: currentWorkStation=workingStation.getWorkingStaion(1); break; case 2: case 6: case 10: case 14: case 18: currentWorkStation=workingStation.getWorkingStaion(2); break; case 3: case 7: case 11: case 15: case 19: currentWorkStation=workingStation.getWorkingStaion(3); break; case 4: case 8: case 12: case 16: case 20: currentWorkStation=workingStation.getWorkingStaion(4); break; case 21: //neuen Auftrag ansto�en break; case 22: //Meldung alles kaputt break; } } if ((0<status) & (status<=20)){ switch (status){ case 1: case 2: case 3: case 4: currentWorkStation.setStatus(1); mainWindow.updateWorkstationState(1); break; case 5: case 6: case 7: case 8: //action to "Weiterfahrt"; break; case 9: case 10: case 11: case 12: //arbeit beginnen; break; case 13: case 14: case 15: case 16: currentWorkStation.setStatus(0); mainWindow.updateWorkstationState(0); currentStepNumber++; if(currentStepNumber<currentOrder.size()){ mainWindow.updateActiveOrder(currentOrder, currentStepNumber); } else{ mainWindow.updateActiveOrder(null,-1); } break; case 17: case 18: case 19: case 20: //arbeit konnte nicht durchgef�hrt werden; break; } } } public void setCurrentStep(ProductionStep step) { currentStep=step; } public ProductionStep getCurrentStep() { return currentStep; } public void orderCreatedAction(ProductionOrder order) { list.add(order); mainWindow.updateOrderList(list); if(isInWaitingPosition==true){ reachedParkingPositionInd(21); } } public void orderRemovedAction(int orderID) { ListIterator<ProductionOrder> iterator=list.listIterator(); while(iterator.hasNext()){ ProductionOrder temp=iterator.next(); if (temp.getId()==orderID){ list.remove(temp); } } mainWindow.updateOrderList(list); } public int getNextOrderId() { return currentStepNumber++; } public void moveOrderDown(int orderID) { int i=0; ListIterator<ProductionOrder> iterator=list.listIterator(); while(iterator.hasNext()&(i==0)){ ProductionOrder temp=iterator.next(); if (temp.getId()==orderID){ if(iterator.hasNext()){ list.remove(temp); int index =iterator.nextIndex(); list.add(index, temp); i=1; } } } mainWindow.updateOrderList(list); } public void moveOrderUp(int orderID) { int i=0; ListIterator<ProductionOrder> iterator=list.listIterator(); while(iterator.hasNext()&(i==0)){ ProductionOrder temp=iterator.next(); if (temp.getId()==orderID){ if(iterator.hasNext()){ list.remove(temp); int index =iterator.nextIndex(); index=index-2; list.add(index, temp); i=1; } } } mainWindow.updateOrderList(list); } public void orderUpdatedAction(ProductionOrder tmp) { ListIterator<ProductionOrder> iterator=list.listIterator(); while (iterator.hasNext()){ ProductionOrder order =iterator.next(); if(order.getId()==tmp.getId()){ iterator.set(tmp); } } mainWindow.updateOrderList(list); } //Auftrag erfolgreich �bertragen, keine Reaktion public void giveAcknowledgement(boolean answer) { } public void transmitActualState(int state) { statusNXT=state; evaluateStatusNXT(); } public void reachedParkingPositionInd(int nextWorkingStep) { if (nextWorkingStep==21){ if(isInWaitingPosition==false){ list.remove(0); } if(list.isEmpty()==false){ currentOrder=list.getFirstOrder(); mainWindow.updateActiveOrder(currentOrder, 0); btManager.transmitProductionOrder(currentOrder); isInWaitingPosition=false; } else{ isInWaitingPosition=true; } } } public void connectBT(String MAC) { btManager.connectWithDevice(MAC); } @Override public void connectBT(byte[] MAC) { // TODO Auto-generated method stub } @Override public void activeOrderCanceledAction() { // TODO Auto-generated method stub } }
Markdown
UTF-8
592
2.671875
3
[]
no_license
# Web programming: __Team Members:__ * Shawn * Tiya * Vaibhav * Madiha * Yousuf __Game:__ * 2D * MMOG ver. of pac-man called PacRace __Game plan (inspired by OG Pac-Man):__ * General overview (see attached img) * On entry to the game, the players will spawn on one corner of the map. * ***The AIM*** of the game is to keep eating the 'pellets' which will randomly spawn on the map. Eat as many pellets as you can, first player to eat all the pellets, wins * 1 pellet = 1 score __Trailer__: *link<src="https://www.youtube.com/watch?v=vQWuWTi61RE&feature=youtu.be">
SQL
UTF-8
2,444
2.859375
3
[]
no_license
insert into Authors (name) select 'Author 1' insert into Authors (name) select 'Author 2' insert into Genres (name) select 'Genre 1' insert into Genres (name) select 'Genre 2' insert into Books (name, author_id) select 'Book 1', a.id from Authors a where a.name = 'Author 1' insert into Books (name, author_id) select 'Book 2', a.id from Authors a where a.name = 'Author 2' insert into Books (name, author_id) select 'Book 3', a.id from Authors a where a.name = 'Author 1' insert into Books (name, author_id) select 'Book 4', a.id from Authors a where a.name = 'Author 2' insert into Book_Genres (book_id, genre_id) select b.id, g.id from Books b, Genres g where b.name = 'Book 1' and g.name = 'Genre 1' insert into Book_Genres (book_id, genre_id) select b.id, g.id from Books b, Genres g where b.name = 'Book 2' and g.name = 'Genre 2' insert into Book_Genres (book_id, genre_id) select b.id, g.id from Books b, Genres g where b.name = 'Book 3' and g.name = 'Genre 2' insert into Book_Genres (book_id, genre_id) select b.id, g.id from Books b, Genres g where b.name = 'Book 4' and g.name = 'Genre 1' insert into Users (name, password, roles) select 'Kermilov', '{bcrypt}$2a$10$qYsehZsH1WTF0AgD6XIc9eWdAn0nLiecpFihfeF1g9DAa/eI5wJoy', 'USER' insert into Users (name, password, roles) select 'OtusTeacher', '{bcrypt}$2a$10$s/S4UgP9rGdZV6HZi5TZsux7xZ//m12/farZ7IR6DtEY07L38F3Va', 'USER' insert into Book_Comments (book_id, user_id, comment) select b.id, u.id, 'Book 1 Comment 1' from Books b, Users u where b.name = 'Book 1' and u.name = 'OtusTeacher' insert into Book_Comments (book_id, user_id, comment) select b.id, u.id, 'Book 1 Comment 2' from Books b, Users u where b.name = 'Book 1' and u.name = 'Kermilov' insert into acl_sid (principal, sid) select 1, u.name from Users u insert into acl_sid (principal, sid) select distinct 0, u.roles from Users u insert into acl_class (class) values ('ru.otus.spring.kermilov.books.domain.BookComment') insert into acl_object_identity (object_id_class, object_id_identity, parent_object, owner_sid, entries_inheriting) select cl.id, bc.id, null, sid.id, 0 from acl_class cl, Book_Comments bc, acl_sid sid where sid.sid = 'USER' insert into acl_entry (acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_failure) select aoi.id, 0, sid.id, 16, 1, 0, 0 from acl_object_identity aoi, Book_Comments bc, Users u, acl_sid sid where bc.id = aoi.object_id_identity and u.id = bc.user_id and sid.sid = u.name
Ruby
UTF-8
281
3.4375
3
[]
no_license
require 'pry' class Human attr_accessor :name, :game_symbol, :go_first def initialize(game_symbol) @name = name @game_symbol = game_symbol # The instance variable below is used in the coin_toss method to check for who goes first. @go_first = false end end
Java
UTF-8
644
2.21875
2
[]
no_license
package com.hami.sys.jdbc.record; import java.io.Serializable; import java.util.List; /** * <pre> * <li>Program Name : RecordSet * <li>Description : * <li>History : 2018. 2. 17. * </pre> * * @author HHG */ public interface RecordSet extends Serializable, List { public abstract RecordMetadata getMetadata(); public abstract int getRowCount(); public abstract int getColumnCount(); public abstract Iterable<?> getColumns(); public abstract Record getRecord(int i); public abstract Object[] getRow(int i); public abstract Record addRecord(); public abstract Object getValue(int i, int j); }
Java
UTF-8
5,046
2.484375
2
[]
no_license
package il.ac.technion.cs.sd.app.mail; import org.apache.commons.io.FileUtils; import com.google.gson.stream.JsonWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import il.ac.technion.cs.sd.lib.clientserver.Server; /** * The server side of the TMail application. <br> * This class is mainly used in our tests to start, stop, and clean the server */ public class ServerMailApplication { private Server _server; private ServerTaskMail _task; private PersistentConfig _persistentConfig; /** * Starts a new mail server. Servers with the same name retain all their information until * {@link ServerMailApplication#clean()} is called. * * @param name The name of the server by which it is known. */ public ServerMailApplication(String name) { _server = new Server(name); _persistentConfig = new DefaultPersistentConfig(); } void setServer(Server s) { _server = s; } // default PersistentConfig: default text file is used. private class DefaultPersistentConfig implements PersistentConfig { @Override public InputStream getPersistentMailInputStream() throws IOException { File file = getServerPesistentFilename(); if (!file.exists()) { clearAndInitPersistentDataFile(); } assert(file.exists()); return new FileInputStream(file); } @Override public OutputStream getPersistentMailOverwriteOutputStream() throws FileNotFoundException { File file = getServerPesistentFilename(); getPesistentDirOfAllServers().mkdirs(); return new FileOutputStream(file,false); } } //TODO: maybe have all persistent content logic in a seperate module. private void clearAndInitPersistentDataFile() throws IOException { getPesistentDirOfAllServers().mkdirs(); File file = getServerPesistentFilename(); OutputStream stream = new FileOutputStream(file, false); JsonWriter writer = new JsonWriter(new OutputStreamWriter(stream, "UTF-8")); writer.beginArray(); writer.endArray(); writer.close(); } private static File getPesistentDirOfAllServers() { return new File("./TMP___ServersData"); } private File getServerPesistentFilename() { String baseName = _server.getserverAddress() + ".txt"; return new File(getPesistentDirOfAllServers(), baseName); } public void setPersistentConfig (PersistentConfig persistentConfig) { _persistentConfig = persistentConfig; } /** * @return the server's address; this address will be used by clients connecting to the server */ public String getAddress() { return _server.getserverAddress(); } /** * Starts the server; any previously sent mails, data and indices under this server name are loaded. It is possible * to start a new server instance in same, or another process. You may assume that two server instances with the * same name won't be in parallel. Similarly, {@link ServerMailApplication#stop()} will be called before subsequent * calls to {@link ServerMailApplication#start()}. * @throws ListenLoopAlreadyBeingDone */ public void start() { try { _task = new ServerTaskMail(_persistentConfig); _task.loadPersistentData(); _server.startListenLoop(_task); } catch (IOException e) { throw new IOExceptionRuntime(); } catch (InterruptedException e) { throw new InterruptedExceptionRuntime(); } } /** * Stops the server. A stopped server can't accept mail, but doesn't delete any data. A stopped server does not use * any system resources (e.g., messengers). * @throws NoCurrentListenLoop. */ public void stop() { try { _server.stopListenLoop(); if (_task != null) _task.savePersistentData(); } catch (IOException e) { throw new IOExceptionRuntime(); } catch (InterruptedException e) { throw new InterruptedExceptionRuntime(); } } /** * Deletes <b>all</b> previously saved data. This method will be used between tests to assure that each test will * run on a new, clean server. you may assume the server is stopped before this method is called. */ public void clean() { try { clearAndInitPersistentDataFile(); } catch (IOException e) { throw new IOExceptionRuntime(); } } /* Removes current content of servers data directory (if currently exists) * and makes sure the directory exists. */ public static void cleanAndInitPersistentDataDirOfAllServers() { File persistentDataDir = getPesistentDirOfAllServers(); if (persistentDataDir.exists()) { try { FileUtils.deleteDirectory(persistentDataDir); } catch (IOException e) { throw new IOExceptionRuntime(); } } persistentDataDir.mkdirs(); } public static class InterruptedExceptionRuntime extends RuntimeException {private static final long serialVersionUID = 1L;} public static class IOExceptionRuntime extends RuntimeException {private static final long serialVersionUID = 1L;} }
Java
UTF-8
1,245
3.109375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package problema1; import java.util.Locale; import java.util.Scanner; /** * * @author Usuario iTC */ public class Problema1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner entrada= new Scanner(System.in); entrada.useLocale(Locale.US); double vKilovatios; double kConsumidos; double total; int edad; double porcentaje = 10; double descuento; System.out.println("Ingresar el costo de kilovatios por hora"); vKilovatios= entrada.nextDouble(); System.out.println("Ingrese los kilovatios consumidos al mes"); kConsumidos= entrada.nextDouble(); System.out.println("Ingrese edad"); edad= entrada.nextInt(); total= vKilovatios * kConsumidos; if(edad >5){ descuento= (porcentaje*total)/100; total= total - descuento; } System.out.println("El valor total a pagar es:" +total); } }
JavaScript
UTF-8
915
2.640625
3
[ "MIT" ]
permissive
import DataLoader from 'dataloader'; export async function getMultipleMongoDocuments({ documentIds, collectionName, mongo }) { const documents = await mongo .collection(collectionName) .find({ _id: { $in: documentIds } }) .toArray(); // return documents in order they were queried because that's how dataloader knows // which id correlates to what. Return null if mongo has no doc for a specific id // TODO because this always is a sequential search maybe use something similar to // https://github.com/facebook/dataloader/blob/master/examples/RethinkDB.md return documentIds.map(documentId => { return documents.find(doc => doc._id === documentId) || null; }); } export function createMongoLoader({ collectionName, mongo }) { return new DataLoader(documentIds => getMultipleMongoDocuments({ documentIds, collectionName, mongo }) ); }
TypeScript
UTF-8
2,865
3.40625
3
[]
no_license
"use strict"; (function(): void{ let color: string = "green"; let color2: string = "black"; let squareSizeNum: number = 100; let squareSize: string = squareSizeNum + 'px'; let changeColorB: boolean = true; let button: Element = document.createElement('button'); let div: Element = document.createElement('div'); (div as HTMLElement).style.width = squareSize; (div as HTMLElement).style.height = squareSize; (div as HTMLElement).style.border = '1px solid black'; // button.textContent = 'Change color'; // document.body.appendChild(button); // document.body.appendChild(div); // let colorChange: Function = function(elem: Element,color:string):boolean { // (elem as HTMLElement).style.backgroundColor = color; // return true; // }; // (button as HTMLElement).onclick = function(event:Event){ // if (changeColorB){ // colorChange(div,color); // changeColorB = !changeColorB; // } else { // colorChange(div,color2); // changeColorB = !changeColorB; // }; // }; //****************************** Excersise 2 starts: class colorChange2{ div:Element; constructor(div:Element){ this.div = div; }; changeColor(color:string): boolean{ (this.div as HTMLElement).style.backgroundColor = color; return true; }; }; interface ElementSet{ div: Element; button: Element; }; let Element: ElementSet = { div: document.createElement('div'), button: document.createElement('button') }; enum Colors{ Green, Red, Blue, Orange }; class numericColor extends colorChange2 { static Colors = Colors; constructor(div: Element) { super(div); (this.div as HTMLElement).style.width = squareSize; (this.div as HTMLElement).style.height = squareSize; }; }; let elementSets: Array<ElementSet> = []; for (let i:number = 0;i<4;i++){ elementSets.push({ div: document.createElement('div'), button: document.createElement('button') }); }; elementSets.map(function(elem,index){ let colorChangeClass = new colorChange2(elem.div); (elem.div as HTMLElement).style.width = squareSize; (elem.div as HTMLElement).style.height = squareSize; (elem.div as HTMLElement).style.border = '1px solid black'; elem.button.textContent = 'Change Color'; (elem.button as HTMLElement).onclick = function(elem){ colorChangeClass.changeColor(Colors[index]); }; document.body.appendChild(elem.button); document.body.appendChild(elem.div); }); })();
Go
UTF-8
762
4.40625
4
[]
no_license
package main import "fmt" /* 1.关于 channel,下面语法正确的是() A. var ch chan int B. ch := make(chan int) C. <- ch D. ch <- 答案:ABC A、B都是声明channel C 读取channel 写 channel必须带上值,所以D错误 */ /* 2.下面这段代码输出什么? A. 0 B. 1 C. Compilation error type person struct { name string } func main() { var m map[person] int p := person{"mike"} fmt.Println(m[p]) } 答案:输出 0 打印一个 map 中不存在的值时,返回元素类型的零值,m中不存在p */ /* 3.下面这段代码输出什么? A. 18 B. 5 C. Compilation error */ func hello(num ...int) { num[0] = 18 } func main() { i := []int{5,6,7} hello(i...) fmt.Println(i[0]) } /* 答案:18 可变函数 */
PHP
UTF-8
2,079
2.734375
3
[]
no_license
<?php /* ** Definit une option. ** ** @package Ninaca ** @author Nivl <nivl@free.fr> ** @started 09/02/2009, 04:57 PM ** @last Nivl <nivl@free.fr> 03/28/2010, 04:23 PM ** @link http://nivl.free.fr ** @copyright Copyright (C) 2009 Laplanche Melvin ** ** This program 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 3 of the License, or ** (at your option) any later version. ** ** This program 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/>. */ class TaskOption { const BOOL = 1; const TEXT = 2; protected $type = self::TEXT, $name = null, $value = null, $default = null, $shortcut = null, $description = null; public function __construct($name, $description, $default, $shortcut = null, $type = self::TEXT) { $this->name = $name; $this->description = _($description); $this->type = $type; $this->default = $default; $this->shortcut = $shortcut; if ( !in_array($type, array(self::BOOL, self::TEXT)) ) $this->type = self::TEXT; } public function setValue($val) { return $this->value = $val; } public function hasValue() { return $this->value !== null; } public function hasShortcut() { return $this->shortcut !== null; } public function getName() { return $this->name; } public function getDescription() { return $this->description; } public function getValue() { return $this->value ?: $this->default; } public function getShortcut() { return $this->shortcut; } public function isBool() { return $this->type === self::BOOL; } }
C#
UTF-8
2,572
2.65625
3
[]
no_license
//FILE : BattleUnit.cs //PROJECT : Will of the Woods //PROGRAMMER : Gavin McGuire //FIRST VERSION : 06/12/2019 using System.Collections; using System.Collections.Generic; using UnityEngine; //NAME : BattleUnit //PURPOSE : interact with other units for the final battle [System.Serializable] public class BattleUnit { protected int unitTier; protected bool defeated; private bool fought; private bool spawned; private const int MINRANGE = 0; private const int MAXRANGE = 20; public BattleUnit(int tier) { unitTier = tier; defeated = false; fought = false; spawned = false; WaveManager.StartWave += StartWave; } //Function : SkillCheck //DESCRIPTION : adds a random value in range to unit tier //PARAMETERS : none //RETURNS : int : indicating battle performance public int SkillCheck() { fought = true; return (unitTier + Random.Range(MINRANGE, MAXRANGE)); } //Function : Weaken //DESCRIPTION : lowers unit's tier by a set amount //PARAMETERS : int amount : the amount by which to reduce the tier //RETURNS : none public void Weaken(int amount) { unitTier -= amount; } //Function : Defeat //DESCRIPTION : Sets bool that marks the unit's defeat //PARAMETERS : none //RETURNS : none public void Defeat() { defeated = true; } //Function : IsDefeated //DESCRIPTION : returns the bool that marks the unit's defeat //PARAMETERS : none //RETURNS : bool defeated : indicating whether the public bool IsDefeated() { return defeated; } //Function : HasFought //DESCRIPTION : returns whether the unit has fought this wave or no //PARAMETERS : none //RETURNS : bool fought : indicates if the unit has fought this round public bool HasFought() { return fought; } //Function : Spawn //DESCRIPTION : sets the unit so it has spawned //PARAMETERS : none //RETURNS : none public void Spawn() { spawned = true; } //Function : HasSpawned //DESCRIPTION : returns a bool stating whether the unit has spawned //PARAMETERS : none //RETURNS : bool spawned : indicates if the unit has spawned public bool HasSpawned() { return spawned; } //Function : WaveStart //DESCRIPTION : prepares unit for new wave cycle //PARAMETERS : none //RETURNS : none private void StartWave() { fought = false; } }
Python
UTF-8
3,249
2.59375
3
[ "Apache-2.0" ]
permissive
import datetime import json import os import time import pandas as pd from config import * def encode_text(word_map, c): return [word_map.get(word, word_map['<unk>']) for word in c] + [word_map['<end>']] class Lang: def __init__(self, filename): word_map = json.load(open(filename, 'r')) self.word2index = word_map self.index2word = {v: k for k, v in word_map.items()} self.n_words = len(word_map) class AverageMeter(object): """ Keeps track of most recent, average, sum, and count of a metric. """ def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count # Exponentially weighted averages class ExpoAverageMeter(object): # Exponential Weighted Average Meter def __init__(self, beta=0.9): self.reset() def reset(self): self.beta = 0.9 self.val = 0 self.avg = 0 self.count = 0 def update(self, val): self.val = val self.avg = self.beta * self.avg + (1 - self.beta) * self.val def adjust_learning_rate(optimizer, shrink_factor): """ Shrinks learning rate by a specified factor. :param optimizer: optimizer whose learning rate must be shrunk. :param shrink_factor: factor in interval (0, 1) to multiply learning rate with. """ print("\nDECAYING learning rate.") for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr'] * shrink_factor print("The new learning rate is %f\n" % (optimizer.param_groups[0]['lr'],)) def ensure_folder(folder): if not os.path.exists(folder): os.makedirs(folder) def save_checkpoint(epoch, encoder, optimizer, val_acc, is_best): ensure_folder(save_folder) state = {'encoder': encoder, 'optimizer': optimizer} if is_best: filename = '{0}/checkpoint_{1}_{2:.3f}.tar'.format(save_folder, epoch, val_acc) torch.save(state, filename) # If this checkpoint is the best so far, store a copy so it doesn't get overwritten by a worse checkpoint torch.save(state, '{}/BEST_checkpoint.tar'.format(save_folder)) def encode_text(word_map, c): return [word_map.get(word, word_map['<unk>']) for word in c] + [word_map['<end>']] def accuracy(scores, targets, k=1): batch_size = targets.size(0) _, ind = scores.topk(k, 1, True, True) correct = ind.eq(targets.view(-1, 1).expand_as(ind)) # print('correct: ' + str(correct)) correct_total = correct.view(-1).float().sum() # 0D tensor return correct_total.item() * (100.0 / batch_size) def parse_user_reviews(split): if split == 'train': filename = os.path.join(train_folder, train_filename) elif split == 'valid': filename = os.path.join(valid_folder, valid_filename) else: filename = os.path.join(test_a_folder, test_a_filename) user_reviews = pd.read_csv(filename) return user_reviews def timestamp(): return datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
Java
UTF-8
1,467
3.171875
3
[]
no_license
package org.alien8.client; import java.io.IOException; import java.io.ObjectInputStream; import org.alien8.core.ServerMessage; public class ClientTCP extends Thread { private ObjectInputStream fromServer; private volatile boolean run = true; /** * Constructor * * @param fromServer Input Stream for reading data from server */ public ClientTCP(ObjectInputStream fromServer) { this.fromServer = fromServer; } /** * Run loop to keep reading info from server through TCP channel */ public void run() { while (run) { try { ServerMessage msg = (ServerMessage) fromServer.readObject(); if (msg.getType() == 0) { // Game ended Client.getInstance().waitToExit(); } else if (msg.getType() == 1) { // Time before exiting Client.getInstance().setTimeBeforeExiting(msg.getTimeBeforeExiting()); } else if (msg.getType() == 2) { // Server stopped Client.getInstance().disconnect(); } else if (msg.getType() == 3) { // Start game Client.getInstance().setState(Client.State.IN_GAME); } } catch (IOException ioe) { // Unexpected disconnection or other I/O errors Client.getInstance().disconnect(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } System.out.println("Client TCP thread ended"); } /** * Stop the thread */ public void end() { this.run = false; } }
Shell
UTF-8
247
2.6875
3
[]
no_license
#!/bin/bash HOST=$1 destination_ingresses="server frontend image-server" for ing in $destination_ingresses; do kubectl patch ingress $ing --type='json' -p "[{\"op\": \"replace\", \"path\": \"/spec/rules/0/host\", \"value\": \"$HOST\"}]" done
TypeScript
UTF-8
1,412
2.515625
3
[]
no_license
import { Injectable } from '@angular/core'; import {PicketReport} from "../tachymetry/models/tachymetry-report/picket-report.model"; import {LatLngLiteral} from "@agm/core"; @Injectable() export class UtilsService { createErrorMessage(errors) { let errorMessage = ''; errors.forEach(error => { if (error.message) { errorMessage = 'Error message: ' + error.message + '\n'; } if (error.field) { errorMessage += 'Error field: ' + error.field + '\n'; } if (error.reasons && error.reasons.length) { errorMessage += 'Reasons: \n'; error.reasons.forEach(reason => { if (reason.message) { errorMessage += reason.message + '\n'; } }); } }); return errorMessage; } calculateControlPointsDistance(startingPoint: PicketReport, endPoint: PicketReport): number { const res1 = Math.pow((endPoint.latitude - startingPoint.latitude), 2); const res2 = Math.pow((Math.cos(((startingPoint.latitude * Math.PI) / 180)) * (endPoint.longitude - startingPoint.longitude)), 2); return +((Math.sqrt(res1 + res2)) * (40075.704 / 360) * 1000).toFixed(2) ; } createPath(picketFrom: PicketReport, picketTo: PicketReport): LatLngLiteral[] { return [ { lat: picketFrom.latitude, lng: picketFrom.longitude }, { lat: picketTo.latitude, lng: picketTo.longitude } ]; } }
Java
UTF-8
5,209
3.203125
3
[]
no_license
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.*; import java.util.concurrent.TimeUnit; import javax.swing.*; import javax.swing.event.MouseInputListener; public class GameOfLifeClass implements ActionListener{ private JFrame frame; private int[][] cells=new int[116][78]; private Thread gamePlay; private JButton startButton,stopButton,resetButton; private Board board; /** * Launch the application. */ public static void main(String[] args) { GameOfLifeClass window = new GameOfLifeClass(); window.frame.setVisible(true); } /** * Create the application. */ public GameOfLifeClass() { initialize(); } /** * Initialize the contents of the frame. */ public void initialize() { frame = new JFrame(); frame.setTitle("Game Of Life"); frame.setSize(1286,829); frame.setVisible(true); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); board=new Board(); frame.setContentPane(board); startButton = new JButton("Start"); startButton.addActionListener(this); stopButton = new JButton("Stop"); stopButton.addActionListener(this); resetButton = new JButton("Reset"); resetButton.addActionListener(this); frame.add(startButton); frame.add(stopButton); frame.add(resetButton); } @Override //Listens for any event triggered by the buttons. public void actionPerformed(ActionEvent e) { if (e.getSource().equals(resetButton)) gameReset(); else if(e.getSource().equals(startButton)) { gamePlay=new Thread(board); gamePlay.start(); } else gamePlay.interrupt(); } //Function for resetting the grid public void gameReset() { cells=new int[116][78]; frame.repaint(); } /** * Initialize JPanel Class to listen to Mouse event and update the grid with the surviving cells. */ public int space=1; public int mx=-100; public int my=-100; public class Board extends JPanel implements MouseMotionListener,MouseListener,Runnable{ public Board() { addMouseListener(this); addMouseMotionListener(this); } public void paintComponent(Graphics g) { //Fills cell with red if the cell is alive for(int i=5;i<=115;i++) { for(int j=5;j<=77;j++) { if(cells[i][j]==1) { g.setColor(Color.red); g.fillRect((10*i+10),(10*j+10), 10, 10); } } } // Painting the Grid g.setColor(Color.BLACK); for (int i=5; i<=115; i++) g.drawLine(((i*10)+10), 60, (i*10)+10, 10 + (10*75)); for (int i=5; i<=75; i++) g.drawLine(60, ((i*10)+10), 10*(115+1), ((i*10)+10)); } //run() function is automatically called whenever a thread starts. public void run() { int count,x,y; int [][]b=new int[116][78]; for( x=5; x<115 ; x++) { for( y=5; y<75 ; y++) { count = 0; if(cells[x+1][y] == 1 && (x+1)<115) // next element in the row count++; if(cells[x-1][y] == 1 && (x-1)>5) // previous element in row count++; if(cells[x][y+1] == 1 && (y+1)<75) // element above it count++; if(cells[x][y-1] == 1 && (y-1)>5) // element below it count++; if(cells[x+1][y+1] == 1 && (x+1)<115 && (y+1)<75) // element to bottom right count++; if(cells[x+1][y-1] == 1 && (x+1)<115 && (y+1)>5) // element to bottom left count++; if(cells[x-1][y+1] == 1 && (x-1)>5 && (y+1)<115) // element top right count++; if(cells[x-1][y-1] == 1 && (x-1)>5 && (y-1)>5) // element top left count++; if(cells[x][y] == 1) { if(count>=4) // over population death b[x][y]=0; else if( count>=2) // remains alive b[x][y]=1; else // death due to solitude b[x][y]=0; } else if(cells[x][y]==0) if(count == 3) // population condition b[x][y]=1; else b[x][y]=0; } } gameReset(); cells=b; frame.repaint(); try { Thread.sleep(1000/5);//Adds a delay to the game for better visualization of the simulation run(); } catch (InterruptedException ex) {} } public void mouseClicked(MouseEvent e) { mx=e.getX()/10-1; my=e.getY()/10-1; if(cells[mx][my]==1) cells[mx][my]=0; frame.repaint(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { mx=e.getX()/10-1; my=e.getY()/10-1; frame.repaint(); } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { mx=e.getX()/10-1; my=e.getY()/10-1; cells[mx][my]=1; frame.repaint(); } @Override public void mouseMoved(MouseEvent e) { } } }
Python
UTF-8
1,602
3.671875
4
[]
no_license
# 爬取最好大学网上的大学排名信息 (定向爬虫) # 1. 从网络上获取大学排名网页内容 getHTMLText() # 2. 提取网页内容中信息到合适的数据结构 fillUnivList() # 3. 利用数据结构展示并输出结果 printUnivList() # BeautifulSoup只是bs4库中的一个类 import bs4 container = "html.parser" import requests from bs4 import BeautifulSoup def getHTMLText(url): try: r = requests.get(url) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return "" def fillUnivList(ulist, html): soup = BeautifulSoup(html, container) for t in soup.find("tbody").children: if isinstance(t, bs4.element.Tag): tds = t("td") # print(tds) # 在列表ulist中的添加字段 ulist.append([tds[0].string, tds[1].string, tds[2].string, tds[3].string]) def printUnivList(ulist, num): tplt = "{0:^10}\t{1:{4}^10}\t{2:^10}\t{3:{4}^10}" print(tplt.format("排名", "学校名称", "地点", "总分", chr(12288))) for i in range(num): u = ulist[i] print(tplt.format(u[0] if u[0] else "", u[1] if u[1] else "", u[2] if u[2] else "", u[3] if u[3] else "", chr(12288))) def main(): uinfo = [] url = "http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html" html = getHTMLText(url) fillUnivList(uinfo, html) # top 20 printUnivList(uinfo, 20) if __name__ == "__main__": main()
Ruby
UTF-8
527
2.75
3
[]
no_license
require "net/http" require "uri" def to_log(output, result) File.open("./result.txt", "a") do |f| f.puts "Test case: Update user #{output} , #{result} " end end uri = URI('http://localhost:3000/api/users/30') req = Net::HTTP::Put.new(uri) req.set_form_data({ "email": "test@update.com", "first_name": "lana", "last_name": "ch" }) resp = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end case resp when Net::HTTPSuccess, Net::HTTPRedirection to_log('PASS',resp.code) else to_log('FAIL',resp.code) end
Java
UTF-8
1,956
2.46875
2
[ "Apache-2.0" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package USAirlines.Q3; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; /** * * @author priyankb */ public class Q3Combiner extends Reducer<Text, Q3MapperOutput, Text, Q3MapperOutput> { Map<String, Integer> data = new HashMap(); @Override protected void reduce(Text key, Iterable<Q3MapperOutput> mapperOutputs, Context context) throws IOException, InterruptedException { String year = key.toString(); for (Q3MapperOutput mapperOutput : mapperOutputs) { int year2 = mapperOutput.getYear().get(); String airport = mapperOutput.getAirport().toString(); int numFlights = mapperOutput.getNumFlights().get(); if (year2 == -1 && numFlights == -1) { context.write(key, mapperOutput); } else { if (!data.containsKey(airport)) { data.put(airport, numFlights); } else { Integer flights = data.get(airport); flights += numFlights; data.put(airport, flights); } } } for (Map.Entry<String, Integer> entrySet : data.entrySet()) { String airport = entrySet.getKey(); int numFlights = entrySet.getValue(); Q3MapperOutput mapperOutput = new Q3MapperOutput(); mapperOutput.setYear(new IntWritable(Integer.parseInt(year))); mapperOutput.setAirport(new Text(airport)); mapperOutput.setNumFlights(new IntWritable(numFlights)); context.write(new Text(year), mapperOutput); } } }
PHP
UTF-8
559
2.703125
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Message extends Model { use SoftDeletes; /** * 資料表可輸入的屬性。 * * @var array */ protected $fillable = [ 'name', 'title', 'content', 'avatar' ]; /** * Message表、Replies表 建立關聯。 * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function replys() { return $this->hasMany(Replies::class, 'message_id'); } }
TypeScript
UTF-8
2,596
3.359375
3
[]
no_license
import * as expr from 'expression-eval'; import { AST, VariableValues, Expression, Identifier } from './'; /** * returns true if the expression can be evaluated in this context. * NOTE: Does not perform type checking, so no guarantee is made * that an expression will evaluate to a reasonable value * @param ast * @param context */ function every( element: Array<boolean> ) { for ( let result of element ) { if ( result === false ) return false; } return true; } export function canEvaluate( ast: AST, context: VariableValues = {} ): boolean { let localThis = this; function can( ast: AST ) { switch ( ast.type ) { case "Literal": return true; case "Identifier": return context.hasOwnProperty( ast.name ); case "BinaryExpression": return ( can( ast.left ) && can( ast.right ) ); case "LogicalExpression": return ( can( ast.left ) && can( ast.right ) ); case "UnaryExpression": return can( ast.argument ); case "ArrayExpression": return every( ast.elements.map( (e) => can( e ) ) ); case "MemberExpression": if ( ! can( ast.object ) ) return false; let object = expr.eval.apply( localThis, [ ast.object, context ] ); let property; if ( ast.computed ) { if ( ! can( ast.property ) ) return false; property = expr.eval.apply( localThis, [ ast.property, context ] ); } else { property = ((ast.property) as Identifier ).name; } return object.hasOwnProperty(property); case "ThisExpression": return true; case "CallExpression": return ( can( ast.callee ) && every( ast.arguments.map( (e) => can( e ) ) ) && typeof( expr.eval.apply( localThis, [ ast.callee, context ] ) ) === "function" ); case "ConditionalExpression": return ( can( ast.test ) && can( ast.consequent ) && can( ast.alternate ) ); default: return false; } } return can( ast ); }
JavaScript
UTF-8
1,197
2.640625
3
[]
no_license
const fs = require('fs').promises; const express = require('express'); const app = express(); app.use(express.json()); app.use(express.static('../client/build')); const path = './data.json'; app.get('/api/tickets', async (req, res) => { const tickets = await fs.readFile(path); const ticketsJson = JSON.parse(tickets); if (!req.query.searchText) { res.send(ticketsJson); } else { const ticketsArray = ticketsJson.filter((item) => item.title.toLowerCase().includes(req.query.searchText.toLowerCase())); res.send(ticketsArray); } }); app.post('/api/tickets/:ticketId/:done', async (req, res) => { const tickets = await fs.readFile(path); let ticketsJson = JSON.parse(tickets); let updated = false; const done = req.params.done === "done" try { const ticketsArray = ticketsJson.map((item) => { if (item.id === req.params.ticketId) { if (item.done !== done) { item.done = done; updated = true; } } return item; }); ticketsJson = JSON.stringify(ticketsArray); await fs.writeFile(path, ticketsJson); res.send({ updated }); } catch (e) { res.send({ updated: false })} }) module.exports = app;
Java
UTF-8
452
2.875
3
[]
no_license
//셀프넘버 package algo; public class Boj4673 { public static void main(String[] args) { boolean[] chk = new boolean[10001]; for (int i = 1; i <= 10000; i++) { int a = i / 1000; int b = (i / 100) % 10; int c = (i / 10) % 10; int d = i % 10; int next = a + b + c + d + i; if (next > 10000) continue; chk[next] = true; } for (int i = 1; i <= 10000; i++) { if (!chk[i]) System.out.println(i); } } }
Markdown
UTF-8
9,457
2.625
3
[]
no_license
# BUILD YOUR DREAM ROSTER [LIVE][roster] - Author: Zidian Lyu - Apr-2017 - Credit to: Nick Gassmann && The Harker School ## Overviews ### Introduction - Page View ![](https://github.com/zidianlyu/BaseballTeamBuilder/blob/master/asset/img/intro.png) ### BuildForm - Page View ![](https://github.com/zidianlyu/BaseballTeamBuilder/blob/master/asset/img/build_form.png) ### PrintForm - Page View ![](https://github.com/zidianlyu/BaseballTeamBuilder/blob/master/asset/img/print_form.png) ## Features && Implementations ### Framework - This project is built on [React.js](https://facebook.github.io/react/) - Webpack dependencies ```javascript "babel-core": "^6.24.1", "babel-loader": "^7.0.0", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "babel-preset-stage-1": "^6.24.1", "lodash": "^4.17.4", "react": "^15.5.4", "react-dom": "^15.5.4", "react-redux": "^5.0.4", "react-router": "^4.1.1", "redux": "^3.6.0", "webpack": "^2.4.1", "webpack-dev-server": "^2.4.2" ``` ### Page Structure - Homepage - loader - navbar - main content - intro section - build form section - print form section ### Component Managements - Add event listener on DOM content ```javascript document.addEventListener('DOMContentLoaded', () => { ReactDOM.render( <Root/>, document.getElementById('main')); }); ``` - Build Component By Part: Separate the table into parts to make the codes easily to read and update ```html <PlayerInfo/> <TeamInfo/> <NumSelector/> ... ``` ### Logic and Tests #### Scaling and time complexity matter - Due to the limitations to satisfy all the rules, the innings number should be limited by the player numbers selected - With that being said, player numbers, innings numbers and satisfy roles requirements can contradict to each other - therefore, in order to satisfy all the roles, I tested and set the upper bound to each playerNum and inningNum combination - for example, for 8 players to satisfy all the rules and guarantee the program works efficiently, there should have maximum 6 innings #### Selector - Update the player number and inning number from user input - Pass Back to the parent elements - the pitcher('P') option should be excluded from the preferredPositions and avoidPositions options, because the user already have rights to identify each player should pitch or not - Update the parent state (props) ```javascript //trigger the update in option tag <select className="selectpicker" data-style="btn-primary" value={numPlayers()} onChange={updateSelectPlayer}> //child component const updateSelectPlayer = (event) => { props.updateSelectPlayer(event.target.value); } //update the parent and related state updateSelectPlayer = () => { return ((value) => { let playerLists = this.state.playerLists; playerLists = this.constructTeamLists(parseInt(value)); this.setState({playerNum: value, playerLists: playerLists}); }); } ``` #### Build Player Form - Assign Pitcher - if yes, then active the Inning Pitching - if no, return "Not Applicable" - Selection-exclude algorithm - update the selected pitching - update the available pitch innings stack - display the current selection at the top - put the remaining at the bottom and sort ```javascript return ((newSelection) => { const newPlayers = this.state.playerLists; let newInnings = [...this.state.availablePitchInnings]; if (newSelection !== 'Not Applicable') { newSelection = parseInt(newSelection); let oldIndex = this.state.availablePitchInnings.indexOf(newSelection); newInnings = [ ...newInnings.slice(0, oldIndex), ...newInnings.slice(oldIndex + 1) ]; } if (newPlayers[idx].selectedPitchInning !== 'Not Applicable') { newInnings.push(newPlayers[idx].selectedPitchInning); } newPlayers[idx].selectedPitchInning = newSelection; this.setState({playerLists: newPlayers, availablePitchInnings: newInnings.sort()}); }); ``` - exclude taken options ![](https://github.com/zidianlyu/BaseballTeamBuilder/blob/master/asset/img/select_exclude.png) - Initialize the player form by assigning random preferred roles and avoid rules ![](https://github.com/zidianlyu/BaseballTeamBuilder/blob/master/asset/img/build_form_1.png) ![](https://github.com/zidianlyu/BaseballTeamBuilder/blob/master/asset/img/build_form_2.png) this is achieve by random select role from array for each player exclude it from stack if picked to ensure no repeat can happen ```javascript const allPositions = ['P','C',...]; let prePos = allPositions[Math.floor(Math.random() * allPositions.length)]; allPositions.splice(allPositions.indexOf(prePos), 1); ``` - For Updates on specific position - Locate the change; return the index and content - update the state ```javascript const fieldName = this.getPositionField(type); return ((fieldIdx, selection) => { const playerLists = this.state.playerLists; playerLists[rowIdx][`${fieldName}`][fieldIdx] = selection; this.setState({playerLists}); }) ``` - Ensure the modified data is updated - update the playerLists in BuildForm - update according to the input data change - construct the team lists with player details ```javascript updateSelectPlayer = () => { return ((value) => { let playerLists = this.state.playerLists; playerLists = this.constructTeamLists(parseInt(value)); this.setState({playerNum: value, playerLists: playerLists}); }); } ``` #### Generate Print Form - Generate the form by using Backtracking Algorithm (simular to Sudoku) - keep tracking until satisfy all the rules (all return true) - handle basic rule - there shouldn't be any repetitive role in each inning - render the board, return false if find any repetitive ```javascript for (let row = 0; row < props.playerLists.length; row++) { if (board[row][j] == c) { return false; } } ``` - handle the minimum rule 1 - Applying Pigeon Hole Principle: - satisfy the both infield and outfield minimum requirement without counting the Bench Player ```javascript if (min1CheckIn > 1) { min1CheckIn = 2; } if (min1CheckOut > 0) { min1CheckOut = 1; } if (min1CheckIn + min1CheckOut < 3) { return false; } ``` - handle the minimum rule 2 - check the player's previous innings role - if find a role that have been assigned twice, return false and backtrack ```javascript let min2Check = 0; for (let col = 0; col < props.innings.length; col++) { if (board[i][col] == c) { min2Check += 1; } if (min2Check === 2) { return false; } } ``` - handle the option rule 1 - if find two bench player, return false ```javascript let opt1check = 0; for (let col = 0; col < props.innings.length; col++) { if (board[i][col] === 'BN') { opt1check += 1; } if (opt1check > 2) { return false; } } ``` - handle the option rule 2 - keep check on the current role and the previous, return false if both are BN ```javascript for (let col = 1; col < props.innings.length; col++) { if (board[i][col] == 'BN' && board[i][col - 1] == 'BN') { return false; } } ``` - handle the option rule 3 - simular to rule 2, except for outfield ```javascript for (let col = 1; col < props.innings.length; col++) { if (outfield.has(board[i][col]) && outfield.has(board[i][col - 1])) { return false; } } ``` ### Styling - Applied styling elements from [Bootstrap](http://getbootstrap.com/) - Designed page icon <img src="https://github.com/zidianlyu/BaseballTeamBuilder/blob/master/asset/img/logo.png" align="center" width="200" overflow="hidden"> - Designed page loader and pick random random page-loader ```html <div className="object-animation-one" id="first_object"></div> <div className="object-animation-one" id="second_object"></div> <div className="object-animation-one" id="third_object"></div> <div className="object-animation-one" id="forth_object"></div> ``` ```javascript loader[Math.floor(Math.random() * loader.length)] ``` - Designed animation to give the user more guidelines ![](https://github.com/zidianlyu/BaseballTeamBuilder/blob/master/asset/img/arrow_animation.png) the animation is done by implementing CSS: ```javascript @-webkit-keyframes bounceRight { 0%, 20%, 60%, 100% { -webkit-transform: translateY(0); } ... } ``` - Read and hide component - assign component to variable and switch them base on condition ```javascript // JS if (originForm !== "") { selector = ""; buildOriginFormBtn = ...; } ``` ```javascript // HTML <div> {selector} {originForm} {buildOriginFormBtn} <div> ``` ## Future Implementations ### Database - Apply MySQL or PostgreSQL to store the user information ### User Authentication - The user can login or signup ### Real Time News - Update the realtime news from the latest sport's report [roster]: https://zidianlyu.github.io/BaseballTeamBuilder/
PHP
UTF-8
3,767
2.578125
3
[]
no_license
<?php namespace EventjetTest\I18n; use Eventjet\I18n\Language\Language; use Eventjet\I18n\Translate\Factory\TranslationMapFactory; use Eventjet\I18n\Translate\Translation; use Eventjet\I18n\Translate\TranslationInterface; use Eventjet\I18n\Translate\TranslationMap; use Eventjet\I18n\Translate\TranslationMapInterface; use PHPUnit_Framework_TestCase; class TranslationMapTest extends PHPUnit_Framework_TestCase { public function testHasReturnsFalseIfTranslationDoesNotExist() { $map = new TranslationMap([new Translation(Language::get('de'), 'Test')]); $this->assertFalse($map->has(Language::get('en'))); } public function testWithTranslation() { $map = new TranslationMap([new Translation(Language::get('de'), 'Deutsch')]); $en = Language::get('en'); $english = 'English'; $newMap = $map->withTranslation(new Translation($en, $english)); $this->assertEquals($english, $newMap->get($en)); $this->assertFalse($map->has($en)); } public function testWithTranslationOverridesExistingTranslation() { $de = Language::get('de'); $map = new TranslationMap([new Translation($de, 'Original')]); $newMap = $map->withTranslation(new Translation($de, 'Overridden')); $this->assertEquals('Overridden', $newMap->get($de)); $this->assertEquals('Original', $map->get($de)); } public function testGetAllReturnsArrayOfTranslations() { $map = new TranslationMap([ new Translation(Language::get('de'), 'Deutsch'), new Translation(Language::get('en'), 'English'), new Translation(Language::get('it'), 'Italiano'), ]); $translations = $map->getAll(); $this->assertContainsOnlyInstancesOf(TranslationInterface::class, $translations); } /** * @expectedException \InvalidArgumentException */ public function testEmptyMapThrowsException() { new TranslationMap([]); } public function testGetReturnsNullIfNoTranslationsExistsForTheGivenLanguage() { $map = new TranslationMap([new Translation(Language::get('de'), 'Test')]); $this->assertNull($map->get(Language::get('en'))); } public function testJsonSerialize() { $map = new TranslationMap([ new Translation(Language::get('en'), 'My Test'), new Translation(Language::get('de'), 'Mein Test'), ]); $json = $map->jsonSerialize(); $this->assertCount(2, $json); $this->assertEquals($json['en'], 'My Test'); $this->assertEquals($json['de'], 'Mein Test'); } public function equalsData() { $data = [ [['de' => 'DE'], ['de' => 'DE'], true], [['de' => 'DE'], ['de' => 'EN'], false], [['de' => 'DE'], ['en' => 'DE'], false], [['de' => 'DE'], ['de' => 'DE', 'en' => 'EN'], false], [['de' => 'DE'], ['de' => 'DE', 'en' => 'DE'], false], [['de' => 'DE', 'en' => 'EN'], ['en' => 'EN', 'de' => 'DE'], true], ]; $factory = new TranslationMapFactory; $data = array_map(function ($d) use ($factory) { return [$factory->create($d[0]), $factory->create($d[1]), $d[2]]; }, $data); $data['same object'] = [$data[0][0], $data[0][0], true]; return $data; } /** * @param TranslationMapInterface $a * @param TranslationMapInterface $b * @param boolean $equal * @dataProvider equalsData */ public function testEquals(TranslationMapInterface $a, TranslationMapInterface $b, $equal) { $this->assertEquals($equal, $a->equals($b)); $this->assertEquals($equal, $b->equals($a)); } }
Markdown
UTF-8
1,615
2.796875
3
[ "MIT" ]
permissive
# Google Cloud PubSub Emulator for Docker [![Docker Pulls](https://img.shields.io/docker/pulls/vovimayhem/google-pubsub-emulator.svg)](https://hub.docker.com/r/vovimayhem/google-pubsub-emulator) [![Docker Build Status](https://img.shields.io/docker/build/vovimayhem/google-pubsub-emulator.svg)](https://hub.docker.com/r/vovimayhem/google-pubsub-emulator) [![Docker Automated Build](https://img.shields.io/docker/cloud/automated/vovimayhem/google-pubsub-emulator.svg)](https://hub.docker.com/r/vovimayhem/google-pubsub-emulator) This is the Docker image for the [Google Cloud PubSub Emulator](https://cloud.google.com/pubsub/docs/emulator) ## Basic Usage This command will download the image if it isn't present, and start the emulator, making it available at localhost:8085: ```bash docker run -p 8085:8085 vovimayhem/google-pubsub-emulator ``` ## Advanced Usage ### Data volume This image accepts mounting a volume for the emulator to store data. Inside the pubsub, the emulator expects the data to be available at `/data`: ```bash docker run -p 8085:8085 -v /tmp/data:/data vovimayhem/google-pubsub-emulator ``` ### Docker Compose You can also use it on your `docker-compose.yml` file. Notice the env variable `PUBSUB_EMULATOR_HOST` on the app service to configure the client so it points to the emulator: ```yaml version: "2.4" volumes: pubsub_data: services: pubsub: image: vovimayhem/google-pubsub-emulator:latest ports: - ${PUBSUB_PORT:-8085}:8085 volumes: - pubsub_data:/data app: # Some lines ommitted environment: PUBSUB_EMULATOR_HOST: pubsub:8085 ```
Java
UTF-8
520
2.234375
2
[]
no_license
/* * Efecto sonido para cuando se rompe la barrera */ package codigo; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; /** * * @author Javier */ public class Crash { Clip sonidoCrash = null; public void ruido(){ try { sonidoCrash= AudioSystem.getClip(); sonidoCrash.open(AudioSystem.getAudioInputStream(getClass().getResource("/sonido/crash.wav"))); } catch (Exception ex) { } } }
Java
UTF-8
827
2.4375
2
[]
no_license
/* * Created on Dec 10, 2004 */ package com.jds.architecture.exceptions; /** * This class represents nonfatal exceptions that occur within HRS * * @author Eugene Lozada * * */ public class HRSLogicalException extends HRSException { private static final long serialVersionUID = 1L; /** * Creates a new HRSLogicalException with logging disabled * * @param messageKey the message key * @param cause the cause of this exception */ public HRSLogicalException(String messageKey, Throwable cause){ super(messageKey, cause, HRSException.OFF, false); } /** * Creates a new HRSLogicalException with logging disabled and no <code>Throwable</code> cause * * @param messageKey the message key */ public HRSLogicalException(String messageKey){ super(messageKey, null, HRSException.OFF, false); } }
C#
UTF-8
768
2.609375
3
[]
no_license
using System; using System.Windows.Forms; namespace BatteryMonitor.Forms { public partial class FormPcName : Form { public string PcName { get; private set; } public bool HasChange { get; private set; } public FormPcName(string pcName) { InitializeComponent(); PcName = PcName; TbPcName.Text = pcName; } private void BtnAcept_Click(object sender, EventArgs e) { PcName = TbPcName.Text; HasChange = true; Close(); } private void BtnCancel_Click(object sender, EventArgs e) => Close(); private void TbPcName_TextChanged(object sender, EventArgs e) => BtnAcept.Enabled = TbPcName.Text.Length > 0; } }
Java
UTF-8
2,112
2.203125
2
[ "Apache-2.0" ]
permissive
package com.mhuang.module.index.controller; import java.util.HashMap; import java.util.Map; import org.bson.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.mhuang.common.exception.BusinessException; import com.mhuang.common.frame.controller.BaseController; import com.mhuang.common.frame.factorybean.MongoFacotry; import com.mongodb.BasicDBObject; import com.mongodb.Block; import com.mongodb.DBObject; @Controller @RequestMapping("/welcome") public class IndexController extends BaseController{ @Autowired private MongoFacotry mongoFactory; @RequestMapping(value="/error",method = RequestMethod.GET) public void error() throws Exception{ mongoFactory.getDBCollection("Test").find().forEach(new Block<Document>() { @Override public void apply(Document t) { throw new BusinessException(t.get("EXCEPTION").toString()); } }); } @RequestMapping("/indexs/{id}") public String index(@PathVariable("id") String id,Model model){ model.addAttribute("id",id); DBObject obObject= new BasicDBObject("EXCEPTION","业务异常"); mongoFactory.getDBCollection("Test").insertOne(new Document(obObject.toMap()));; return "index"; } @ResponseBody @RequestMapping("/get/${id}") public Map<String, String> get(@PathVariable("id") String id){ Map<String, String> map = new HashMap<String, String>(){/** * */ private static final long serialVersionUID = 1L; { put("1", "张三"); put("2", "李四"); put("3", "王五"); }}; Map<String, String> resultMap = new HashMap<String, String>(); if(map.containsKey(id)){ resultMap.put(id,map.get(id)); }else{ resultMap.put(id,"其他"); } return resultMap; } }
PHP
UTF-8
260
2.75
3
[]
no_license
<?php class language { public function set($key, $value) { helper::setMember ( 'lang', $key, $value ); } public function show($obj, $key) { $obj = ( array ) $obj; if (isset ( $obj [$key] )) echo $obj [$key]; else echo ''; } }
Python
UTF-8
232
3.6875
4
[]
no_license
def diferencia(): x=int(input("introduce el primer número: ")) y=int(input("introduce el segundo número: ")) if x>y: return x-y else: return y-x print("La diferencia es ",diferencia())
C++
UTF-8
819
2.703125
3
[]
no_license
class Solution { public: vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& persons) { vector<pair<int, int>> fs; for (int i = 0; i < (int)flowers.size(); ++i) { fs.emplace_back(flowers[i][0], flowers[i][1]); } sort(fs.rbegin(), fs.rend()); vector<pair<int, int>> qs; for (int i = 0; i < (int)persons.size(); ++i) { qs.emplace_back(persons[i], i); } sort(qs.begin(), qs.end()); multiset<int> ms; vector<int> ret(persons.size()); for (const auto& q : qs) { while (!fs.empty() && fs.back().first <= q.first) { ms.insert(fs.back().second); fs.pop_back(); } while (!ms.empty() && *ms.begin() < q.first) { ms.erase(ms.begin()); } ret[q.second] = (int)ms.size(); } return ret; } };
JavaScript
UTF-8
23,323
2.625
3
[ "BSD-2-Clause" ]
permissive
/* jshint asi: true */ 'use strict'; var RESOURCE_WARNING_FRACTION = 0.80 var RESOURCE_ERROR_FRACTION = 0.95 // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = window.jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } function sameOrigin(url) { // test that a given url is a same-origin URL // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier xhr.setRequestHeader('X-CSRFToken', csrftoken); } } }); function get_ajax_url(action) { var url = window.location.href; if (url[url.length - 1] == '#') url = url.slice(0, url.length - 1) if (url[url.length - 1] != '/') url += '/' url += action return url } // http://stackoverflow.com/q/10420352/2211825 function getReadableFileSizeString(fileSizeInBytes) { var i = -1; var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB']; do { fileSizeInBytes = fileSizeInBytes / 1024; i++; } while (fileSizeInBytes > 1024); return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i]; } function get_resource_alert_level(resource_value, resource_limit) { var alert_level = 0; var fraction = resource_value / resource_limit; if (fraction > RESOURCE_WARNING_FRACTION) alert_level = 1; if (fraction > RESOURCE_ERROR_FRACTION) alert_level = 2; return alert_level; } function update_procinfo(procinfo) { var box = $('#' + process_id(procinfo)); if (!box) { return; } var level = 0; // stash a copy of the last known resource levels into the dom element, for later retrieval // they will be used to adjust the alert level for the process; even if we do not have // up-to-date resource levels, we want to make the program and group divs the correct color // based on the last reported levels, otherwise they revert back to green. box.data('procinfo', procinfo); // modify the alert level based on resource levels if ('fileno' in procinfo && 'max_fileno' in procinfo) level = Math.max(level, get_resource_alert_level( procinfo.fileno, procinfo.max_fileno)); if ('vmsize' in procinfo && 'max_vmsize' in procinfo) level = Math.max(level, get_resource_alert_level( procinfo.vmsize, procinfo.max_vmsize)); var fileno_div = box.find('div.resource.fileno'); if ('fileno' in procinfo) { if ('max_fileno' in procinfo) { fileno_div.find('.textual-value') .text(procinfo.fileno + " / " + procinfo.max_fileno); fileno_div.find('.progress-bar'). attr('aria-valuenow', procinfo.fileno). attr('aria-valuemax', procinfo.max_fileno). css('width', (procinfo.fileno*100/procinfo.max_fileno) + '%'); fileno_div.find('.progress').show(); } else { fileno_div.find('.textual-value').text(procinfo.fileno); } fileno_div.find('.textual-value').attr('title', procinfo.numfiles + " open files, " + procinfo.numconnections + " sockets") fileno_div.show(); } else { fileno_div.hide(); } var vmsize_div = box.find('div.resource.vmsize'); if ('vmsize' in procinfo) { if ('max_vmsize' in procinfo) { vmsize_div.find('.textual-value').text( getReadableFileSizeString(procinfo.vmsize) + " / " + getReadableFileSizeString(procinfo.max_vmsize)); vmsize_div.find('.progress-bar'). attr('aria-valuenow', procinfo.vmsize). attr('aria-valuemax', procinfo.max_vmsize). css('width', (procinfo.vmsize*100/procinfo.max_vmsize) + '%'); vmsize_div.find('.progress').show(); } else { vmsize_div.find('.textual-value').text( getReadableFileSizeString(procinfo.vmsize)); } vmsize_div.show(); } else { vmsize_div.hide(); } var numchildren_div = box.find('div.resource.numchildren'); if ('numchildren' in procinfo && procinfo.numchildren) { numchildren_div.show().find('.numchildren').text(procinfo.numchildren); } else { numchildren_div.hide(); } var numthreads_div = box.find('div.resource.numthreads'); if ('numthreads' in procinfo && procinfo.numthreads > 1) { numthreads_div.show().find('.numthreads').text(procinfo.numthreads); } else { numthreads_div.hide(); } var sparkline; var timestamp; var new_value; var cpu_div = box.find('div.resource.cpu'); if ('cpu' in procinfo) { sparkline = cpu_div.find('.sparkline'); timestamp = procinfo.cpu[0]; var cpu = procinfo.cpu[1] + procinfo.cpu[2]; if (sparkline.data('last_timestamp') !== undefined) { new_value = (cpu - sparkline.data('last_cpu')) / (timestamp - sparkline.data('last_timestamp')); if (new_value >= 0) { var values = sparkline.data('values'); values.push(Math.round(new_value*100)); while (values.length > 60) { values.shift(); } } sparkline.sparkline(sparkline.data('values'), { type: 'line', height: '32', lineWidth: 2, chartRangeMin: 0, chartRangeMax: 100, }) } else { sparkline.data('values', []); } sparkline.data('last_cpu', cpu); sparkline.data('last_timestamp', timestamp); cpu_div.show(); } else { cpu_div.hide(); } var diskio_div = box.find('div.resource.diskio') if ('diskio' in procinfo) { sparkline = diskio_div.find('.sparkline'); timestamp = procinfo.diskio[0]; var diskio = (procinfo.diskio[3] + procinfo.diskio[4]) / 1024; if (sparkline.data('last_timestamp') !== undefined) { new_value = (diskio - sparkline.data('last_diskio')) / (timestamp - sparkline.data('last_timestamp')) if (new_value >= 0) { var values = sparkline.data('values'); values.push(Math.round(new_value*100)) while (values.length > 60) { values.shift() } } sparkline.sparkline(sparkline.data('values'), { type: 'line', height: '32', lineWidth: 2 }); } else { sparkline.data('values', []); } sparkline.data('last_diskio', diskio); sparkline.data('last_timestamp', timestamp); diskio_div.show(); } else { diskio_div.hide(); } box.find('.resources').show(); box.attr('data-level', level).data('level', level); } function open_stream(button, stream) { var program_div = $(button).parent('div.program') var program = program_div.attr('data-program-name') var group = program_div.parents('div.group').attr('data-group-name') var server = program_div.parents('div.server').attr('data-server-name') $.ajax({ url: get_ajax_url('data/program-logs'), data: { stream: stream, program: program, pid: program_div.attr('data-pid'), group: group, server: server, } }).done(function(data) { var pre = $('#show-logs-dialog div.modal-body pre') pre.text(data) var h = Math.round($(window).height()*0.7) pre.css('height', h + 'px') pre.css('max-height', h + 'px') $('#show-logs-dialog .modal-title').text( server + ": " + group + ':' + program + " " + stream); $('#show-logs-dialog').modal() }) } window.open_stdout = function(button) { return open_stream(button, 'stdout'); } window. open_stderr = function(button) { return open_stream(button, 'stderr'); } window.open_applog = function (button) { return open_stream(button, 'applog'); } function group_action() { var button = $(this); var action = button.data('action'); var box = button.closest('.box'); var groups; if (box.hasClass('procgroup')) { groups = box; } else { groups = box.find('.procgroup:visible'); } var data = { action: action, procs: JSON.stringify($.makeArray(groups.map(function () { return [[$(this).data('supervisor'), $(this).data('group')]]}))) }; $(button).button('loading') $.ajax({ url: '/group_action', type: 'POST', data: data }).complete(function() { $(button).button('reset') }) } function process_action() { var button = $(this); var action = button.data('action'); var proc = $(button).closest('.process').data('process'); var data = { action: action, supervisor: proc.supervisor, group: proc.group, process: proc.process, }; $(button).button('loading') $.ajax({ url: '/action', type: 'POST', data: data }).complete(function() { $(button).button('reset') }) } function set_group_monitor(box, state) { if (!box.hasClass('procgroup')) { // Only when you open a group return; } var root = box.closest('.rootbox'); var monitored = root.data('monitored'); var new_mon = Object(); var procs = box.find('.process'); if (state) { procs.each(function () { monitored[$(this).attr('id')] = true; new_mon[$(this).attr('id')] = true; }); } else { procs.each(function () { delete monitored[$(this).attr('id')]; }); } refresh_monitored(new_mon); } function refresh_monitored(monitored) { var procs = $.map(monitored, function (v, k) { var proc = $('#' + k).data('process'); if (proc) { return { supervisor: proc.supervisor, group: proc.group, process: proc.process }; } }); if (procs.length == 0) { return; } $.ajax({ url: '/monitor', type: 'POST', data: { procs: JSON.stringify($.makeArray(procs)) } }); } function data2procs(data) { var procs = []; for (var sname in data.supervisors) { var sdata = data.supervisors[sname]; for (var gname in sdata.groups) { var gdata = sdata.groups[gname]; gdata.tags = gdata.tags || []; gdata.tags.push('supervisor:' + sname); gdata.tags.sort(); for (var pname in gdata.processes) { var proc = gdata.processes[pname]; proc.supervisor = sname; proc.group = gname; proc.sup_group = sname + '-' + gname; proc.process = pname; proc.id = process_id(proc); proc.tags = gdata.tags; // Convert tags into attributes too for (var i in proc.tags) { var tag = proc.tags[i]; var c = tag.search(':'); if (c > -1) { proc[tag.substring(0,c)] = tag.substring(c+1); } else { proc[tag] = true; } } procs.push(proc); } } } return procs; } function process_id(process) { return 'proc-' + process.supervisor + '-' + process.group + '-' + process.process; } function Axis (label) { this.label = label this.values = []; } Axis.prototype.add_value = function (value) { if (0 > $.inArray(value, this.values)) { this.values.push(value); } } function collect_axes(procs) { var rv = Object(); // Collect the possible attributes we may care. Some we know, some we // get from the tags. $.each(procs, function(i, proc) { $.each(proc.tags, function(j, tag) { var c = tag.search(':'); var attr = $.trim(tag.substring(0,c)); var val = $.trim(tag.substring(c+1)); if (rv[attr] === undefined) rv[attr] = new Axis(attr); rv[attr].add_value(val); }); }); // Collect the values from the attributes found $.each(procs, function(i, proc) { for (var attr in rv) { if (rv[attr].label != '') { rv[attr].add_value(proc[attr] || 'undefined'); } } }); // Sort values and arrays rv = $.map(rv, function (v) { v.values.sort(); return v; }); rv.sort(function (a1, a2) { return a1.label > a2.label; }); return rv; } /* Set the 'filtered' property on every process of the list */ function set_filtered(procs, control) { var filters = control.find('input.filter:checked'); if (!filters.length) { procs.each(function () { var proc = $(this).data('process'); proc.filtered = false; }); return; } var mode_and = (!! control.find('.tag-filter-mode').prop('checked')); procs.each(function () { var proc = $(this).data('process'); var should_add = mode_and; filters.each(function () { var filter = $(this); if (filter.data('attname')) { var pval = proc[filter.data('attname')] + ''; var fval = filter.data('attvalue') + ''; if (mode_and) { if (fval != pval) should_add = false; } else { if (fval == pval) should_add = true; } } else { var tag = filter.data('attvalue') + ''; if (mode_and) { if (proc.tags.indexOf(tag) == -1) should_add = false; } else { if (proc.tags.indexOf(tag) >= 0) should_add = true; } } }); proc.filtered = !should_add; }); } function render_box(group, target, axes) { var process = group.find('.process').data('process'); if (axes.length) { var attr = axes[0]; var val = process[attr] + ''; // the string "undefined" if none var cls = 'attr-' + attr + '-' + val; var box = target.find('.' + cls).first(); if (!box.length) { var box = $('#protos .box').clone() .addClass(cls) .addClass('attr-' + attr) .data('attname', attr) .data('attvalue', val); box.find('.attname').text(attr); box.find('.attvalue').text(val); insert_box_inplace(box, target); } render_box(group, box.find('.children').first(), axes.slice(1)); } else { insert_box_inplace(group.detach(), target); } } function render_group(process, target) { var attr = 'sup_group'; var val = process[attr]; var cls = 'attr-' + attr + '-' + val; var box = target.find('.' + cls).first(); if (!box.length) { var box = $('#protos .box').clone() .addClass(cls) .addClass('attr-' + attr) .addClass('procgroup') .data('supervisor', process.supervisor) .data('group', process.group) .data('attname', attr) .data('attvalue', val); box.find('.attname').text(""); box.find('.attvalue').text(process.group); var badges = box.find('.badges'); $.each(process.tags, function(i, tag) { var badge = badges .append('<span class="badge">' + tag + '</span> ') .find(':last-child'); var c = tag.search(':'); if (c > -1) { badge.attr('data-attname', tag.substring(0,c)); } }); insert_box_inplace(box, target); } var pbox = $('#protos .process').clone(); render_process(process, pbox); insert_box_inplace(pbox, box.find('.children').first()); } function insert_box_inplace(box, target) { // Find the place to insert to keep them in order var cc = target.children(); var ins = false; for (var i = 0, ii = (cc.length); i < ii; i++) { var ch = $(cc[i]); if (box.data('attvalue') < ch.data('attvalue')) { ch.before(box); ins = true; break; } } if (!ins) { target.append(box); } } function render_process(process, box) { box.attr('id', process.id); box.find('.name').text(process.process); box.data('attvalue', process.process); // for sorting update_process(process, box); } function update_process(process, box) { if (!box) { box = $('#' + process.id) } box.data('process', process); box.attr('data-state', process.statename); box.find('.program-state').text(process.statename); if (process.filtered) { box.addClass('filtered'); } } function render_boxes(target, groups, control) { // Stash the already rendered groups away target.find('.procgroup').removeClass('filtered').appendTo(groups); target.empty(); set_filtered(groups.find('.process'), control); groups.find('.procgroup').each(function() { render_box($(this), target, control.data('axes')); }); update_counts(target); // Restore the expanded state var expanded = target.data('expanded'); for (var cls in expanded) { if (!expanded[cls]) continue; var box = $(cls); if (box.length == 1) { toggle_box_expand(box); } } // Restore the badges visibility control.find('input.group').each(function () { var badges = target.find( '.badge[data-attname="' + $(this).data('attname') + '"]'); if ($(this).prop('checked')) badges.hide(); else badges.show(); }); } function render_groups(procs, target) { $.each(procs, function(i, proc) { render_group(proc, target); }); } function update_counts(target) { // Reset counters target.find('.box') .data('nprocs', 0).data('nrunning', 0).data('nerrors', 0) .data('nfiltered', 0); // Accumulate the counts in the parent boxes target.find('.process').each(function () { var proc = $(this); proc.parents('.box').each(function () { var box = $(this); box.data('nprocs', box.data('nprocs') + 1); if (proc.data('process').filtered) { box.data('nfiltered', box.data('nfiltered') + 1); } var sname = proc.data('process').statename; if (sname == 'RUNNING') { box.data('nrunning', box.data('nrunning') + 1); } else if (sname == 'BACKOFF' || sname == 'FATAL') { box.data('nerrors', box.data('nerrors') + 1); } }); }); // Render the elements in the boxes target.find('.box').each(function () { var box = $(this); if (box.data('nprocs') > 1) { var span = box.find('.nprocs-counts').show(); span.find('.nprocs-running').text(box.data('nrunning')); span.find('.nprocs-total').text(box.data('nprocs')); } else { box.find('.nprocs-counts').hide(); box.find('.btn-startall').text('Start'); box.find('.btn-stopall').text('Stop'); } if (box.data('nrunning') == box.data('nprocs')) { box.attr('data-state', 'RUNNING'); } else if (box.data('nerrors') > 0) { box.attr('data-state', 'ERRORS'); } else { box.attr('data-state', 'STOPPED'); } if (box.data('nfiltered') == box.data('nprocs')) { box.addClass('filtered'); } }); } function update_levels(target) { // Reset counters target.find('.box').data('level', 0); // Accumulate the counts in the parent boxes target.find('.process').each(function () { var proc = $(this); proc.parents('.box').each(function () { var box = $(this); box.data('level', Math.max(box.data('level'), proc.data('level') || 0)); }); }); // Render the elements in the boxes target.find('.box').each(function () { var box = $(this); box.attr('data-level', box.data('level')); }); } function render_tags_controls(control, procs) { var got_axes = collect_axes(procs); $(got_axes).each(function () { var attrname = this.label; var tr = $('#protos .tags_group').clone() .appendTo(control.find('table.tags_groups')); if (attrname != '') { tr.find('.taggroup-label') .text(attrname).data('attname', attrname); } else { tr.find('.taggroup-label').closest('td').empty(); } tr.find('input').data('attname', attrname); $(this.values).each(function () { var attrval = this; var btn = $('#protos label.tag').clone() .appendTo(tr.find('div.taggroup')); btn.find('span.tag-label').text(attrval); btn.children('input') .data('attname', attrname) .data('attvalue', attrval); }); }); } function get_box_path(box) { var cls = '.box.attr-' + box.data('attname') + '-' + box.data('attvalue'); var par = box.parents('.box').first(); if (par.length) { cls = get_box_path(par) + ' ' + cls; } return cls; } function toggle_box_expand(box) { var root = box.closest('.rootbox'); var exp = box.toggleClass('expanded').hasClass('expanded'); root.data('expanded')[get_box_path(box)] = exp; set_group_monitor(box, exp); }
Java
UTF-8
743
2.84375
3
[ "Apache-2.0" ]
permissive
package pattern.observer; import java.util.ArrayList; import java.util.List; public abstract class AllyControlCenter { protected String allyName; protected List<Observer> playerList = new ArrayList<>(); public void join(Observer observer) { System.out.println(observer.getName() + "加入战队" + allyName); playerList.add(observer); }; public void quit(Observer observer) { System.out.println(observer.getName()+"退出战队"+allyName); playerList.remove(observer); }; public abstract void notifyPlays(String name); public String getAllyName() { return allyName; } public void setAllyName(String allyName) { this.allyName = allyName; } }
Java
UTF-8
170
1.742188
2
[]
no_license
package com.ruanko.hwm.service; import com.ruanko.hwm.bean.SingerType; public interface ISingerTypeService { public SingerType getSingerTypeById(Integer id); }
Swift
UTF-8
423
3.0625
3
[]
no_license
import Foundation final class Atomic<T> { private var _value: T private let lock = NSLock() init(_ value: T) { self._value = value } var value: T { get { lock.lock() let result = _value lock.unlock() return result } set { lock.lock() _value = newValue lock.unlock() } } }
Python
UTF-8
3,488
3.96875
4
[ "MIT" ]
permissive
''' Question: Given an array A of size N, there are two types of queries on this array. 1. q l r: In this query you need to print the minimum in the sub-array . 2. u l r v In this query you need to update the range from l to r by v. Time Complexity: update query: log(n) min in range query: log(n) ''' import math as mt class SegmentTree: def __init__(self, array): self.MAX_INT = 2**31-1 self.src = array self.len = len(array) self.total_nodes = (2**mt.ceil(mt.log(self.len, 2))*2-1) self.tree = [0] * self.total_nodes self.dues = [0] * self.total_nodes def build(self): self.build_tree(l=0, r=self.len-1, par=0) def build_tree(self, l, r, par): if l == r: self.tree[par] = self.src[l] return div = (l+r)//2 self.build_tree(l, div, (par<<1)+1) self.build_tree(div+1, r, (par<<1)+2) self.tree[par]=min(self.tree[(par<<1)+1], self.tree[(par<<1)+2]) def min_in_range(self, low, high): return self.min_(low, high, 0, self.len-1, 0) def min_(self, low, high, left, right, par): if low > right or high < left: return self.MAX_INT if self.dues[par] > 0: self.tree[par] += self.dues[par] if left is not right: self.dues[(par<<1)+1] += self.dues[par] self.dues[(par<<1)+2] += self.dues[par] self.dues[par]=0; if low <= left and high >= right: return self.tree[par] div = int((right+left)/2) return min(self.min_(low, high, left, div, (par<<1)+1), self.min_(low, high, div+1, right, (par<<1)+2) ) def update_range(self, low, high, value): return self.update(low, high, value, 0, self.len-1, 0) def update(self, low, high, value, left, right, par): if self.dues[par] > 0: self.tree[par] += self.dues[par] if left is not right: self.dues[(par<<1)+1] += self.dues[par] self.dues[(par<<1)+2] += self.dues[par] self.dues[par]=0; if low > right or high < left: return; if low <= left and high >= right: self.tree[par] += value if(left is not right): self.dues[(par<<1)+1] += value self.dues[(par<<1)+2] += value return div = (right+left)//2 self.update(low, high, value, left, div, (par<<1)+1) self.update(low, high, value, div+1, right, (par<<1)+2) if __name__=='__main__': array = list(map(int, input('Enter space seprated number\n').strip().split(' '))) sg = SegmentTree(array) sg.build() n_query = int(input('Enter number of queries\n')) print('Query format\nq low high (to find minimum in range e.g: q 0 3)\nu low high value (to add "value" to all elements e.g: u 3 4 99)') while n_query: n_query -= 1 args = input('Enter query: ').strip().split(' ') if args[0] == 'q' and len(args) == 3: print(sg.min_in_range(low=int(args[1]), high=int(args[2]))) elif args[0] == 'u' and len(args) == 4: sg.update_range(low=int(args[1]), high=int(args[2]), value=int(args[3])) print('Update Successfully!') else: print('Invalid query format') n_query += 1
C
UTF-8
8,845
2.8125
3
[]
no_license
#include "unistd.h" #include "limits.h" #include "string.h" #include "stdio.h" #include "stdlib.h" #include "sys/mman.h" const int BUFFER_SIZE = 1024; const int WRITE_ZERO_TRY_COUNT = 10; const int MMAP_BUFFERS_SIZE = 32; const int MAX_BUFF_SIZE = INT_MAX/2; void nop(void * data){} void* raw_allocate(size_t size) { return mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); } int raw_deallocate(void * start_address, size_t total_size) { return munmap(start_address, total_size); } int write_impl(int fd, const char * buf, int len, int min_write_count, void (*err_handler) (void*), void * err_handler_data){ int ret2; int remained = len; int zero_try_counter = 0; if(min_write_count <= 0) min_write_count = len; while(remained > 0){ ret2 = write(fd, buf + len - remained, remained); if(ret2 < 0) { err_handler(err_handler_data); return EXIT_FAILURE; }else if(ret2 == 0){ ++zero_try_counter; if(zero_try_counter == WRITE_ZERO_TRY_COUNT){ return EXIT_FAILURE; } }else{ zero_try_counter = 0; } remained -= ret2; min_write_count -= ret2; if(min_write_count <= 0) break; } return len - remained; } int write_impl_no_err_hadler(int fd, const char * buf, int len, int min_write_count){ return write_impl(fd, buf, len, min_write_count, nop, NULL); } int read_impl(int fd, char * buf, int len, void (*err_handler) (void*), void * err_handler_data){ int ret = read(fd, buf, len); if(ret == -1) err_handler(err_handler_data); return ret; } int read_impl_no_err_hadler(int fd, char * buf, int len){ return read_impl(fd, buf, len, nop, NULL); } void read_from_input_fd_err_handler(void * data){ char err[255 + PATH_MAX]; sprintf(err, "Reading fd #%d", *((int*)data) + 1); perror(err); } void write_to_stdout_err_handler(void * data){ perror("Writing to STDOUT"); } int bufcpy(char * buf, int len, char ** mmap_buffers, int * mmap_buffer_count, int * caret, int *buff_id, int PAGE_SIZE){ int len1 = (PAGE_SIZE << *buff_id) - *caret; if (len1 > len) len1 = len; int i; for(i = 0; i < len1; ++i) mmap_buffers[*buff_id][i + *caret] = buf[i]; *caret += len1; if(len > len1){ (*buff_id)++; if(*buff_id == *mmap_buffer_count){ int new_size = PAGE_SIZE << *buff_id; if(new_size >= MAX_BUFF_SIZE){ const char * err_msg = "Max buffer size limit exceed: to long line"; write_impl_no_err_hadler(STDERR_FILENO, err_msg, strlen(err_msg), 0); return EXIT_FAILURE; } void * allocated_memory = raw_allocate(new_size); if(allocated_memory == MAP_FAILED){ perror("Can't allocate memory for line buffer"); return EXIT_FAILURE; } mmap_buffers[*buff_id] = allocated_memory; (*mmap_buffer_count)++; } for(i = 0; i + len1 < len; ++i) mmap_buffers[*buff_id][i] = buf[i + len1]; *caret = i; } return EXIT_SUCCESS; } void reverse_char_array(char * array, int len){ int i; char c; for(i = 0; (i << 1) < len; ++i){ c = array[i]; array[i] = array[len - i - 1]; array[len - i - 1] = c; } } int buf_print_reversed(char ** mmap_buffers, int * mmap_buffer_count, int *caret, int *buff_id, int PAGE_SIZE){ int ret2; int _buff_id = *buff_id, _caret = *caret; do{ reverse_char_array(mmap_buffers[_buff_id], _caret); _buff_id--; _caret = PAGE_SIZE << _buff_id; }while(_buff_id >= 0); do{ ret2 = write_impl(STDOUT_FILENO, mmap_buffers[*buff_id], *caret, 0, write_to_stdout_err_handler, NULL); if(ret2 < 0) return EXIT_FAILURE; (*buff_id)--; *caret = PAGE_SIZE << (*buff_id); }while(*buff_id >= 0); (*buff_id)++; return EXIT_SUCCESS; } int process_fd_impl(int fd_id, int fd, char ** mmap_buffers, int * mmap_buffer_count, char ** mmap_buffers2, int * mmap_buffer_count2, int PAGE_SIZE){ char buf[BUFFER_SIZE]; int caret = 0, buff_id = 0; int caret2 = 0, buff_id2 = 0; int ret, ret2; int buff1_is_used = 0; char newline_char = '\n'; int i, j; /*int lnc = 0;*/ do{ ret = read_impl(fd, buf, BUFFER_SIZE, read_from_input_fd_err_handler, &fd_id); if(ret == 0) break; if(ret < 0) return EXIT_FAILURE; for(i = 0; i < ret; ++i){ if(buf[i] == '\n'){ /*printf("line #%d found\n", lnc++);*/ if(buff1_is_used){ ret2 = bufcpy(buf, i, mmap_buffers2, mmap_buffer_count2, &caret2, &buff_id2, PAGE_SIZE); if(ret2 != EXIT_SUCCESS) return ret2; ret2 = buf_print_reversed(mmap_buffers2, mmap_buffer_count2, &caret2, &buff_id2, PAGE_SIZE); if(ret2 != EXIT_SUCCESS) return ret2; //Print \n ret2 = write_impl(STDOUT_FILENO, &newline_char, 1, 0, write_to_stdout_err_handler, NULL); if(ret2 < 0) return EXIT_FAILURE; ret2 = buf_print_reversed(mmap_buffers, mmap_buffer_count, &caret, &buff_id, PAGE_SIZE); if(ret2 != EXIT_SUCCESS) return ret2; //Print \n ret2 = write_impl(STDOUT_FILENO, &newline_char, 1, 0, write_to_stdout_err_handler, NULL); if(ret2 < 0) return EXIT_FAILURE; buff1_is_used = 0; }else{ ret2 = bufcpy(buf, i, mmap_buffers, mmap_buffer_count, &caret, &buff_id, PAGE_SIZE); if(ret2 != EXIT_SUCCESS) return ret2; buff1_is_used = 1; } for(j = 0; i + j + 1 < ret; ++j) buf[j] = buf[i + j + 1]; ret = j; i = 0; } } if(buff1_is_used) ret2 = bufcpy(buf, ret, mmap_buffers2, mmap_buffer_count2, &caret2, &buff_id2, PAGE_SIZE); else ret2 = bufcpy(buf, ret, mmap_buffers, mmap_buffer_count, &caret, &buff_id, PAGE_SIZE); if(ret2 != EXIT_SUCCESS) return ret2; }while(1); if(buff1_is_used){ ret2 = buf_print_reversed(mmap_buffers2, mmap_buffer_count2, &caret2, &buff_id2, PAGE_SIZE); if(ret2 != EXIT_SUCCESS) return ret2; //Print \n ret2 = write_impl(STDOUT_FILENO, &newline_char, 1, 0, write_to_stdout_err_handler, NULL); if(ret2 < 0) return EXIT_FAILURE; } ret2 = buf_print_reversed(mmap_buffers, mmap_buffer_count, &caret, &buff_id, PAGE_SIZE); if(ret2 != EXIT_SUCCESS) return ret2; return EXIT_SUCCESS; } int process_fd(int i, int fd, char * postfix, int postfix_len, int PAGE_SIZE){ char * mmap_buffers[MMAP_BUFFERS_SIZE]; int mmap_buffer_count = 1; char * mmap_buffers2[MMAP_BUFFERS_SIZE]; int mmap_buffer_count2 = 1; int ret; char line_buffer[PAGE_SIZE]; char line_buffer2[PAGE_SIZE]; mmap_buffers[0] = &line_buffer[0]; mmap_buffers2[0] = &line_buffer2[0]; int return_value = process_fd_impl(i, fd, mmap_buffers, &mmap_buffer_count, mmap_buffers2, &mmap_buffer_count2, PAGE_SIZE); if(return_value == EXIT_SUCCESS && postfix_len > 0){ ret = write_impl(STDOUT_FILENO, postfix, postfix_len, 0, write_to_stdout_err_handler, 0); if(ret < 0) return_value = EXIT_FAILURE; } if(mmap_buffer_count > 1){ int i; for(i = 1; i < mmap_buffer_count; ++i){ ret = raw_deallocate(mmap_buffers[i], PAGE_SIZE << i); if(ret < 0){ perror("Failed to deallocate line buffer memory"); return_value = EXIT_FAILURE; break; } } } if(mmap_buffer_count2 > 1){ int i; for(i = 1; i < mmap_buffer_count2; ++i){ ret = raw_deallocate(mmap_buffers2[i], PAGE_SIZE << i); if(ret < 0){ perror("Failed to deallocate line buffer memory"); return_value = EXIT_FAILURE; break; } } } return return_value; } int main(int argc, char ** argv){ int PAGE_SIZE = sysconf(_SC_PAGE_SIZE); char * delimeter = argv[1]; int delimeter_len = strlen(delimeter); int fd_count = argc - 2; char ** fd_strs = argv + argc - fd_count; for(int i=0; i<fd_count; ++i){ int fd; sscanf(fd_strs[i], "%d", &fd); int fd_res = process_fd(i, fd, i == fd_count - 1 ? "" : delimeter, i == fd_count - 1 ? 0 : delimeter_len, PAGE_SIZE); if(fd_res != EXIT_SUCCESS) return fd_res; } return EXIT_SUCCESS; }
TypeScript
UTF-8
4,119
2.8125
3
[]
no_license
import { Account, BpfLoader, BPF_LOADER_PROGRAM_ID, Connection, PublicKey, } from '@solana/web3.js'; import fs from 'mz/fs'; /** * This script should be run before the jest suite starts running tests on the contracts. * 1) establish a connection to localnet * 2) create an array of accounts with a balance (add to global) * 3) Deploy contracts * */ const DIST_DIRECTORY = './dist'; export const PROGRAM_PATHS: Record<string, string> = fs .readdirSync(DIST_DIRECTORY) .reduce((acc, fileName) => { const path = `${DIST_DIRECTORY}/${fileName}`; acc[fileName] = path; return acc; }, {} as Record<string, string>); export const LOCALNET_URL = 'http://localhost:8899'; export const sleep = (ms: number): Promise<void> => { return new Promise((resolve) => setTimeout(resolve, ms)); }; export type NewAccountOptions = { lamports: number; noAirdropCheck: boolean; }; /** * Create a new account with an airdropped amount of tokens * @param connection * @param {NewAccountOptions} options */ export const newAccountWithLamports = async ( connection: Connection, options: NewAccountOptions = { lamports: 1000000, noAirdropCheck: false, }, ): Promise<Account> => { const account = new Account(); if (options.noAirdropCheck) { connection.requestAirdrop(account.publicKey, options.lamports); return account; } let retries = 10; await connection.requestAirdrop(account.publicKey, options.lamports); for (;;) { await sleep(500); if (options.lamports == (await connection.getBalance(account.publicKey))) { return account; } if (--retries <= 0) { break; } } throw new Error(`Airdrop of ${options.lamports} failed`); }; export default class TestHelper { connection!: Connection; accounts: Array<Account> = []; programs: Record<string, PublicKey> = {}; constructor(programs?: Record<string, PublicKey>) { if (programs) { this.programs = programs; } this.establishConnection(); } /** * establishes connection to Solana cluster * @param url */ establishConnection(url: string = LOCALNET_URL): void { this.connection = new Connection(url, 'recent'); } /** * Creates 10 accounts for help with tests */ async createAccounts(): Promise<void> { let numberOfAccounts = 10; for (;;) { const account = await newAccountWithLamports(this.connection, { // create accounts with a lot of lamports for testing purposes lamports: 10000000000000, noAirdropCheck: true, }); this.accounts.push(account); if (--numberOfAccounts <= 0) { break; } } } /** * Load program onto connection * @param pathToProgram */ async loadProgram( pathToProgram: string, payerAccount: Account, name: string, ): Promise<void> { const data = await fs.readFile(pathToProgram); const programAccount = new Account(); await BpfLoader.load( this.connection, payerAccount, programAccount, data, BPF_LOADER_PROGRAM_ID, ); const programId = programAccount.publicKey; this.programs[name] = programId; } /** * deploy specified contracts */ async deployContracts(): Promise<void> { // create a new account to pay for the release const payerAccount = await newAccountWithLamports(this.connection, { lamports: 10000000000000, noAirdropCheck: true, }); await Promise.all( Object.keys(PROGRAM_PATHS).map(async (programName) => { await this.loadProgram( PROGRAM_PATHS[programName], payerAccount, programName, ); }), ); await this.writeDeployedPrograms(); } /** * Write the deployed programs to testDeployed.json */ writeDeployedPrograms = async (): Promise<void> => { const programsAsStrings = Object.keys(this.programs).reduce((acc, key) => { acc[key] = this.programs[key].toString(); return acc; }, {} as Record<string, string>); return fs.writeFile('testDeployed.json', JSON.stringify(programsAsStrings)); }; }
C++
UTF-8
428
2.671875
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { int N,T,c=1,b,ans,i; cin>>T; while(T--) { vector <int> t; cin>>N; for(i=0;i<N;i++) { cin>>b; t.push_back(b); } sort(t.begin(),t.end()); cout<< "Case "<<c<< ": "<<t[N-1]<<endl; t.erase(t.begin(),t.end()); c++; }return 0; }
Markdown
UTF-8
2,789
2.625
3
[ "MIT" ]
permissive
# koa-swapi [![node](https://img.shields.io/node/v/passport.svg?style=flat-square)](https://github.com/haowen737/koa-swapi) [![npm](https://img.shields.io/npm/v/npm.svg?style=flat-square)](https://github.com/haowen737/koa-swapi) [![GitHub last commit](https://img.shields.io/github/last-commit/google/skia.svg?style=flat-square)](https://github.com/haowen737/koa-swapi) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) [![Packagist](https://img.shields.io/packagist/l/doctrine/orm.svg?style=flat-square)](https://github.com/haowen737/koa-swapi) > 在Koa中使用更先进的路由 [English](https://github.com/haowen737/koa-swapi/blob/master/README.md) | [中文](https://github.com/haowen737/koa-swapi/blob/master/docs/README-zh.md) *Koa-swapi* 是一款用起来还算顺手的koa路由中间件, 你可以像 [Hapijs](https://hapijs.com/)一样定义路由, koa-swapi 会进行所有的请求参数校验, 并能生成 [OpenAPI](https://www.openapis.org/) 文档 ([Swagger](https://swagger.io/) RESTful API 文档说明). ## Install ```shell npm i koa-swapi --save ``` ## Usage Guide Build Schema ```js const Joi = require('joi') const { Route, Validator } = require('koa-swapi') const catSchemas = [ Route .get('/cat/:id') .tags(['catt', 'aninaml']) .summary('获得一只帅气猫') .description('想获得一只帅气猫的时候可以调用这个接口') .validate( Validator .params({ id: Joi.string().required().min(2).max(4).description('猫的id') }) .query({ name: Joi.string().required().min(3).max(100).description('猫的名字'), sex: Joi.any().required().valid(['0', '1']).description('猫的性别, 0:男, 1:女') }) .output({ 200: { body: Joi.string() } }) ) .create('getCat') ] ``` Build Controller ```js const controller = module.exports = {} controller.getCat = async (ctx) => { ctx.status = 200; ctx.body = 'miaomiaomiao' } ``` Build Api ```js const { api } = require('koa-swapi') const apis = [ api.schemas(catSchemas).handler(catController) ] ``` Register ```js // app.js const Koa = require('koa') const { Swapi } = require('koa-swapi') const app = new Koa() const swapi = new Swapi() swapi.register(app, { basePath: '/api', apis: apis }) app.listen(3333) ``` ## 感谢 - [hapi](https://hapijs.com/) 路由即文档的一款node框架 - [Joi](https://github.com/hapijs/joi) 语义化的对象数据模式验证库 - [hapi-swagger](https://github.com/glennjones/hapi-swagger)hapi的一款swagger构建插件 - [Swagger UI](https://github.com/swagger-api/swagger-ui) 精美且强大的api接口文档管理平台
PHP
UTF-8
641
2.59375
3
[]
no_license
<?php $mem = null; if ( ($mem_host = config('cache1.host')) && ($mem_port = config('cache1.port')) ) { $mem = new Memcached; $mem->addServer(config('cache1.host'), config('cache1.port')); } function memset($key, $value, $timeout = 0) { global $mem; if (is_null($mem)) { return false; } return $mem->set($key, $value, $timeout); } function memget($key, $default = false) { global $mem; if (is_null($mem)) { return false; } $value = $mem->get($key); return is_null($value) ? $default : $value; } function memdel($key) { global $mem; if (is_null($mem)) { return false; } return $mem->delete($key); }
Java
UTF-8
666
3.234375
3
[]
no_license
package MartinHongLab7; public class Lab7Driver { public static void main(String[] args) { System.out.println("Lab7 Martin Hong"); Lab7MethodClass lab7MethodClass = new Lab7MethodClass(); // flower exception try { lab7MethodClass.flowerMethod(); } catch (FlowerException e) { System.err.println(e); } System.out.println(); // rose exception try { lab7MethodClass.roseMethod(); } catch (RoseException e) { System.err.println(e); } System.out.println(); // tulip exception try { lab7MethodClass.tulipMethod(); } catch (TulipException e) { System.err.println(e); } } }
SQL
UTF-8
1,705
2.890625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1:3306 -- Tiempo de generación: 20-05-2021 a las 22:35:02 -- Versión del servidor: 5.7.31 -- Versión de PHP: 7.2.33 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `producto` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `datos` -- DROP TABLE IF EXISTS `datos`; CREATE TABLE IF NOT EXISTS `datos` ( `id` int(11) NOT NULL AUTO_INCREMENT, `description` varchar(248) COLLATE utf8_bin NOT NULL, `reference` varchar(30) COLLATE utf8_bin NOT NULL, `stock` int(45) NOT NULL, `price` float NOT NULL, `currency` varchar(45) COLLATE utf8_bin NOT NULL, `imagen` longblob NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Volcado de datos para la tabla `datos` -- INSERT INTO `datos` (`id`, `description`, `reference`, `stock`, `price`, `currency`, `imagen`) VALUES (8, 'carro', 'toy', 5, 350000, 'USD', 0x433a66616b6570617468706c616e20646520616c63616e63652070616c6d206c6f676f2e706e67), (6, 'Carro Azul', 'renaull', 300, 320000, 'USD', 0x433a66616b657061746854657874696c2070616c6d2e706e67); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C++
UTF-8
758
2.703125
3
[]
no_license
#include<iostream> #include<stdio.h> #include<math.h> using namespace std; int main() { int n,i,ans,cnt; while(scanf("%d",&n)!=EOF) { if(n==1) { printf("0\n"); continue; } ans=n; for(i=2;i*i<=n;i++) { if(n%i==0)//每次去除质因数 { while(n%i==0) n/=i; cnt=i;//保存最大的质因数 } } if(n>1)//若不是1,则剩余n为质数 ,否则被完全分解,除 cnt=n; printf("%d\n",ans/cnt); } return 0; }
Ruby
UTF-8
3,262
2.875
3
[]
no_license
#!/usr/bin/env ruby ################################################################ require 'digest' require 'zlib' ################################################################ module Digest class CRC32 < Digest::Class def initialize reset end def reset @crc = 0 end def update(str) @crc = Zlib::crc32_combine(@crc, Zlib::crc32(str), str.size) end alias << update def digest_length; 4; end def finish; [@crc].pack("N"); end end end ################################################################ HASHERS = { "--crc" => Digest::CRC32, "--md5" => Digest::MD5, "--sha1" => Digest::SHA1, "--sha256" => Digest::SHA256, "--sha512" => Digest::SHA512, } DEFAULTS = ["--md5", "--sha1", "--sha256"] ################################################################ BLOCKSIZE=2**16 # 64k read size ################################################################ def usage puts "Usage:" puts " #{File.basename __FILE__} <hashers...> [<file(s)...>]" puts puts "Purpose:" puts " Hashes data streamed through a pipe to STDIN, or files specified on the command line." puts " The computed hash(es) are output to STDERR." puts puts "Options/Hashers:" HASHERS.each do |opt, klass| puts " #{opt.ljust(10)} => #{klass}" end puts " -a / --all => All of the above!" puts puts " -p / --parallel => Compute each hash in its own process (uses multiple CPUs)" puts puts "(Note: Defaults to #{DEFAULTS.join(", ")} if no hashers specified)" puts puts "Example:" puts " curl http://hostname.website/file.iso | pipesum --sha1 > file.iso" puts end ################################################################ opts, args = ARGV.partition { |arg| arg[/^--?\w/] } if opts.delete("--help") or opts.delete("-h") usage exit end opts += DEFAULTS if opts.empty? if opts.delete("--all") or opts.delete("-a") opts += HASHERS.keys end ################################################################ def sum(digests, input, output=nil, messages=$stderr, parallel=false) if parallel puts "ERROR: Parallel mode not yet implemented." exit 1 end while data = input.read(BLOCKSIZE) digests.each {|digest| digest << data } output.write(data) if output end digests.each do |digest| algo = digest.class.to_s.split("::").last messages.puts "#{algo.rjust(9)}: #{digest}" end output.close if output end def create_digests(opts) opts.uniq.map do |opt| if klass = HASHERS[opt] klass.new else puts "Unrecognized option: #{opt}" exit 1 end end end require 'epitools' if args.any? paths = args.flat_map do |arg| path = arg.to_Path if path.dir? path.ls else path end end paths.each do |path| # puts "=== #{path} =========================================" puts path puts "#{"size".rjust(9)}: #{path.size.commatize} bytes" digests = create_digests(opts) begin open(path, "rb") { |f| sum(digests, f, nil, $stdout) } rescue => e puts " #{e.inspect}" end puts end else parallel = (opts.delete("--parallel") or opts.delete("-p")) sum(create_digests(opts), $stdin, $stdout, $stderr, parallel) end
Java
UTF-8
261
2.109375
2
[ "MIT" ]
permissive
package com.hcl.myhotel.exception; public class HotelDetailsNotFoundException extends Exception{ /** * @author Sridhar reddy */ private static final long serialVersionUID = 1L; public HotelDetailsNotFoundException(String message) { super(message); } }
Java
UTF-8
471
2.921875
3
[ "Apache-2.0" ]
permissive
package net.sf.javagimmicks.util; /** * An interface for objects that can filter other objects. * * @param <E> * the type of objects to filter */ public interface Predicate<E> { /** * Determines of a given element is accepted by this {@link Predicate}. * * @param element * the element to filter out or not * @return if the given element is accepted by this {@link Predicate} */ public boolean test(E element); }
Python
UTF-8
395
3.5625
4
[]
no_license
from random import randint def getRandomCharacters(ch1, ch2): return chr(randint(ord(ch1), ord(ch2))) def getRandomLowerCharacter(): return getRandomCharacters('a', 'z') def getRandomUpperCharacter(): return getRandomCharacters('A', 'Z') def getRandomDigitCharacter(): return getRandomCharacters('0', '9') def getRandomASCIICharacter(): return chr(randint(0, 127))
C#
UTF-8
399
2.875
3
[]
no_license
public class CustomList<T> { private List<T> internalList = new List<T>(); public T this[int index] { get{ return internalList[index]; } set{ internalList[index] = value;} } //Error public void Add(T item) { // Method logic goes here. } public void Remove(T item) { // Method logic goes here. } }
JavaScript
UTF-8
1,096
2.78125
3
[ "Unlicense" ]
permissive
// share code executing a command and returning its output import when from 'when'; import spawn from 'cross-spawn-async'; export default function get_command_output( executable, options ) { options = options || {}; options.params = options.params || []; options.timeout = options.timeout || 3000; options.env = process.env; return when(new Promise((resolve, reject) => { //console.log(`Exec : spawning ${executable}`, options.exec_opts); const spawn_instance = spawn(executable, options.params, options); spawn_instance.on('error', err => { //console.log(`Exec : got err:`, err); reject(err); }); spawn_instance.stdout.on('data', data => { //console.log(`Exec : stdout: "${data}"`); resolve(('' + data).trim()); }); spawn_instance.stderr.on('data', data => { //console.log(`Exec : got stderr : "${data}"`); reject(new Error(data)); }); spawn_instance.on('close', code => { //console.log(`Exec : child process exited with code ${code}`); if (code !== 0) reject(new Error(`Exec : child process exited with code ${code}`)); }); })); }
Markdown
UTF-8
764
2.53125
3
[ "MIT" ]
permissive
#event capture event captureは収集した情報をGoogleカレンダーに登録するツールです。 *** ###アカウント情報の設定 config/gcal.sample.ymlをgcal.ymlに、config/twitter.sample.ymlをtwitter.ymlにリネームします。 そこにGoogleカレンダー、Twitterのアカウント情報を記述します。 ###Heroku環境変数に登録 $> rake heroku_env ###実行時間または時刻を設定 config/clock.ymlに実行する時間または時刻を設定します。 ####全てのモジュール共通 default="19:00" ####モジュールごと個別 module_name="8:45" ###プロセスを起動 $> heroku scale clock=1 ##License Licensed under the MIT http://www.opensource.org/licenses/mit-license.php
Java
UTF-8
1,452
3.109375
3
[]
no_license
package nbody.moving; import nbody.Coordinates; import nbody.bodies.Body; import nbody.main.Simulation; import java.util.List; public class BouncingMovement implements MovingAbility { private double px, py; // momentums private double maxMomentum = 300.0; private double mass; public BouncingMovement(double mass) { this.px = Math.random() * maxMomentum * 2 - maxMomentum; this.py = Math.random() * maxMomentum * 2 - maxMomentum; this.mass = mass; } @Override public Coordinates newCoordinates( Body current, List<Body> bodies, double dt) { Coordinates coordinates = current.getCoordinates(); if (coordinates.getX() <= current.getRadius() || coordinates.getX() >= Simulation.FRAME - current.getRadius()) { px *= -1.0; } if (coordinates.getY() <= current.getRadius() || coordinates.getY() >= Simulation.FRAME - current.getRadius()) { py *= -1.0; } return new Coordinates( coordinates.getX() + px / current.getMass() * dt, coordinates.getY() + py / current.getMass() * dt); } public double getPX() { return px; } public double getPY() { return px; } @Override public double getVX() { return px / mass; } @Override public double getVY() { return px / mass; } public boolean equals(Object o) { if (!(o instanceof BouncingMovement)) { throw new ClassCastException(); } BouncingMovement ob = (BouncingMovement)o; return px == ob.getPX() && py == ob.getPY(); } }
C++
UTF-8
2,233
2.640625
3
[]
no_license
//#define BOOST_SPIRIT_DEBUG #include <boost/fusion/adapted/struct.hpp> #include <boost/spirit/include/qi.hpp> #include <iomanip> namespace qi = boost::spirit::qi; namespace ascii = qi::ascii; namespace ast { struct JEDEC { std::string caption; struct field { char id; std::string value; }; std::vector<field> fields; uint16_t checksum; }; inline static std::ostream& operator<<(std::ostream& os, JEDEC const& jedec) { os << "Start: " << jedec.caption << "*\n"; for(auto& f : jedec.fields) os << f.id << " " << f.value << "*\n"; auto saved = os.rdstate(); os << "End: " << std::hex << std::setw(4) << std::setfill('0') << jedec.checksum; os.setstate(saved); return os; } } BOOST_FUSION_ADAPT_STRUCT(ast::JEDEC::field, (char, id)(std::string, value)) BOOST_FUSION_ADAPT_STRUCT(ast::JEDEC, (std::string, caption) (std::vector<ast::JEDEC::field>, fields) (uint16_t, checksum)) template <typename It> struct JedecGrammar : qi::grammar<It, ast::JEDEC(), ascii::space_type> { JedecGrammar() : JedecGrammar::base_type(start) { const char STX = '\x02'; const char ETX = '\x03'; value = *(ascii::char_("\x20-\x7e\r\n") - '*') >> '*'; field = ascii::graph >> value; start = STX >> value >> *field >> ETX >> xmit_checksum; BOOST_SPIRIT_DEBUG_NODES((start)(field)(value)) } private: qi::rule<It, ast::JEDEC(), ascii::space_type> start; qi::rule<It, ast::JEDEC::field()> field; qi::rule<It, std::string()> value; qi::uint_parser<uint16_t, 16, 4, 4> xmit_checksum; }; int main() { typedef boost::spirit::istream_iterator It; It first(std::cin>>std::noskipws), last; JedecGrammar<It> g; ast::JEDEC jedec; bool ok = phrase_parse(first, last, g, ascii::space, jedec); if (ok) { std::cout << "Parse success\n"; std::cout << jedec; } else std::cout << "Parse failed\n"; if (first != last) std::cout << "Remaining input unparsed: '" << std::string(first, last) << "'\n"; }
C#
UTF-8
1,620
2.90625
3
[]
no_license
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; namespace RelevesMeteo { public class BoolToVisibilityConverter : IValueConverter { /// <summary> /// /// </summary> /// <param name="value">Combobox</param> /// <param name="targetType"></param> /// <param name="parameter">Dictionnaire de ressources</param> /// <param name="culture"></param> /// <returns></returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = ((bool)value ? Visibility.Visible : Visibility.Hidden); return v; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class DoubleToColorBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double d = (double)value; double seuil = (double)parameter; Color c = (d < seuil ? Colors.Yellow : Colors.White); return new SolidColorBrush(c); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
Python
UTF-8
2,000
4.03125
4
[]
no_license
import string #1A def is_word_guessed(secret_word,letters_guessed): ''' This Function is used to check if all the letters guessed are in the secret word, str1 is a blank string used to convert the set of characters in letters_guessed into a string to compare it with the secret word''' S1 = set(secret_word) S2 = set(letters_guessed) if (S2.issubset(S1)): return True else: return False #1B def get_guessed_word(secret_word,letters_guessed): str1 = '' returnString ='' for char in secret_word: if char in str1.join(letters_guessed): returnString = returnString + (char) else: returnString = returnString +'_' return returnString #1C def get_available_letters(letters_guessed): str1 = '' returnString ='' for char in string.ascii_lowercase: if char not in str1.join(letters_guessed): returnString = returnString + (char) return returnString def hangman(secret_word): letters_guessed = [] print 'The secret word Contains ',len(secret_word),'letters' guesses = len(secret_word) - 1 while(guesses>0): print 'You have ',guesses,'guesses remaining.' print 'letters remaining ->',get_available_letters(letters_guessed) charinput = list(raw_input('Enter you letter.. --->')) letters_guessed = letters_guessed + charinput if (is_word_guessed(secret_word, letters_guessed) == True): print 'The Word you guessed is in the secret word.' else: print 'The word you guessed is not in the secret word.' print(get_guessed_word(secret_word, letters_guessed)) print'letters remaining ->' ,(get_available_letters(letters_guessed)) guesses = guesses - 1 print '===============================' print 'The letters you guessed are ->',letters_guessed hangman('hurshwa')
C++
UTF-8
2,181
3.640625
4
[]
no_license
inline Color::Color() : red_(0.0f) , green_(0.0f) , blue_(0.0f) {} inline Color::Color(float red, float green, float blue) : red_(red) , green_(green) , blue_(blue) {} inline void Color::set_red(float red) { red_ = red; } inline void Color::set_green(float green) { green_ = green; } inline void Color::set_blue(float blue) { blue_ = blue; } inline float Color::get_red() const { return red_; } inline float Color::get_green() const { return green_; } inline float Color::get_blue() const { return blue_; } inline Color& Color::operator += (const Color& c) { red_ += c.red_; green_ += c.green_; blue_ += c.blue_; return *this; } inline Color& Color::operator -= (const Color& c) { red_ -= c.red_; green_ -= c.green_; blue_ -= c.blue_; return *this; } inline Color& Color::operator *= (const Color& c) { red_ *= c.red_; green_ *= c.green_; blue_ *= c.blue_; return *this; } inline const Color Color::operator + (const Color& c) { Color result(*this); result += c; return result; } inline const Color Color::operator - (const Color& c) { Color result(*this); result -= c; return result; } inline const Color Color::operator * (const Color& c) { Color result(*this); result *= c; return result; } inline Color& Color::operator *= (float factor) { red_ *= factor; green_ *= factor; blue_ *= factor; return *this; } inline Color& Color::operator /= (float factor) { red_ /= factor; green_ /= factor; blue_ /= factor; return *this; } inline const Color Color::operator * (float factor) { Color result(*this); result *= factor; return result; } inline const Color Color::operator / (float factor) { Color result(*this); result /= factor; return result; } inline const Color operator * (float factor, const Color& c) { Color result(c); result *= factor; return result; } inline std::ostream& operator << (std::ostream& os, const Color& c) { os << "(" << c.get_red() << "," << c.get_green() << "," << c.get_blue() << ")"; return os; }
Shell
UTF-8
929
2.859375
3
[]
no_license
#!/bin/sh host=192.168.10.100 app=FocusEyeSelector echo getting latest executable tftp -g -r $app $host #tftp -g -r $app.ini $host chmod a+x ./$app skip_setup= skip_data= if [ $skip_setup ] then echo skipping setup else cd /usr/lib tftp -g -r libcxcore.so.2 $host tftp -g -r libcv.so.2 $host tftp -g -r libhighgui.so.2 $host tftp -g -r libz.so.1 $host #tftp -g -r libEyeSegmentationLib.so $host #tftp -g -r libBiOmega.so $host chmod a+x *.so* fi cd if [ $skip_data ] then echo Skipping data update else mkdir -p data/Input mkdir -p data/Output echo getting data for i in 44 45 46 47 48 49 50 100 101 102 103; do echo $i; tftp -g -r data_focus/EyeSwipeMini/LeftCamera/eye_$i.pgm -l data/Input/eye_$i.pgm $host; done #for i in 0 1; do echo $i; tftp -g -r data_eyeSeg/test/Test$i.pgm -l data/test/Test$i.pgm $host; done #tftp -g -r data_eyeSeg/database/IrisCodeDatabase.bin -l data/database/IrisCodeDatabase.bin $host fi
PHP
UTF-8
373
2.578125
3
[]
no_license
<?php // Set the location to redirect the page header ('Location: Main_Tool.php'); // Open the text file in writing mode $file = fopen("form-save.txt", "a"); foreach($_POST as $name => $value) { fwrite($file, $name); fwrite($file, "="); fwrite($file, $value); fwrite($file, "\r\n"); } fwrite($file, "\r\n"); fclose($file); exit; ?>
Python
UTF-8
9,385
2.578125
3
[]
no_license
# Dependencies: from pymprog import * # pip install pymprog from icalendar import * # pip install icalendar from datetime import * from swiglpk import * # pip install swiglpk import pytz # pip install pytz from tzlocal import get_localzone ################################################################################ # Helper functions ################################################################################ def split(e): """ Splits long events (> 2 hours) in two new separate events (with different UID). This is intended for Friday's 4 hours lab slots. """ twoHours = timedelta(seconds = 60 * 60 * 2) start = e['DTSTART'].dt end = e['DTEND'].dt if (end - start <= twoHours): return [e] mid = vDDDTypes(start + twoHours) e1 = e.copy() e2 = e.copy() e1['DTEND'] = mid e2['DTSTART'] = mid e2['UID'] = e2['UID'] + 'b' return [e1, e2] def partition(cal): """ Parition the events in the calendar in 3 dictionaries (indexed by start date) using the description field (grading, labs, exercises). """ (grads, labs, exs) = ([], [], []) for e in cal.walk('VEvent'): desc = e['DESCRIPTION'] if "Laboration\nPresentation" in desc: grads.append(e) elif "Laboration" in desc: labs += split(e) elif "Exercise" in desc: exs.append(e) return [ { e['DTSTART'].dt : e for e in d } for d in (grads, labs, exs) ] def mkAttendee(name): """ Create an address object for a grader """ a = vCalAddress(name) # "MAILTO:" + mail[i] for mail invite a.params['cn'] = name return a ################################################################################ # Report ################################################################################# def summary(d, events): """ Per grader view of the events contained in the dictionary d """ kd = sorted(d.keys()) ts = [ (i,j) for (i,j) in kd if d[i,j].primal ] r = { k : [] for k in zip(*kd)[0] } for (i,j) in ts: e = events[j] r[i].append(e) return r def fmt_budget(k, u, a): fmt = " {}: {} / {}" return fmt.format(k, u, a) def fmt_budget_summary(d): title = "Hour count:\n" body = [fmt_budget(k, b[0], b[1]) for (k, b) in sorted(d.items())] return "\n".join([title] + body) def fmt_slot(e) : start = e['DTSTART'].dt.astimezone(get_localzone()) end = e['DTEND'].dt.astimezone(get_localzone()) loc = e['LOCATION'] s1 = start.strftime("%a %d %b %H:%M") s2 = end.strftime("%H:%M") s3 = " @ " + loc if loc else "" return " " + s1 + " - " + s2 + s3 def fmt_summary(desc, es): title = desc + ":\n" body = [fmt_slot(e) for e in es] return "\n".join([title] + body) def sep(): return "\n\n" + 80 * "-" + "\n\n" def report(T, budget, *ss): with open("report.md", "wt") as r: title = "Report - IFP 18\n" pre = fmt_budget_summary(budget) r.write("\n".join([title,pre])) for k in T: r.write(sep()) r.write("### " + k + "\n\n") tt = [fmt_summary(desc, s[k]) for (desc, s) in ss] r.write("\n\n".join(tt)) r.write(sep()) ################################################################################ # Create calendars ################################################################################ def mkCals(A, events): """ Create a complete calendar with all grader and one for each grader """ def mkCal(pid): return Calendar(PRODID = pid , VERSION = 2.0) # version 2.0 is important! full_cal = mkCal(Course) single_cal = { k : mkCal(Course + k) for k in A.keys() } for e in events.values(): full_cal.add_component(e) for k in e['ATTENDEE']: e1 = e.copy() e1['UID'] = k + e1['UID'] single_cal[k].add_component(e1) return (full_cal, single_cal) ################################################################################ ########### # Parsing # ########### # Name of the timeEdit ics file for the course. cal_file = 'TimeEdit_TKDAT-1_N1COS-1-GU_TDA555_2018-08-31_09_03.ics' with open(cal_file, 'rb') as g: cal = Calendar.from_ical(g.read()) (grads, labs, exs) = partition(cal) events = { k : e for (k, e) in grads.items() + labs.items() + exs.items() } ######### # Model # ######### Course = 'IFP 2018 - TA schedule' M = begin(Course) # Variables phd = { 'Marco' : "vassena@chalmers.se" , 'Elisabet' : "elilob@chalmers.se" # , 'Matthi' : "" # , 'Sola' : "" , 'Benjamin' : "" } msc = { 'Henrik' : "henrost@student.chalmers.se" , 'Sarosh' : "sarosh.nasir@gmail.com;" , 'Adi' : "hrustic@student.chalmers.se" , 'Karin' : "karin.wibergh@gmail.com" } mail = { k : v for (k,v) in phd.items() + msc.items()} T = sorted(phd.keys() + msc.keys()) B = var('budget', T) # Domains Es = sorted(exs.keys()) Gs = sorted(grads.keys()) Ls = sorted(labs.keys()) slots = sorted(Es + Gs + Ls) Y = 2018 Sep = 9 Oct = 10 # When you won't be able to make it? Clash = { 'Marco' : { date(Y,Sep,d) for d in {6, 11} } | { date(Y,Oct,d) for d in {22, 23, 24} } , 'Elisabet' : { date(Y,Oct,d) for d in xrange(8, 16 + 1) } | { date(Y,Sep,d) for d in {14, 17, 19, 20} } # Octopi Seminar , 'Henrik' : { date(Y,Oct,1) } # , 'Matthi' : { date(Y,Sep,d) for d in xrange(22, 29 + 1) } # , 'Sola' : { date(Y,Sep,d) for d in xrange(12, 20 + 1) } , 'Karin' : { date(Y,Sep,d) for d in xrange(3, 9 + 1) } , 'Adi' : { date(Y,Sep,d) for d in {7, 14} } | { date(Y,Sep,d) for d in {20} } | { date(Y,Oct,d) for d in {4, 11, 18, 25} } , 'Benjamin' : { date(Y,Sep,d) for d in xrange(1, 9) } , 'Sarosh' : { date(Y,Sep,d) for d in {10, 17, 24} } # no mondays (Sep) | { date(Y,Oct,d) for d in {1, 8, 15, 22} } # no mondays (Oct) | { date(Y,Sep,d) for d in {5, 12, 19, 26} } # no wed (Sep) | { date(Y,Oct,d) for d in {3, 10, 17, 24} } # no wed (Oct) } # 1 if T has to serve on a time slot E = var('exercise', iprod(T, Es), bool) G = var('grading', iprod(T, Gs), bool) L = var('labs', iprod(T, Ls), bool) # Penalty: it's used to relax constraints PE = var('penalty exercise', iprod(T, Es), int) PG = var('penalty grading', iprod(T, Gs), int) # D[i,j] is the absolute value of the difference in the number of hours between # TA i and j. D = var('delta', iprod(T,T)) ############### # Constraints # ############### # TODO: create an object for TA to store all this information # Budget for i in {'Marco', 'Elisabet'} : B[i] <= 130 for i in msc.keys() + ['Benjamin'] : B[i] <= 90 # Count hours for i in B.keys(): B[i] == sum ([2 * L[i,j] for j in Ls] + [2 * G[i,h] for h in Gs] + [3 * E[i,k] for k in Es]) # 4 TA per lab for j in Ls: sum( L[i,j] for i in T ) == 4 # 3 TA per exercise session for j in Es: sum( E[i,j] for i in T ) == 3 # same msc TA for exercises for k in msc: for i in Es: for j in Es: E[k,i] == E[k,j] # + PE[k,j] # Always one PhD at exercise for j in Es: sum(E[i,j] for i in phd.keys()) == 1 # All TAs at grading for j in Gs: n = 7 if j.date().weekday() == 0 else 5 # 7 on Monday, 5 otherwise (tuesday) sum( G[i,j] + PG[i,j] for i in T ) >= n # TODO: It should be == # Either exercise on Monday or grading on Tuesday # Too strict with few TAs #for i in msc.keys(): # for j in Es: # tuesdays = {k for k in Gs if k.date().weekday() == 1} # for k in tuesdays: # E[i,j] + G[i,k] <= 1 # Clashes for d in [L,E,G]: for (j,k) in d.keys(): #print "".join(["Clash?", str(k.date()), str(j), str(k.date() in Clash.get(j,{}))]) if k.date() in Clash.get(j,{}): d[j,k] == 0 # Compute delta for i in T: for j in T: D[i,j] <= 10 # Only small bias # compute delta (absolute value) B[i] - B[j] <= D[i,j] B[j] - B[i] <= D[i,j] # Objective function # Minimize penalties and biased schedules minimize(sum ( [ 10000 * PG[i,j] for i in T for j in Gs ] + [ 25 * PE[i,j] for i in T for j in Es ] + [ D[i,j] for i in T for j in T ] )) #################### # Solve and report # #################### verbose(True) solver( 'intopt' , mip_gap = 3.0, # Or we look for ever without really improving ) solve() stat = M.get_status() if stat == GLP_INFEAS or stat == GLP_NOFEAS: print(KKT()) exit("No solution: relax constraints") elif stat == GLP_SOL or stat == GLP_FEAS or stat == GLP_OPT: budget_sum= { k : (B[k].primal , B[k].bounds[1]) for k in sorted(B.keys()) } ex_sum = summary(E, events) gr_sum = summary(G, events) lab_sum = summary(L, events) # Text report ss = [ ("Exercises", ex_sum) , ("Labs", lab_sum) , ("Grading", gr_sum)] report(T, budget_sum, *ss) # Ics Report (calendar) # Attende object for each TA A = { k : mkAttendee(k) for k in T } all_sum = ex_sum.items() + gr_sum.items() + lab_sum.items() # Add TA to ics events for (i, es) in all_sum: for e in es: e.add('ATTENDEE', A[i]) (full_cal, single_cal) = mkCals(A, events) # Write calendars with open("full.ics","wb") as out: out.write(full_cal.to_ical()) for (k, cal) in single_cal.items(): with open(k + ".ics", "wb") as out: out.write(cal.to_ical()) #sensitivity() # sensitivity report (bug!) end()
Python
UTF-8
1,585
2.9375
3
[]
no_license
import pandas as pd import numpy as np seattle_zipcodes = [98101, 98102, 98103, 98104, 98105, 98106, 98107, 98108, 98109, 98112, 98115, 98116, 98117, 98118, 98119, 98121, 98122, 98125, 98126, 98133, 98136, 98144, 98177, 98199] neighborhoods = {98101: 'Downtown', 98102: 'Captiol Hill', 98103: 'Wallingford', 98104: 'Pioneer Square', 98105: 'University District', 98106: 'Highland Park', 98107: 'Ballard', 98108: 'Georgetown/Beacon Hill', 98109: 'Westlake', 98112: 'Montlake', 98115 : 'Wedgewood', 98116: 'West Seattle/Alki', 98117: 'Crown Hill', 98118: 'Rainier Valley', 98119: 'Queen Anne', 98121: 'BellTown', 98122: 'Capitol Hill/Madrona', 98125: 'Lake City', 98126: 'West Seattle', 98133: 'North Park', 98136: 'Fauntleroy', 98144: 'Mt. Baker', 98177: 'Richmond Beach', 98199: 'Magnolia'} def create_rent_df(rent_filepath): return pd.read_csv(rent_filepath) def clean_rental_data(rent_filepath): rent_data = create_rent_df(rent_filepath) reduced_rent = rent_data[rent_data['RegionName'].isin(seattle_zipcodes)].copy() pruned_rent = reduced_rent.dropna(axis=1, how='all').copy() years=[] for num in range(2011,2018): years.append(str(num)) for year in years: pruned_rent[year] = pruned_rent.loc[:, pruned_rent.columns.str.startswith(year)].median(axis=1) pruned_rent['neighborhood']= pruned_rent['RegionName'].map(neighborhoods) pruned_rent = pruned_rent.rename(columns={'RegionName':'zipcode'}) clean_rent = pruned_rent.filter(items=['zipcode', 'neighborhood', *years]).reset_index(drop=True).copy() return clean_rent
Swift
UTF-8
702
2.65625
3
[]
no_license
// // ModalOverlayNode.swift // SpaceUp // // Created by David Chin on 22/06/2015. // Copyright (c) 2015 David Chin. All rights reserved. // import SpriteKit class ModalOverlayNode: SKShapeNode { init(rectOfSize size: CGSize) { super.init() let rect = CGRect(origin: CGPoint(x: size.width / -2, y: size.height / -2), size: size) path = CGPathCreateWithRect(rect, nil) fillColor = UIColor(white: 0, alpha: 0.5) strokeColor = UIColor.clearColor() position = CGPoint(x: rect.width / 2, y: rect.height / 2) userInteractionEnabled = false zPosition = -1 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
Java
UTF-8
2,028
3.234375
3
[]
no_license
package array; import java.util.Random; public class main { public static void main(String[] args) { Random gerador = new Random(); int time1,time2; int batalhas =1500,contc=0,contt=0,mortost=0,mortosc=0; while(batalhas>0) { time1 = gerador.nextInt(5)+1; time2 = gerador.nextInt(5)+1; Totodile[] tototime = new Totodile[time1]; System.out.println(time1+" totodiles"); System.out.println(time2+" Cyndaquils"); for(int h = 0;h<time1;h++) { Totodile t = new Totodile("Toto"); tototime[h] = t; } Cyndaquil[] cyndatime = new Cyndaquil[time2]; for(int h = 0;h<time2;h++) { Cyndaquil t = new Cyndaquil("Cynda"); cyndatime[h] = t; } Batalha B1 = new Batalha(); boolean flag = true; boolean atktorc = true;//quem ataca primeiro cyndaquil ou toto; int i,j; while(flag) { if(atktorc == true) {//cyndatime ataca i = B1.indice(cyndatime); j = B1.indice(tototime); System.out.println("Totodile "+j+" HP:"+tototime[j].HP+" Toma:"+ tototime[j].tomouataque(cyndatime[i].ataque(gerador.nextInt(5)))+" de Dano do Cyndaquil "+i); if(B1.morreu(tototime, j)==-1) { mortost++; flag = false; System.out.println("Cynda time ganhou"); break; } mortost+=B1.morreu(tototime, j); atktorc = false; } else { //tototime ataca i = B1.indice(tototime); j = B1.indice(cyndatime); System.out.println("Cyndaquil "+j+" HP:"+cyndatime[j].HP+" Toma:"+ cyndatime[j].tomouataque(tototime[i].ataque(gerador.nextInt(5)))+" de Dano do Totodile "+i); if(B1.morreu(cyndatime, j)==-1) { mortosc++; flag = false; System.out.println("Toto time ganhou"); break; } mortosc+=B1.morreu(cyndatime, j); atktorc = true; } } if(atktorc) { contc++; } else { contt++; } batalhas--; } System.out.println("Tototime venceu:"+contt+"\n"+"Cyndatime venceu:"+contc+ "\nTotodiles mortos:"+mortost+" Cyndaquils mortos:"+mortosc); } }
Java
UTF-8
2,021
2.1875
2
[]
no_license
package com.ciazhar.qrbarcodescanner; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; public class SplashActivity extends AppCompatActivity { AgendaRepository database; RequestQueue queue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); queue = Volley.newRequestQueue(this); database = new AgendaRepository(this); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(SplashActivity.this,AgendaActivity.class); // startActivity(intent); getAgendaFromServer(intent); finish(); } },3000L); } public void getAgendaFromServer(final Intent intent) { int method = Request.Method.GET; String url = "http://103.246.107.213:9999/api/agenda/all"; JsonArrayRequest request = new JsonArrayRequest(method, url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { database.deleteAllAgendaFromDatabase(); database.insertAgendaToDatabase(response); startActivity(intent); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); queue.add(request); } }
Go
UTF-8
4,794
2.8125
3
[ "MIT" ]
permissive
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * rpc/hd_socket_trans.go * * * * hprose half duplex socket transport for Go. * * * * LastModified: Jan 7, 2017 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ package rpc import ( "net" "runtime" "sync" "sync/atomic" "time" ) type halfDuplexConnEntry struct { conn net.Conn timer *time.Timer } type halfDuplexSocketTransport struct { idleTimeout time.Duration connPool chan *halfDuplexConnEntry connCount int32 nextid uint32 createConn func() (net.Conn, error) cond sync.Cond } func newHalfDuplexSocketTransport() (hd *halfDuplexSocketTransport) { hd = new(halfDuplexSocketTransport) hd.idleTimeout = 0 hd.connPool = make(chan *halfDuplexConnEntry, runtime.NumCPU()) hd.connCount = 0 hd.nextid = 0 hd.cond.L = &sync.Mutex{} return } func (hd *halfDuplexSocketTransport) setCreateConn(createConn func() (net.Conn, error)) { hd.createConn = createConn } // IdleTimeout returns the conn pool idle timeout of hprose socket client func (hd *halfDuplexSocketTransport) IdleTimeout() time.Duration { return hd.idleTimeout } // SetIdleTimeout sets the conn pool idle timeout of hprose socket client func (hd *halfDuplexSocketTransport) SetIdleTimeout(timeout time.Duration) { hd.idleTimeout = timeout } // MaxPoolSize returns the max conn pool size of hprose socket client func (hd *halfDuplexSocketTransport) MaxPoolSize() int { return cap(hd.connPool) } // SetMaxPoolSize sets the max conn pool size of hprose socket client func (hd *halfDuplexSocketTransport) SetMaxPoolSize(size int) { if size > 0 { pool := make(chan *halfDuplexConnEntry, size) for i := 0; i < len(hd.connPool); i++ { select { case pool <- <-hd.connPool: default: } } hd.connPool = pool } } func (hd *halfDuplexSocketTransport) getConn() *halfDuplexConnEntry { for hd.connPool != nil { select { case entry, ok := <-hd.connPool: if !ok { panic(ErrClientIsAlreadyClosed) } if entry.timer != nil { entry.timer.Stop() } if entry.conn != nil { return entry } continue default: return nil } } panic(ErrClientIsAlreadyClosed) } func (hd *halfDuplexSocketTransport) fetchConn() (*halfDuplexConnEntry, error) { hd.cond.L.Lock() for { entry := hd.getConn() if entry != nil && entry.conn != nil { hd.cond.L.Unlock() return entry, nil } if int(atomic.AddInt32(&hd.connCount, 1)) <= cap(hd.connPool) { hd.cond.L.Unlock() conn, err := hd.createConn() if err == nil { return &halfDuplexConnEntry{conn: conn}, nil } atomic.AddInt32(&hd.connCount, -1) return nil, err } atomic.AddInt32(&hd.connCount, -1) hd.cond.Wait() } } func (hd *halfDuplexSocketTransport) close() { if hd.connPool != nil { connPool := hd.connPool hd.connPool = nil hd.connCount = 0 close(connPool) for entry := range connPool { if entry.timer != nil { entry.timer.Stop() } if entry.conn != nil { entry.conn.Close() } } } } func (hd *halfDuplexSocketTransport) closeConn(conn net.Conn) { conn.Close() atomic.AddInt32(&hd.connCount, -1) } func (hd *halfDuplexSocketTransport) sendAndReceive( data []byte, context *ClientContext) ([]byte, error) { entry, err := hd.fetchConn() if err != nil { hd.cond.Signal() return nil, err } conn := entry.conn err = conn.SetDeadline(time.Now().Add(context.Timeout)) if err == nil { err = hdSendData(conn, data) } if err == nil { data, err = hdRecvData(conn, data) } if err == nil { err = conn.SetDeadline(time.Time{}) } if err != nil { hd.closeConn(conn) hd.cond.Signal() return nil, err } if hd.idleTimeout > 0 { if entry.timer == nil { entry.timer = time.AfterFunc(hd.idleTimeout, func() { hd.closeConn(conn) entry.conn = nil entry.timer = nil }) } else { entry.timer.Reset(hd.idleTimeout) } } hd.connPool <- entry hd.cond.Signal() return data, nil }
Java
UTF-8
3,161
2.296875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2003 - 2014 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.ui.wicket.resources; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.util.io.IClusterable; /** * This class is used as a Reference to an Object in the eFaps-DataBase.<br> * * @author The eFaps Team */ public class EFapsContentReference implements IClusterable { /** * Needed for serialization. */ private static final long serialVersionUID = 1L; /** * the name of this EFapsContentReference. With this name the Object from * the eFpas-DataBase will be identified. */ private final String name; /** * Constructor setting the name of the EFapsContentReference, from combining * the name of the class and the name. * * @param _scope class the name will be included * @param _name name of the Object */ public EFapsContentReference(final Class<?> _scope, final String _name) { this(_scope.getPackage().getName() + "." + _name); } /** * Constructor setting the name of the EFapsContentReference. * * @param _name Name to set */ public EFapsContentReference(final String _name) { this.name = _name; } /** * This is the getter method for the instance variable {@link #name}. * * @return value of instance variable {@link #name} */ public String getName() { return this.name; } /** * get the URL to an Image from the eFaps-DataBase. * * @return URL as a String */ public String getImageUrl() { return EFapsContentReference.getImageURL(this.name); } /** * get the URL to a Static Content from the eFaps-DataBase. * * @return URL as a String */ public String getStaticContentUrl() { return EFapsContentReference.getContentURL(this.name); } /** * Gets the image URL. * * @param _name the name * @return the image URL */ public static String getImageURL(final String _name) { return RequestCycle.get().getUrlRenderer().renderContextRelativeUrl("servlet/image/" + _name); } /** * Gets the content URL. * * @param _name the name * @return the content URL */ public static String getContentURL(final String _name) { return RequestCycle.get().getUrlRenderer().renderContextRelativeUrl("servlet/static/" + _name); } }
JavaScript
UTF-8
2,209
2.9375
3
[]
no_license
import React, {Component} from 'react'; import Plaintext from './components/Plaintext'; import Ciphertext from './components/Ciphertext'; import Shift from './components/Shift'; import Paper from '@material-ui/core/Paper'; class Main extends Component { constructor() { super(); this.state = { indexTable: {}, letters: 'abcdefghijklmnopqrstuvwxyz', cipherText: "", plainText: "" }; } createWordIndex = () => { const { letters } = this.state; let table = {}; for (let index = 0; index < letters.length; index++) { const element = letters[index]; table[element] = index + 1; } this.setState({ indexTable: table }); }; componentDidMount(){ // create index for easy and faster mapping this.createWordIndex(); } findLetterInIndex = (value) => { const { indexTable } = this.state; return Object.keys(indexTable).find(key => indexTable[key] === value); }; encrypt = (word = "", shift = 1) => { const { indexTable } = this.state; let result = word.split('').map( letter => { let currIndex = indexTable[letter]; if(currIndex) return this.findLetterInIndex(currIndex + Number(shift)) else return letter }); return result.join(''); }; handleShiftChange = (event) => { let shift = event.target.value; let { plainText } = this.state; let cipherText = this.encrypt(plainText, shift); this.setState({ cipherText, plainText, shift }) }; handlePlainTextInput = (event) => { let text = event.target.value; let { shift } = this.state; let cipherText = this.encrypt(text, shift); this.setState({ cipherText, plainText: text, shift }) }; render() { return ( <div className="container"> <center><h1>Caesar's Cipher</h1></center> <Shift onChange={this.handleShiftChange}></Shift> <Paper elevation={10} className="child-container"> <Plaintext onChange={this.handlePlainTextInput}></Plaintext> <Ciphertext cipherText={this.state.cipherText}></Ciphertext> </Paper> </div> ); } } export default Main;