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
Swift
UTF-8
6,479
2.8125
3
[]
no_license
// // EOINInstanceVariableParser.swift // CreateJsonSwiftObjects // // Created by Eoin Norris on 06/01/2015. // Copyright (c) 2015 Eoin Norris. All rights reserved. // import Cocoa public class myObject:NSObject { override init(){ super.init() } init(jsonDictionary:NSDictionary) { super.init() } } public class JSONParser{ func convertNSArrayToArrayOfType<T>(inArray:NSArray)->[T]{ var array = [T]() for potentialStr in inArray{ if let str = potentialStr as? T{ array.append(str) } } return array } func convertNSArrayOfDictionariesToArraysOfObjects(inArray:NSArray)->[myObject]{ var objectArray:[myObject] = [] for probableDict in inArray{ if let dict: NSDictionary = probableDict as? NSDictionary{ var thisFriend = myObject(jsonDictionary: dict) objectArray.append(thisFriend) } } return objectArray } } class EOINInstanceVariableParser: EoinJSONSuper { let initCreator:EOINInitMethodCreator = EOINInitMethodCreator() func isString(value:AnyObject, keyStr:String)->(name:String?,isString:Bool){ var result:String? = nil var resultBool:Bool = false let possibleValueStr:NSString? = value as? NSString if let valueStr = possibleValueStr{ result = "\tvar " + keyStr + ": String?\n" resultBool = true } return (result,resultBool) } func nsNumber2Type(number:NSNumber)->String{ var result:String = "" let charStr:UnsafePointer<Int8> = number.objCType let typeStrPossible = String(UTF8String: charStr); if let typeStr = typeStrPossible{ switch (typeStr){ case "i": result = "Int?" case "f": result = "Float?" case "c": result = "Bool?" case "d": result = "Double?" default: result = "Int?" } } return result } func isNumber(value:AnyObject, keyStr:String)->(name:String?,isNumber:Bool){ var result:String? = nil var resultBool:Bool = false let possibleValueInt:NSNumber? = value as? NSNumber if let valueInt = possibleValueInt{ let realType = nsNumber2Type(valueInt) result = "\tvar " + keyStr + ": \(realType)\n" resultBool = true } return (result,resultBool) } func isArray(value:AnyObject, keyStr:String)->(name:String?,isArray:Bool,elementType:EOINParamaterType){ var result:String? = nil var resultBool:Bool = false var (varStr,type) = ("",EOINParamaterType()) let possibleValueArray:NSArray? = value as? NSArray if let valueArray = possibleValueArray{ var count = valueArray.count var arrayType = "" if count>0 { var item:AnyObject = valueArray[0] (varStr,type) = getInstanceVariableType(item, keyStr: keyStr) arrayType = varStr arrayType = cleanUpTypeForParamaterization(arrayType) } if (arrayType.isEmpty==false){ result = "\tvar " + keyStr + ": Array<" + arrayType + ">?\n" } else { result = "\tvar " + keyStr + ": Array?\n" } resultBool = true } return (result,resultBool,type) } let prefix = "MyClass" func getObjectName(value:AnyObject, keyStr:String)->(name:String?,isDict:Bool){ var result:String? = nil var resultBool:Bool = false var name = keyStr //todo move into utility name = name.firstCharacterUpperCase() if name.hasSuffix("s"){ name = name.substringToIndex(name.endIndex.predecessor()) // "Dolphi" } var typeStr = "\(prefix)\(name)" // JSON Objects are dicts let possibleValueDictionary:NSDictionary? = value as? NSDictionary if let valueDict = possibleValueDictionary{ resultBool = true result = "\tvar " + name + ": \(typeStr)\n" } return (result,resultBool) } typealias instanceResultType = (name:String, type:EOINParamaterType) func getInstanceVariableType(value:AnyObject, keyStr:String)->(instanceResultType) { var paramType = EOINParamaterType() var elementType = EOINParamaterType() var (valueStr, isValidStr) = isString(value, keyStr: keyStr) if isValidStr{ paramType.paramaterName = keyStr; paramType.paramaterTypeStr = cleanUpTypeForParamaterization(valueStr!) paramType.paramType = ParamamterType.Simple return (valueStr!,paramType) } (valueStr, isValidStr) = isNumber(value, keyStr: keyStr) if isValidStr{ paramType.paramaterName = keyStr; paramType.paramaterTypeStr = cleanUpTypeForParamaterization(valueStr!); paramType.paramType = ParamamterType.Simple return (valueStr!,paramType) } (valueStr, isValidStr,elementType) = isArray(value, keyStr: keyStr) if isValidStr{ paramType.paramaterName = keyStr; paramType.paramaterTypeStr = cleanUpTypeForParamaterization(valueStr!); switch(elementType.paramType){ case .Simple: paramType.paramType = ParamamterType.ArrayOfInBuilts case .Object: paramType.paramType = ParamamterType.ArrayOfCustomItems default: paramType.paramType = ParamamterType.ArrayOfInBuilts } return (valueStr!,paramType) } (valueStr, isValidStr) = getObjectName(value, keyStr: keyStr) if isValidStr{ paramType.paramaterName = keyStr; paramType.paramaterTypeStr = cleanUpTypeForParamaterization(valueStr!); paramType.paramType = ParamamterType.Object return (valueStr!,paramType) } return ("\n",paramType) } }
C++
UTF-8
12,315
3.296875
3
[ "MIT" ]
permissive
/* Next player is o. states are represented by long long. 0:empty, 1:o, 2:x ox- o-o --x is 011000_010001_000010 you can change size by boardSize. Run c++ -std=c++17 -O3 reachable_state.cpp ./a.out */ #include <iostream> #include <unordered_map> #include <vector> #include <time.h> #include <bitset> // 0: empty, 1: o, 2: x // i=0; bottom // j=0; right using namespace std; typedef long long ll; typedef unordered_map<ll, int> stateMap; // element is 1. no meaning const int boardSize = 4; vector< vector<ll> > cellNumbers; // it is used to get a cell number. vector<ll> rowNumbers; // it is used to get a row numbers. // use to check win vector<ll> xWinMasks; // check row, column and diagonal line vector<ll> oWinMasks; vector<ll> eWinMasks; // TODO: remove this. it should be save to storage. if 5 by 5 not enough memory. vector<stateMap> allStateSet; bool contains(stateMap *base, ll state){ return base->find(state) != base->end(); } int moveLeft(int rowState, int i){ // move the piece(index) to left // rowState is one row state // index 0 is right int newRow = 0; // add cell from right for(int j=0;j<boardSize-1;j++){ if (j<i){ newRow += int(cellNumbers[0][j]) & rowState; // same as base row state }else{ newRow += (int(cellNumbers[0][j+1]) & rowState) >> 2; // 1 bit shift to right } } newRow += 2 << (boardSize-1)*2; // the left is x (2). turn is always x(because the turn already changed) return newRow; } int moveRight(int rowState, int i){ // move the piece(index) to right // rowState is one row state // index 0 is right int newRow = 0; // add cell from left for(int j=boardSize-1;j>0;j--){ if (j>i){ newRow += int(cellNumbers[0][j]) & rowState; // same as base row state }else{ newRow += (int(cellNumbers[0][j-1]) & rowState) << 2; // 1 bit shift to left } } newRow += 2; // the right is x. return newRow; } ll getCellNumber(int row, int column, ll state){ return cellNumbers[row][column] & state; } int getShiftedCellNumber(int row, int column, ll state){ ll cellNumber = getCellNumber(row, column, state); return int(cellNumber >> (row*boardSize + column)*2); } ll swapPlayer(ll state){ ll newState = 0ll; int n; for(int i=boardSize-1;i>=0;i--){ for(int j=boardSize-1;j>=0;j--){ newState = newState << 2; n = getShiftedCellNumber(i, j, state); // swap 1 and 2 (o and x) if (n == 1){ newState += 2ll; }else if (n == 2){ newState += 1ll; } } } return newState; } ll reverseState(ll state){ // return reverse (mirror) state ll newState = 0ll; for(int i=boardSize-1;i>=0;i--){ for(int j=boardSize-1;j>=0;j--){ newState = newState << 2; newState += ll(getShiftedCellNumber(i, boardSize - j - 1, state)); } } return newState; } ll rotatedState(ll state){ // {1, 2, 3, // 4, 5, 6 // 7, 8, 9} // to // {3, 6, 9, // 2, 5, 8 // 1, 4, 7} ll newState = 0; for(int i=boardSize-1;i>=0;i--){ for(int j=boardSize-1;j>=0;j--){ newState = newState << 2; newState += ll(getShiftedCellNumber(j, boardSize - i - 1, state)); } } return newState; } ll symmetricState(ll state){ // return the minimum state of all symmetric states ll rState = reverseState(state); ll minState = min(state, rState); vector<ll> searchingStates = {state, rState}; for(ll s: searchingStates){ for(int i=0;i<3;i++){ s = rotatedState(s); minState = min(minState, s); } } return minState; } void printState(ll state){ cout << "print state" << endl; cout << bitset<boardSize*boardSize*2>(state) << endl; int n; for(int i=0;i<boardSize;i++){ for(int j=0;j<boardSize;j++){ n = getShiftedCellNumber(i, j, state); if(n==0){ cout << "-"; }else if (n==1){ cout << "o"; }else if (n==2){ cout << "x"; }else if (n==3){ cout << "e"; } } cout << endl; } cout << endl; } void init(){ // initialize cellNumbers vector< vector<ll> > cells(boardSize, vector<ll>(boardSize)); for(int i=0;i<boardSize;i++){ for(int j=0;j<boardSize;j++){ cells[i][j] = 3ll << (i * boardSize + j)*2; } } cellNumbers = cells; // initialize rowNumbers vector<ll> rows(boardSize); // create base number: 1111111111 (binary number) ll baseNumber = 3ll; for(int i=0;i<boardSize-1;i++){ baseNumber = (baseNumber<<2) + 3ll; } for(int i=0;i<boardSize;i++){ rows[i] = baseNumber << i*boardSize*2; } rowNumbers = rows; // make masks to check win ll oWin = 0ll; ll xWin = 0ll; ll eWin = 0ll; // diagonal for(int i=0;i<boardSize;i++){ oWin += 1ll << (i*boardSize+i)*2; xWin += 2ll << (i*boardSize+i)*2; eWin += 3ll << (i*boardSize+i)*2; } oWinMasks.push_back(oWin); xWinMasks.push_back(xWin); eWinMasks.push_back(eWin); oWinMasks.push_back(reverseState(oWin)); xWinMasks.push_back(reverseState(xWin)); eWinMasks.push_back(reverseState(eWin)); // row oWin = 1ll; xWin = 2ll; eWin = 3ll; for(int i=0;i<boardSize-1;i++){ oWin = oWin << 2; xWin = xWin << 2; eWin = eWin << 2; oWin += 1ll; xWin += 2ll; eWin += 3ll; } for(int i=0;i<boardSize;i++){ oWinMasks.push_back(oWin<<(2*i*boardSize)); xWinMasks.push_back(xWin<<(2*i*boardSize)); eWinMasks.push_back(eWin<<(2*i*boardSize)); } // column oWin = 1ll; xWin = 2ll; eWin = 3ll; for(int i=0;i<boardSize-1;i++){ oWin = oWin << 2*boardSize; xWin = xWin << 2*boardSize; eWin = eWin << 2*boardSize; oWin += 1ll; xWin += 2ll; eWin += 3ll; } for(int i=0;i<boardSize;i++){ oWinMasks.push_back(oWin<<(i*2)); xWinMasks.push_back(xWin<<(i*2)); eWinMasks.push_back(eWin<<(i*2)); } } int isWin(ll state){ // return 0:not decided, 1:win, -1:lose // turn is o; // if there is line of x, lose // else if there is line of o, win for(int i=0;i<eWinMasks.size();i++){ if ((state & eWinMasks.at(i)) == xWinMasks.at(i)){ return -1; } } for(int i=0;i<eWinMasks.size();i++){ if ((state & eWinMasks.at(i)) == oWinMasks.at(i)){ return 1; } } return 0; } stateMap *createNextStates(ll presentState, bool chooseEmpty){ // if chooseEmpty, increase o number. choose e. turn is o. // else, the number of o, x, e are same. choose o. turn is o. // before creating states, swap turn presentState = swapPlayer(presentState); auto *nextStates = new stateMap; // if this state is end of the game (there is line) no next states. // TODO: save the information of win?? if (isWin(presentState)!=0){ return nextStates; } int movingRow, newRow; ll newState; // choose only switch row, then rotate and switch row again. // search present state and rotated state. vector<ll> searchingStates = {presentState, rotatedState(presentState)}; for(ll state : searchingStates){ for(int i=0;i<boardSize;i++){ for(int j=0;j<boardSize;j++){ if(0<i && i<boardSize-1 && 0<j && j<boardSize-1){ // not edge continue; } if (chooseEmpty && getShiftedCellNumber(i, j, state)!=0){ // need to choose empty but the cell is not empty. continue; } if (!chooseEmpty && getShiftedCellNumber(i, j, state)!=2){ // need to choose x but the cell is not x. turn is already changed. continue; } // TODO: refactor. move right and move left are similar. make it simple. if(j!=boardSize-1){ // move to left movingRow = int((state & rowNumbers[i]) >> 2*i*boardSize); newRow = moveLeft(movingRow, j); newState = (state & ~rowNumbers[i]) | (ll(newRow) << 2*i*boardSize); newState = symmetricState(newState); // select minimum state in symmetric states. // add to nextStates if (nextStates->find(newState) == nextStates->end()){ (*nextStates)[newState] = 1; } } if(j!=0){ // move to right movingRow = int((state & rowNumbers[i]) >> 2*i*boardSize); newRow = moveRight(movingRow, j); newState = (state & ~rowNumbers[i]) | (ll(newRow) << 2*i*boardSize); newState = symmetricState(newState); // select minimum state in symmetric states. // add to nextStates if (nextStates->find(newState) == nextStates->end()){ (*nextStates)[newState] = 1; } } } } } return nextStates; } stateMap *createSaveStateSet(stateMap *initialStates){ // create state set from initial states and save them to storage // return next initial state map pointer stateMap *createdStates = initialStates; auto *nextInitialStates = new stateMap; // next state has 2 types. #o and #x auto *presentStates = new stateMap; while (createdStates != nullptr && !createdStates->empty()){ // create new states which is reachable from createdState // save present state auto *newStates = new stateMap; for(auto stateItr = createdStates->begin(); stateItr != createdStates->end(); ++stateItr){ // save (*presentStates)[stateItr->first] = 1; // create reachable states // choose empty. add to nextInitialStates auto nextStates = createNextStates(stateItr->first, true); for(auto itr=nextStates->begin();itr!=nextStates->end();itr++){ if(nextInitialStates->find(itr->first) == nextInitialStates->end()){ (*nextInitialStates)[itr->first] = 1; } } // choose circle. add to newStates nextStates = createNextStates(stateItr->first, false); for(auto itr=nextStates->begin();itr!=nextStates->end();itr++){ if(!contains(newStates, itr->first) && !contains(presentStates, itr->first) && !contains(createdStates, itr->first)){ (*newStates)[itr->first] = 1; } } } delete createdStates; createdStates = newStates; } // TODO: save present states to strage allStateSet.push_back(*presentStates); delete presentStates; return nextInitialStates; } stateMap *createInitialStates(){ int initialState = 0; auto *initialStates = new stateMap; (*initialStates)[initialState] = initialState; return initialStates; } int createTree(){ // return 0 if success // save results to storage. stateMap *initialStates = createInitialStates(); int counter = 0; while (initialStates != nullptr && !initialStates->empty()){ // repeat until initialStates is null initialStates = createSaveStateSet(initialStates); // TODO: it should be divided into 2 types (the numebr of o and x) cout << ++counter << endl; } return 0; } int main(){ clock_t start = clock(); init(); createTree(); clock_t end = clock(); cout << "end : " << (double)(end - start)/ CLOCKS_PER_SEC << " sec" << endl; // count the number of states int sum = 0; for(auto sm: allStateSet){ cout << sm.size() << endl; sum += sm.size(); } cout << sum << endl; }
Java
UTF-8
1,072
2.40625
2
[]
no_license
package com.owen.codeframework.http; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; /** * REST网络接口请求类 * * Created by Owen on 2015/11/3. */ public class RESTClient { private static AsyncHttpClient sClient = new AsyncHttpClient(); static { sClient.addHeader("Accept", "application/json"); sClient.setTimeout(20*1000); } /** * HTTP-GET */ private static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { sClient.get(url, params, responseHandler); } /** * HTTP-POST */ private static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { sClient.post(url, params, responseHandler); } /** * HTTP-DELETE */ private static void delete(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { sClient.delete(url, params, responseHandler); } }
C++
UTF-8
1,084
2.75
3
[]
no_license
#include <iostream> #include <vector> #include <unordered_map> #include <queue> using namespace std; #define INPUT_SIZE 101 struct nodo{ vector<char> out; vector<char> in; bool visited = false; bool inqueue = false; }; unordered_map<char, nodo> adj; bool checkNode(char c){ if(adj[c].visited) return false; for(auto x : adj[c].in) if(!adj[x].visited) return false; return true; } int main(){ freopen("C:\\Users\\Laurens\\Documents\\School\\Jaar 2\\Kwartiel 2\\Datastructures\\AoC2018\\Day7\\input7.txt", "r", stdin); for(int i = 0; i < INPUT_SIZE; i++){ char da, a; scanf("Step %c must be finished before step %c can begin.\n", &da, &a); adj[da].out.push_back(a); adj[a].in.push_back(da); } string ans = ""; while(ans.size() != adj.size()){ char next = ('Z'+1); for(auto x : adj){ if(checkNode(x.first)) next = min(next, x.first); } ans += next; adj[next].visited = true; } cout << ans << endl; return 0; }
C#
UTF-8
981
3.578125
4
[]
no_license
using System; namespace ch5_1 { class Program { static void Main(string[] args) { int num = int.Parse(Console.ReadLine()); int max = -1000000, min= 1000000; int[] array = new int[num]; string str = Console.ReadLine(); string[] str_unit = str.Split(' '); int[] unit = new int[num]; for(int i = 0; i< num; i++) { unit[i] = int.Parse(str_unit[i]); } for(int i = 0; i < num; i++) { array[i] = unit[i]; } for (int i = 0; i < num; i++) { if (min > array[i]) { min = array[i]; } if (max < array[i]) { max = array[i]; } } Console.WriteLine(min + " " + max); } } }
C
UTF-8
6,834
3.203125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <limits.h> //djikstra implementation inspired by https://www.geeksforgeeks.org/c-program-for-dijkstras-shortest-path-algorithm-greedy-algo-7/ // and https://www.geeksforgeeks.org/printing-paths-dijkstras-shortest-path-algorithm/?ref=lbp struct stop { char location[300]; }; #define GRAPHSIZE 7667 #define stoplim 7668 struct stop stops[stoplim]; int next_field ( FILE *csv , int which); int matrix[GRAPHSIZE][GRAPHSIZE]; void init(int array[][GRAPHSIZE]) { int i,j; for(i = 0; i < GRAPHSIZE; i++) for(j = 0; j < GRAPHSIZE; j++) array[i][j] = 0; } void addEdge(int source, int dest ,int weight) { matrix[source][dest] = weight; // fills array with two way edge given values matrix[dest][source] = weight; } int printSolution(int dist[], int n,int source, int destination) { printf("%d -> %d\n", source, destination); printf("Total\n%s -> %s = %d\n", stops[source].location , stops[destination].location, dist[destination]); } int minDistance(int dist[], bool permanent[]) { int min = INT_MAX; int min_index; for (int i = 0; i < GRAPHSIZE; i++) if (permanent[i] == false && dist[i] <= min) { min = dist[i]; min_index = i; } return min_index; } void printroute(int used[],int destination){ int i = used[destination]; int j = destination; if(i == -1){ return; } printroute(used, i); printf("\n%s -> %s = %d", stops[i].location, stops[j].location, matrix[j][i]); //printf("%d ", destination); } //https://www.geeksforgeeks.org/c-program-for-dijkstras-shortest-path-algorithm-greedy-algo-7/ void dijkstra(int matrix[GRAPHSIZE][GRAPHSIZE], int source, int destination) { int used[GRAPHSIZE]; int dist[GRAPHSIZE]; // The output array. bool permanent[GRAPHSIZE]; // permanent[i] will be true if vertex i is included in shortest // path tree or shortest distance from src to i is finalized for (int i = 0; i < GRAPHSIZE; i++) {// Initialize all distances as INFINITE and permanent[] as false dist[i] = INT_MAX; permanent[i] = false; used[source] = -1; } dist[source] = 0; // Distance of source vertex from itself is always 0 used[source] = -1; // Find shortest path for all vertices for (int count = 0; count < GRAPHSIZE - 1; count++) { int u = minDistance(dist, permanent); //start with min permanent[u] = true; // Mark the picked vertex as processed for (int v = 0; v < GRAPHSIZE; v++) // Update dist value of the adjacent vertices of the picked vertex. // Update dist[v] only if is not in permanent, there is an edge from // u to v, if ((!permanent[v] && matrix[u][v]) && (dist[u] != INT_MAX) && (dist[u] + matrix[u][v] < dist[v])){ // total weight of path from src to v through u must be smaller than current value of dist[v] dist[v] = dist[u] + matrix[u][v]; used[v] = u; } } // print the constructed distance array printroute(used, destination); printSolution(dist, GRAPHSIZE,source, destination); } int main(){ init(matrix); FILE *csv; csv = (FILE *)malloc(sizeof(FILE)); int n = 0; char duplicate[100] = {}; csv = fopen("vertices.csv", "r"); while(n != 2){ n = next_field(csv,0); if (n == 1){ // printf("\n\n"); } if (n == 3){ // printf("\n"); } if (n == 2); //printf("\n\n\n"); } fclose(csv); FILE *csv2; csv2 = (FILE *)malloc(sizeof(FILE)); n = 0; csv2 = fopen("edges.csv", "r"); while(n != 2){ n = next_field(csv2,1); if (n == 1){ //printf("\n\n"); } if (n == 3){ //printf("\n"); } } fclose(csv2); dijkstra(matrix,300, 253); char input1[10]; char input2[10]; printf("\n enter two stop nos\n"); gets( input1); gets( input2); int in1 = atoi(input1); int in2 = atoi(input2); dijkstra(matrix, in1,in2); printf("\n code over"); return 0; } void stores(int no, char buffer[], int data){ //stores in struct from csv if (no != 0){ // ignores headings switch (data) { case (1): for (int i = 0; i < 300; i++){ stops[no].location[i] = buffer[i]; } break; default : break; } } } void storesedge(int no, char buffer[], int data){ static int from; static int to; int weight; //printf("\ndata = %d , no = %d", data, no); if (no != 0){ // ignores headings //printf("I'm in to stroreedge"); switch (data) { case (0): from = atoi(buffer); break; case (1): to = atoi(buffer); break; case (2): weight = atoi(buffer); addEdge(from, to, weight); } } } int next_field ( FILE *csv , int which){ // reads from csv into buffer char buffer[300] = {0} ; bool quote = false; char c; static int no = 0; //4 data points 0-3 static int data = 0; int n = 0; while(true){ c = fgetc(csv); if (c == '"') quote = !quote; else if (c == EOF){ //printf("%s", buffer); if (which == 0){ stores( no, buffer, data); data = 0; no = 0; } else { storesedge(no,buffer,data); printf("\nand for that reason,I'm out\n"); } return 2; } else if ((c == ',') && (quote == false)){ //printf("%s", buffer); if (which == 0){ stores( no, buffer, data); } else { storesedge(no,buffer,data); } data++; return 3; } else if (c == '\n'){ //printf("%s", buffer); if (which == 0){ stores(no, buffer, data); } else { storesedge(no,buffer,data); } no++; data = 0; return 1; } else { buffer[n] = c; n++; } } }
C++
UTF-8
2,093
2.84375
3
[]
no_license
#include <SDL2/SDL.h> # define FPS 60 # define WIDTH 1300 # define HEIGHT 1000 # define MUL 80 double f(const double &x) { return (sqrt(x)); } double draw_zero_pow() { return (1. / 2); } double draw_first_pow(const double &x) { return (x + 1. / 8); } void draw_lines(SDL_Renderer *renderer) { for (int y = 0; y < HEIGHT; y += 1) { SDL_RenderDrawPoint(renderer, WIDTH / 2, y); } for (int x = 0; x < WIDTH; ++x) { SDL_RenderDrawPoint(renderer, x, HEIGHT / 2); } } void draw_plots(SDL_Renderer *renderer) { SDL_SetRenderDrawColor(renderer, 169, 169, 169, 0); draw_lines(renderer); for (double x = 0; x <= 10; x += 0.0001) { SDL_SetRenderDrawColor(renderer, 0, 0, 255, 0); SDL_RenderDrawPoint(renderer, WIDTH / 2 + x * MUL, HEIGHT / 2 - f(x) * MUL + 1); SDL_SetRenderDrawColor(renderer, 255, 255, 51, 0); SDL_RenderDrawPoint(renderer, WIDTH / 2 + x * MUL, HEIGHT / 2 - draw_zero_pow() * MUL + 1); SDL_SetRenderDrawColor(renderer, 255, 0, 0, 0); SDL_RenderDrawPoint(renderer, WIDTH / 2 + x * MUL, HEIGHT / 2 - draw_first_pow(x) * MUL + 1); } } int main() { SDL_Window *window; SDL_Renderer *renderer; SDL_Event event; Uint32 start; const int a = 0; const int b = 1; SDL_CreateWindowAndRenderer(1300, 1000, 0, &window, &renderer); SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); while (true) { SDL_RenderClear(renderer); if (SDL_PollEvent(&event) && (event.type == SDL_QUIT || event.key.keysym.sym == SDLK_ESCAPE)) break; start = SDL_GetTicks(); draw_plots(renderer); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); SDL_RenderPresent(renderer); SDL_UpdateWindowSurface(window); if (1000 / FPS > SDL_GetTicks() - start) { SDL_Delay(1000 / FPS - (SDL_GetTicks() - start)); } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return (0); }
Java
UTF-8
509
2.046875
2
[]
no_license
package com.sample.rest; import org.springframework.boot.SpringApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by jayati on 18/11/17. */ @RestController public class SampleController { @RequestMapping("/") String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { SpringApplication.run(SampleController.class, args); } }
Python
UTF-8
379
3.25
3
[]
no_license
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: fi = None se = head while se: t = se.next se.next = fi fi = se se = t return fi
Java
UTF-8
4,892
1.804688
2
[]
no_license
package com.ca.arcflash.ui.client.homepage.navigation; import com.ca.arcflash.ui.client.UIContext; import com.ca.arcflash.ui.client.coldstandby.ColdStandbyManager; import com.ca.arcflash.ui.client.coldstandby.ColdStandbyTaskPanel; import com.ca.arcflash.ui.client.common.AppType; import com.ca.arcflash.ui.client.homepage.SocialNetworkingPanel; import com.ca.arcflash.ui.client.homepage.SupportPanel; import com.ca.arcflash.ui.client.homepage.TaskPanel; import com.ca.arcflash.ui.client.vsphere.homepage.VSphereTaskPanel; import com.extjs.gxt.ui.client.Style.HorizontalAlignment; import com.extjs.gxt.ui.client.event.ComponentEvent; import com.extjs.gxt.ui.client.widget.CollapsePanel; import com.extjs.gxt.ui.client.widget.ComponentHelper; import com.extjs.gxt.ui.client.widget.ContentPanel; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData; import com.extjs.gxt.ui.client.widget.layout.TableData; import com.extjs.gxt.ui.client.widget.layout.TableLayout; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.AbstractImagePrototype; public class NavigationCollapsePanel extends CollapsePanel { private LayoutContainer bodyContainer; private BorderLayoutData parentData; private AppType appType = AppType.D2D; protected static ContentPanel contentPanel; public NavigationCollapsePanel(ContentPanel panel, BorderLayoutData data) { super(panel, data); parentData = data; createBodyContainer(); } public NavigationCollapsePanel(ContentPanel panel, BorderLayoutData data,AppType appType) { super(panel, data); parentData = data; this.appType = appType; createBodyContainer(); } protected void createBodyContainer() { // a layout container for the Navigation buttons bodyContainer = new LayoutContainer(); TableLayout tl = new TableLayout(1); tl.setWidth("100%"); tl.setCellHorizontalAlign(HorizontalAlignment.CENTER); tl.setCellPadding(0); bodyContainer.setLayout(tl); TableData td = new TableData(); td.setHeight("50px"); // tasks NavigationButtonItem naviButtonItem = new NavigationButtonItem(AbstractImagePrototype.create(UIContext.IconBundle.tasks_backup()), getTaskPanel(), parentData); bodyContainer.add(naviButtonItem,td); // support if(UIContext.customizedModel == null || UIContext.customizedModel.getShowSupportHeader()){ naviButtonItem = new NavigationButtonItem(AbstractImagePrototype.create(UIContext.IconBundle.googleGroup()), new SupportPanel(appType), parentData); bodyContainer.add(naviButtonItem,td); } if(UIContext.customizedModel == null || UIContext.customizedModel.getShowSocialNetworkHeader()) { // social NW if (UIContext.serverVersionInfo.isShowSocialNW() != null && UIContext.serverVersionInfo.isShowSocialNW()) { naviButtonItem = new NavigationButtonItem(AbstractImagePrototype.create(UIContext.IconBundle.userCenter()), new SocialNetworkingPanel(appType), parentData); bodyContainer.add(naviButtonItem,td); } } //testMenuBar(); } @Override protected void onRender(Element target, int index) { super.onRender(target, index); // the header is OK by the above super.onRender(), below is to prepare the body bwrap = el().createChild("<div class=" + bwrapStyle + "></div>"); Element bw = bwrap.dom; body = fly(bw).createChild("<div class=" + bodStyle + "></div>"); // remove the background-color and borders from body body.setStyleAttribute("background-color", "transparent"); body.setBorders(false); // render the layout container bodyContainer.render(body.dom, 0); bodyContainer.layout(); } @Override protected void doAttachChildren() { super.doAttachChildren(); ComponentHelper.doAttach(bodyContainer); } @Override protected void doDetachChildren() { super.doDetachChildren(); ComponentHelper.doDetach(bodyContainer); } @Override public void onComponentEvent(ComponentEvent ce) { // TODO Auto-generated method stub //super.onComponentEvent(ce); } protected ContentPanel getTaskPanel(){ switch(appType){ case D2D: contentPanel = new TaskPanel(true); break; case VSPHERE: contentPanel = new VSphereTaskPanel(); break; case VCM: if(contentPanel == null || !(contentPanel instanceof ColdStandbyTaskPanel)) { contentPanel = new ColdStandbyTaskPanel(true); ColdStandbyTaskPanel taskPanel = ColdStandbyManager.getInstance().getTaskPanel(); if(taskPanel != null) { ((ColdStandbyTaskPanel)contentPanel).getContainerActivityLog() .setEnabled(taskPanel.getContainerActivityLog().isEnabled()); ((ColdStandbyTaskPanel)contentPanel).getContainerSetting() .setEnabled(taskPanel.getContainerSetting().isEnabled()); } } break; default: contentPanel = new TaskPanel(true); } return contentPanel; } }
Java
UTF-8
3,324
2.59375
3
[]
no_license
package com.robert.springmvcwebapp; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; /** * Programmatic configuration of the instead of web.xml */ public class Bootstrap implements WebApplicationInitializer { /** * Listener Initialized first to load rootSpringContext. RootContext should contain business objects * or data access objects. ServletContext are cannot access beans from other ServletContext. ServletContext should * contains beans specific to the Servlet such as controllers * * @param container the servlet context for this webapplication * @throws ServletException */ @Override public void onStartup(ServletContext container) throws ServletException { /** * If you plan to map the DispatcherServlet to the application root, make sure you account for static resources * such as HTML pages, CSS and JavaScript files, and images. Some online tutorials demonstrate how to set up * Spring Framework to serve static resources, but doing so is not necessary and does not perform well. When * any Servlet is mapped to the application root (without an asterisk), more-specific URL patterns always * override it. So permitting your Servlet container to serve static resources is as simple as adding mappings * for those resources to the Servlet named default (which all containers provide automatically). This can be * accomplished in the deployment descriptor like so: */ container.getServletRegistration("default").addMapping( "/resources/*", "*.css", "*.js", "*.png", "*.gif", "*.jpg"); /** * Register rootContext * The root application context should hold services, repositories, and other pieces of business logic, whereas * the DispatcherServlet’s application context should contain web controllers */ AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(RootContextConfiguration.class); container.addListener(new ContextLoaderListener(rootContext)); //Register servletContext and Create Dispatcher servlet AnnotationConfigWebApplicationContext servletContext = new AnnotationConfigWebApplicationContext(); servletContext.register(ServletContextConfiguration.class); ServletRegistration.Dynamic dispatcher = container.addServlet("springDispatcher", new DispatcherServlet(servletContext)); dispatcher.setLoadOnStartup(1); /** * The lone forward slash without an asterisk is sufficient to get the Servlet to respond to all URLs in your * application and while still enabling the Servlet container’s JSP mechanism to handle JSP requests A trailing * asterisk causes the Servlet container to send even internal JSP requests to that Servlet, which is not desirable */ dispatcher.addMapping("/"); } }
Java
UTF-8
1,041
3.453125
3
[]
no_license
package clocks.base; /** * * @author S.Lavruhin * */ public class Point implements Comparable<Point>{ private final double precession = 0.0001; public final double x; public final double y; /** * * @param x * @param y */ public Point(double x, double y) { this.x = x; this.y = y; } /** * * @param p */ public Point(final Point p) { this(p.x, p.y); } /** * Wrapper to initialize a Point with double values. * * @param x * @param y * @return */ public static java.awt.Point toUtilPoint(double x, double y) { return new java.awt.Point((int)Math.round(x), (int)Math.round(y)); } @Override public String toString() { return String.format("x=%.2f, y=%.2f", x, y ); } @Override public int compareTo(Point p) { double deltaX = Math.abs(x - p.x), deltaY = Math.abs(y - p.y); return deltaX > precession ? (x > p.x ? 1 : -1) : deltaY > precession ? (y > p.y ? 1 : -1) : 0; } }
JavaScript
UTF-8
2,125
2.6875
3
[]
no_license
// This file needed to be run on node 0.12 in order to make sure that library runs on 0.12 var crypto = require('crypto'); var Estimator = require('../index'); var FeeRate = require('../build/FeeRate'); // For test we will assume that 4 transactions can be added to mempool on each iterration block and 3 can be mined function generateRandomMempoolData(len, height) { var mempool = {}; for (var i = 0; i < len; i++) { mempool[crypto.createHash('sha256').update((Date.now() + Math.random()).toString()).digest('hex')] = { size: 23818, fee: (Math.random() * (0.00047646 - 0.00023823)) + 0.00023823, // fee: 0.00023823, modifiedfee: 0.00023823, time: 1510165507, height: height, startingpriority: 15191056856720.27, currentpriority: 15191056856720.27, descendantcount: 1, descendantsize: 23818, descendantfees: 23823, depends: [ ], }; } return mempool; } function transformMempoolData(rawmempooldata) { var hashes = Object.keys(rawmempooldata); var arr = []; for (var i = 0; i < hashes.length; i++) { rawmempooldata[hashes[i]].hash = hashes[i]; arr.push(rawmempooldata[hashes[i]]); } return arr; } function generateBlock(mempooldata, prevBlockHeight, transactionsToInclude) { mempooldata.sort(function (a, b){return b.fee - a.fee}); var txToIncludeInBlock = mempooldata.splice(0, transactionsToInclude); return { height: prevBlockHeight + 1, tx: txToIncludeInBlock.map(function (tx) {return tx.hash}), }; } var estimator = new Estimator(); var wholePool = []; for (var i = 1; i < 11; i++) { var newBlock = generateBlock(wholePool, i - 1, 10); var newMempoolData = generateRandomMempoolData(11, i); wholePool = wholePool.concat(transformMempoolData(newMempoolData)); estimator.processBlock(newBlock.height, newBlock.tx); estimator.processNewMempoolTransactions(newMempoolData); } var fees = []; for (var i = 1; i < 7; i++) { fees.push(estimator.estimateSmartFee(i)); } if (fees[0] instanceof FeeRate) { console.log('0.12 test pass'); } else { console.log('0.12 test not pass'); }
Java
UTF-8
1,068
2.8125
3
[]
no_license
package com.artpro.service; import com.artpro.model.CargoTransport; //Для грузового разработать метод который проверит можно ли загрузить в //него xxx груза //Метод должен проверять если это кол-во груза помещается в грузовик то //выводит в консоль ”Грузовик загружен”, если кол-во груза которое нужно //загрузить больше чем то которое может влезть в наш грузовик то выводим //“Вам нужен грузовик побольше ”. public class CargoTransportService { public void calculationCargoTransportService(CargoTransport cargoTransport, double cargo) { if (cargo <= cargoTransport.getLoadCapacity()) { System.out.println("Грузовик загружен"); } else { System.out.println("Вам нужен грузовик побольше"); } } }
Java
UTF-8
1,245
2.3125
2
[]
no_license
package fr.insa.soa.ExchangeSemester.services; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import javax.xml.bind.DatatypeConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import fr.insa.soa.ExchangeSemester.dao.UserRepository; import fr.insa.soa.ExchangeSemester.model.User; @Service public class UserService { private UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public boolean saveUser(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (userRepository.findByLogin(user.getLogin()) == null) { // login not found in the db, can save byte[] byteChaine = user.getPassword().getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] hash = md.digest(byteChaine); String myHash = DatatypeConverter.printHexBinary(hash).toLowerCase(); user.setPassword(myHash); userRepository.save(user); return true; } else { // login already used, cannot save return false; } } }
Java
UTF-8
870
2.34375
2
[ "Apache-2.0" ]
permissive
package com.david.calendaralarm.data.pojo; import org.joda.time.DateTime; public class Item { private String title; private String summary; private DateTime currentDate; private DateTime executionDate; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public DateTime getCurrentDate() { return currentDate; } public void setCurrentDate(DateTime currentDate) { this.currentDate = currentDate; } public DateTime getExecutionDate() { return executionDate; } public void setExecutionDate(DateTime executionDate) { this.executionDate = executionDate; } }
C++
UTF-8
488
2.9375
3
[]
no_license
#include "Polymorph.hpp" Polymorph::Polymorph() : ASpell("Polymorph", "turned into a critter") {}; Polymorph::~Polymorph() {}; Polymorph::Polymorph(Polymorph const & src) : ASpell("Polymorph", "turned into a critter") { (void)src; }; Polymorph & Polymorph::operator = (Polymorph const & src) { if (this != &src) { this->_name = src._name; this->_effects = src._effects; } return (*this); }; ASpell * Polymorph::clone() { return (new Polymorph); };
Java
UTF-8
203
2.890625
3
[]
no_license
package Day18; class Number implements Expression { private final int value; public Number(int value) { this.value = value; } @Override public long evaluate() { return value; } }
C++
UTF-8
2,173
3.609375
4
[]
no_license
#include<iostream> #include<queue> #include<map> #include<list> #define null 0 using namespace std; class Node { public: int data; Node *left; Node *right; Node(){} Node(int data){ this->data=data; left=right=null; } }; class Object{ public: Node *node; int distance; Object(){} Object(Node *node,int diatance){ this->node=node; this->distance = diatance; } }; void verticalOrderTraversal(Node *root){ if(root==null){ return ; } else{ map<int,list<int> > m; queue<Object> q; Object o(root,0); q.push(o);// or use q.push(Object(root,0)); while(!q.empty()){ Object o = q.front(); q.pop(); m[o.distance].push_back(o.node->data); if(o.node->left!=null){ // Object l(o.node->left,o.distance-1); q.push(Object(o.node->left,o.distance-1)); //or use q.push(l); } if(o.node->right!=null){ // Object r(o.node->right,o.distance+1); q.push( Object(o.node->right,o.distance+1)); // or use q.push(r); } } for(auto it:m){ cout <<"["<< it.first<<"]->"; // remove this line if you do not want keys on output. for(auto element:it.second){ cout <<element<<" "; } cout<<"\n"; } } } int main(){ Node * root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right= new Node(5); root->right->left= new Node(6); root->right->left->left= new Node(10); root->right->right= new Node(7); root->right->right->left = new Node(8); root->right->right->right = new Node(9); cout <<"\nThe vertical order of tree \n"; verticalOrderTraversal(root); /* The vertical order of tree keys->values [-2]->4 [-1]->2 10 [0]->1 5 6 [1]->3 8 [2]->7 [3]->9 */ }
PHP
UTF-8
2,372
2.625
3
[ "MIT" ]
permissive
<?php namespace Arkade\RetailDirections; use Carbon\Carbon; use Illuminate\Support\Fluent; use Illuminate\Support\Collection; class GiftVoucherFinaliseRequest extends Fluent { protected $giftVoucherReference; protected $giftVoucherSchemaCode; protected $pin; protected $statusInd; /** * Customer constructor. * * @param array $attributes */ public function __construct(array $attributes = []) { parent::__construct($attributes); } /** * @return mixed */ public function getGiftVoucherReference() { return $this->giftVoucherReference; } /** * @param mixed $giftVoucherReference */ public function setGiftVoucherReference($giftVoucherReference) { $this->giftVoucherReference = $giftVoucherReference; return $this; } /** * @return mixed */ public function getGiftVoucherSchemaCode() { return $this->giftVoucherSchemaCode; } /** * @param mixed $giftVoucherSchemaCode */ public function setGiftVoucherSchemaCode($giftVoucherSchemaCode) { $this->giftVoucherSchemaCode = $giftVoucherSchemaCode; return $this; } /** * @return mixed */ public function getPin() { return $this->pin; } /** * @param mixed $pin */ public function setPin($pin) { $this->pin = $pin; return $this; } /** * @return mixed */ public function getStatusInd() { return $this->statusInd; } /** * @param mixed $statusInd */ public function setStatusInd($statusInd) { $this->statusInd = $statusInd; return $this; } public static function fromXml( \SimpleXMLElement $xml ) { $giftVoucherRequest = new static; $giftVoucherRequest->setGiftVoucherReference((string) $xml->giftvoucher_reference); $giftVoucherRequest->setGiftVoucherSchemaCode((string) $xml->giftvoucherscheme_code); $giftVoucherRequest->setStatusInd((string) $xml->status_ind); $giftVoucherRequest->setPin((string) $xml->pin); foreach ($xml->children() as $key => $value) { $giftVoucherRequest->{$key} = (string) $value; } return $giftVoucherRequest; } }
Java
UTF-8
19,399
1.890625
2
[]
no_license
package com.yunda.jx.jxgc.workplanmanage.manager; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.persistence.Entity; import javax.persistence.Id; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.hibernate.persister.entity.AbstractEntityPersister; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Service; import com.yunda.common.BusinessException; import com.yunda.frame.common.Constants; import com.yunda.frame.common.JXBaseManager; import com.yunda.frame.common.Page; import com.yunda.frame.common.SearchEntity; import com.yunda.frame.util.CommonUtil; import com.yunda.frame.util.StringUtil; import com.yunda.frame.util.sqlmap.SqlMapUtil; import com.yunda.jx.jxgc.producttaskmanage.entity.WorkCard; import com.yunda.jx.jxgc.producttaskmanage.entity.Worker; import com.yunda.jx.jxgc.producttaskmanage.manager.WorkerManager; import com.yunda.jx.jxgc.producttaskmanage.qualitychek.entity.QCResult; import com.yunda.jx.jxgc.producttaskmanage.qualitychek.manager.QCResultManager; import com.yunda.jx.jxgc.workplanmanage.entity.JobProcessNode; /** * <li>标题: 机车检修整备管理信息系统 * <li>说明: 作业工单查询业务类 * <li>创建人:程锐 * <li>创建日期:2015-4-29 * <li>修改人: * <li>修改日期: * <li>修改内容: * <li>版权: Copyright (c) 2008 运达科技公司 * @author 信息系统事业部检修整备系统项目组 * @version 1.0 */ @Service(value = "workCardQueryManager") public class WorkCardQueryManager extends JXBaseManager<WorkCard, WorkCard> { @Resource private WorkerManager workerManager; @Resource private QCResultManager qCResultManager; /** * <li>说明:获取流程节点关联的作业工单分页列表 * <li>创建人:程锐 * <li>创建日期:2015-4-29 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param searchEntity 查询实体 * @return 流程节点关联的作业工单分页列表 * @throws BusinessException */ public Page<WorkCardQueryBean> getWorkCardListByNode(SearchEntity<WorkCard> searchEntity) throws BusinessException { WorkCard entity = searchEntity.getEntity(); // 查询条件 - 车型 if (StringUtil.isNullOrBlank(entity.getNodeCaseIDX())) return new Page<WorkCardQueryBean>(); String sql = SqlMapUtil.getSql("jxgc-workcardquery:getWorkCardListByNode") .replace("#nodeIDX#", entity.getNodeCaseIDX()); StringBuilder sb = new StringBuilder(sql); // 查询条件 - 作业名称 if (!StringUtil.isNullOrBlank(entity.getWorkCardName())) { sb.append(" AND A.WORK_CARD_NAME LIKE '%").append(entity.getWorkCardName()).append("%'"); } AbstractEntityPersister meta = (AbstractEntityPersister) getDaoUtils().getSessionFactory().getClassMetadata(WorkCardQueryBean.class); String sortString = ""; Order[] orders = searchEntity.getOrders(); if (orders != null && orders.length > 0) { for (Order order : orders) { String[] orderStrings = StringUtil.tokenizer(order.toString(), " "); if (orderStrings == null || orderStrings.length != 2) continue; if (orderStrings[0].equals("workCardCode") || orderStrings[0].equals("workCardName") || orderStrings[0].equals("status")) { sortString = CommonUtil.buildOrderSql("A.", meta, orderStrings); } } sb.append(sortString); } else { sb.append(" ORDER BY A.WORK_CARD_CODE ASC"); } sql = sb.toString(); StringBuilder totalSql = new StringBuilder("SELECT COUNT(*) AS ROWCOUNT FROM (").append(sql).append(Constants.BRACKET_R); Page<WorkCardQueryBean> page = this.acquirePageList(totalSql.toString(), sql, searchEntity.getStart(), searchEntity.getLimit(), false); //准备拼接作业人员姓名 for (WorkCardQueryBean w : page.getList()) { StringBuffer stringBuffer = new StringBuffer(300); //如果worker为空说明工单为处理中,处理人通过作业工单id反查pjgc_worker表的worker人员 if (StringUtil.isNullOrBlank(w.getWorker())) { Worker worker = new Worker(); worker.setWorkCardIDX(w.getIdx()); //通过worCardIDX查询对应的work信息,用,分割 List<Worker> list = workerManager.findList(worker); int listSize = list.size(); for (int i = 0; i < listSize; i++) { Worker wo = list.get(i); if (i == listSize - 1) { }else { stringBuffer.append(wo.getWorkerName()).append(","); } } //如果是处理完成的,直接取worker字段中的值即可 }else{ stringBuffer.append(w.getWorker()); } w.setWorker(stringBuffer.toString()); } return page; } /** * <li>说明:基于sql查询语句的分页查询 * <li>创建人:程锐 * <li>创建日期:2015-1-28 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param totalSql 查询总记录数的sql语句 * @param sql 查询语句 * @param start 开始行 * @param limit 每页记录数 * @param isQueryCacheEnabled 是否启用查询缓存 * @return Page<ZbglJYRdpBean> 分页查询列表 * @throws BusinessException */ @SuppressWarnings("unchecked") public Page<WorkCardQueryBean> acquirePageList(String totalSql, String sql, int start, int limit, Boolean isQueryCacheEnabled) throws BusinessException { final int beginIdx = start < 0 ? 0 : start; final int pageSize = limit < 0 ? Page.PAGE_SIZE : limit; final String total_sql = totalSql; final String fSql = sql; final Boolean useCached = isQueryCacheEnabled; HibernateTemplate template = this.daoUtils.getHibernateTemplate(); return (Page<WorkCardQueryBean>) template.execute(new HibernateCallback() { public Page<WorkCardQueryBean> doInHibernate(Session s) { SQLQuery query = null; try { query = s.createSQLQuery(total_sql); query.addScalar("rowcount", Hibernate.INTEGER); query.setCacheable(useCached); // 缓存开关 int total = ((Integer) query.uniqueResult()).intValue(); query.setCacheable(false); int begin = beginIdx > total ? total : beginIdx; query = (SQLQuery) s.createSQLQuery(fSql).addEntity(WorkCardQueryBean.class).setFirstResult(begin).setMaxResults(pageSize); query.setCacheable(useCached); // 缓存开关 return new Page<WorkCardQueryBean>(total, query.list()); } catch (HibernateException e) { throw e; } finally { if (query != null) query.setCacheable(false); } } }); } /** * <li>说明:获取节点关联的已完成的作业工单数量 * <li>创建人:程锐 * <li>创建日期:2015-5-22 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param nodeIDX 节点IDX * @return 节点关联的已完成的作业工单数量 */ public int getCompleteWorkCardCountByNode(String nodeIDX) { return CommonUtil.getListSize(getCompleteWorkCardByNode(nodeIDX)); } /** * <li>说明:获取节点关联的作业工单数量 * <li>创建人:程锐 * <li>创建日期:2015-5-22 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param nodeIDX 节点IDX * @return 节点关联的作业工单数量 */ public int getWorkCardCountByNode(String nodeIDX) { return CommonUtil.getListSize(getWorkCardByNode(nodeIDX)); } /** * <li>说明:获取节点关联的已处理或已终止的作业工单列表 * <li>创建人:程锐 * <li>创建日期:2015-5-22 * <li>修改人: 程锐 * <li>修改日期:2015-6-4 * <li>修改内容:加入质检中状态的作业工单 * @param nodeIDX 节点IDX * @return 节点关联的已处理或已终止的作业工单列表 */ @SuppressWarnings("unchecked") public List<WorkCard> getCompleteWorkCardByNode(String nodeIDX) { Map paramMap = new HashMap<String, String>(); paramMap.put("nodeCaseIDX", nodeIDX); StringBuilder status = new StringBuilder(); status.append("in'") .append(WorkCard.STATUS_HANDLED) .append("','") .append(WorkCard.STATUS_TERMINATED) .append("','") .append(WorkCard.STATUS_FINISHED) .append("'"); paramMap.put("status", status.toString()); return getWorkCardList(paramMap); } /** * <li>说明:获取节点关联的作业工单列表 * <li>创建人:程锐 * <li>创建日期:2015-5-6 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param nodeIDX 节点IDX * @return 节点关联的作业工单列表 */ @SuppressWarnings("unchecked") public List<WorkCard> getWorkCardByNode(String nodeIDX) { Map paramMap = new HashMap<String, String>(); paramMap.put("nodeCaseIDX", nodeIDX); return getWorkCardList(paramMap); } /** * <li>说明:获取作业工单列表 * <li>创建人:程锐 * <li>创建日期:2015-5-6 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param paramMap 查询参数map key:字段名 value:字段值 * @return 作业工单列表 */ @SuppressWarnings("unchecked") private List<WorkCard> getWorkCardList(Map paramMap) { StringBuilder hql = new StringBuilder(); hql.append("from WorkCard where 1 = 1 ").append(CommonUtil.buildParamsHql(paramMap)).append(" and recordStatus = 0"); return daoUtils.find(hql.toString()); } /** * <li>说明:根据工艺节点获取处理中和已处理的作业工单列表 * <li>创建人:程锐 * <li>创建日期:2013-7-31 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param nodeCaseIDX 流程节点ID * @param workPlanIDX 作业计划IDX * @return 处理中和已处理的作业工单列表 * @throws Exception */ @SuppressWarnings("all") public List getOnGoingCardByNode(String nodeCaseIDX, String workPlanIDX) throws Exception{ String sql = SqlMapUtil.getSql("jxgc-workcardquery:getOnGoingCardByNode").replace("#nodeCaseIDX#", nodeCaseIDX) .replace("#STATUS_HANDLING#", WorkCard.STATUS_HANDLING) .replace("#STATUS_HANDLED#", WorkCard.STATUS_HANDLED) .replace("#STATUS_FINISHED#", WorkCard.STATUS_FINISHED) .replace("#tecProcessCaseIDX#", nodeCaseIDX) .replace("#STATUS_GOING#", JobProcessNode.STATUS_GOING) .replace("#STATUS_COMPLETE#", JobProcessNode.STATUS_COMPLETE) .replace("#workPlanIDX#", workPlanIDX); return daoUtils.executeSqlQuery(sql); } /** * <li>说明:获取节点下无工位和班组的未完成的作业工单列表 * <li>创建人:程锐 * <li>创建日期:2015-5-21 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param nodeIDX 节点IDX * @return 节点下无工位和班组的未完成的作业工单列表 * @throws Exception */ @SuppressWarnings("unchecked") public List<WorkCard> getNoStationAndTeamListByNode(String nodeIDX) throws Exception { String hql = SqlMapUtil.getSql("jxgc-workcardquery:getNoStationAndTeamListByNode") .replace("#nodeIDXS#", CommonUtil.buildInSqlStr(nodeIDX)) .replace("#STATUS_HANDLING#", WorkCard.STATUS_HANDLING) .replace("#STATUS_NEW#", WorkCard.STATUS_NEW) .replace("#STATUS_OPEN#", WorkCard.STATUS_OPEN); return daoUtils.find(hql); } /** * <li>说明:根据作业工单列表构造作业工单IDX为以,号分隔的sql字符串 * <li>创建人:程锐 * <li>创建日期:2015-4-28 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param list 作业工单列表 * @return 以,号分隔的作业工单IDX的sql字符串 * @throws Exception */ public String buildSqlIDXStr(List<WorkCard> list) throws Exception { return CommonUtil.buildInSqlStr(buildIDXBuilder(list).toString()); } /** * <li>说明:根据作业工单列表构造作业工单IDX为以,号分隔的字符串 * <li>创建人:程锐 * <li>创建日期:2015-5-21 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param list 作业工单列表 * @return 以,号分隔的作业工单IDX字符串 * @throws Exception */ public StringBuilder buildIDXBuilder(List<WorkCard> list) throws Exception { StringBuilder idxs = new StringBuilder(); for (WorkCard card : list) { idxs.append(card.getIdx()).append(","); } idxs.deleteCharAt(idxs.length() - 1); return idxs; } /** * <li>说明:根据作业工单列表构造作业工单IDX数组 * <li>创建人:程锐 * <li>创建日期:2015-5-21 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param list 作业工单列表 * @return 作业工单IDX数组 */ public String[] buildIDXArray(List<WorkCard> list) { String[] ids = new String[list.size()]; for (int i = 0; i < list.size(); i++) { ids[i] = list.get(i).getIdx(); } return ids; } /** * <li>说明:获取作业工单的其他处理人员 * <li>创建人:程锐 * <li>创建日期:2015-7-8 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param workCardIDX 作业工单IDX * @param empid 当前人员ID * @return 作业人员列表 */ public List<Worker> getOtherWorkerByWorkCard(String workCardIDX, String empid) { return workerManager.getOtherWorkerByWorkCard(workCardIDX, empid); } /** * <li>说明:根据作业工单idx获取需要指派的质量检查项列表 * <li>创建人:程锐 * <li>创建日期:2014-11-24 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param workCardIDXS 作业工单idx,多个idx用,分隔 * @return 需要指派的质量检查项列表 * @throws Exception */ public List<QCResult> getIsAssignCheckItems(String workCardIDXS) throws Exception { return qCResultManager.getIsAssignCheckItems(workCardIDXS); } /** * <li>标题: 机车检修整备管理信息系统 * <li>说明: 作业工单查询实体 * <li>创建人:程锐 * <li>创建日期:2015-4-29 * <li>修改人: * <li>修改日期: * <li>修改内容: * <li>版权: Copyright (c) 2008 运达科技公司 * @author 信息系统事业部检修整备系统项目组 * @version 1.0 */ @Entity private static class WorkCardQueryBean { /* idx主键 */ @Id private String idx; /* 作业卡编码 */ private String workCardCode; /* 作业卡名称 */ private String workCardName; /*质量检查*/ private String qcName; /* 状态 */ private String status; /* 状态 */ private String extensionClass; /* 作业人员 */ private String worker; /** * <li>说明:默认构造方法 * <li>创建人:程锐 * <li>创建日期:2015-4-29 * <li>修改人: * <li>修改日期: */ public WorkCardQueryBean() { } public String getWorker() { return worker; } public void setWorker(String worker) { this.worker = worker; } public String getIdx() { return idx; } public void setIdx(String idx) { this.idx = idx; } public String getQcName() { return qcName; } public void setQcName(String qcName) { this.qcName = qcName; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getWorkCardCode() { return workCardCode; } public void setWorkCardCode(String workCardCode) { this.workCardCode = workCardCode; } public String getWorkCardName() { return workCardName; } public void setWorkCardName(String workCardName) { this.workCardName = workCardName; } public String getExtensionClass() { return extensionClass; } public void setExtensionClass(String extensionClass) { this.extensionClass = extensionClass; } } }
JavaScript
UTF-8
2,228
2.640625
3
[]
no_license
function createDot () { let dot = document.createElement("div") dot.style.position = "absolute" dot.style.height = "10px" dot.style.width = "10px" dot.style.background = "#fff" dot.style.boxSizing = "border-box" dot.style.border = "1px solid #000" return dot } function createOutline () { let outline = document.createElement("div") outline.classList.add("_outline") outline.style.position = "absolute" outline.style.zIndex = "1988" outline.style.top = "0" outline.style.left = "0" outline.style.height = "100px" outline.style.width = "100px" outline.style.boxSizing = "border-box" outline.style.border = "1px dotted #333" outline.style.pointerEvents = "none" let dot = createDot() dot.style.left = "-5px" dot.style.top = "-5px" outline.appendChild(dot) dot = createDot() dot.style.left = "-5px" dot.style.bottom = "-5px" outline.appendChild(dot) dot = createDot() dot.style.right = "-5px" dot.style.top = "-5px" outline.appendChild(dot) dot = createDot() dot.style.right = "-5px" dot.style.bottom = "-5px" outline.appendChild(dot) return outline } export default { install (Vue) { Vue.directive("highlight", { unbind: function (el, binding) { if (el.outline) { el.outline.parentNode.removeChild(el.outline) } }, componentUpdated: function (el, binding) { el._show = binding.value if (!el.outline) { el.outline = createOutline() el.parentNode.appendChild(el.outline) el._resize = function () { el.outline.style.display = el._show ? "block" : "none" el.outline.style.top = el.offsetTop + "px" el.outline.style.left = el.offsetLeft + "px" el.outline.style.width = el.offsetWidth + "px" el.outline.style.height = el.offsetHeight + "px" if (event) event.stopPropagation() // 阻止冒泡,避免影响上级组件 } el.addEventListener("transitionend", el._resize) el.addEventListener("load", el._resize) } if (binding.value) { el._resize() } else { el.outline.style.display = "none" } } }) } }
C++
GB18030
544
3.875
4
[]
no_license
//ȡƳȾλ1±ֵ+1±0ʼ16 = 10000򳤶5 2= 0010Ϊ2 #include <iostream> using namespace std; int length(int num) { int count = 0; while(num) { count++; num >>= 1; } return count; } int main() { int number; cout << "" << endl; while(cin >> number) { cout << "Ƴǣ " << length(number) << endl; cout << "" << endl; } return 0; }
C#
UTF-8
1,715
2.609375
3
[]
no_license
using econoomic_planer_X.Market; using System; namespace econoomic_planer_X.ResourceSet { public class TradingResource : Resource, IComparable, IEquatable<TradingResource> { public Population Owner { get; set; } public TradingResource() { } public TradingResource(Population Owner, ResourceType resourceType, double Amount) : base(resourceType, Amount) { this.Owner = Owner; } public ExternatlTradingResource SplitExternal(double ratio, ExternalMarket destination, double localTravelTime) { double splitAmount = Amount * ratio; Amount -= splitAmount; return new ExternatlTradingResource(Owner, ResourceType, destination, splitAmount, localTravelTime); } public bool AffordTransport() { return Owner.AffordTransport(); } public void Trade(double ratio, double price) { Owner.TradeGain(ratio * Amount * price); Amount -= ratio * Amount; } public bool Empty() { return Amount <= 0; } public int CompareTo(TradingResource tr) { if (Owner.ID.CompareTo(tr.Owner.ID) == 0 && ResourceType.Id == tr.ResourceType.Id) { return 0; } return -1; } public int CompareTo(object obj) { return CompareTo((TradingResource)obj); } internal void Add(TradingResource su) { this.Amount += su.Amount; } public bool Equals(TradingResource other) { return CompareTo(other) == 0; } } }
Python
UTF-8
601
3.671875
4
[]
no_license
import numpy as np import pandas as pd # 연습 문제 # 1. 모든 행과 열에 라벨을 가지는 5 x 5 이상의 크기를 가지는 데이터프레임을 만든다. df = pd.DataFrame(np.arange(10, 35).reshape(5, 5), index=["a", "b", "c", "d", "e"], columns=["A", "B", "C", "D","E"]) df # 2. 10가지 이상의 방법으로 특정한 행과 열을 선택한다. df[:"a"] df["A"] df["a":"e"] df.loc["a","A"] df.loc["b":,"A"] df.loc["a", :] df.loc[["a","b"],["B","D"]] df.iloc[0,1] # df.loc["a","A"] 와 같음 df.iloc[:2] df.iloc[0, -2:] df.iloc[2:3, 1:3]
Markdown
UTF-8
2,131
2.8125
3
[ "MIT" ]
permissive
autoGrow jQuery plugin ====================== Auto resize input fields to fit content when user types. Works both with jQuery and Zepto.js. Usage ----- To autoresize text field use: ```js $('#myTextField').autoGrow({ comfortZone: 70 // default value }); // or just $('#myTextField').autoGrow(70); ``` When you update styles that change text size use: ```js $('#myTextField').autoGrow(); ``` You can also update comfort zone: ```js $('#myTextField').autoGrow(newComfortZone); ``` To disable autogrowing: ```js $('#myTextField').autoGrow('remove'); // or $('#myTextField').autoGrow(false); // or $('#myTextField').autoGrow({remove: true}); ``` Limiting width -------------- To limit width use css properties `min-width` and `max-width`. When `min-width` is set to `0px` (default browser value), minimum width is limited to current width. Animating --------- If you wish smoothly resize textfields use following styles: ```css #myTextField { transition: width 100ms linear; } ``` Do not forget to add vendor prefixes for transition. License ------- Copyright © 2012—2013 Roman Kivalin 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.
JavaScript
UTF-8
1,774
2.984375
3
[]
no_license
const postsNode = document.getElementById('posts'); function show() { fetch('/posts') .then(response => response.json()) .then(posts => { let html = ''; for (const post of posts) { html += ` <h2>${post[1]} <sup>#${post[0]}</sup></h2> <time class="badge badge-info">${new Date(post[3] * 1000)}</time> <button class="btn btn-sm btn-outline-danger" onClick="deletePost(${post[0]})">Delete</button> <article>${post[2]}</article> `; } postsNode.innerHTML = html; }).catch(error => { console.log(error); }); } show(); function deletePost(id) { fetch(`/posts/${id}`, { method: 'DELETE' }).then(function (_response) { show(); }).catch(function (error) { console.log(error); }) } const addPostForm = document.getElementById('add-post-form'); const controls = document.querySelectorAll('input, textarea'); const submitButton = document.querySelector('[type="submit"]'); const setSubmitEnabled = (doEnable) => { if (doEnable) { submitButton.removeAttribute('disabled'); } else { submitButton.setAttribute('disabled', ''); }; }; addPostForm.addEventListener('submit', event => { event.preventDefault(); setSubmitEnabled(false); const data = {}; Array.from(controls).forEach(el => { data[el.getAttribute('name')] = el.value; }); fetch('/posts/create', { method: 'POST', body: JSON.stringify(data), }).then(function (_response) { addPostForm.reset(); setSubmitEnabled(true); show(); }).catch(function (error) { setSubmitEnabled(true); console.log(error); }) });
JavaScript
UTF-8
749
2.6875
3
[]
no_license
(function () { //instance in controller var prod = new productnamespace.Product(1, " SampleProduct", 500, 'Product description'); // binding the object properties to the view document.write(prod.prodId); document.write(prod.prodName); document.write(prod.prodPrice); document.write(prod.prodDesc); })(window.productnamespace, window.ns); (function () { //instance in controller var corolla = new ns.Vehicle(111, "Toyota", "Hebbal Main Road"); // binding the object properties to the view document.write("----------------Name Space two------------"); document.write(corolla.vId); document.write(corolla.vName); document.write(corolla.vAddress); })(window.ns);
PHP
UTF-8
968
3.140625
3
[]
no_license
<?php require "Equacao2grau.php"; class EquacoesTest extends PHPUnit_Framework_TestCase { public function testConstruct(){ $eq2g = new Equacao2grau(1, 2, 3); $this->assertEquals(1, $eq2g->a); $this->assertEquals(2, $eq2g->b); $this->assertEquals(3, $eq2g->c); } public function testSetDelta(){ $eq2g = new Equacao2grau(1, -4, 3); $eq2g->setDelta(); $this->assertEquals(4, $eq2g->delta); $eq2g = new Equacao2grau(2, -4, 2); $eq2g->setDelta(); $this->assertEquals(0, $eq2g->delta); } public function testCalcular(){ $eq2g = new Equacao2grau(1, -4, 3); $eq2g->calcular(); $this->assertEquals(3, $eq2g->raiz1); $this->assertEquals(1, $eq2g->raiz2); $eq2g = new Equacao2grau(2, -4, 2); $eq2g->calcular(); $this->assertEquals(1, $eq2g->raiz1); $this->assertEquals(1, $eq2g->raiz2); } } ?>
Python
UTF-8
1,353
2.59375
3
[]
no_license
import requests from yarl import URL url = 'http://budget.gov.ru/epbs/registry/7710568760-BUDGETS/data' payload = dict( pageSize=2, filterstatus='ACTIVE', pageNum=1, ) conversion = dict() class ApiDataLoader: """ """ def __init__(self, timeout=5) -> None: self.timeout = timeout self.session = requests.Session def get_raw_data(self, url, payload): """ """ with self.session() as session: response = session.get(url, params=payload, timeout=self.timeout) response.raise_for_status() return response.json() @staticmethod def get_data(raw_data, key_field): """ """ return raw_data[key_field] @staticmethod def convert_data(data, conversion): """ """ new_data = [] for element in data: for k, v in element.items(): k = conversion.get(k, k) new_data.append({k: v}) return new_data def get_data_from_api(self, url, payload, key_field='data', conversion=None): """ """ url = URL(url) raw_data = self.get_raw_data(url, payload) data = self.get_data(raw_data, key_field) if conversion is not None: return self.convert_data(data, conversion) return data
TypeScript
UTF-8
609
2.84375
3
[]
no_license
import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform, } from '@nestjs/common'; @Injectable() export class ValidFilterPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { const theNYTimesOption = 'thenytimes'; const theGuardianOption = 'theguardian'; const isValid = value === theNYTimesOption || value === theGuardianOption; if (!isValid && value) { throw new BadRequestException( `The param: ${metadata.data} can pass only ${theNYTimesOption} either ${theGuardianOption} `, ); } return value; } }
Python
UTF-8
475
3.390625
3
[]
no_license
a, b = list(map(int, input().split())) g1 = [["#" for i in range(100)] for i in range(20)] g2 = [["." for i in range(100)] for i in range(20)] a, b = a-1, b-1 j = 0 while a!=0: for i in range(0, 100, 2): g1[j][i] = "." a -= 1 if a==0: break j += 2 j = 1 while b!=0: for i in range(0, 100, 2): g2[j][i] = "#" b -= 1 if b==0: break j += 2 g1.extend(g2) print(40, 100) for ele in g1: print("".join(ele))
Python
UTF-8
347
3.703125
4
[]
no_license
def fibonacci(num): if num == 1: return 0 elif num == 2: return 1 index = 2 def calc(first, second): nonlocal index index = index + 1 result = first + second if index == num: return result return calc(second, result) return calc(0, 1) print(fibonacci(5))
C++
UTF-8
1,580
3.421875
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; #define BIGINT_SIZE (1000) class BigInt { private: unsigned int _num[BIGINT_SIZE]{}; void carry_up() { for (int i = 0; i < BIGINT_SIZE - 1; ++i) { if (_num[i] >= 10) { _num[i + 1] += _num[i] / 10; _num[i] %= 10; } } } public: BigInt() { for (unsigned int &i : _num) { i = 0; } } void add(int num) { _num[0] += num; carry_up(); } string to_string() { int i = BIGINT_SIZE - 1; for (; i >= 0; --i) { if (_num[i] != 0) break; } if (i < 0) { return "0"; } string ret; while (i >= 0) { ret += ::to_string(_num[i]); i--; } return ret; } }; int main() { string s, t; cin >> s >> t; BigInt count; int prev_pos = -1; for (char c : t) { if (++prev_pos >= s.length()) { prev_pos = 0; count.add(s.length()); } int pos_from_prev_pos = s.find(c, prev_pos); if (pos_from_prev_pos != string::npos) { prev_pos = pos_from_prev_pos; continue; } count.add(s.length()); int pos_from_top = s.find(c); if (pos_from_top == string::npos) { cout << "-1" << endl; return 0; } prev_pos = pos_from_top; } count.add(prev_pos + 1); string answer = count.to_string(); cout << answer << endl; }
Java
UTF-8
272
1.710938
2
[]
no_license
/** * @autor Chekmarev Andrey * 3rd year, 7th group * @version 1.0 * Main class */ public class Main { public static void main(String[] args) throws Exception { InjectTest injectTest = new Injector().inject(new InjectTest()); injectTest.doSmth(); } }
C#
UTF-8
551
2.765625
3
[]
no_license
using UnityEngine; namespace Game { /// <summary> /// ECS Component that contains the properties required for the ECS Systems that handles gravity to work properly. /// </summary> public class GravityForce : MonoBehaviour { [Tooltip("The gravity force to apply to this GameObject")] [SerializeField] private float gravityForceFactor = 1.0f; public float GravityForceFactor { get => gravityForceFactor; private set => gravityForceFactor = value; } } }
Go
UTF-8
193
2.84375
3
[]
no_license
//全量读文件 package main import ( "io/ioutil" ) func main() { data, err := ioutil.ReadFile("t0001.go") if err != nil { println(err.Error()) } else { println(string(data)) } }
C++
UTF-8
1,660
2.609375
3
[]
no_license
#include "Project.h" using namespace simplesql::operators; Project::Project(const std::vector<ExpressionBase *>& _projectList, OperatorBase* _child) : OperatorBase(_Project), child(children[0]) { child = _child; projectList.assign(_projectList.begin(), _projectList.end()); children[1] = nullptr; } Project::~Project() { for (size_t i = 0; i < projectList.size(); i++) delete projectList[i]; if (child != nullptr) delete child; } bool Project::equalTo(OperatorBase* that) const { Project* _that = (Project*)that; if (that == nullptr) return false; if (that->type != _Project) return false; for (size_t i = 0; i < projectList.size(); i++) if(!projectList[i]->equalTo(_that->projectList[i])) return false; return child->equalTo(_that->child); } bool Project::open() { // maybe assert `resolved` here. return child->open(); } bool Project::close() { return child->close(); } std::string Project::projectString() const { std::string result; for (auto iter : projectList) result += iter->toString() + ","; return result; } NextResult Project::next() { NextResult nextResult = child->next(); if (nextResult.row == nullptr) return NextResult(nullptr); MemoryPool* mp = nextResult.mp; size_t listLen = projectList.size(); AnyValue** results = (AnyValue**)mp->allocate(listLen * sizeof(AnyValue*)); for (size_t i = 0; i < listLen; i++) results[i] = projectList[i]->eval(nextResult.row, mp); Row* newRow = Row::create(results, listLen, mp); return NextResult(newRow, mp); }
C++
UTF-8
1,026
3.265625
3
[ "BSD-3-Clause" ]
permissive
#include <vector> #include <iostream> using namespace std; class Solution { public: int minDistance(string word1, string word2) { int n = word1.length(); int m = word2.length(); vector<vector<int> > f; f.resize(n + 1); for (int i = 0; i <= n; i++) { f[i].resize(m + 1); } for (int i = 0; i <= n; i++) { f[i][0] = i; } for (int j = 0; j <= m; j++) { f[0][j] = j; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int val = std::min(f[i-1][j-1], std::min(f[i-1][j], f[i][j-1])) + 1; if (i < j) { val = std::min(f[i][i] + j-i, val); } if (i > j) { val = std::min(f[j][j] + i-j, val); } if (word1[i-1] == word2[j-1]) { val = std::min(f[i-1][j-1], val); } f[i][j] = val; } } return f[n][m]; } }; int main(int argc, char* argv[]) { Solution s; int distance = s.minDistance("sea", "ate"); cout << distance << endl; return 0; }
C++
UTF-8
676
2.796875
3
[]
no_license
#include "subsystems/Drivetrain.h" double boundValue(const double value, const double bound){ /** * Bounds value to range [-bound,bound] * If value is outside boundary, return appropriate boundry. Otherwise, return value. */ if(value < (-1.0 * bound)) return -1.0 * bound; if(value > bound) return bound; return value; } Drivetrain::Drivetrain() { //Set encoder and spark parameters here } void Drivetrain::Drive(const double left,const double right){ double bounded_left=boundValue(left,1.0); double bounded_right=boundValue(right,1.0); FLMotor->Set(bounded_left); BLMotor->Set(bounded_left); FRMotor->Set(bounded_right); BRMotor->Set(bounded_right); }
C++
UTF-8
1,539
3.25
3
[]
no_license
#include "Color.h" #include <SDL.h> const SDL_PixelFormat* Color::kFormat = SDL_AllocFormat(SDL_PIXELFORMAT_ARGB8888); Color Color::GetAlphaBlend(const Color& source, const Color& destination) { float sourceAlpha = static_cast<float>(source.alpha()) / 255.0f; float destinationAlpha = 1.0f - sourceAlpha; uint8_t r = static_cast<uint8_t>(source.red() * sourceAlpha + destination.red() * destinationAlpha); uint8_t g = static_cast<uint8_t>(source.green() * sourceAlpha + destination.green() * destinationAlpha); uint8_t b = static_cast<uint8_t>(source.blue() * sourceAlpha + destination.blue() * destinationAlpha); uint8_t a = 255; return Color(r, g, b, a); } Color::Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { value_ = SDL_MapRGBA(kFormat, r, g, b, a); } uint8_t Color::red() const { return GetChannel(Channel::kRed); } uint8_t Color::green() const { return GetChannel(Channel::kGreen); } uint8_t Color::blue() const { return GetChannel(Channel::kBlue); } uint8_t Color::alpha() const { return GetChannel(Channel::kAlpha); } uint8_t Color::GetChannel(Channel channel) const { uint8_t r; uint8_t g; uint8_t b; uint8_t a; SDL_GetRGBA(value_, kFormat, &r, &g, &b, &a); switch (channel) { case Channel::kRed: return r; case Channel::kGreen: return g; case Channel::kBlue: return b; case Channel::kAlpha: return a; default: return 0; } }
Swift
UTF-8
3,171
2.671875
3
[ "MIT" ]
permissive
// // Copyright © 2018 Frallware. All rights reserved. // import UIKit import Frallware final class PageView: UIView { let firstView = UIView() let secondView = UIView() private lazy var pan = UIPanGestureRecognizer(target: self, action: #selector(didPan)) var pageChangeAction: (() -> Void)? override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { addGestureRecognizer(pan) [firstView, secondView].forEach { view in view.clipsToBounds = true addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ view.centerXAnchor.constraint(equalTo: centerXAnchor), view.centerYAnchor.constraint(equalTo: centerYAnchor), view.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, multiplier: 1.0), view.heightAnchor.constraint(lessThanOrEqualTo: heightAnchor, multiplier: 1.0), ]) } secondView.isHidden = true } @objc private func didPan(_ pan: UIPanGestureRecognizer) { let shortestSideLength = min(firstView.bounds.width, firstView.bounds.height) let largestCornerRadius = shortestSideLength / 2 let translation = pan.translation(in: self) let transform = CGAffineTransform(translationX: translation.x, y: translation.y) let translationDistance = sqrt(translation.x * translation.x + translation.y * translation.y) switch pan.state { case .began, .possible: break case .changed: firstView.layer.cornerRadius = min(1.5 * translationDistance, largestCornerRadius) firstView.transform = transform case .ended, .cancelled, .failed: performTransition(withVelocity: pan.velocity(in: self)) } } private func performTransition(withVelocity velocity: CGPoint) { let diff = 0.4 * velocity // let firstViewEndPoint = center + diff // let secondViewStartPoint = center - diff let velocityParam = CGVector(dx: velocity.x, dy: velocity.y).normalized() let parameters = UISpringTimingParameters(dampingRatio: 1.0, initialVelocity: velocityParam) let animator = UIViewPropertyAnimator(duration: 0.3, timingParameters: parameters) secondView.isHidden = false secondView.transform = CGAffineTransform(translationX: -diff.x, y: -diff.y) pan.isEnabled = false animator.addAnimations { self.firstView.layer.cornerRadius = 0 self.firstView.transform = CGAffineTransform(translationX: diff.x, y: diff.y) self.secondView.transform = .identity } animator.addCompletion { position in self.firstView.transform = .identity self.secondView.isHidden = true self.pan.isEnabled = true self.pageChangeAction?() } animator.startAnimation() } }
SQL
UTF-8
1,874
3.34375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.9.5 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Jul 04, 2021 at 01:00 PM -- Server version: 5.7.24 -- PHP Version: 7.4.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; 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 */; -- -- Database: `hr-digital` -- -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `ID` int(4) NOT NULL, `PRODUCT_ID` int(6) NOT NULL, `PRODUCT_NAME` varchar(100) CHARACTER SET utf8mb4 NOT NULL, `PRODUCT_PRICE` int(7) NOT NULL, `PRODUCT_ARTICLE` varchar(20) CHARACTER SET utf8mb4 NOT NULL, `PRODUCT_QUANTITY` int(7) NOT NULL, `DATE_CREATE` date NOT NULL, `VISABLE` char(3) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `products` -- INSERT INTO `products` (`ID`, `PRODUCT_ID`, `PRODUCT_NAME`, `PRODUCT_PRICE`, `PRODUCT_ARTICLE`, `PRODUCT_QUANTITY`, `DATE_CREATE`, `VISABLE`) VALUES (1, 1, 'Мясо', 223, '1V234', 11, '2021-07-03', 'YES'), (2, 2, 'Молоко', 150, '1B234', 34, '2021-07-04', 'YES'); -- -- Indexes for dumped tables -- -- -- Indexes for table `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`ID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `products` -- ALTER TABLE `products` MODIFY `ID` int(4) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; 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 */;
Markdown
UTF-8
4,422
2.78125
3
[ "Apache-2.0" ]
permissive
# Contributing to Browsersync We'd love for you to contribute to Browsersync and help make it even better than it is today! Here are the guidelines we'd like you to follow: - [Question or Problem?](#question) - [Issues and Bugs](#issue) - [Tips for a creating a great issue report](#tips) - [Feature Requests](#feature) - [Pull Requests](#pull) - [Coding Rules](#rules) - [Thank you](#thanks) ## <a name="question"></a> Got a Question or Problem? If you have questions about how to *use* Browsersync, or about your particular setup, please ask on [Stack Overflow](http://stackoverflow.com/). We're trying to keep the Issues thread for actual bugs with code & implementation. ## <a name="issue"></a> Found an Issue? On that note, if you think you *have* found a bug in Browsersync, please report it via [Github Issues](https://github.com/BrowserSync/browser-sync/issues). ## <a name="tips"></a> Tips for a creating a great issue report Whilst we do try to look at each and every issue as soon as possible, there are certain aspects about your report that will determine how quickly/deeply we'll delve into it. A great issue will contain at least the following: * Operating System + Version * Use case for Browsersync - are you using the built-in server, proxying your own server, or just using the snippet mode? * Example configuration - show us your full `gulpfile.js`, `Gruntfile.js`, `bs-config.js` or any other code related to how you're using Browsersync. If we have to respond to your very first issue report with "please provide information about how you're using Browsersync" then it's very likely to fall to the bottom of the heap. Help us out by providing as much detail as possible! * Provide a reduced test case. "Browsersync is not working with my app" is far less helpful than "Here's a example project showing the problem". An example project might contain a single `index.html` file with some JS/CSS from CDNs & a short description of the issue. If we can just pull a repo/gist and see the problem for ourselves, your issue will jump straight to the top of the stack. * Screencast or GIF - not always appropriate, but can be very helpful where possible. (non-issue related gifs are always welcome, we'll often respond with something from giphy :p) ## <a name="feature"></a> Want a Feature? You can request a new feature by submitting an issue to our [Github Issues](https://github.com/BrowserSync/browser-sync/issues) page. Prefix the title of your issue with "Feature Request:". ## <a name="docs"></a> Want a Doc Fix? Head over to the [Browsersync Website Repo](https://github.com/BrowserSync/browsersync.github.io) & submit issues there. ## <a name="pull"></a> Submitting a Pull Request Pull requests should always be branched off the main **Master** branch. (There's no guarantee that what lives on the develop branch will ever make it back to master, I do a **lot** of experimentation). **Never** commit directly to the master branch, instead create a new branch and submit a PR. This applies to users who have write access also. **Note:** If your first PR is merged, you'll get write access to all Browsersync repos. ## <a name="rules"></a> Coding Advice To ensure consistency throughout the source code, keep these rules in mind as you are working. * If you're not sure how to provide tests for a feature or bug fix, you should still submit it and we'll help you complete the PR in one of the following ways: * we can advise you how to go about it * we can write the test, and then explain them to you. * This project has a [.editorconfig](.editorconfig) file to help with code style; go to [EditorConfig.org](http://editorconfig.org) and download the plugin for your IDE. * Don't introduce any extra 3rd party libraries unless you're creating a brand new feature that requires it. * Try to keep your code simple and readable. * Improve my code! Browsersync has a lot of moving parts and I don't pretend to be skilled in any particular area. If *you* have particular experience though, then feel free to rip my code apart and tell me a better way to do something - I'll be extremely grateful (as will the growing number of users!). ## <a name="thanks"></a> Thank you! If you contribute to Browsersync, or any other Open Source project, you're awesome! This project has been vastly improved by community input & contributions and we look forward to continuing that trend.
Markdown
UTF-8
5,611
3.15625
3
[]
no_license
--- title: "Sanity checks" categories: sre opinion --- In my line of work I've dealt with a lot of automated data pipelines that feed into production systems. Validating the output of these pipelines in an automated manner is frequently difficult. Suppose you had a different data source you could validate against. If you could reliably tell whether your pipeline was producing invalid data using this data source, why not directly incorporate this data into your pipeline? Alternatively, if the data source isn't reliable enough to do so, chances are you'll need a human to come look at the diffs either way. Another option is to simulate the production system under the new data, using historical or current load. This is often prohibitively expensive and a large maintenance burden, and usually impossible for data that rolls out at a high cadence (sometimes this is unavoidable). It can work well in select scenarios, however. This assumes you have good monitoring in place with a high degree of coverage. If your production system tolerates data version skew between instances, you can get around validation by simply canarying the data to a small fraction of your production instances. While this should prevent global outages, depending on the nature of the service it might allow frequent smaller outages that eat into your SLO. Proper semantic canarying might also be infeasible for data that rolls out at a high cadence, but it's still worth the effort to catch crashes and other immediately apparent problems. The simplest and least expensive way to validate pipeline output is by sanity checking the data before rolling it out. In my experience, simple absolute checks like making sure the output (or input) is not empty will go a long way in preventing outages. For more complex pipelines, performing these checks at every stage can be very effective. Absolute sanity checks may quickly become dated if the data experiences natural growth. In this case, it is common to compare the new data against the data currently in production (which is assumed to be valid). If the new data differs from the old by some threshold, the new data is considered to be invalid and the pipeline stalls. This works well when the data is difficult to validate at face value, even by a human. Usually it's difficult to determine what this threshold should be when you're writing the check. I think most people just pick something that looks reasonable, instead of doing a thorough analysis. I've heard people imply these kinds of checks may as well be removed, given the arbitrariness of the threshold. I've never really understood this argument. Often, it's really difficult to do any kind of meaningful analysis. Data changes over time, and it's likely that any analysis will quickly be dated. Surely having a (loose) relative check is better than not having one at all? Relative sanity checks have the problem of being noisy. In my experience only a small fraction of alerts based on relative checks expose actual problems. But this small fraction also prevents serious outages. Over time, well-tuned thresholds can reduce the amount of noise, but it's hard to make it go away entirely. This noise in itself can cause outages; I've seen two main classes of this, both caused by humans. The first is in a poorly automated system, where engineers frequently need to inspect failing relative checks. This tends to cause fatigue. A failing relative check due to a serious issue might be hidden beneath many other failing checks, or masked by the fact that the failure is usually benign. If the usual response is to simply let the data through, it's hard to blame the engineer when this inevitably causes an outage. This usually indicates a problem with the pipeline. If a check fails often, either relax/remove it or fix the underlying issue. The second is when a sanity check fails, and the engineer has correctly determined that the failure is benign. The engineer reruns the pipeline with sanity checks disabled, at which point a different bug or data problem manifests itself and causes a serious outage when the data rolls out to production. This is solved by making it easy for an engineer to rerun the pipeline with selectively relaxed thresholds. Risk can be further minimized by making sure the pipeline is hermetic and deterministic. A properly hermetic pipeline also makes it much easier to debug issues after a failure. You could make a case for rolling out the output that failed the benign sanity check rather than rerunning the pipeline, but this requires extra logic to hold on to the data until a human is able to look at it and roll it out. If this code path is not very well tested, it could also cause an outage. This is especially the case if it is not executed very often. Additionally, if the pipeline has been stalled for a while, a large enough delta may have accumulated that the next run fails as well. In this case, being able to selectively relax thresholds is crucial anyway, meaning the extra complexity required to push after failing a check is usually not worth it. Pipelines that are stalled too long are often problematic when they rely on relative checks for validation. If the data is not easily sanity checked by a human, you can be left completely blind to whether or not the data makes sense. The longer the pipeline remains stalled the larger the delta and the worse the problem becomes. The easiest way to deal with this is by making sure it doesn't happen in the first place. Otherwise, having a good monitoring and canarying story is often the only way out.
Python
UTF-8
2,444
3.578125
4
[]
no_license
""" - Reduce prices to peaks and troughs: highs: [3, 4, 6, 7] lows: [1, 2, 4, 5] - Iterate all 2-part slicing on highs-lows pair. for split in range(0, length-of-lows): use D&C to calculate max profit of left part use max(highs[s:]) - lows[s] to calculate max profit of right part profit-of-one-split = profit of left + profit of right final result is the maximum of all profit-of-one-split """ from typing import List class Solution: def __init__(self): self.prices = None self.highs = [] self.lows = [] self.subs = {} # { "4-7": (5, 2, 9) }, val (max profit, min, max) def reduce(self, prices): for idx, p in enumerate(prices): if idx == 0: if p < prices[idx + 1]: self.lows.append(p) elif idx == len(prices) - 1: if prices[idx - 1] < p: self.highs.append(p) else: if prices[idx - 1] >= p < prices[idx + 1]: self.lows.append(p) elif prices[idx - 1] < p >= prices[idx + 1]: self.highs.append(p) def maxWithOneTradeOnHl(self, s: int, e: int): if s < 0 or e < 0: raise ValueError if e - s == 1: h, l = self.highs[s], self.lows[s] return h - l, l, h key = f"{s}-{e}" if key in self.subs: return self.subs[key] half = (e - s) // 2 + s l_profit, l_min, l_max = self.maxWithOneTradeOnHl(s, half) r_profit, r_min, r_max = self.maxWithOneTradeOnHl(half, e) cross_profit = max(r_max - l_min, 0) max_profit = max(l_profit, r_profit, cross_profit) r = (max_profit, min(l_min, r_min), max(l_max, r_max)) self.subs[key] = r return r def maxProfit(self, prices: List[int]) -> int: if len(prices) <= 1: return 0 self.reduce(prices) assert len(self.lows) == len(self.highs) p_len = len(self.lows) if p_len < 1: return 0 elif p_len == 1: return self.highs[0] - self.lows[0] result = 0 for split in range(len(self.lows)): l_profit = self.maxWithOneTradeOnHl(0, split)[0] if split > 0 else 0 r_profit = max(0, max(self.highs[split:]) - self.lows[split]) result = max(result, l_profit + r_profit) return result
Java
UTF-8
6,312
2.40625
2
[]
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 com.kk.AutoFillSystem.Windows; import com.kk.AutoFillSystem.utility.PriceEstimation; import static com.kk.AutoFillSystem.utility.Tools.closeWindow; import static com.kk.AutoFillSystem.utility.Tools.showAlert; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.TextField; /** * FXML Controller class * * @author Yi */ public class SetCostTemplateWindowController implements Initializable { private MainWindowController mainWindow; private PriceEstimation pe = PriceEstimation.getInstance(); private double currencyRate; private double discount; private double initfee; private double extrafee; private int boxweight; private double vipDiscount; private int shipCnt; @FXML private TextField textFieldRate; @FXML private TextField textFieldInitFee; @FXML private TextField textFieldExtraFee; @FXML private TextField textFieldDiscount; @FXML private TextField textFieldVIPDiscount; @FXML private TextField textFieldShipCount; @FXML private TextField textFieldBoxWeight; @FXML private Button btnSave; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // init values discount = pe.getDiscount(); textFieldDiscount.setText("" + discount*100); textFieldDiscount.requestFocus(); textFieldDiscount.textProperty().addListener((observable, oldValue, newValue) -> { try { discount = Double.parseDouble(newValue)/100; } catch (NumberFormatException e) { showAlert("Error", "Invalid Format :", "Discount has to be a number !", Alert.AlertType.ERROR); textFieldDiscount.setText(oldValue); } }); currencyRate = pe.getCurrencyRatio(); textFieldRate.setText(""+ currencyRate); textFieldRate.textProperty().addListener((observable, oldValue, newValue) -> { try { currencyRate = Double.parseDouble(newValue); } catch (NumberFormatException e) { showAlert("Error", "Invalid Format :", "Currency rate has to be a number !", Alert.AlertType.ERROR); textFieldRate.setText(oldValue); } }); initfee = pe.getInitalShipFee(); textFieldInitFee.setText(""+ initfee); textFieldInitFee.textProperty().addListener((observable, oldValue, newValue) -> { try { initfee = Double.parseDouble(newValue); } catch (NumberFormatException e) { showAlert("Error", "Invalid Format :", "Shipping initial fee has to be a number !", Alert.AlertType.ERROR); textFieldInitFee.setText(oldValue); } }); extrafee = pe.getExtraShipFee(); textFieldExtraFee.setText(""+ extrafee); textFieldExtraFee.textProperty().addListener((observable, oldValue, newValue) -> { try { extrafee = Double.parseDouble(newValue); } catch (NumberFormatException e) { showAlert("Error", "Invalid Format :", "Shipping extra fee has to be a number !", Alert.AlertType.ERROR); textFieldExtraFee.setText(oldValue); } }); vipDiscount = pe.getVipDiscount(); textFieldVIPDiscount.setText("" + vipDiscount *100); textFieldVIPDiscount.textProperty().addListener((observable, oldValue, newValue) -> { try { vipDiscount = Double.parseDouble(newValue) / 100; } catch (NumberFormatException e) { showAlert("Error", "Invalid Format :", "VIP discount has to be a number !", Alert.AlertType.ERROR); textFieldVIPDiscount.setText(oldValue); } }); shipCnt = pe.getCount(); textFieldShipCount.setText(""+ shipCnt); textFieldShipCount.textProperty().addListener((observable, oldValue, newValue) -> { try { shipCnt = Integer.parseInt(newValue); } catch (NumberFormatException e) { showAlert("Error", "Invalid Format :", "Ship count has to be a number !", Alert.AlertType.ERROR); textFieldShipCount.setText(oldValue); } }); boxweight = pe.getExtraBoxWeight(); textFieldBoxWeight.setText("" + boxweight); textFieldBoxWeight.textProperty().addListener((observable, oldValue, newValue) -> { try { boxweight = Integer.parseInt(newValue); } catch (NumberFormatException e) { showAlert("Error", "Invalid Format :", "Box weight has to be a number !", Alert.AlertType.ERROR); textFieldBoxWeight.setText(oldValue); } }); //save button btnSave.setOnAction(e->save(e)); } private void save(ActionEvent e){ pe.setCount(shipCnt); pe.setCurrencyRatio(currencyRate); pe.setDiscount(discount); pe.setExtraBoxWeight(boxweight); pe.setExtraShipFee(extrafee); pe.setInitalShipFee(initfee); pe.setVipDiscount(vipDiscount); showAlert("Success", "New Settings Saved :", "The new set of parameters has been save successfully !", Alert.AlertType.INFORMATION); } //getters and setters public MainWindowController getMainWindow() { return mainWindow; } public void setMainWindow(MainWindowController mainWindow) { this.mainWindow = mainWindow; } }
C++
UTF-8
1,248
3.515625
4
[]
no_license
/** * @file node.cpp */ #include "node.hpp" #include <cstring> #include <iostream> Node::Node() { this->is_final = false; for (unsigned int i = 0; i < 27; i++) { this->tab[i] = nullptr; } } Node::~Node() { Node * temp = this; for(unsigned int i = 0; i < 27; i++) { delete temp->tab[i]; temp->tab[i] = nullptr; } } Node* Node::getNode(const unsigned short int & i) const { if (i < 27) return tab[i]; if (i == static_cast<unsigned int>('+')) return tab[26]; if (i - 'A' < 26) return tab[i - 'A']; return nullptr; } bool Node::isFinal() const { return is_final; } Node* Node::addNode(const bool & b) { Node * ptr = new Node(); ptr->is_final = b; for (unsigned int i = 0 ; i < 27; i++) { ptr->tab[i] = nullptr; } return ptr; } void Node::addNode(const std::string & s) { unsigned int i = 0, size = s.size(); unsigned short int c; Node * tmp = this; for (i = 0; i < size; i++) { if (s[i] == '+') //il s'agit d'un '+' c = 26; else // il s'agit d'une lettre c = s[i] - 'A'; if (tmp->tab[c] == nullptr) //le chemin vers cette case n'existe pas encore tmp->tab[c] = addNode( (i == size - 1) ); tmp = tmp->tab[c]; } }
C++
UTF-8
1,404
2.953125
3
[]
no_license
#pragma once #include <algorithm> #include <initializer_list> class MojNizInt { public: MojNizInt() : c_{1}, n_{0}, p_{new int[1]} {}; MojNizInt(std::initializer_list<int> a) : c_{a.size()}, n_{a.size()}, p_{new int[n_]} {std::copy(std::begin(a), std::end(a), p_);} MojNizInt(const MojNizInt&); //copy konstruktor MojNizInt(MojNizInt&& drugi); //move-copy konstruktor MojNizInt& operator=(const MojNizInt&); //copy jednako MojNizInt& operator=(MojNizInt&&); ~MojNizInt() {delete[] p_;}; //destruktor size_t size() const {return n_;} size_t capacity() const {return c_;} int at(const int& i) const; int& at(const int& i); //ovo je potrebno kako bi se moglo promijeniti vrijednost sa at int& operator[](const size_t& i) const {return p_[i];}; //MojNizInt operator*(int&&); //ovo slobodno ignorisi MojNizInt& operator*=(const int& i) {for(size_t j =0; j<n_; j++) p_[j]*=i; return *this;}; MojNizInt& operator+=(const MojNizInt&); MojNizInt operator++(int); //postfix++ il ti ga sufix MojNizInt& operator++(); //++prefix void push_back(const int&); void pop_back() {n_-=1;}; int& front(); int& back(); private: size_t c_; size_t n_; int* p_; }; MojNizInt operator*(MojNizInt, const int&); MojNizInt operator*(const int&, MojNizInt); MojNizInt operator+(MojNizInt, const MojNizInt& drugi);
C++
UTF-8
411
2.875
3
[]
no_license
#include "LogLevel.h" std::string ToString(LogLevel level) { switch (level) { case LogLevel::TRACE: return "TRACE"; case LogLevel::INFO: return "INFO"; case LogLevel::WARN: return "WARN"; case LogLevel::ERROR: return "ERROR"; case LogLevel::SEVERE: return "SEVERE"; default: assert(false); return "UNKNOWN_LOG_LEVEL"; } }
C#
UTF-8
693
2.53125
3
[]
no_license
 using System.ComponentModel.DataAnnotations.Schema; namespace UrbanDictionary.DataAccess.Entities { /// <summary> /// Implement the many-to-many relationship with <see cref="Entities.User"/> and its saved <see cref="Entities.Word"/>. /// </summary> public class UserSavedWord { /// <summary> /// Id of specific <see cref="User"/> /// </summary> public string UserId { get; set; } public User User { get; set; } /// <summary> /// <see cref="User"/>s saved <see cref="Entities.Word"/> Id. /// </summary> public long SavedWordId { get; set; } public Word SavedWord { get; set; } } }
Markdown
UTF-8
1,963
3.046875
3
[]
no_license
# MC_WS17-18_2.PNG **NOte**: a)-c) are multiple choice. d)-f) are questions to be answered with plain text. a) Q: What is the main advantage of having a convex loss function? A: They are relatively easy to optimize. **Note**: Because there exists only one minimum which is per definition the global minimum. b) Q: The k-means algorithm is an example of which of the following? A: Unsupervised learning **Note**: k-means is a clustering algorithm c) Q: he gradient of a function f points in the direction of ____ of f. A: steepest ascent d) Q: What is the aim of supervised machine learning? A: To train a classifier f with/on a given set of inputs and their respective labels (values in Regression) in order to accurately predict the labels of yet unseen datapoints. e) Q: Describe the phenomena of “overfitting” and give an example of a technique one can employ to avoid it. A: In overfitting, a too complex classifier that fits the training(!) data too well and that does therefore not accurately predict yet unseen data. The classifier does not "generalize" well to new data. f) Q: Describe how the random forest algorithm works. You may assume that it is known how decision trees work. A: From the training data select a random sample with replacements (note, if the original dataset has n datapoints, the sample has n datapoins as well). (This, with the below described averaging/majority-vote is called bagging.) Grow a decision tree on the dataset, but to determine each split of internal nodes a random subset of features (m<d) is selected and the optimal split is determined among those m features. (This can be called feature-bagging and distinguishes the random forest from just plain bagging.) Using the above procedure, arbitrarily many (users choice) decision trees are built which form the random forest. The prediction of the random forest is then done using e.g. majority-vote for classification or averaging for regression.
Java
UTF-8
8,117
1.757813
2
[ "Artistic-1.0", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "EPL-1.0", "CPL-1.0", "LGPL-2.1-or-later", "BSD-3-Clause", "LGPL-3.0-only", "ECL-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-jdom", "LicenseRef-scancode-freemarker", "LicenseRef-scancode-unk...
permissive
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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. */ package org.kuali.rice.kim.api.identity.type; import org.kuali.rice.core.api.CoreConstants; import org.kuali.rice.core.api.mo.AbstractDataTransferObject; import org.kuali.rice.core.api.mo.ModelBuilder; import org.kuali.rice.kim.api.identity.address.EntityAddress; import org.kuali.rice.kim.api.identity.email.EntityEmail; import org.kuali.rice.kim.api.identity.phone.EntityPhone; import org.w3c.dom.Element; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import java.io.Serializable; import java.util.Collection; @XmlRootElement(name = EntityTypeContactInfoDefault.Constants.ROOT_ELEMENT_NAME) @XmlAccessorType(XmlAccessType.NONE) @XmlType(name = EntityTypeContactInfoDefault.Constants.TYPE_NAME, propOrder = { EntityTypeContactInfoDefault.Elements.ENTITY_TYPE_CODE, EntityTypeContactInfoDefault.Elements.DEFAULT_ADDRESS, EntityTypeContactInfoDefault.Elements.DEFAULT_EMAIL_ADDRESS, EntityTypeContactInfoDefault.Elements.DEFAULT_PHONE_NUMBER, CoreConstants.CommonElements.FUTURE_ELEMENTS }) public final class EntityTypeContactInfoDefault extends AbstractDataTransferObject { @XmlElement(name = Elements.ENTITY_TYPE_CODE, required = true) private final String entityTypeCode; @XmlElement(name = Elements.DEFAULT_ADDRESS, required = false) private final EntityAddress defaultAddress; @XmlElement(name = Elements.DEFAULT_EMAIL_ADDRESS, required = false) private final EntityEmail defaultEmailAddress; @XmlElement(name = Elements.DEFAULT_PHONE_NUMBER, required = false) private final EntityPhone defaultPhoneNumber; @SuppressWarnings("unused") @XmlAnyElement private final Collection<Element> _futureElements = null; /** * Private constructor used only by JAXB. */ private EntityTypeContactInfoDefault() { this.entityTypeCode = null; this.defaultAddress = null; this.defaultEmailAddress = null; this.defaultPhoneNumber = null; } public EntityTypeContactInfoDefault(String entityTypeCode, EntityAddress defaultAddress, EntityEmail defaultEmailAddress, EntityPhone defaultPhoneNumber) { this.entityTypeCode = entityTypeCode; this.defaultAddress = defaultAddress; this.defaultEmailAddress = defaultEmailAddress; this.defaultPhoneNumber = defaultPhoneNumber; } public EntityTypeContactInfoDefault(Builder builder) { this.entityTypeCode = builder.getEntityTypeCode(); this.defaultAddress = builder.getDefaultAddress() == null ? null : builder.getDefaultAddress().build(); this.defaultEmailAddress = builder.getDefaultEmailAddress() == null ? null : builder.getDefaultEmailAddress().build(); this.defaultPhoneNumber = builder.getDefaultPhoneNumber() == null ? null : builder.getDefaultPhoneNumber().build(); } public String getEntityTypeCode() { return this.entityTypeCode; } public EntityAddress getDefaultAddress() { return this.defaultAddress; } public EntityEmail getDefaultEmailAddress() { return this.defaultEmailAddress; } public EntityPhone getDefaultPhoneNumber() { return this.defaultPhoneNumber; } public final static class Builder implements Serializable, ModelBuilder { private String entityTypeCode; private EntityAddress.Builder defaultAddress; private EntityEmail.Builder defaultEmailAddress; private EntityPhone.Builder defaultPhoneNumber; private Builder() { } public static Builder create() { return new Builder(); } public static Builder create(EntityTypeContactInfoDefault immutable) { if (immutable == null) { throw new IllegalArgumentException("EntityTypeDataDefault is null"); } Builder builder = new Builder(); builder.setEntityTypeCode(immutable.entityTypeCode); if (immutable.getDefaultAddress() != null) { builder.setDefaultAddress(EntityAddress.Builder.create(immutable.getDefaultAddress())); } if (immutable.getDefaultEmailAddress() != null) { builder.setDefaultEmailAddress(EntityEmail.Builder.create(immutable.getDefaultEmailAddress())); } if (immutable.getDefaultPhoneNumber() != null) { builder.setDefaultPhoneNumber(EntityPhone.Builder.create(immutable.getDefaultPhoneNumber())); } return builder; } public static Builder create(EntityTypeContactInfoContract contract) { if (contract == null) { throw new IllegalArgumentException("contract is null"); } Builder builder = new Builder(); builder.setEntityTypeCode(contract.getEntityTypeCode()); if (contract.getDefaultAddress() != null) { builder.setDefaultAddress(EntityAddress.Builder.create(contract.getDefaultAddress())); } if (contract.getDefaultEmailAddress() != null) { builder.setDefaultEmailAddress(EntityEmail.Builder.create(contract.getDefaultEmailAddress())); } if (contract.getDefaultPhoneNumber() != null) { builder.setDefaultPhoneNumber(EntityPhone.Builder.create(contract.getDefaultPhoneNumber())); } return builder; } public EntityTypeContactInfoDefault build() { return new EntityTypeContactInfoDefault(this); } public String getEntityTypeCode() { return entityTypeCode; } public void setEntityTypeCode(String entityTypeCode) { this.entityTypeCode = entityTypeCode; } public EntityAddress.Builder getDefaultAddress() { return defaultAddress; } public void setDefaultAddress(EntityAddress.Builder defaultAddress) { this.defaultAddress = defaultAddress; } public EntityEmail.Builder getDefaultEmailAddress() { return defaultEmailAddress; } public void setDefaultEmailAddress(EntityEmail.Builder defaultEmailAddress) { this.defaultEmailAddress = defaultEmailAddress; } public EntityPhone.Builder getDefaultPhoneNumber() { return defaultPhoneNumber; } public void setDefaultPhoneNumber(EntityPhone.Builder defaultPhoneNumber) { this.defaultPhoneNumber = defaultPhoneNumber; } } /** * Defines some internal constants used on this class. * */ static class Constants { final static String ROOT_ELEMENT_NAME = "entityTypeDataDefault"; final static String TYPE_NAME = "EntityTypeDataDefaultType"; } /** * A private class which exposes constants which define the XML element names to use when this object is marshalled to XML. * */ static class Elements { final static String ENTITY_TYPE_CODE = "entityTypeCode"; final static String DEFAULT_ADDRESS = "defaultAddress"; final static String DEFAULT_EMAIL_ADDRESS = "defaultEmailAddress"; final static String DEFAULT_PHONE_NUMBER = "defaultPhoneNumber"; } }
Shell
UTF-8
3,279
3.65625
4
[ "MIT" ]
permissive
flei_docker_get_compose_project_name() { flei_get_clean_project_name } flei_get_docker_compose_path() { flei_require @flei/common-paths flei_require @flei/get-flei-image local FLEI_IMAGE FLEI_IMAGE="$(flei_get_flei_image)" local DOCKER_COMPOSE_PATH_BASE DOCKER_COMPOSE_PATH_BASE="$(flei_resolve_path "${1}" "/docker/" "${BASH_SOURCE[1]}" ".docker-compose")" local DOCKER_COMPOSE_PATH_YML="${DOCKER_COMPOSE_PATH_BASE}.yml" local DOCKER_COMPOSE_PATH_JS="${DOCKER_COMPOSE_PATH_BASE}.js" local DOCKER_COMPOSE_PATH_GENERATED="${DOCKER_COMPOSE_PATH_BASE}.js.yml" if [ -f "${DOCKER_COMPOSE_PATH_JS}" ]; then local PROJECT_ROOT PROJECT_ROOT="$(flei_project_root)" local PROJECT_ROOT_IN_DOCKER="/opt/flei-project-root" local DOCKER_COMPOSE_RELATIVE_TO_PROJECT_ROOT="${DOCKER_COMPOSE_PATH_JS#"${PROJECT_ROOT}/"}" local DOCKER_COMPOSE_PATH_IN_DOCKER="${PROJECT_ROOT_IN_DOCKER}/${DOCKER_COMPOSE_RELATIVE_TO_PROJECT_ROOT}" docker run --rm -i -u "${RUN_UID}:${RUN_GID}" \ -v "${PROJECT_ROOT}:${PROJECT_ROOT_IN_DOCKER}" \ "${FLEI_IMAGE}" \ flei generate-docker-compose-config-from-js "${DOCKER_COMPOSE_PATH_IN_DOCKER}" echo "${DOCKER_COMPOSE_PATH_GENERATED}" exit 0 fi echo "${DOCKER_COMPOSE_PATH_YML}" } flei_docker() { flei_require @flei/resolve-path flei_require @flei/common-paths flei_require @flei/get-project-name flei_require @flei/get-flei-image local FLEI_IMAGE FLEI_IMAGE="$(flei_get_flei_image)" export RUN_UID RUN_UID="$(id -u)" export RUN_GID RUN_GID="$(id -g)" export FLEI_PROJECT_ROOT FLEI_PROJECT_ROOT="$(flei_project_root)" local DOCKER_COMPOSE_PATH DOCKER_COMPOSE_PATH="$(flei_get_docker_compose_path "${@}")" export COMPOSE_PROJECT_NAME COMPOSE_PROJECT_NAME="$(flei_docker_get_compose_project_name)" local DOCKER_COMPOSE_CONFIG DOCKER_COMPOSE_CONFIG=$(docker-compose -f "${DOCKER_COMPOSE_PATH}" config) local VOLUMES VOLUMES="$(echo "${DOCKER_COMPOSE_CONFIG}" | docker run --rm -i -u "${RUN_UID}:${RUN_GID}" \ "${FLEI_IMAGE}" \ flei get-volumes-from-docker-compose-config)" flei_docker_fix_volume_owner "${VOLUMES}" set +o errexit docker-compose -f "${DOCKER_COMPOSE_PATH}" run --rm "${@:2}" DOCKER_EXIT_CODE=$? set -o errexit docker-compose -f "${DOCKER_COMPOSE_PATH}" down if [ ${DOCKER_EXIT_CODE} -ne 0 ]; then exit ${DOCKER_EXIT_CODE} fi } function flei_docker_fix_volume_owner_generate_service_volumes() { for var in "$@"; do echo " - ${var}:/opt/flei-fix-volume-owner/${var}" done } function flei_docker_fix_volume_owner_generate_volume_configuration() { for var in "$@"; do echo " ${var}:" done } flei_docker_fix_volume_owner() { flei_require @flei/get-flei-image local FLEI_IMAGE FLEI_IMAGE="$(flei_get_flei_image)" DOCKER_COMPOSE=" services: fix-volume-owner: image: ${FLEI_IMAGE} volumes: $(flei_docker_fix_volume_owner_generate_service_volumes "${@}") command: | sh -c \"chown ${RUN_UID}:${RUN_GID} /opt/flei-fix-volume-owner/*\" volumes: $(flei_docker_fix_volume_owner_generate_volume_configuration "${@}") " echo "${DOCKER_COMPOSE}" | docker-compose -f - run --rm fix-volume-owner echo "${DOCKER_COMPOSE}" | docker-compose -f - down }
Python
UTF-8
745
2.5625
3
[]
no_license
# preprocessor directives import fresh_tomatoes import media # Movie objects bladerunner = media.Movie( "Blade Runner", "https://www.youtube.com/watch?v=4lW0F1sccqk" ) mad_max = media.Movie( "Mad Max: Fury Road", "https://www.youtube.com/watch?v=hEJnMQG9ev8" ) point_break = media.Movie( "Point Break", "https://www.youtube.com/watch?v=0hd49bnStgU" ) brazil = media.Movie( "Brazil", "https://www.youtube.com/watch?v=4Wh2b1eZFUM" ) isteve = media.Movie( "iSteve", "https://www.youtube.com/watch?v=0FChm-Ayj7g" ) # an array of Movie objects movies = [bladerunner, point_break, mad_max, brazil, isteve] # calling fresh_tomatoes() to create page fresh_tomatoes.open_movies_page(movies)
Java
WINDOWS-1250
3,881
2.109375
2
[]
no_license
package com.luxsoft.siipap.cxc.swing.cobranza; import org.apache.log4j.Logger; import com.luxsoft.siipap.cxc.catalogos.ComentarioDeRevisionForm; import com.luxsoft.siipap.ventas.domain.VentaACredito; import com.luxsoft.siipap.ventas.managers.VentasManager; /** * Soporte adicional para la funcionalidad de RevisionView * * @author Ruben Cancino * */ public class RevisionSupport { private Logger logger=Logger.getLogger(getClass()); private VentasManager manager; public RevisionSupport(){ } public void actualizarComentarios(final VentaACredito v){ final ComentarioDeRevisionForm form=new ComentarioDeRevisionForm(v); form.open(); if(!form.hasBeenCanceled()){ getManager().actualizarVenta(v.getVenta()); getManager().refresh(v.getVenta()); } } /** * Prepara una lista de notas de credito para descuento que se requieren para facturas en especifico para las * cuales se autoriza su impresion para mandar a revision * * @param ventas * @return public void generarNotasPorAnticipado(final EventList<Venta> ventasTodas,final Date fecha){ final EventList<Venta> ventas=filtrar(ventasTodas); final Comparator<NotasDeCreditoDet> c=GlazedLists.beanPropertyComparator(NotasDeCreditoDet.class, "clave"); final SortedList<NotasDeCreditoDet> dets=new SortedList<NotasDeCreditoDet>(new BasicEventList<NotasDeCreditoDet>(),c); for(Venta v:ventas){ if(v.getCliente().getCredito().isNotaAnticipada()){ NotasDeCreditoDet det=NotasUtils.getNotaDet(v); dets.add(det); } } final GroupingList<NotasDeCreditoDet> grupos=new GroupingList<NotasDeCreditoDet>(dets,c); final List<NotaDeCredito> res=new ArrayList<NotaDeCredito>(); for(int i=0;i<grupos.size();i++){ final List<NotasDeCreditoDet> partidas=grupos.get(i); NotasUtils.ordenarPorFactura(partidas); final List<NotaDeCredito> notas=NotasUtils.getNotasFromDetalles(partidas); for(NotaDeCredito nota:notas){ NotasUtils.configurarParaDescuento(nota); } res.addAll(notas); } NotasUtils.aplicarProvision(res); NotasUtils.actualizarFecha(res, fecha); if(logger.isDebugEnabled()){ logger.debug("Notas generadas: "+res.size()); } NotasPorAnticipado dialog=new NotasPorAnticipado(res); dialog.open(); if(!dialog.hasBeenCanceled()){ salvarNotas(res); MessageUtils.showMessage("Verifique que en el panel de control de windows la\n impresora seleccionada sea la correcta", "Impresin de Notas"); imprimirNotas(res); } } public void salvarNotas(final List<NotaDeCredito> notas){ ServiceLocator.getNotasManager().salvarNotasCre(notas); for(NotaDeCredito nota:notas){ for(NotasDeCreditoDet det:nota.getPartidas()){ //Actualizamos la provision de la venta getManager().aplicarProvision(det.getFactura()); } } } public void imprimirNotas(final List<NotaDeCredito> notas){ for(NotaDeCredito nota:notas){ final Map<String, Object> params=new HashMap<String, Object>(); params.put("NOTA_ID", nota.getId()); params.put("IMPORTE_LETRA", ImporteALetra.aLetra(nota.getTotalAsMoneda())); ReportUtils.printReport("reportes/"+CXCReportes.NotaDeCredito.name()+".jasper" , params, false); } } private EventList<Venta> filtrar(final EventList<Venta> ventas){ final Matcher<Venta> matcher=new Matcher<Venta>(){ public boolean matches(Venta item) { return ((item.getSaldo().doubleValue()>0) && (item.getProvision()!=null) && (!item.getProvision().isAplicado()) ); } }; final FilterList<Venta> filtro=new FilterList<Venta>(ventas,matcher); return filtro; } */ public VentasManager getManager() { return manager; } public void setManager(VentasManager manager) { this.manager = manager; } }
C++
UTF-8
3,485
2.59375
3
[]
no_license
#include "stdafx.h" using namespace std; using namespace nb; int main() { PackageManager packageManager; packageManager.initFromFolder( "./data/debug_packageManager" ); const std::list<Package>& pkgsByName = packageManager.getLoadedPackages(); const Package* newPackage = packageManager.getPackageByName( "NewPackage" ); const Package* testpackage = packageManager.getPackageByName( "Testpackage" ); const MetaFile* npm1 = packageManager.getMetaFileById( "NewPackage:mario1" ); const MetaFile* npm2 = packageManager.getMetaFileById( "NewPackage:mario2" ); const MetaFile* nptf = packageManager.getMetaFileById( "NewPackage:textfile" ); const MetaFile* npmt = packageManager.getMetaFileById( "NewPackage:textures:myTexture" ); const MetaFile* tpm1 = packageManager.getMetaFileById( "Testpackage:mario1" ); const MetaFile* tpm2 = packageManager.getMetaFileById( "Testpackage:mario2" ); const MetaFile* tpm3 = packageManager.getMetaFileById( "Testpackage:mario3" ); const MetaFile* tptf = packageManager.getMetaFileById( "Testpackage:textfile" ); // cout << "-- Package names:" << endl; cout << newPackage->getName() << endl; cout << testpackage->getName() << endl; // const MetaFile* _npm1 = newPackage->getMetaFileById( "mario1" ); const MetaFile* _npm2 = newPackage->getMetaFileById( "mario2" ); const MetaFile* _nptf = newPackage->getMetaFileById( "textfile" ); const MetaFile* _npmt = newPackage->getMetaFileById( "textures:myTexture" ); const MetaFile* _tpm1 = testpackage->getMetaFileById( "mario1" ); const MetaFile* _tpm2 = testpackage->getMetaFileById( "mario2" ); const MetaFile* _tpm3 = testpackage->getMetaFileById( "mario3" ); const MetaFile* _tptf = testpackage->getMetaFileById( "textfile" ); cout << boolalpha; cout << "-- Compare MetaFiles:" << endl; cout << (npm1 == _npm1) << endl; cout << (npm2 == _npm2) << endl; cout << (nptf == _nptf) << endl; cout << (npmt == _npmt) << endl; cout << (tpm1 == _tpm1) << endl; cout << (tpm2 == _tpm2) << endl; cout << (tpm3 == _tpm3) << endl; cout << (tptf == _tptf) << endl; // cout << "-- Local ID, Global ID, Connected Filepath:" << endl; cout << npm1->getId() << endl; cout << newPackage->convertLocalToGlobalId( npm1->getId() ) << endl; cout << npm1->getConnectedFilePath() << endl; cout << npm2->getId() << endl; cout << newPackage->convertLocalToGlobalId( npm2->getId() ) << endl; cout << npm2->getConnectedFilePath() << endl; cout << nptf->getId() << endl; cout << newPackage->convertLocalToGlobalId( nptf->getId() ) << endl; cout << nptf->getConnectedFilePath() << endl; cout << npmt->getId() << endl; cout << newPackage->convertLocalToGlobalId( npmt->getId() ) << endl; cout << npmt->getConnectedFilePath() << endl; cout << tpm1->getId() << endl; cout << testpackage->convertLocalToGlobalId( tpm1->getId() ) << endl; cout << tpm1->getConnectedFilePath() << endl; cout << tpm2->getId() << endl; cout << testpackage->convertLocalToGlobalId( tpm2->getId() ) << endl; cout << tpm2->getConnectedFilePath() << endl; cout << tpm3->getId() << endl; cout << testpackage->convertLocalToGlobalId( tpm3->getId() ) << endl; cout << tpm3->getConnectedFilePath() << endl; cout << tptf->getId() << endl; cout << testpackage->convertLocalToGlobalId( tptf->getId() ) << endl; cout << tptf->getConnectedFilePath() << endl; cout << "-----------------" << endl; cout << "NewBitPackageManagerTest complete" << endl; system( "pause" ); packageManager.save(); }
PHP
UTF-8
2,210
2.625
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: Chelsea * Date: 3/1/2015 * Time: 3:44 PM */ namespace App\Impl\Reponsitory\Product; use App\Http\Requests\ProductFormRequest; use App\Impl\Service\Cache\CacheInteface; use App\Products; use Carbon\Carbon; use Illuminate\Http\Request; use Intervention\Image\Facades\Image; class EloquentProducts implements ProductInterface { protected $products; protected $cache; public function __construct(Products $products, CacheInteface $cache){ $this->products = $products; $this->cache = $cache; } public function all() { $key = md5('products'); if($this->cache->has($key)) { return $this->cache->get($key); } $this->cache->put($key, $this->products->all(), 10); return $this->products->all(); } public function delete($id) { $this->products->destroy($id); } public function save(ProductFormRequest $request) { if(!$request->has('id')) { $products = new Products(); } else { $products = $this->products->findOrFail($request->input('id')); } $products->product_name = $request->get('product_name'); $products->description = $request->get('description'); $image = $request->file('img'); $fileName = $image->getClientOriginalName(); $path = public_path('img/'.$fileName); //Image::make($image->getRealPath())->resize(200, 200)->save($path); Image::make($image->getRealPath())->resize(200, 200)->save($path); $products->img = 'img/'.$fileName; $products->quanlity = $request->get('quanlity'); $products->price = $request->get('price'); $this->cache->deleteCaCheFile(md5('products')); return $products->save(); } public function find($id) { $key = md5('findProduct'); if($this->cache->has($key)) { return $this->cache->get($key); } $products = $this->products->findOrFail($id); $this->cache->put($key, $products, 10); return $products; } }
Python
UTF-8
729
3.90625
4
[]
no_license
class Parent: parent_attr = 100 def __init__(self): print("调用父类构造函数") def parent_method(self): print("调用父类方法") def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print("父类属性 :", Parent.parentAttr) class Child(Parent): def __init__(self): print("调用子类构造函数") def child_method(self): print("调用子类方法") c = Child() # 实例化子类 c.child_method() # 调用子类的方法 c.parent_method() # 调用父类方法 c.setAttr(200) # 再次调用父类的方法 - 设置属性值 c.getAttr() # 再次调用父类的方法 - 获取属性值
C#
UTF-8
19,099
2.578125
3
[]
no_license
using System; using System.Collections.ObjectModel; namespace StokerStocks { static class BancoDados { /// <summary> /// Carrega os ativos da carteira /// </summary> /// <returns></returns> public static ObservableCollection<Ativo> CarregarAtivos() { ObservableCollection<Ativo> temp = new ObservableCollection<Ativo>(); return temp; } public static ObservableCollection<Ordem> CarregarOrdens(string Ticket) { return new ObservableCollection<Ordem>() { new Ordem(){ Date = new DateTime(2016, 09, 12), Operação = Operações.Compra, Quantidade = 27, ValorUnitário = 55.5m }, new Ordem(){ Date = new DateTime(2016, 10, 04), Operação = Operações.Compra, Quantidade = 10, ValorUnitário = 57.6m }, new Ordem(){ Date = new DateTime(2016, 10, 19), Operação = Operações.Compra, Quantidade = 3, ValorUnitário = 61.3m }, new Ordem(){ Date = new DateTime(2017, 02, 06), Operação = Operações.Venda, Quantidade = 2, ValorUnitário = 80.5m }, new Ordem(){ Date = new DateTime(2017, 03, 08), Operação = Operações.Compra, Quantidade = 10, ValorUnitário = 81.1m }, new Ordem(){ Date = new DateTime(2017, 03, 15), Operação = Operações.Venda, Quantidade = 38, ValorUnitário = 81.5m }, new Ordem(){ Date = new DateTime(2019, 06, 25), Operação = Operações.Venda, Quantidade = 10, ValorUnitário = 88.9m }, }; } /// <summary> /// Carrega o historico de cotações para um periodo de tempo limitado /// </summary> /// <param name="Inicio"></param> /// <param name="Final"></param> /// <returns></returns> public static ObservableCollection<Cotacao> CarregarCotacoes(DateTime Inicio, DateTime Final) { ObservableCollection<Cotacao> DB = new ObservableCollection<Cotacao>() { new Cotacao() { Data = new DateTime(2019,7,19), Abertura=88.90m, Maxima=89.00m, Minima=87.07m, Fechamento=87.18m }, new Cotacao() { Data = new DateTime(2019,6,28), Abertura=88.97m, Maxima=88.97m, Minima=86.30m, Fechamento=88.03m }, new Cotacao() { Data = new DateTime(2019,5,31), Abertura=88.2m, Maxima=90m, Minima=86m, Fechamento=89m }, new Cotacao() { Data = new DateTime(2019,5,31), Abertura=88.2m, Maxima=90m, Minima=86m, Fechamento=89m }, new Cotacao() { Data = new DateTime(2019,4,30), Abertura=85.95m, Maxima=88.9m, Minima=84m, Fechamento=88.2m }, new Cotacao() { Data = new DateTime(2019,3,29), Abertura=80.89m, Maxima=88m, Minima=79.5m, Fechamento=86m }, new Cotacao() { Data = new DateTime(2019,2,128), Abertura=80.94m, Maxima=82.79m, Minima=78.75m, Fechamento=81m }, new Cotacao() { Data = new DateTime(2019,1,31), Abertura=75.24m, Maxima=81.99m, Minima=74.8m, Fechamento=80.5m }, new Cotacao() { Data = new DateTime(2018,12,28), Abertura=74.79m, Maxima=77.99m, Minima=72.26m, Fechamento=75.26m }, new Cotacao() { Data = new DateTime(2018,11,30), Abertura=73.9m, Maxima=75.2m, Minima=72.02m, Fechamento=74.95m }, new Cotacao() { Data = new DateTime(2018,10,31), Abertura=72.75m, Maxima=75m, Minima=70m, Fechamento=74.86m }, new Cotacao() { Data = new DateTime(2018,9,28), Abertura=72.48m, Maxima=73.27m, Minima=71.16m, Fechamento=72.75m }, new Cotacao() { Data = new DateTime(2018,8,31), Abertura=74m, Maxima=74.59m, Minima=71m, Fechamento=72.71m }, new Cotacao() { Data = new DateTime(2018,7,31), Abertura=72.2m, Maxima=74.95m, Minima=70.99m, Fechamento=74.39m }, new Cotacao() { Data = new DateTime(2018,6,29), Abertura=71.99m, Maxima=72.89m, Minima=69.13m, Fechamento=72.2m }, new Cotacao() { Data = new DateTime(2018,5,30), Abertura=79.2m, Maxima=79.2m, Minima=67.16m, Fechamento=73m }, new Cotacao() { Data = new DateTime(2018,4,30), Abertura=77.6m, Maxima=80m, Minima=76.81m, Fechamento=79m }, new Cotacao() { Data = new DateTime(2018,3,29), Abertura=77.6m, Maxima=80m, Minima=74.4m, Fechamento=79.95m }, new Cotacao() { Data = new DateTime(2018,2,28), Abertura=79m, Maxima=80.2m, Minima=74.5m, Fechamento=77.5m }, new Cotacao() { Data = new DateTime(2018,1,31), Abertura=74.51m, Maxima=80m, Minima=74.05m, Fechamento=79.05m }, new Cotacao() { Data = new DateTime(2017,12,29), Abertura=74.4m, Maxima=75m, Minima=72.03m, Fechamento=74.37m }, new Cotacao() { Data = new DateTime(2017,11,30), Abertura=74.49m, Maxima=75.74m, Minima=71.2m, Fechamento=75m }, new Cotacao() { Data = new DateTime(2017,10,31), Abertura=73.3m, Maxima=76m, Minima=71.2m, Fechamento=74.5m }, new Cotacao() { Data = new DateTime(2017,9,29), Abertura=72.59m, Maxima=73.4m, Minima=70.11m, Fechamento=73.36m }, new Cotacao() { Data = new DateTime(2017,8,31), Abertura=68.7m, Maxima=73m, Minima=68.7m, Fechamento=72.6m }, new Cotacao() { Data = new DateTime(2017,7,31), Abertura=70.11m, Maxima=73.48m, Minima=68.9m, Fechamento=68.9m }, new Cotacao() { Data = new DateTime(2017,6,30), Abertura=70m, Maxima=74.85m, Minima=68.5m, Fechamento=72m }, new Cotacao() { Data = new DateTime(2017,5,31), Abertura=71.77m, Maxima=74m, Minima=67m, Fechamento=71.35m }, new Cotacao() { Data = new DateTime(2017,4,28), Abertura=72.5m, Maxima=74.99m, Minima=67m, Fechamento=72.3m }, new Cotacao() { Data = new DateTime(2017,3,31), Abertura=63.67m, Maxima=75m, Minima=63.65m, Fechamento=71.5m }, new Cotacao() { Data = new DateTime(2017,2,24), Abertura=63m, Maxima=64.95m, Minima=62.5m, Fechamento=64m }, new Cotacao() { Data = new DateTime(2017,1,31), Abertura=60.26m, Maxima=63.63m, Minima=58.36m, Fechamento=63.4m }, new Cotacao() { Data = new DateTime(2016,12,29), Abertura=58m, Maxima=60.8m, Minima=55.3m, Fechamento=60.8m }, new Cotacao() { Data = new DateTime(2016,11,30), Abertura=61m, Maxima=62m, Minima=53.01m, Fechamento=58m }, new Cotacao() { Data = new DateTime(2016,10,31), Abertura=59m, Maxima=63.95m, Minima=55.51m, Fechamento=61m }, new Cotacao() { Data = new DateTime(2016,9,30), Abertura=60m, Maxima=60m, Minima=54.2m, Fechamento=59.85m }, new Cotacao() { Data = new DateTime(2016,8,31), Abertura=74.99m, Maxima=80m, Minima=57.3m, Fechamento=59.12m }, new Cotacao() { Data = new DateTime(2016,7,29), Abertura=69.69m, Maxima=79.49m, Minima=68m, Fechamento=75.8m }, new Cotacao() { Data = new DateTime(2016,6,30), Abertura=69.75m, Maxima=69.99m, Minima=67.8m, Fechamento=69.7m }, new Cotacao() { Data = new DateTime(2016,5,31), Abertura=67m, Maxima=69.99m, Minima=64m, Fechamento=69.19m }, new Cotacao() { Data = new DateTime(2016,4,29), Abertura=68.48m, Maxima=69m, Minima=65.1m, Fechamento=68.4m }, new Cotacao() { Data = new DateTime(2016,3,31), Abertura=54.02m, Maxima=69.89m, Minima=53.1m, Fechamento=67.99m }, new Cotacao() { Data = new DateTime(2016,2,29), Abertura=56.01m, Maxima=56.49m, Minima=51.62m, Fechamento=55.33m }, new Cotacao() { Data = new DateTime(2016,1,29), Abertura=60.42m, Maxima=60.42m, Minima=55m, Fechamento=56.5m }, new Cotacao() { Data = new DateTime(2015,12,30), Abertura=64.49m, Maxima=64.49m, Minima=58.57m, Fechamento=61.3m }, new Cotacao() { Data = new DateTime(2015,11,30), Abertura=64.98m, Maxima=64.98m, Minima=62m, Fechamento=64.5m }, new Cotacao() { Data = new DateTime(2015,10,30), Abertura=63.96m, Maxima=65m, Minima=61.61m, Fechamento=65m }, new Cotacao() { Data = new DateTime(2015,9,30), Abertura=68m, Maxima=68.45m, Minima=62.5m, Fechamento=64.88m }, new Cotacao() { Data = new DateTime(2015,8,31), Abertura=70.11m, Maxima=70.11m, Minima=65.22m, Fechamento=69m }, new Cotacao() { Data = new DateTime(2015,7,31), Abertura=70.34m, Maxima=70.5m, Minima=69.31m, Fechamento=70.5m }, new Cotacao() { Data = new DateTime(2015,6,30), Abertura=70.25m, Maxima=71m, Minima=69.13m, Fechamento=70.7m }, new Cotacao() { Data = new DateTime(2015,5,29), Abertura=70.1m, Maxima=71.97m, Minima=68m, Fechamento=70.69m }, new Cotacao() { Data = new DateTime(2015,4,30), Abertura=70.75m, Maxima=72.49m, Minima=68.83m, Fechamento=72.29m }, new Cotacao() { Data = new DateTime(2015,3,31), Abertura=70.53m, Maxima=71.48m, Minima=68.01m, Fechamento=70m }, new Cotacao() { Data = new DateTime(2015,2,27), Abertura=73.44m, Maxima=73.44m, Minima=71m, Fechamento=71m }, new Cotacao() { Data = new DateTime(2015,1,30), Abertura=74.98m, Maxima=74.99m, Minima=71m, Fechamento=73.47m }, new Cotacao() { Data = new DateTime(2014,12,30), Abertura=70.99m, Maxima=72.5m, Minima=68.68m, Fechamento=72.48m }, new Cotacao() { Data = new DateTime(2014,11,28), Abertura=73m, Maxima=73.48m, Minima=67.25m, Fechamento=71.4m }, new Cotacao() { Data = new DateTime(2014,10,31), Abertura=71.8m, Maxima=74.11m, Minima=67.05m, Fechamento=73.19m }, new Cotacao() { Data = new DateTime(2014,9,30), Abertura=73.11m, Maxima=74.78m, Minima=70.01m, Fechamento=70.02m }, }; ObservableCollection<Cotacao> Resultado = new ObservableCollection<Cotacao>(); DateTime FinalMes = new DateTime(Final.Year, Final.Month, DateTime.DaysInMonth(Final.Year, Final.Month), 23, 59, 59); DateTime InicioMes = new DateTime(Inicio.Year, Inicio.Month, 1, 0, 0, 0); foreach (Cotacao item in DB) { if ((item.Data > InicioMes) && (item.Data <= FinalMes)) { Resultado.Add(item); } } return Resultado; } /// <summary> /// Carrega o historico de cotações de uma data de inicio até hoje /// </summary> /// <param name="Inicio"></param> /// <returns></returns> public static ObservableCollection<Cotacao> CarregarCotacoes(DateTime Inicio) { ObservableCollection<Cotacao> DB = new ObservableCollection<Cotacao>() { new Cotacao() { Data = new DateTime(2019,7,19), Abertura=88.90m, Maxima=89.00m, Minima=87.07m, Fechamento=87.18m }, new Cotacao() { Data = new DateTime(2019,6,28), Abertura=88.97m, Maxima=88.97m, Minima=86.30m, Fechamento=88.03m }, new Cotacao() { Data = new DateTime(2019,5,31), Abertura=88.2m, Maxima=90m, Minima=86m, Fechamento=89m }, new Cotacao() { Data = new DateTime(2019,5,31), Abertura=88.2m, Maxima=90m, Minima=86m, Fechamento=89m }, new Cotacao() { Data = new DateTime(2019,4,30), Abertura=85.95m, Maxima=88.9m, Minima=84m, Fechamento=88.2m }, new Cotacao() { Data = new DateTime(2019,3,29), Abertura=80.89m, Maxima=88m, Minima=79.5m, Fechamento=86m }, new Cotacao() { Data = new DateTime(2019,2,28), Abertura=80.94m, Maxima=82.79m, Minima=78.75m, Fechamento=81m }, new Cotacao() { Data = new DateTime(2019,1,31), Abertura=75.24m, Maxima=81.99m, Minima=74.8m, Fechamento=80.5m }, new Cotacao() { Data = new DateTime(2018,12,28), Abertura=74.79m, Maxima=77.99m, Minima=72.26m, Fechamento=75.26m }, new Cotacao() { Data = new DateTime(2018,11,30), Abertura=73.9m, Maxima=75.2m, Minima=72.02m, Fechamento=74.95m }, new Cotacao() { Data = new DateTime(2018,10,31), Abertura=72.75m, Maxima=75m, Minima=70m, Fechamento=74.86m }, new Cotacao() { Data = new DateTime(2018,9,28), Abertura=72.48m, Maxima=73.27m, Minima=71.16m, Fechamento=72.75m }, new Cotacao() { Data = new DateTime(2018,8,31), Abertura=74m, Maxima=74.59m, Minima=71m, Fechamento=72.71m }, new Cotacao() { Data = new DateTime(2018,7,31), Abertura=72.2m, Maxima=74.95m, Minima=70.99m, Fechamento=74.39m }, new Cotacao() { Data = new DateTime(2018,6,29), Abertura=71.99m, Maxima=72.89m, Minima=69.13m, Fechamento=72.2m }, new Cotacao() { Data = new DateTime(2018,5,30), Abertura=79.2m, Maxima=79.2m, Minima=67.16m, Fechamento=73m }, new Cotacao() { Data = new DateTime(2018,4,30), Abertura=77.6m, Maxima=80m, Minima=76.81m, Fechamento=79m }, new Cotacao() { Data = new DateTime(2018,3,29), Abertura=77.6m, Maxima=80m, Minima=74.4m, Fechamento=79.95m }, new Cotacao() { Data = new DateTime(2018,2,28), Abertura=79m, Maxima=80.2m, Minima=74.5m, Fechamento=77.5m }, new Cotacao() { Data = new DateTime(2018,1,31), Abertura=74.51m, Maxima=80m, Minima=74.05m, Fechamento=79.05m }, new Cotacao() { Data = new DateTime(2017,12,29), Abertura=74.4m, Maxima=75m, Minima=72.03m, Fechamento=74.37m }, new Cotacao() { Data = new DateTime(2017,11,30), Abertura=74.49m, Maxima=75.74m, Minima=71.2m, Fechamento=75m }, new Cotacao() { Data = new DateTime(2017,10,31), Abertura=73.3m, Maxima=76m, Minima=71.2m, Fechamento=74.5m }, new Cotacao() { Data = new DateTime(2017,9,29), Abertura=72.59m, Maxima=73.4m, Minima=70.11m, Fechamento=73.36m }, new Cotacao() { Data = new DateTime(2017,8,31), Abertura=68.7m, Maxima=73m, Minima=68.7m, Fechamento=72.6m }, new Cotacao() { Data = new DateTime(2017,7,31), Abertura=70.11m, Maxima=73.48m, Minima=68.9m, Fechamento=68.9m }, new Cotacao() { Data = new DateTime(2017,6,30), Abertura=70m, Maxima=74.85m, Minima=68.5m, Fechamento=72m }, new Cotacao() { Data = new DateTime(2017,5,31), Abertura=71.77m, Maxima=74m, Minima=67m, Fechamento=71.35m }, new Cotacao() { Data = new DateTime(2017,4,28), Abertura=72.5m, Maxima=74.99m, Minima=67m, Fechamento=72.3m }, new Cotacao() { Data = new DateTime(2017,3,31), Abertura=63.67m, Maxima=75m, Minima=63.65m, Fechamento=71.5m }, new Cotacao() { Data = new DateTime(2017,2,24), Abertura=63m, Maxima=64.95m, Minima=62.5m, Fechamento=64m }, new Cotacao() { Data = new DateTime(2017,1,31), Abertura=60.26m, Maxima=63.63m, Minima=58.36m, Fechamento=63.4m }, new Cotacao() { Data = new DateTime(2016,12,29), Abertura=58m, Maxima=60.8m, Minima=55.3m, Fechamento=60.8m }, new Cotacao() { Data = new DateTime(2016,11,30), Abertura=61m, Maxima=62m, Minima=53.01m, Fechamento=58m }, new Cotacao() { Data = new DateTime(2016,10,31), Abertura=59m, Maxima=63.95m, Minima=55.51m, Fechamento=61m }, new Cotacao() { Data = new DateTime(2016,9,30), Abertura=60m, Maxima=60m, Minima=54.2m, Fechamento=59.85m }, new Cotacao() { Data = new DateTime(2016,8,31), Abertura=74.99m, Maxima=80m, Minima=57.3m, Fechamento=59.12m }, new Cotacao() { Data = new DateTime(2016,7,29), Abertura=69.69m, Maxima=79.49m, Minima=68m, Fechamento=75.8m }, new Cotacao() { Data = new DateTime(2016,6,30), Abertura=69.75m, Maxima=69.99m, Minima=67.8m, Fechamento=69.7m }, new Cotacao() { Data = new DateTime(2016,5,31), Abertura=67m, Maxima=69.99m, Minima=64m, Fechamento=69.19m }, new Cotacao() { Data = new DateTime(2016,4,29), Abertura=68.48m, Maxima=69m, Minima=65.1m, Fechamento=68.4m }, new Cotacao() { Data = new DateTime(2016,3,31), Abertura=54.02m, Maxima=69.89m, Minima=53.1m, Fechamento=67.99m }, new Cotacao() { Data = new DateTime(2016,2,29), Abertura=56.01m, Maxima=56.49m, Minima=51.62m, Fechamento=55.33m }, new Cotacao() { Data = new DateTime(2016,1,29), Abertura=60.42m, Maxima=60.42m, Minima=55m, Fechamento=56.5m }, new Cotacao() { Data = new DateTime(2015,12,30), Abertura=64.49m, Maxima=64.49m, Minima=58.57m, Fechamento=61.3m }, new Cotacao() { Data = new DateTime(2015,11,30), Abertura=64.98m, Maxima=64.98m, Minima=62m, Fechamento=64.5m }, new Cotacao() { Data = new DateTime(2015,10,30), Abertura=63.96m, Maxima=65m, Minima=61.61m, Fechamento=65m }, new Cotacao() { Data = new DateTime(2015,9,30), Abertura=68m, Maxima=68.45m, Minima=62.5m, Fechamento=64.88m }, new Cotacao() { Data = new DateTime(2015,8,31), Abertura=70.11m, Maxima=70.11m, Minima=65.22m, Fechamento=69m }, new Cotacao() { Data = new DateTime(2015,7,31), Abertura=70.34m, Maxima=70.5m, Minima=69.31m, Fechamento=70.5m }, new Cotacao() { Data = new DateTime(2015,6,30), Abertura=70.25m, Maxima=71m, Minima=69.13m, Fechamento=70.7m }, new Cotacao() { Data = new DateTime(2015,5,29), Abertura=70.1m, Maxima=71.97m, Minima=68m, Fechamento=70.69m }, new Cotacao() { Data = new DateTime(2015,4,30), Abertura=70.75m, Maxima=72.49m, Minima=68.83m, Fechamento=72.29m }, new Cotacao() { Data = new DateTime(2015,3,31), Abertura=70.53m, Maxima=71.48m, Minima=68.01m, Fechamento=70m }, new Cotacao() { Data = new DateTime(2015,2,27), Abertura=73.44m, Maxima=73.44m, Minima=71m, Fechamento=71m }, new Cotacao() { Data = new DateTime(2015,1,30), Abertura=74.98m, Maxima=74.99m, Minima=71m, Fechamento=73.47m }, new Cotacao() { Data = new DateTime(2014,12,30), Abertura=70.99m, Maxima=72.5m, Minima=68.68m, Fechamento=72.48m }, new Cotacao() { Data = new DateTime(2014,11,28), Abertura=73m, Maxima=73.48m, Minima=67.25m, Fechamento=71.4m }, new Cotacao() { Data = new DateTime(2014,10,31), Abertura=71.8m, Maxima=74.11m, Minima=67.05m, Fechamento=73.19m }, new Cotacao() { Data = new DateTime(2014,9,30), Abertura=73.11m, Maxima=74.78m, Minima=70.01m, Fechamento=70.02m }, }; ObservableCollection<Cotacao> Resultado = new ObservableCollection<Cotacao>(); DateTime FinalMes = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month), 23, 59, 59); DateTime InicioMes = new DateTime(Inicio.Year, Inicio.Month, 1, 0, 0, 0); foreach (Cotacao item in DB) { if ((item.Data > InicioMes) && (item.Data <= FinalMes)) { Resultado.Add(item); } } return Resultado; } } }
Java
UTF-8
3,191
2.84375
3
[]
no_license
package com.mq.demo.rpc; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Channel; import com.rabbitmq.client.QueueingConsumer; import com.rabbitmq.client.AMQP.BasicProperties; /** * Created by hzzhaolong on 2016/2/3. */ public class RPCServer { private static final String RPC_REQUEST_QUEUE_NAME = "hzzhaolong_rpc_queue"; private static final int QUEUE_PORT = 5672; private static final String IP = "xxx"; private static final String USERNAME = "admin"; private static final String PASSWORD = "d97aNp"; private static int fib(int n) { if (n ==0) return 0; if (n == 1) return 1; return fib(n-1) + fib(n-2); } public static void main(String[] argv) { Connection connection = null; Channel channel = null; try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(IP); factory.setUsername(USERNAME); factory.setPassword(PASSWORD); factory.setPort(QUEUE_PORT); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_REQUEST_QUEUE_NAME, false, false, false, null); // 设置每个消费这最多处理一个任务 channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_REQUEST_QUEUE_NAME, false, consumer); System.out.println(" [x] Awaiting RPC requests"); while (true) { String response = null; // Main application-side API: wait for the next message delivery and return it. QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties requestProps = delivery.getProperties(); // 相应只要指定请求ID即可 BasicProperties replyProps = new BasicProperties .Builder() .correlationId(requestProps.getCorrelationId()) .build(); try { String message = new String(delivery.getBody(),"UTF-8"); int n = Integer.parseInt(message); System.out.println(" [.] fib(" + message + ")"); response = "" + fib(n); } catch (Exception e){ System.out.println(" [.] " + e.toString()); response = ""; } finally { // 写入response队列 channel.basicPublish( "", requestProps.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) {} } } } }
JavaScript
UTF-8
893
2.765625
3
[]
no_license
import axios from "axios"; export const fetchOrganisationsByQueryService = async (qwery = "") => { try { const response = await axios( `https://api.github.com/search/users?q=type:org+${qwery}` ); const { items } = response.data; return items; } catch (error) { return []; } }; export const fetchOrganisationMembersByNameService = async name => { try { const response = await axios(`https://api.github.com/orgs/${name}/members`); return response.data; } catch (error) { return []; } }; export const fetchOrganisationByNameService = async name => { try { const response = await axios(`https://api.github.com/orgs/${name}`); const organisationData = response.data; organisationData.members = await fetchOrganisationMembersByNameService( name ); return organisationData; } catch (error) { return null; } };
Markdown
UTF-8
9,621
2.828125
3
[]
no_license
# swagger_client.InvoiceResourceApi All URIs are relative to *https://localhost:8080* Method | HTTP request | Description ------------- | ------------- | ------------- [**create_invoice_using_post**](InvoiceResourceApi.md#create_invoice_using_post) | **POST** /api/invoices | createInvoice [**delete_invoice_using_delete**](InvoiceResourceApi.md#delete_invoice_using_delete) | **DELETE** /api/invoices/{id} | deleteInvoice [**get_all_invoices_using_get**](InvoiceResourceApi.md#get_all_invoices_using_get) | **GET** /api/invoices | getAllInvoices [**get_invoice_by_subscriber_using_get**](InvoiceResourceApi.md#get_invoice_by_subscriber_using_get) | **GET** /api/invoices/subscriber/{subscriberSecureId} | getInvoiceBySubscriber [**get_invoice_using_get**](InvoiceResourceApi.md#get_invoice_using_get) | **GET** /api/invoices/{id} | getInvoice [**update_invoice_using_put**](InvoiceResourceApi.md#update_invoice_using_put) | **PUT** /api/invoices | updateInvoice # **create_invoice_using_post** > Invoice create_invoice_using_post(invoice) createInvoice ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure API key authorization: apiKey configuration = swagger_client.Configuration() configuration.api_key['Authorization'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['Authorization'] = 'Bearer' # create an instance of the API class api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration)) invoice = swagger_client.Invoice() # Invoice | invoice try: # createInvoice api_response = api_instance.create_invoice_using_post(invoice) pprint(api_response) except ApiException as e: print("Exception when calling InvoiceResourceApi->create_invoice_using_post: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **invoice** | [**Invoice**](Invoice.md)| invoice | ### Return type [**Invoice**](Invoice.md) ### Authorization [apiKey](../README.md#apiKey) ### HTTP request headers - **Content-Type**: application/json - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **delete_invoice_using_delete** > delete_invoice_using_delete(id) deleteInvoice ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure API key authorization: apiKey configuration = swagger_client.Configuration() configuration.api_key['Authorization'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['Authorization'] = 'Bearer' # create an instance of the API class api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration)) id = 789 # int | id try: # deleteInvoice api_instance.delete_invoice_using_delete(id) except ApiException as e: print("Exception when calling InvoiceResourceApi->delete_invoice_using_delete: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **id** | **int**| id | ### Return type void (empty response body) ### Authorization [apiKey](../README.md#apiKey) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **get_all_invoices_using_get** > list[Invoice] get_all_invoices_using_get() getAllInvoices ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure API key authorization: apiKey configuration = swagger_client.Configuration() configuration.api_key['Authorization'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['Authorization'] = 'Bearer' # create an instance of the API class api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration)) try: # getAllInvoices api_response = api_instance.get_all_invoices_using_get() pprint(api_response) except ApiException as e: print("Exception when calling InvoiceResourceApi->get_all_invoices_using_get: %s\n" % e) ``` ### Parameters This endpoint does not need any parameter. ### Return type [**list[Invoice]**](Invoice.md) ### Authorization [apiKey](../README.md#apiKey) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **get_invoice_by_subscriber_using_get** > list[Invoice] get_invoice_by_subscriber_using_get(subscriber_secure_id) getInvoiceBySubscriber ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure API key authorization: apiKey configuration = swagger_client.Configuration() configuration.api_key['Authorization'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['Authorization'] = 'Bearer' # create an instance of the API class api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration)) subscriber_secure_id = 'subscriber_secure_id_example' # str | subscriberSecureId try: # getInvoiceBySubscriber api_response = api_instance.get_invoice_by_subscriber_using_get(subscriber_secure_id) pprint(api_response) except ApiException as e: print("Exception when calling InvoiceResourceApi->get_invoice_by_subscriber_using_get: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **subscriber_secure_id** | **str**| subscriberSecureId | ### Return type [**list[Invoice]**](Invoice.md) ### Authorization [apiKey](../README.md#apiKey) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **get_invoice_using_get** > Invoice get_invoice_using_get(id) getInvoice ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure API key authorization: apiKey configuration = swagger_client.Configuration() configuration.api_key['Authorization'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['Authorization'] = 'Bearer' # create an instance of the API class api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration)) id = 789 # int | id try: # getInvoice api_response = api_instance.get_invoice_using_get(id) pprint(api_response) except ApiException as e: print("Exception when calling InvoiceResourceApi->get_invoice_using_get: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **id** | **int**| id | ### Return type [**Invoice**](Invoice.md) ### Authorization [apiKey](../README.md#apiKey) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **update_invoice_using_put** > Invoice update_invoice_using_put(invoice) updateInvoice ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure API key authorization: apiKey configuration = swagger_client.Configuration() configuration.api_key['Authorization'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['Authorization'] = 'Bearer' # create an instance of the API class api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration)) invoice = swagger_client.Invoice() # Invoice | invoice try: # updateInvoice api_response = api_instance.update_invoice_using_put(invoice) pprint(api_response) except ApiException as e: print("Exception when calling InvoiceResourceApi->update_invoice_using_put: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **invoice** | [**Invoice**](Invoice.md)| invoice | ### Return type [**Invoice**](Invoice.md) ### Authorization [apiKey](../README.md#apiKey) ### HTTP request headers - **Content-Type**: application/json - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
PHP
UTF-8
3,442
2.53125
3
[]
no_license
<?php /** * Copyright. "NewGen" investment engine. All rights reserved. * Any questions? Please, visit https://newgen.company */ namespace App\Console\Commands\Automatic; use App\Http\Controllers\Admin\WithdrawalRequestsController; use App\Models\Currency; use App\Models\PaymentSystem; use App\Models\Transaction; use App\Models\TransactionType; use App\Models\Wallet; use Illuminate\Console\Command; /** * Class ProcessInstantPaymentsCommand * @package App\Console\Commands\Automatic */ class ProcessInstantPaymentsCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'process:instant_payments'; /** * The console command description. * * @var string */ protected $description = 'Process customers instant payments.'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * @throws \Exception */ public function handle() { /** @var TransactionType $transactionWithdrawType */ $transactionWithdrawType = TransactionType::getByName('withdraw'); /** @var Transaction $orders */ $orders = Transaction::where('type_id', $transactionWithdrawType->id) ->where('approved', 0) ->get(); $messages = []; $this->info('Found '.$orders->count().' orders.'); $this->line('---'); /** @var Transaction $order */ foreach ($orders as $order) { $this->info('Start processing withdraw order with ID '.$order->id.' and amount '.$order->amount); /** @var Wallet $wallet */ $wallet = $order->wallet()->first(); /** @var PaymentSystem $paymentSystem */ $paymentSystem = $wallet->paymentSystem()->first(); /** @var Currency $currency */ $currency = $wallet->currency()->first(); if (null == $wallet || null == $paymentSystem) { continue; } if (null === $limits = $paymentSystem->instant_limit) { $this->info('Limits is not set up..'); return; } $decodedLimits = @json_decode($limits, true); if (!isset($decodedLimits[$currency->code])) { $this->info('Limit for this currency '.$currency->code.' not found.'); return; } $limit = (float) $decodedLimits[$currency->code]; if ($limit <= 0) { $this->info('Skip. Payment system instant limit is 0.'); continue; } if ($order->amount > $limit) { $this->info('Skip. Order amount '.$order->amount.' and payment system limit '.$limit); continue; } try { $message = WithdrawalRequestsController::approve($order->id, true); } catch (\Exception $e) { $message = $e->getMessage(); } $messages[] = $message; } if (count($messages) == 0) { return; } $msg = 'Processed '.count($messages).' instant payments. Results:\n'.implode('<hr>', $messages); $this->info($msg); \Log::info($msg); } }
C#
UTF-8
289
2.953125
3
[]
no_license
using System; namespace RocketEquation { public static class FuelCalculator { public static int RequiredFuel(int mass) { var step1 = Math.Floor((double) mass / 3); var step2 = step1 - 2; return (int)step2; } } }
PHP
UTF-8
8,675
2.5625
3
[ "Apache-2.0" ]
permissive
<?php /** op-unit-curl:/Curl.class.php * * @created 2017-06-01 * @version 1.0 * @package op-unit-curl * @author Tomoaki Nagahara <tomoaki.nagahara@gmail.com> * @copyright Tomoaki Nagahara All right reserved. */ /** namespace * * @created 2018-07-02 */ namespace OP\UNIT; /** Used class * */ use OP\OP_CORE; use OP\OP_UNIT; use OP\OP_DEBUG; use OP\IF_UNIT; use OP\Config; use OP\Notice; use OP\UNIT\CURL\File; use function OP\RootPath; use function OP\ConvertURL; use function OP\UNIT\CURL\GetReferer; /* use function OP\UNIT\CURL\GetCookieFilePath; */ /** Curl * */ class Curl implements IF_UNIT { /** trait. * */ use OP_CORE, OP_UNIT, OP_DEBUG; /** Last error message. * * @var string */ static private $_errors; /** Parse header string. * * @param string $header * @return array $header */ static private function _Header($headers) { // ... $result = []; // ... foreach( explode("\r\n", $headers) as $header ){ if( strlen($header) === 0 ){ // ... }else if( $pos = strpos($header, ':') ){ // ... $key = substr($header, 0, $pos ); $val = substr($header, $pos+1); // ... $result[strtolower($key)] = trim($val); // Content-Type if( strtolower($key) === 'content-type' ){ // MIME, Charset list($mime, $charset) = explode(';', $val.';'); // MIME $result['mime'] = trim($mime); // Charset if( $charset ){ list($key, $val) = explode('=', trim($charset)); $result[$key] = $val; }; }; }else if( strpos($header, 'HTTP/') === 0 ){ list($result['http'], $result['status']) = explode(' ', $header); }else{ $result[] = $header; }; }; // ... return $result; } /** Convert to string from array at post data. * * @param array $post * @param string $format * @return string $data */ static private function _Data($post, $format=null) { switch( $format ){ case 'json': $data = json_encode($post); break; default: // Content-Type: application/x-www-form-urlencoded /* $temp = []; foreach( $post as $key => $val ){ $temp[$key] = self::Escape($val); } */ $data = http_build_query($post, null, '&'); } // ... return $data; } /** Execute to Curl. * * @param string $url * @param array $post * @param array $option * @return string $body */ static private function _Execute($url, $post, $option=[]) { // ... $config = Config::Get('curl'); // ... $option = array_merge($config, $option); // ... if(!empty($option['cookie']) ){ // ... $parsed = parse_url($url); // ... $path = RootPath('asset').'cache/cookie/'.$parsed['host']; // ... foreach(['cookie_read','cookie_write'] as $key){ if( empty($option[$key]) ){ $option[$key] = $path; } } } // ... $format = $option['format'] ?? null; // Json, Xml $referer = $option['referer'] ?? null; // Specified referer. $has_header = $option['header'] ?? null; // Return request and response headers. // Timeout second. $timeout = $option['timeout'] ?? $config['ua'] ?? 10; // Specified User Agent. $ua = $option['ua'] ?? $config['ua'] ?? null; // Content Type switch( $format ){ default: $content_type = 'application/x-www-form-urlencoded'; }; // Get referer at current app uri. if( $referer === true ){ require_once(__DIR__.'/function/GetReferer.php'); $referer = GetReferer(); } // Data serialize. $data = $post ? self::_Data($post, $format): null; // HTTP Header $header = []; $header[] = "Content-Type: {$content_type}"; $header[] = "Content-Length: ".strlen($data); // Cookie is direct string. if( $cookie = $option['cookie_string'] ?? null ){ $header[] = "Cookie: $cookie"; } // Referer if( $referer ){ $header[] = "Referer: $referer"; } // Check if installed PHP CURL. if(!defined('CURLOPT_URL') ){ // ... D('PHP CURL is not installed.'); // ... if( $post ){ // ... $context = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => implode("\r\n", $header), 'content' => $data ], /* 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, ], */ ]); }; // ... return file_get_contents($url, false, ($context ?? null)); }; // ... $curl = curl_init(); // ... if( $has_header ){ curl_setopt($curl, CURLOPT_HEADER, true); }; // POST if( $post !== null ){ curl_setopt( $curl, CURLOPT_CUSTOMREQUEST , 'POST' ); curl_setopt( $curl, CURLOPT_POST , true ); curl_setopt( $curl, CURLOPT_POSTFIELDS , $data ); }; // SSL if( strpos($url, 'https://') === 0 ){ curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true); curl_setopt( $curl, CURLOPT_CAINFO, __DIR__.'/cacert.pem'); }; // Cookie read/write foreach(['cookie_read' => CURLOPT_COOKIEFILE, 'cookie_write' => CURLOPT_COOKIEJAR] as $key => $var){ // ... if(!$path = $option[$key] ?? null ){ continue; } // ... if(!file_exists($path)){ require_once(__DIR__.'/File.class.php'); File::Create($path); }; // ... curl_setopt($curl, $var, $path); } // ... $curl_option = [ CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $header, CURLOPT_USERAGENT => $ua, CURLOPT_REFERER => $referer, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $timeout, ]; // ... curl_setopt_array($curl, $curl_option); // ... if(!$body = curl_exec($curl)){ $info = curl_getinfo($curl); // ... if( $errno = curl_errno($curl) ){ $error = sprintf('Error(%s): %s', $errno, $url); self::$_errors[] = $error; }; }; // Return ['head','body'] array. if( $has_header ){ $body = curl_exec($curl); $size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); return [ 'errno'=> $errno ?? null, 'info' => $info ?? null, 'head' => self::_Header( substr($body, 0, $size) ), 'body' => substr($body, $size), ]; }; // Return body string only. return $body; } /** Separate error routine. * * @param integer $error is Curl error code * @param integer $info is Curl transfer information * @param string $url is fetch URL * @param integer $timeout is timeout sec */ static private function _ExecuteError($errno, $info, $url, $timeout) { // ... switch( $errno ){ case CURLE_OK: break; case CURLE_URL_MALFORMAT: self::$_errors[] = 'The URL was not properly formatted.'; break; case CURLE_COULDNT_RESOLVE_HOST: self::$_errors[] = 'Couldn\'t resolve host. The given remote host was not resolved.'; break; case 28: case OPERATION_TIMEOUTED: self::$_errors[] = "Response is timeout. ({$timeout} sec.)"; break; case 60: case CURLE_PEER_FAILED_VERIFICATION: self::$_errors[] = 'The remote server\'s SSL certificate or SSH md5 fingerprint was deemed not OK.'; break; default: self::$_errors[] = "Response is error. ({$errno}, {$url})"; break; } // ... switch( $code = $info['http_code'] ){ case 0: return false; case 200: case 302: case 403: case 404: case 405: break; /* case 301: if(!$body ){ $body = $info; }; break; */ default: Notice::Set("Http status code is {$code}."); break; } } /** Escape of string. * * @param string $string * @return string $string */ static function Escape($string) { $string = preg_replace('/&/' , '%26', $string); $string = preg_replace('/ /' , '%20', $string); $string = preg_replace('/\t/', '%09', $string); $string = preg_replace('/\s/', '%20', $string); return $string; } /** Get method. * * @param string $url * @param array $data * @param string $option * @return string $body */ static function Get($url, $data=null, $option=[]) { // ... if( $data ){ // ... if( strpos($url, '?') ){ list($url, $query) = explode('?', $url); parse_str($query, $query); $data = array_merge($query, $data); } // ... $url .= '?'.http_build_query($data); } // ... return self::_Execute($url, null, $option); } /** Post method. * * @param string $url * @param array $post * @param string $option * @return string $body */ static function Post($url, $post=[], $option=null) { return self::_Execute($url, $post, $option); } /** Return last error message. * * @return string */ static function Error() { return array_shift(self::$_errors[]); } }
Python
UTF-8
1,593
2.859375
3
[]
no_license
############### #CS519 #Xiao Tan #HW 7 - 2 ############### from collections import defaultdict def best(amount, value): opt = defaultdict(lambda : -1) types = -1 res = [0]*len(value) def _best(i, x): if i < 0 or x < 0 : return 0 if x == 0: opt[i, x] = 1 return opt[i, x] if (i, x) in opt: return opt[i, x] op1 = _best(i-1, x) op2 = _best(i, x - value[i]) opt[i, x] = op1 or op2 return opt[i, x] def trace(i): t, m, n = 0, 0, i flag = 1 tmp = [0]*len(value) while m < amount: if opt[n, m + value[n]]==1: tmp[n] += 1 m += value[n] if flag ==1: t += 1 flag = 0 else: n += 1 flag = 1 return t,tmp _best(len(value)-1, amount) #print opt if opt[len(value)-1, amount]== 0: return None else: for i in range(len(value)): if opt[i, 0] == 1: a, b = trace(i) if types == -1 or types > a: types = a res = b return types, res if __name__ == "__main__": print best(47, [6, 10, 15]) # (3, [2, 2, 1]) print best(59, [6, 10, 15]) # (3, [4, 2, 1]) print best(37, [4, 6, 15]) # (3, [4, 1, 1]) print best(27, [4, 6, 15]) #(2, [3, 0, 1]) print best(75, [4, 6, 15]) #(1, [0, 0, 5]) print best(17, [2, 4, 6]) #None
JavaScript
UTF-8
2,926
2.78125
3
[]
no_license
export default function buildSlider() { const sliderWrapper = document.getElementsByClassName('slider-wrapper')[0]; const sliderNav = document.getElementsByClassName('slider-nav')[0]; const slides = [ { name: '1 slide', img: '', startActive: true}, { name: '2 slide', img: ''}, { name: '3 slide', img: ''}, { name: '4 slide', img: ''} ]; slides .map((slide, i) => { let newSlide = document.createElement(`div`); let newNav = document.createElement(`a`); if(slide.startActive) { newSlide.className = 'slider-wrapper__slide active-slide-left'; newNav.className = 'slider-nav__slide active-nav'; } else { newSlide.className = 'slider-wrapper__slide'; newNav.className = 'slider-nav__slide'; } newSlide.innerHTML = `<span>${slide.name}</span>`; newNav.href = '#'; newNav.onclick = (e) => { let activeNav = document.getElementsByClassName('active-nav')[0]; if(e.target !== activeNav) { activeNav.classList.toggle('active-nav'); e.target.classList.toggle('active-nav'); let pastActive; let futureActive; for(let i = 0; i < sliderNav.children.length; i++) { if(sliderNav.children[i] === activeNav) { pastActive = i; } if(sliderNav.children[i] === e.target) { futureActive = i; } } if(pastActive < futureActive) { sliderWrapper.children[pastActive].classList.add('hide-slide-left') setTimeout(function(){ sliderWrapper.children[pastActive].classList.remove('active-slide-right') sliderWrapper.children[pastActive].classList.remove('active-slide-left') sliderWrapper.children[pastActive].classList.remove('hide-slide-left') }, 500); sliderWrapper.children[futureActive].classList.add('active-slide-left') } else if(pastActive > futureActive) { sliderWrapper.children[pastActive].classList.add('hide-slide-right') setTimeout(function(){ sliderWrapper.children[pastActive].classList.remove('active-slide-left') sliderWrapper.children[pastActive].classList.remove('active-slide-right') sliderWrapper.children[pastActive].classList.remove('hide-slide-right') }, 500); sliderWrapper.children[futureActive].classList.add('active-slide-right') } } } sliderWrapper.appendChild(newSlide); sliderNav.appendChild(newNav); }); }
Go
UTF-8
49,882
2.546875
3
[ "MIT" ]
permissive
package wrapper import ( "bytes" "encoding/base64" "errors" "fmt" "net/http" "net/url" "strings" "github.com/alaingilbert/ogame/pkg/ogame" "github.com/alaingilbert/ogame/pkg/utils" echo "github.com/labstack/echo/v4" ) // APIResp ... type APIResp struct { Status string Code int Message string Result any } // SuccessResp ... func SuccessResp(data any) APIResp { return APIResp{Status: "ok", Code: 200, Result: data} } // ErrorResp ... func ErrorResp(code int, message string) APIResp { return APIResp{Status: "error", Code: code, Message: message} } // HomeHandler ... func HomeHandler(c echo.Context) error { version := c.Get("version").(string) commit := c.Get("commit").(string) date := c.Get("date").(string) return c.JSON(http.StatusOK, map[string]any{ "version": version, "commit": commit, "date": date, }) } // TasksHandler return how many tasks are queued in the heap. func TasksHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.GetTasks())) } // GetServerHandler ... func GetServerHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.GetServer())) } // GetServerDataHandler ... func GetServerDataHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.serverData)) } // SetUserAgentHandler ... // curl 127.0.0.1:1234/bot/set-user-agent -d 'userAgent="New user agent"' func SetUserAgentHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) userAgent := c.Request().PostFormValue("userAgent") bot.SetUserAgent(userAgent) return c.JSON(http.StatusOK, SuccessResp(nil)) } // ServerURLHandler ... func ServerURLHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.ServerURL())) } // GetLanguageHandler ... func GetLanguageHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.GetLanguage())) } // PageContentHandler ... // curl 127.0.0.1:1234/bot/page-content -d 'page=overview&cp=123' func PageContentHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) if err := c.Request().ParseForm(); err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } pageHTML, _ := bot.GetPageContent(c.Request().Form) return c.JSON(http.StatusOK, SuccessResp(pageHTML)) } // LoginHandler ... func LoginHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) if _, err := bot.LoginWithExistingCookies(); err != nil { if err == ogame.ErrBadCredentials { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // LogoutHandler ... func LogoutHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) bot.Logout() return c.JSON(http.StatusOK, SuccessResp(nil)) } // GetUsernameHandler ... func GetUsernameHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.GetUsername())) } // GetUniverseNameHandler ... func GetUniverseNameHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.GetUniverseName())) } // GetUniverseSpeedHandler ... func GetUniverseSpeedHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.serverData.Speed)) } // GetUniverseSpeedFleetHandler ... func GetUniverseSpeedFleetHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.serverData.SpeedFleet)) } // ServerVersionHandler ... func ServerVersionHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.serverData.Version)) } // ServerTimeHandler ... func ServerTimeHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.ServerTime())) } // IsUnderAttackHandler ... func IsUnderAttackHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) isUnderAttack, err := bot.IsUnderAttack() if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(isUnderAttack)) } // IsVacationModeHandler ... func IsVacationModeHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) isVacationMode := bot.isVacationModeEnabled return c.JSON(http.StatusOK, SuccessResp(isVacationMode)) } // GetUserInfosHandler ... func GetUserInfosHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.GetUserInfos())) } // GetCharacterClassHandler ... func GetCharacterClassHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.CharacterClass())) } // HasCommanderHandler ... func HasCommanderHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) hasCommander := bot.hasCommander return c.JSON(http.StatusOK, SuccessResp(hasCommander)) } // HasAdmiralHandler ... func HasAdmiralHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) hasAdmiral := bot.hasAdmiral return c.JSON(http.StatusOK, SuccessResp(hasAdmiral)) } // HasEngineerHandler ... func HasEngineerHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) hasEngineer := bot.hasEngineer return c.JSON(http.StatusOK, SuccessResp(hasEngineer)) } // HasGeologistHandler ... func HasGeologistHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) hasGeologist := bot.hasGeologist return c.JSON(http.StatusOK, SuccessResp(hasGeologist)) } // HasTechnocratHandler ... func HasTechnocratHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) hasTechnocrat := bot.hasTechnocrat return c.JSON(http.StatusOK, SuccessResp(hasTechnocrat)) } // GetEspionageReportMessagesHandler ... func GetEspionageReportMessagesHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) report, err := bot.GetEspionageReportMessages() if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(report)) } // GetEspionageReportHandler ... func GetEspionageReportHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) msgID, err := utils.ParseI64(c.Param("msgid")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid msgid id")) } espionageReport, err := bot.GetEspionageReport(msgID) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(espionageReport)) } // GetEspionageReportForHandler ... func GetEspionageReportForHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) galaxy, err := utils.ParseI64(c.Param("galaxy")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy")) } system, err := utils.ParseI64(c.Param("system")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system")) } position, err := utils.ParseI64(c.Param("position")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position")) } planet, err := bot.GetEspionageReportFor(ogame.Coordinate{Type: ogame.PlanetType, Galaxy: galaxy, System: system, Position: position}) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(planet)) } // SendMessageHandler ... // curl 127.0.0.1:1234/bot/send-message -d 'playerID=123&message="Sup boi!"' func SendMessageHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) playerID, err := utils.ParseI64(c.Request().PostFormValue("playerID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } message := c.Request().PostFormValue("message") if err := bot.SendMessage(playerID, message); err != nil { if err.Error() == "invalid parameters" { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // GetFleetsHandler ... func GetFleetsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) fleets, _ := bot.GetFleets() return c.JSON(http.StatusOK, SuccessResp(fleets)) } // GetSlotsHandler ... func GetSlotsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) slots := bot.GetSlots() return c.JSON(http.StatusOK, SuccessResp(slots)) } // CancelFleetHandler ... func CancelFleetHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) fleetID, err := utils.ParseI64(c.Param("fleetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(bot.CancelFleet(ogame.FleetID(fleetID)))) } // GetAttacksHandler ... func GetAttacksHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) attacks, err := bot.GetAttacks() if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(attacks)) } // GalaxyInfosHandler ... func GalaxyInfosHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) galaxy, err := utils.ParseI64(c.Param("galaxy")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } system, err := utils.ParseI64(c.Param("system")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } res, err := bot.GalaxyInfos(galaxy, system) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(res)) } // GetResearchHandler ... func GetResearchHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.GetResearch())) } // BuyOfferOfTheDayHandler ... func BuyOfferOfTheDayHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) if err := bot.BuyOfferOfTheDay(); err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // GetMoonsHandler ... func GetMoonsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.GetMoons())) } // GetMoonHandler ... func GetMoonHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) moonID, err := utils.ParseI64(c.Param("moonID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid moon id")) } moon, err := bot.GetMoon(moonID) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid moon id")) } return c.JSON(http.StatusOK, SuccessResp(moon)) } // GetMoonByCoordHandler ... func GetMoonByCoordHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) galaxy, err := utils.ParseI64(c.Param("galaxy")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy")) } system, err := utils.ParseI64(c.Param("system")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system")) } position, err := utils.ParseI64(c.Param("position")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position")) } planet, err := bot.GetMoon(ogame.Coordinate{Type: ogame.MoonType, Galaxy: galaxy, System: system, Position: position}) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(planet)) } // GetPlanetsHandler ... func GetPlanetsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) return c.JSON(http.StatusOK, SuccessResp(bot.GetPlanets())) } // GetCelestialItemsHandler ... func GetCelestialItemsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) celestialID, err := utils.ParseI64(c.Param("celestialID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid celestial id")) } items, err := bot.GetItems(ogame.CelestialID(celestialID)) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(items)) } // ActivateCelestialItemHandler ... func ActivateCelestialItemHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) celestialID, err := utils.ParseI64(c.Param("celestialID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid celestial id")) } ref := c.Param("itemRef") if err := bot.ActivateItem(ref, ogame.CelestialID(celestialID)); err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // GetPlanetHandler ... func GetPlanetHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } planet, err := bot.GetPlanet(ogame.PlanetID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(planet)) } // GetPlanetByCoordHandler ... func GetPlanetByCoordHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) galaxy, err := utils.ParseI64(c.Param("galaxy")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy")) } system, err := utils.ParseI64(c.Param("system")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system")) } position, err := utils.ParseI64(c.Param("position")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position")) } planet, err := bot.GetPlanet(ogame.Coordinate{Type: ogame.PlanetType, Galaxy: galaxy, System: system, Position: position}) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(planet)) } // GetResourcesDetailsHandler ... func GetResourcesDetailsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } resources, err := bot.GetResourcesDetails(ogame.CelestialID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(resources)) } // GetResourceSettingsHandler ... func GetResourceSettingsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } res, err := bot.GetResourceSettings(ogame.PlanetID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(res)) } // SetResourceSettingsHandler ... // curl 127.0.0.1:1234/bot/planets/123/resource-settings -d 'metalMine=100&crystalMine=100&deuteriumSynthesizer=100&solarPlant=100&fusionReactor=100&solarSatellite=100' func SetResourceSettingsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } metalMine, err := utils.ParseI64(c.Request().PostFormValue("metalMine")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid metalMine")) } crystalMine, err := utils.ParseI64(c.Request().PostFormValue("crystalMine")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid crystalMine")) } deuteriumSynthesizer, err := utils.ParseI64(c.Request().PostFormValue("deuteriumSynthesizer")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid deuteriumSynthesizer")) } solarPlant, err := utils.ParseI64(c.Request().PostFormValue("solarPlant")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid solarPlant")) } fusionReactor, err := utils.ParseI64(c.Request().PostFormValue("fusionReactor")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid fusionReactor")) } solarSatellite, err := utils.ParseI64(c.Request().PostFormValue("solarSatellite")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid solarSatellite")) } crawler, err := utils.ParseI64(c.Request().PostFormValue("crawler")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid crawler")) } settings := ogame.ResourceSettings{ MetalMine: metalMine, CrystalMine: crystalMine, DeuteriumSynthesizer: deuteriumSynthesizer, SolarPlant: solarPlant, FusionReactor: fusionReactor, SolarSatellite: solarSatellite, Crawler: crawler, } if err := bot.SetResourceSettings(ogame.PlanetID(planetID), settings); err != nil { if err == ogame.ErrInvalidPlanetID { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // GetLfBuildingsHandler ... func GetLfBuildingsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } res, err := bot.GetLfBuildings(ogame.CelestialID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(res)) } // GetLfResearchHandler ... func GetLfResearchHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } res, err := bot.GetLfResearch(ogame.CelestialID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(res)) } // GetResourcesBuildingsHandler ... func GetResourcesBuildingsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } res, err := bot.GetResourcesBuildings(ogame.CelestialID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(res)) } // GetDefenseHandler ... func GetDefenseHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } res, err := bot.GetDefense(ogame.CelestialID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(res)) } // GetShipsHandler ... func GetShipsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } res, err := bot.GetShips(ogame.CelestialID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(res)) } // GetFacilitiesHandler ... func GetFacilitiesHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } res, err := bot.GetFacilities(ogame.CelestialID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(res)) } // BuildHandler ... func BuildHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } ogameID, err := utils.ParseI64(c.Param("ogameID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id")) } nbr, err := utils.ParseI64(c.Param("nbr")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr")) } if err := bot.Build(ogame.CelestialID(planetID), ogame.ID(ogameID), nbr); err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // BuildCancelableHandler ... func BuildCancelableHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } ogameID, err := utils.ParseI64(c.Param("ogameID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id")) } if err := bot.BuildCancelable(ogame.CelestialID(planetID), ogame.ID(ogameID)); err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // BuildProductionHandler ... func BuildProductionHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } ogameID, err := utils.ParseI64(c.Param("ogameID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id")) } nbr, err := utils.ParseI64(c.Param("nbr")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr")) } if err := bot.BuildProduction(ogame.CelestialID(planetID), ogame.ID(ogameID), nbr); err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // BuildBuildingHandler ... func BuildBuildingHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } ogameID, err := utils.ParseI64(c.Param("ogameID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id")) } if err := bot.BuildBuilding(ogame.CelestialID(planetID), ogame.ID(ogameID)); err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // BuildTechnologyHandler ... func BuildTechnologyHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } ogameID, err := utils.ParseI64(c.Param("ogameID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id")) } if err := bot.BuildTechnology(ogame.CelestialID(planetID), ogame.ID(ogameID)); err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // BuildDefenseHandler ... func BuildDefenseHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } ogameID, err := utils.ParseI64(c.Param("ogameID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id")) } nbr, err := utils.ParseI64(c.Param("nbr")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr")) } if err := bot.BuildDefense(ogame.CelestialID(planetID), ogame.ID(ogameID), nbr); err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // BuildShipsHandler ... func BuildShipsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } ogameID, err := utils.ParseI64(c.Param("ogameID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id")) } nbr, err := utils.ParseI64(c.Param("nbr")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr")) } if err := bot.BuildShips(ogame.CelestialID(planetID), ogame.ID(ogameID), nbr); err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // GetProductionHandler ... func GetProductionHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } res, _, err := bot.GetProduction(ogame.CelestialID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(res)) } // ConstructionsBeingBuiltHandler ... func ConstructionsBeingBuiltHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } buildingID, buildingCountdown, researchID, researchCountdown, lfBuildingID, lfBuildingCountdown, lfResearchID, lfResearchCountdown := bot.ConstructionsBeingBuilt(ogame.CelestialID(planetID)) return c.JSON(http.StatusOK, SuccessResp( struct { BuildingID int64 BuildingCountdown int64 ResearchID int64 ResearchCountdown int64 LfBuildingID int64 LfBuildingCountdown int64 LfResearchID int64 LfResearchCountdown int64 }{ BuildingID: int64(buildingID), BuildingCountdown: buildingCountdown, ResearchID: int64(researchID), ResearchCountdown: researchCountdown, LfBuildingID: int64(lfBuildingID), LfBuildingCountdown: lfBuildingCountdown, LfResearchID: int64(lfResearchID), LfResearchCountdown: lfResearchCountdown, }, )) } // CancelBuildingHandler ... func CancelBuildingHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } if err := bot.CancelBuilding(ogame.CelestialID(planetID)); err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // CancelResearchHandler ... func CancelResearchHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } if err := bot.CancelResearch(ogame.CelestialID(planetID)); err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // GetResourcesHandler ... func GetResourcesHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } res, err := bot.GetResources(ogame.CelestialID(planetID)) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(res)) } // GetRequirementsHandler ... func GetRequirementsHandler(c echo.Context) error { ogameID, err := utils.ParseI64(c.Param("ogameID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogameID")) } ogameObj := ogame.Objs.ByID(ogame.ID(ogameID)) if ogameObj != nil { requirements := ogameObj.GetRequirements() return c.JSON(http.StatusOK, SuccessResp(requirements)) } return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogameID")) } // GetPriceHandler ... func GetPriceHandler(c echo.Context) error { ogameID, err := utils.ParseI64(c.Param("ogameID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogameID")) } nbr, err := utils.ParseI64(c.Param("nbr")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr")) } ogameObj := ogame.Objs.ByID(ogame.ID(ogameID)) if ogameObj != nil { price := ogameObj.GetPrice(nbr) return c.JSON(http.StatusOK, SuccessResp(price)) } return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogameID")) } // SendFleetHandler ... // curl 127.0.0.1:1234/bot/planets/123/send-fleet -d 'ships=203,1&ships=204,10&speed=10&galaxy=1&system=1&type=1&position=1&mission=3&metal=1&crystal=2&deuterium=3' func SendFleetHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } if err := c.Request().ParseForm(); err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid form")) } var ships []ogame.Quantifiable where := ogame.Coordinate{Type: ogame.PlanetType} mission := ogame.Transport var duration int64 var unionID int64 payload := ogame.Resources{} speed := ogame.HundredPercent for key, values := range c.Request().PostForm { switch key { case "ships": for _, s := range values { a := strings.Split(s, ",") shipID, err := utils.ParseI64(a[0]) if err != nil || !ogame.ID(shipID).IsShip() { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ship id "+a[0])) } nbr, err := utils.ParseI64(a[1]) if err != nil || nbr < 0 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr "+a[1])) } ships = append(ships, ogame.Quantifiable{ID: ogame.ID(shipID), Nbr: nbr}) } case "speed": speedInt, err := utils.ParseI64(values[0]) if err != nil || speedInt < 0 || speedInt > 10 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid speed")) } speed = ogame.Speed(speedInt) case "galaxy": galaxy, err := utils.ParseI64(values[0]) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy")) } where.Galaxy = galaxy case "system": system, err := utils.ParseI64(values[0]) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system")) } where.System = system case "position": position, err := utils.ParseI64(values[0]) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position")) } where.Position = position case "type": t, err := utils.ParseI64(values[0]) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid type")) } where.Type = ogame.CelestialType(t) case "mission": missionInt, err := utils.ParseI64(values[0]) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid mission")) } mission = ogame.MissionID(missionInt) case "duration": duration, err = utils.ParseI64(values[0]) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid duration")) } case "union": unionID, err = utils.ParseI64(values[0]) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid union id")) } case "metal": metal, err := utils.ParseI64(values[0]) if err != nil || metal < 0 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid metal")) } payload.Metal = metal case "crystal": crystal, err := utils.ParseI64(values[0]) if err != nil || crystal < 0 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid crystal")) } payload.Crystal = crystal case "deuterium": deuterium, err := utils.ParseI64(values[0]) if err != nil || deuterium < 0 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid deuterium")) } payload.Deuterium = deuterium } } fleet, err := bot.SendFleet(ogame.CelestialID(planetID), ships, speed, where, mission, payload, duration, unionID) if err != nil && (err == ogame.ErrInvalidPlanetID || err == ogame.ErrNoShipSelected || err == ogame.ErrUninhabitedPlanet || err == ogame.ErrNoDebrisField || err == ogame.ErrPlayerInVacationMode || err == ogame.ErrAdminOrGM || err == ogame.ErrNoAstrophysics || err == ogame.ErrNoobProtection || err == ogame.ErrPlayerTooStrong || err == ogame.ErrNoMoonAvailable || err == ogame.ErrNoRecyclerAvailable || err == ogame.ErrNoEventsRunning || err == ogame.ErrPlanetAlreadyReservedForRelocation) { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(fleet)) } // GetAlliancePageContentHandler ... func GetAlliancePageContentHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) allianceID := c.QueryParam("allianceId") vals := url.Values{"allianceId": {allianceID}} pageHTML, _ := bot.GetPageContent(vals) return c.HTML(http.StatusOK, string(pageHTML)) } func replaceHostname(bot *OGame, html []byte) []byte { serverURLBytes := []byte(bot.serverURL) apiNewHostnameBytes := []byte(bot.apiNewHostname) escapedServerURL := bytes.Replace(serverURLBytes, []byte("/"), []byte(`\/`), -1) doubleEscapedServerURL := bytes.Replace(serverURLBytes, []byte("/"), []byte("\\\\\\/"), -1) escapedAPINewHostname := bytes.Replace(apiNewHostnameBytes, []byte("/"), []byte(`\/`), -1) doubleEscapedAPINewHostname := bytes.Replace(apiNewHostnameBytes, []byte("/"), []byte("\\\\\\/"), -1) html = bytes.Replace(html, serverURLBytes, apiNewHostnameBytes, -1) html = bytes.Replace(html, escapedServerURL, escapedAPINewHostname, -1) html = bytes.Replace(html, doubleEscapedServerURL, doubleEscapedAPINewHostname, -1) return html } // GetStaticHandler ... func GetStaticHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) newURL := bot.serverURL + c.Request().URL.String() req, err := http.NewRequest(http.MethodGet, newURL, nil) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } req.Header.Add("Accept-Encoding", "gzip, deflate, br") resp, err := bot.client.Do(req) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } defer resp.Body.Close() body, err := utils.ReadBody(resp) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } // Copy the original HTTP headers to our client for k, vv := range resp.Header { // duplicate headers are acceptable in HTTP spec, so add all of them individually: https://stackoverflow.com/questions/4371328/are-duplicate-http-response-headers-acceptable k = http.CanonicalHeaderKey(k) if k != "Content-Length" && k != "Content-Encoding" { // https://github.com/alaingilbert/ogame/pull/80#issuecomment-674559853 for _, v := range vv { c.Response().Header().Add(k, v) } } } if strings.Contains(c.Request().URL.String(), ".xml") { body = replaceHostname(bot, body) return c.Blob(http.StatusOK, "application/xml", body) } contentType := http.DetectContentType(body) if strings.Contains(newURL, ".css") { contentType = "text/css" } else if strings.Contains(newURL, ".js") { contentType = "application/javascript" } else if strings.Contains(newURL, ".gif") { contentType = "image/gif" } return c.Blob(http.StatusOK, contentType, body) } // GetFromGameHandler ... func GetFromGameHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) vals := url.Values{"page": {"ingame"}, "component": {"overview"}} if len(c.QueryParams()) > 0 { vals = c.QueryParams() } pageHTML, _ := bot.GetPageContent(vals) pageHTML = replaceHostname(bot, pageHTML) return c.HTMLBlob(http.StatusOK, pageHTML) } // PostToGameHandler ... func PostToGameHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) vals := url.Values{"page": {"ingame"}, "component": {"overview"}} if len(c.QueryParams()) > 0 { vals = c.QueryParams() } payload, _ := c.FormParams() pageHTML, _ := bot.PostPageContent(vals, payload) pageHTML = replaceHostname(bot, pageHTML) return c.HTMLBlob(http.StatusOK, pageHTML) } // GetStaticHEADHandler ... func GetStaticHEADHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) newURL := "/api/" + strings.Join(c.ParamValues(), "") // + "?" + c.QueryString() if len(c.QueryString()) > 0 { newURL = newURL + "?" + c.QueryString() } headers, err := bot.HeadersForPage(newURL) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } if len(headers) < 1 { return c.NoContent(http.StatusFailedDependency) } // Copy the original HTTP HEAD headers to our client for k, vv := range headers { // duplicate headers are acceptable in HTTP spec, so add all of them individually: https://stackoverflow.com/questions/4371328/are-duplicate-http-response-headers-acceptable k = http.CanonicalHeaderKey(k) for _, v := range vv { c.Response().Header().Add(k, v) } } return c.NoContent(http.StatusOK) } // GetEmpireHandler ... func GetEmpireHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) nbr, err := utils.ParseI64(c.Param("typeID")) if err != nil || nbr > 1 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid typeID")) } getEmpire, err := bot.GetEmpireJSON(nbr) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(getEmpire)) } // DeleteMessageHandler ... func DeleteMessageHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) messageID, err := utils.ParseI64(c.Param("messageID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid message id")) } if err := bot.DeleteMessage(messageID); err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // DeleteEspionageMessagesHandler ... func DeleteEspionageMessagesHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) if err := bot.DeleteAllMessagesFromTab(20); err != nil { // 20 = Espionage Reports return c.JSON(http.StatusBadRequest, ErrorResp(400, "Unable to delete Espionage Reports")) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // DeleteMessagesFromTabHandler ... func DeleteMessagesFromTabHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) tabIndex, err := utils.ParseI64(c.Param("tabIndex")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "must provide tabIndex")) } if tabIndex < 20 || tabIndex > 24 { /* tabid: 20 => Espionage tabid: 21 => Combat Reports tabid: 22 => Expeditions tabid: 23 => Unions/Transport tabid: 24 => Other */ return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid tabIndex provided")) } if err := bot.DeleteAllMessagesFromTab(ogame.MessagesTabID(tabIndex)); err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "Unable to delete message from tab "+utils.FI64(tabIndex))) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // SendIPMHandler ... func SendIPMHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) ipmAmount, err := utils.ParseI64(c.Param("ipmAmount")) if err != nil || ipmAmount < 1 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ipmAmount")) } planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil || planetID < 1 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } galaxy, err := utils.ParseI64(c.Request().PostFormValue("galaxy")) if err != nil || galaxy < 1 || galaxy > bot.serverData.Galaxies { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy")) } system, err := utils.ParseI64(c.Request().PostFormValue("system")) if err != nil || system < 1 || system > bot.serverData.Systems { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system")) } position, err := utils.ParseI64(c.Request().PostFormValue("position")) if err != nil || position < 1 || position > 15 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position")) } planetTypeInt, err := utils.ParseI64(c.Param("type")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } planetType := ogame.CelestialType(planetTypeInt) if planetType != ogame.PlanetType && planetType != ogame.MoonType { // only accept planet/moon types return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid type")) } priority := utils.DoParseI64(c.Request().PostFormValue("priority")) coord := ogame.Coordinate{Type: planetType, Galaxy: galaxy, System: system, Position: position} duration, err := bot.SendIPM(ogame.PlanetID(planetID), coord, ipmAmount, ogame.ID(priority)) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(duration)) } // TeardownHandler ... func TeardownHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) planetID, err := utils.ParseI64(c.Param("planetID")) if err != nil || planetID < 0 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id")) } ogameID, err := utils.ParseI64(c.Param("ogameID")) if err != nil || planetID < 0 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id")) } if err = bot.TearDown(ogame.CelestialID(planetID), ogame.ID(ogameID)); err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // GetAuctionHandler ... func GetAuctionHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) auction, err := bot.GetAuction() if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "could not open auction page")) } return c.JSON(http.StatusOK, SuccessResp(auction)) } // DoAuctionHandler (`celestialID=metal:crystal:deuterium` eg: `123456=123:456:789`) func DoAuctionHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) bid := make(map[ogame.CelestialID]ogame.Resources) if err := c.Request().ParseForm(); err != nil { // Required for PostForm, not for PostFormValue return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid form")) } for key, values := range c.Request().PostForm { for _, s := range values { var metal, crystal, deuterium int64 if n, err := fmt.Sscanf(s, "%d:%d:%d", &metal, &crystal, &deuterium); err != nil || n != 3 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid bid format")) } celestialIDInt, err := utils.ParseI64(key) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid celestial ID")) } bid[ogame.CelestialID(celestialIDInt)] = ogame.Resources{Metal: metal, Crystal: crystal, Deuterium: deuterium} } } if err := bot.DoAuction(bid); err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(nil)) } // PhalanxHandler ... func PhalanxHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) moonID, err := utils.ParseI64(c.Param("moonID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid moon id")) } galaxy, err := utils.ParseI64(c.Param("galaxy")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy")) } system, err := utils.ParseI64(c.Param("system")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system")) } position, err := utils.ParseI64(c.Param("position")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position")) } coord := ogame.Coordinate{Type: ogame.PlanetType, Galaxy: galaxy, System: system, Position: position} fleets, err := bot.Phalanx(ogame.MoonID(moonID), coord) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(fleets)) } // JumpGateHandler ... func JumpGateHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) if err := c.Request().ParseForm(); err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid form")) } moonOriginID, err := utils.ParseI64(c.Param("moonID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid origin moon id")) } moonDestinationID, err := utils.ParseI64(c.Request().PostFormValue("moonDestination")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid destination moon id")) } var ships ogame.ShipsInfos for key, values := range c.Request().PostForm { switch key { case "ships": for _, s := range values { a := strings.Split(s, ",") shipID, err := utils.ParseI64(a[0]) if err != nil || !ogame.ID(shipID).IsShip() { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ship id "+a[0])) } nbr, err := utils.ParseI64(a[1]) if err != nil || nbr < 0 { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr "+a[1])) } ships.Set(ogame.ID(shipID), nbr) } } } success, rechargeCountdown, err := bot.JumpGate(ogame.MoonID(moonOriginID), ogame.MoonID(moonDestinationID), ships) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(map[string]any{ "success": success, "rechargeCountdown": rechargeCountdown, })) } // TechsHandler ... func TechsHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) celestialID, err := utils.ParseI64(c.Param("celestialID")) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid celestial id")) } supplies, facilities, ships, defenses, researches, lfbuildings, err := bot.GetTechs(ogame.CelestialID(celestialID)) if err != nil { return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(map[string]any{ "supplies": supplies, "facilities": facilities, "ships": ships, "defenses": defenses, "researches": researches, "lfbuildings": lfbuildings, })) } // GetCaptchaHandler ... func GetCaptchaHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) _, err := GFLogin(bot.client, bot.ctx, bot.lobby, bot.Username, bot.password, bot.otpSecret, "") var captchaErr *CaptchaRequiredError if errors.As(err, &captchaErr) { questionRaw, iconsRaw, err := StartCaptchaChallenge(bot.GetClient(), bot.ctx, captchaErr.ChallengeID) if err != nil { return c.HTML(http.StatusOK, err.Error()) } questionB64 := base64.StdEncoding.EncodeToString(questionRaw) iconsB64 := base64.StdEncoding.EncodeToString(iconsRaw) html := `<img style="background-color: black;" src="data:image/png;base64,` + questionB64 + `" /><br /> <img style="background-color: black;" src="data:image/png;base64,` + iconsB64 + `" /><br /> <form action="/bot/captcha/solve" method="POST"> <input type="hidden" name="challenge_id" value="` + captchaErr.ChallengeID + `" /> Enter 0,1,2 or 3 and press Enter <input type="number" name="answer" /> </form>` + captchaErr.ChallengeID return c.HTML(http.StatusOK, html) } else if err != nil { return c.HTML(http.StatusOK, err.Error()) } return c.HTML(http.StatusOK, "no captcha found") } // GetCaptchaSolverHandler ... func GetCaptchaSolverHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) challengeID := c.Request().PostFormValue("challenge_id") answer := utils.DoParseI64(c.Request().PostFormValue("answer")) if err := SolveChallenge(bot.GetClient(), bot.ctx, challengeID, answer); err != nil { bot.error(err) } if !bot.IsLoggedIn() { if err := bot.Login(); err != nil { bot.error(err) } } return c.Redirect(http.StatusTemporaryRedirect, "/") } // CaptchaChallenge ... type CaptchaChallenge struct { ID string Question string Icons string } // GetCaptchaChallengeHandler ... func GetCaptchaChallengeHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) _, err := GFLogin(bot.client, bot.ctx, bot.lobby, bot.Username, bot.password, bot.otpSecret, "") var captchaErr *CaptchaRequiredError if errors.As(err, &captchaErr) { questionRaw, iconsRaw, err := StartCaptchaChallenge(bot.GetClient(), bot.ctx, captchaErr.ChallengeID) if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } questionB64 := base64.StdEncoding.EncodeToString(questionRaw) iconsB64 := base64.StdEncoding.EncodeToString(iconsRaw) return c.JSON(http.StatusOK, SuccessResp(CaptchaChallenge{ ID: captchaErr.ChallengeID, Question: questionB64, Icons: iconsB64, })) } else if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(CaptchaChallenge{})) } // GetPublicIPHandler ... func GetPublicIPHandler(c echo.Context) error { bot := c.Get("bot").(*OGame) ip, err := bot.GetPublicIP() if err != nil { return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error())) } return c.JSON(http.StatusOK, SuccessResp(ip)) }
Markdown
UTF-8
11,401
3.59375
4
[ "Apache-2.0", "CC-BY-3.0" ]
permissive
--- title: JavaScript:这是什么意思? subhead: 在 JavaScript 中找出 `this` 的值可能很难,这里介绍了方法…… description: 在 JavaScript 中找出 `this` 的值可能很难,这里介绍了方法…… authors: - jakearchibald date: 2021-03-08 hero: image/CZmpGM8Eo1dFe0KNhEO9SGO8Ok23/cePCOGeXNFT6WCy85gb4.png alt: "this \U0001F914" tags: - blog - javascript --- JavaScript 的`this`产生了许多笑话,因为它非常复杂。但是,我已经看到开发人员做了更复杂和特定领域的事来避免处理`this` 。如果您不确定`this`是什么,希望本文会对您有所帮助。这是我的`this`指南。 我会从最具体的情况开始讲起,以最不具体的情况结束。这篇文章有点像一个大大的`if (…) … else if () … else if (…) …` ,所以您可以直接进入与您要了解的代码相匹配的第一节。 1. [如果函数定义为箭头函数](#arrow-functions) 2. [否则,如果使用`new`](#new)调用函数/类 3. [否则,如果函数有一个“绑定”的`this`值](#bound) 4. [否则,如果`this`是在调用时设置的](#call-apply) 5. 否则,如果函数是通过父对象 (<code>parent.func()</code>) 调用的: {: #object-member } 6. [否则,如果函数或父作用域处于严格模式](#strict) 7. [否则](#otherwise) ## 如果函数定义为箭头函数:{: #arrow-functions } ```js const arrowFunction = () => { console.log(this); }; ``` 在这种情况下,`this`的值*始终*与父作用域的`this`相同: ```js const outerThis = this; const arrowFunction = () => { // Always logs `true`: console.log(this === outerThis); }; ``` 箭头函数好就好在`this`的内部值无法更改,它*始终*与外部`this`相同。 ### 其他示例 使用箭头函数时,*不能*通过[`bind`](#bound)更改 `this`的值: ```js // Logs `true` - bound `this` value is ignored: arrowFunction.bind({foo: 'bar'})(); ``` 使用箭头函数时,*不能*通过[`call`或`apply`](#call-apply)更改`this`的值: ```js // Logs `true` - called `this` value is ignored: arrowFunction.call({foo: 'bar'}); // Logs `true` - applied `this` value is ignored: arrowFunction.apply({foo: 'bar'}); ``` 使用箭头函数时,*不能*通过将函数作为另一个对象的成员调用来更改`this`的值: ```js const obj = {arrowFunction}; // Logs `true` - parent object is ignored: obj.arrowFunction(); ``` 使用对于箭头函数时,*不能*通过将函数作为构造函数调用来更改`this`的值: ```js // TypeError: arrowFunction is not a constructor new arrowFunction(); ``` ### “绑定”实例方法 使用实例方法时,如果您想确保`this`始终指向类实例,最好的方法是使用箭头函数和[类字段](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields): ```js class Whatever { someMethod = () => { // Always the instance of Whatever: console.log(this); }; } ``` 当在组件(例如 React 组件或 Web 组件)中使用实例方法作为事件侦听器时,此模式非常有用。 上面的内容可能会让人觉得它打破了“`this`与父作用域的`this`相同”规则,但如果您将类字段视为在构造函数中设置内容的语法糖,这样就讲得通了: ```js class Whatever { someMethod = (() => { const outerThis = this; return () => { // Always logs `true`: console.log(this === outerThis); }; })(); } // …is roughly equivalent to: class Whatever { constructor() { const outerThis = this; this.someMethod = () => { // Always logs `true`: console.log(this === outerThis); }; } } ``` 替代模式涉及在构造函数中绑定现有函数,或在构造函数中分配函数。如果由于某种原因不能使用类字段,那么在构造函数中分配函数是一个合理的选择: ```js class Whatever { constructor() { this.someMethod = () => { // … }; } } ``` ## 否则,如果使用<code>new</code>调用函数/类 {: #new } ```js new Whatever(); ``` 上面的代码会调用`Whatever`(或如果它是类的话,会调用它的构造函数),并将`this`设置为`Object.create(Whatever.prototype)`的结果。 ```js class MyClass { constructor() { console.log( this.constructor === Object.create(MyClass.prototype).constructor, ); } } // Logs `true`: new MyClass(); ``` 对于旧式构造函数也是如此: ```js function MyClass() { console.log( this.constructor === Object.create(MyClass.prototype).constructor, ); } // Logs `true`: new MyClass(); ``` ### 其他示例 当使用`new`调用时,*无法*用[`bind`](#bound)改变`this`的值: ```js const BoundMyClass = MyClass.bind({foo: 'bar'}); // Logs `true` - bound `this` value is ignored: new BoundMyClass(); ``` 当使用`new`调用时,*不能*通过将函数作为另一个对象的成员调用来更改`this`的值: ```js const obj = {MyClass}; // Logs `true` - parent object is ignored: new obj.MyClass(); ``` ## 否则,如果函数有一个“绑定”的<code>this</code>值 {: #bound } ```js function someFunction() { return this; } const boundObject = {hello: 'world'}; const boundFunction = someFunction.bind(boundObject); ``` 每次调用`boundFunction`时,它的`this`值将是传递给`bind` ( `boundObject` ) 的对象。 ```js // Logs `false`: console.log(someFunction() === boundObject); // Logs `true`: console.log(boundFunction() === boundObject); ``` {% Aside 'warning' %} 避免使用`bind`将函数绑定到它的外部`this` 。相反,使用[箭头函数](#arrow-functions),因为它们通过函数生命让`this`更清晰,而不是在代码后面发生的事情。 不要使用`bind`将`this`设置为与父对象无关的某个值;这通常是出乎意料的,这就是`this`遭人诟病的原因。考虑将值作为参数传递;它更明确,并且可与箭头函数一起使用。 {% endAside %} ### 其他示例 调用绑定函数时,*无法*通过[`call`或`apply`](#call-apply)更改`this`的值: ```js // Logs `true` - called `this` value is ignored: console.log(boundFunction.call({foo: 'bar'}) === boundObject); // Logs `true` - applied `this` value is ignored: console.log(boundFunction.apply({foo: 'bar'}) === boundObject); ``` 调用绑定函数时,*不能*通过将函数作为另一个对象的成员调用来更改`this`的值: ```js const obj = {boundFunction}; // Logs `true` - parent object is ignored: console.log(obj.boundFunction() === boundObject); ``` ## 否则,如果`this`是在调用时设置的:{: #call-apply } ```js function someFunction() { return this; } const someObject = {hello: 'world'}; // Logs `true`: console.log(someFunction.call(someObject) === someObject); // Logs `true`: console.log(someFunction.apply(someObject) === someObject); ``` `this`的值是传递给`call` / `apply`的对象。 {% Aside 'warning' %}不要使用`call`/`apply` 将`this`设置为与父对象无关的某个值;这通常是出乎意料的,这就是`this`遭人诟病的原因。考虑将值作为参数传递;它更明确,并且可与箭头函数一起使用。 {% endAside %} 不幸的是, `this`被诸如 DOM 事件侦听器之类的东西设置为其他一些值,并且使用它可能会导致难以理解的代码: {% Compare 'worse' %} ```js element.addEventListener('click', function (event) { // Logs `element`, since the DOM spec sets `this` to // the element the handler is attached to. console.log(this); }); ``` {% endCompare %} 我会避免在上述情况下使用`this`,而是用: {% Compare 'better' %} ```js element.addEventListener('click', (event) => { // Ideally, grab it from a parent scope: console.log(element); // But if you can't do that, get it from the event object: console.log(event.currentTarget); }); ``` {% endCompare %} ## 否则,如果函数是通过父对象 (`parent.func()`) 调用的: {: #object-member } ```js const obj = { someMethod() { return this; }, }; // Logs `true`: console.log(obj.someMethod() === obj); ``` 在这种情况下,函数作为`obj`的成员被调用,所以`this`会是`obj` 。这发生在调用时,所以如果在没有父对象的情况下调用函数,或者使用不同的父对象调用函数,链接就会断开: ```js const {someMethod} = obj; // Logs `false`: console.log(someMethod() === obj); const anotherObj = {someMethod}; // Logs `false`: console.log(anotherObj.someMethod() === obj); // Logs `true`: console.log(anotherObj.someMethod() === anotherObj); ``` `someMethod() === obj`是 false,因为`someMethod`*不是*作为`obj`的成员调用的。在尝试这样的事情时,您可能遇到过这个问题: ```js const $ = document.querySelector; // TypeError: Illegal invocation const el = $('.some-element'); ``` 这会中断,因为`querySelector`的实现查看自己的`this`值并期望它是某种 DOM 节点,而上述代码中断了该连接。要正确实现上述目标: ```js const $ = document.querySelector.bind(document); // Or: const $ = (...args) => document.querySelector(...args); ``` 有趣的事实:并非所有的 API 都在内部使用`this`。如`console.log`这样的控制台方法已做过更改,从而避免引用`this`,因此不需要将`log`绑定到`console`。 {% Aside 'warning' %}不要将函数移植到对象上,来将<code>this</code>设置为与父对象无关的某个值;这通常是出乎意料的,这就是<code>this</code>遭人诟病的原因。考虑将值作为参数传递;它更明确,并且可与箭头函数一起使用。 {% endAside %} ## 否则,如果函数或父作用域处于严格模式:{: #strict } ```js function someFunction() { 'use strict'; return this; } // Logs `true`: console.log(someFunction() === undefined); ``` 在这种情况下,价值`this`没有定义。 如果父作用域处于[严格模式](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode)(并且所有模块都处于严格模式),则函数中不需要`'use strict'`。 {% Aside 'warning' %}不要依赖这个方法。我的意思是,有更简单的方法可以获得`undefined`值😀。 {% endAside %} ## 否则:{: #otherwise } ```js function someFunction() { return this; } // Logs `true`: console.log(someFunction() === globalThis); ``` 在这种情况下,`this`的值与`globalThis`相同。 {% Aside %} 大多数人(包括我)都将`globalThis`称为全局对象,但这在技术上并不是完全正确的。这里是[Mathias Bynens 的详细介绍](https://mathiasbynens.be/notes/globalthis#terminology),包括为什么将其称为`globalThis`而不是简单的`global` 。 {% endAside %} {% Aside 'warning' %} 避免使用`this`来引用全局对象(是的,我仍然这样称呼它)。相反,请使用更加明确的[`globalThis`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/globalThis) {% endAside %} ## 大功告成! 就是这样!这就是我知道的关于`this`的一切。有任何疑问?我漏掉了什么?请随时[给我发推文](https://twitter.com/jaffathecake)。 感谢 [Mathias Bynens](https://twitter.com/mathias) 、[Ingvar Stepanyan](https://twitter.com/RReverser) 和 [Thomas Steiner](https://twitter.com/tomayac)的校对。
Go
UTF-8
214
3.28125
3
[ "MIT", "Unlicense" ]
permissive
package main import ( "fmt" ) func coprime(x, y int) bool { gcd := func(x, y int) int { for y != 0 { x, y = y, x % y } return x } return gcd(x, y) == 1 } func main() { fmt.Println(coprime(2, 7)) }
PHP
UTF-8
2,654
3.6875
4
[]
no_license
<!-- Q.10) Write a PHP program to sort the student records which are stored in the database using selection sort. --> <!DOCTYPE html> <html> <body> <style> table, td, th { border: 1px solid black; width: 33.3%; text-align: center; background-color: lightblue; border-collapse: collapse; } table { margin: auto; } </style> <?php $servername="localhost"; $username="root"; $password=""; $dbname="weblab"; $a = []; // Create a connection // Opens a new connection to the MySQL server $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection and return the error description from the last connection error, if any. if($conn->connect_error) die("Connection failed: " . $conn->connect_error()); $sql = "SELECT * FROM student"; // Performs a query against the database $result = $conn->query($sql); echo "<br>"; echo "<center> BEFORE SORTING </center>"; echo "<table border='2'>"; echo "<tr>"; echo "<th> USN </th> <th> Name </th> <th> Address </th>"; echo "</tr>"; if($result->num_rows > 0) // If returned result has some data { // Outputs data of each row and fetches result row as an associative array while($row = $result->fetch_assoc()) { echo "<tr>"; echo "<td>" . $row["usn"] . "</td>"; echo "<td>" . $row["name"] . "</td>"; echo "<td>" . $row["addr"] . "</td>"; echo "</tr>"; array_push($a, $row["usn"]); // Insert element to end of array } } else echo "Table is empty"; echo "</table>"; $n = count($a); $b = $a; // Perform selection sort for($i=0; $i<($n-1); $i++) { $pos = $i; for($j=$i+1; $j<$n; $j++) { if($a[$pos] > $a[$j]) $pos = $j; } if($pos != $i) { $temp = $a[$i]; $a[$i] = $a[$pos]; $a[$pos] = $temp; } } $c = []; $d = []; $result = $conn->query($sql); // Output data of each row if($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { for($i=0; $i<$n; $i++) { if($row["usn"] == $a[$i]) { $c[$i] = $row["name"]; $d[$i] = $row["addr"]; } } } } echo "<br>"; echo "<center> AFTER SORTING </center>"; echo "<table border='2'>"; echo "<tr>"; echo "<th> USN </th> <th> Name </th> <th> Address </th>"; echo "</tr>"; for($i=0; $i<$n; $i++) { echo "<tr>"; echo "<td>" . $a[$i] . "</td>"; echo "<td>" . $c[$i] . "</td>"; echo "<td>" . $d[$i] . "</td>"; echo "</tr>"; } echo "</table>"; // Close the connection $conn->close(); ?> </body> </html>
Java
UTF-8
824
3.453125
3
[]
no_license
/*Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. Example: Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length under the problem constraint. Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). */ Solution: class Solution { public int minSubArrayLen(int s, int[] a) { if (a == null || a.length == 0) return 0; int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE; while (j < a.length) { sum += a[j++]; while (sum >= s) { min = Math.min(min, j - i); sum -= a[i++]; } } return min == Integer.MAX_VALUE ? 0 : min; } }
C
UTF-8
107
2.5625
3
[]
no_license
#include <stdio.h> double putchard(double v) { putchar((char) v); fflush(stdout); return 0; }
JavaScript
UTF-8
672
3.40625
3
[]
no_license
// assume div.json with a pre inside var inJson = document.getElementById("json").textContent; console.log("inJson: "+inJson); // same, assume div.cbor with a pre inside document.getElementById("cbor").insertAdjacentText("beforeend", inJson); var encoded = new Uint8Array(CBOR.encode(inJson)); var hexArray = []; for (var i=0; i< encoded.byteLength; i++) { hexArray.push(byteToHex(encoded[i])); } document.getElementById("cborbytes").insertAdjacentText("beforeend", hexArray.join(" ")); document.getElementById("cborbytesize").insertAdjacentText("beforeend", hexArray.length); function byteToHex(b) { return (b >>> 4).toString(16)+(b & 0xF).toString(16)+" "; }
Markdown
UTF-8
4,572
2.625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Класс CConstantTransition ms.date: 11/04/2016 f1_keywords: - CConstantTransition - AFXANIMATIONCONTROLLER/CConstantTransition - AFXANIMATIONCONTROLLER/CConstantTransition::CConstantTransition - AFXANIMATIONCONTROLLER/CConstantTransition::Create - AFXANIMATIONCONTROLLER/CConstantTransition::m_duration helpviewer_keywords: - CConstantTransition [MFC], CConstantTransition - CConstantTransition [MFC], Create - CConstantTransition [MFC], m_duration ms.assetid: f6fa4780-a71b-4cd6-80aa-d4792ace36c2 ms.openlocfilehash: 9641af2f184d2edaa82922363dff75783e79f87e ms.sourcegitcommit: c3093251193944840e3d0a068ecc30e6449624ba ms.translationtype: MT ms.contentlocale: ru-RU ms.lasthandoff: 03/04/2019 ms.locfileid: "57326339" --- # <a name="cconstanttransition-class"></a>Класс CConstantTransition Инкапсулирует постоянный переход. ## <a name="syntax"></a>Синтаксис ``` class CConstantTransition : public CBaseTransition; ``` ## <a name="members"></a>Участники ### <a name="public-constructors"></a>Открытые конструкторы |Имя|Описание| |----------|-----------------| |[CConstantTransition::CConstantTransition](#cconstanttransition)|Создает объект перехода и инициализирует его длительность.| ### <a name="public-methods"></a>Открытые методы |Имя|Описание| |----------|-----------------| |[CConstantTransition::Create](#create)|Вызывает переход библиотеку для создания инкапсулированный перехода COM-объекта. (Переопределяет [CBaseTransition::Create](../../mfc/reference/cbasetransition-class.md#create).)| ### <a name="public-data-members"></a>Открытые члены данных |Имя|Описание| |----------|-----------------| |[CConstantTransition::m_duration](#m_duration)|Длительность перехода.| ## <a name="remarks"></a>Примечания Во время перехода константа значение переменной анимации остается в начальное значение на протяжении перехода. Так как автоматически удаляются все переходы, рекомендуется выделить их с помощью оператора new. Инкапсулированный объект IUIAnimationTransition COM созданный CAnimationController::AnimateGroup, пока то возвращается значение NULL. Изменение переменных-членов, после создания COM-объекта не оказывает влияния. ## <a name="inheritance-hierarchy"></a>Иерархия наследования [CObject](../../mfc/reference/cobject-class.md) [CBaseTransition](../../mfc/reference/cbasetransition-class.md) `CConstantTransition` ## <a name="requirements"></a>Требования **Заголовок:** afxanimationcontroller.h ## <a name="cconstanttransition"></a> CConstantTransition::CConstantTransition Создает объект перехода и инициализирует его длительность. ``` CConstantTransition (UI_ANIMATION_SECONDS duration); ``` ### <a name="parameters"></a>Параметры *Длительность*<br/> Длительность перехода. ## <a name="create"></a> CConstantTransition::Create Вызывает переход библиотеку для создания инкапсулированный перехода COM-объекта. ``` virtual BOOL Create( IUIAnimationTransitionLibrary* pLibrary, IUIAnimationTransitionFactory* \*not used*\); ``` ### <a name="parameters"></a>Параметры *pLibrary*<br/> Указатель на [IUIAnimationTransitionLibrary интерфейс](/windows/desktop/api/uianimation/nn-uianimation-iuianimationtransitionlibrary), который определяет библиотеку стандартных переходов. ### <a name="return-value"></a>Возвращаемое значение Значение TRUE, если переход создан успешно; в противном случае — значение FALSE. ## <a name="m_duration"></a> CConstantTransition::m_duration Длительность перехода. ``` UI_ANIMATION_SECONDS m_duration; ``` ## <a name="see-also"></a>См. также [Классы](../../mfc/reference/mfc-classes.md)
Markdown
UTF-8
18,941
3.171875
3
[ "Apache-2.0" ]
permissive
[TOC] # 硅谷 - NIO ## Java NIO 简介 ```shell # Java NIO <New IO> 是从 Java1.4 版本开始引入的一个新的IO Api,可以替代标准的 Java IO Api。 # NIO 与原来的 IO 有同样的作用和目的,但是使用的方式完全不同,NIO 支持面向缓冲区的、基于通道的 IO 操作。 NIO 将以更加高效的方式进行文件的读写操作。 ``` ## NIO 与 IO 的主要区别 | IO | NIO | | ------------------------- | ----------------------------- | | 面向流(Stream Oriented) | 面向缓冲区(Buffer Oriented) | | 阻塞IO(Bloking IO) | 非阻塞IO(Non Bloking IO) | | (无) | 选择器(Selectors) | ## 通道与缓冲区 ```shell # Java NIO 系统的核心 # 通道表示打开到 IO 设备<例如: 文件、套接字> 的连接。 # 使用 NIO,需要获取用于连接 IO 设备的通道以及用于容纳数据的缓冲区。 # 然后操作缓冲区,对数据进行处理。 # 简而言之: Channel 负责传输,Buffer 负责存储 ``` ### 缓冲区 ```shell # Buffer: # 一个用于特定基本数据类型的容器。由 java.nio 包定义,所有缓冲区都是 Buffer 抽象类的子类 # 主要用于与 NIO 通道进行交互,数据从通道读入缓冲区,从缓冲区写入通道中 # Buffer 就像一个数组,可以保存多个相同类型的数据。 # Buffer 常用子类: # ByteBuffer # CharBuffer # ShortBuffer # IntBuffer # LongBuffer # FloatBuffer # DoubleBuffer # 所有Buffer 子类都采用相似的方法进行管理数据,只是各自的管理数据类型不同。 # 获取Buffer 对象的方法: # static XxxBuffer allocate(int capacity) # 创建一个容量为 capacity 的XxxBuffer 对象 ``` #### Buffer 中的重要概念 ```shell # 容量<capacity>: # 表示 Buffer 最大数据容量,缓冲区容量不能为负,并且创建后不能更改。 # 限制<limit>: # 第一个不应该读取或写入的数据的索引,即位于 limit 后的数据不可读写。 # 缓冲区的限制不能为负,并且不能大于其容量。 # 位置<position>: # 下一个要读取或写入的数据的索引。 # 缓冲区的位置不能为负,并且不能大于其限制。 # 标记与重置<mark And reset> # 标记是一个索引,通过 Buffer 中的 mark() 方法指定 Buffer 中一个特定的 position,之后可以通过调用 reset() 方法恢复到这个 position。 # 标记、位置、限制、容量 遵循以下不变式: # 0 <= mark <= position <= limit <= capacity ``` #### Buffer 的常用方法 ```shell # Buffer clear(): # 清空缓冲区并返回对缓冲区的引用。 # Buffer flip(): # 将缓冲区的界限设置为当前位置,并将当前位置重置为0 # int capacity(): # 返回 Buffer 的 capacity 大小 # boolean hasRemaining(): # 判断缓冲区中是否还有元素 # int limit(): # 返回 Buffer 的界限<limit> 的位置 # Buffer limit(int n): # 将设置缓冲区界限为 n,并返回一个具有新 limit 的缓冲区对象 # Buffer mark(): # 对缓冲区设置标记 # int position(): # 返回缓冲区的当前位置 position # Buffer position(int n): # 将设置缓冲区的当前位置为 n,并返回修改后的 Buffer 对象 # int reamining(): # 返回 position 到 limit 之间的元素个数 # Buffer reset(): # 将位置 position 转到以前设置的 mark 所在的位置 # Buffer rewind(): # 将位置设为0,取消设置的 mark ``` #### 缓冲区的数据操作 ```shell # Buffer 所有子类提供了两个用于数据操作的方法: # get() # put() # 获取 Buffer 中的数据: # get(): 读取单个字节 # get(byte[] dst): 批量读取多个字节到 dst 中 # get(int index): 读取指定索引位置的字节(不会移动 position) # 放入数据到 Buffer 中: # put(byte b): 将给定单个字节写入缓冲区的当前位置 # put(byte[] src): 将 src 中的字节写入缓冲区的当前位置 # put(int index, byte b): 将指定字节写入缓冲区的索引位置(不会移动 position) ``` #### 直接与非直接缓冲区 ```shell # 字节缓冲区要么是直接的,要么是非直接的。 # 直接字节缓冲区: # JVM 会尽最大努力直接在此缓冲区上执行本机 I/O 操作。 # 每次调用基础操作系统的一个本机 I/O 操作之前(或之后),JVM 都会尽量避免将缓冲区的内容复制到中间缓冲区中。(或从中间缓冲区中复制内容) # 直接字节缓冲区可以通过此类的 allocateDirect() 工厂方法来创建,此方法返回的缓冲区进行分配和取消分配所需成本通常高于非直接缓冲区。 # 直接缓冲区的内容可以驻留在 JVM 常规的垃圾回收堆之外,因此,它们对 Application 的内存需求量造成的影响可能并不明显。所以,建议将直接缓冲区主要分配给那些易受基础操作系统的本机 I/O 操作影响的大型、持久的缓冲区。 # 一般情况下,最好仅在直接缓冲区能在程序性能方面带来明显好处时分配它们。 # 直接字节缓冲区还可以通过 FileChannel 的 map() 方法将文件区域直接映射到内存中来创建。该方法返回 MappedByteBuffer,Java 平台的实现有助于通过 JNI 从本机代码创建直接字节缓冲区。如果以上这些缓冲区中的某个缓冲区实例指的是不可访问的内存区域,则试图放问该区域不会更改缓冲区的内容,并且将会在访问期间或稍后的某个时间导致抛出不确定的异常。 # 字节缓冲区是直接缓冲区还是非直接缓冲区可通过调用其 isDirect() 方法来确定,提供此方法是为了能够在性能关键性代码中执行显示缓冲区管理。 ``` ![UTOOLS1573182451353.png](https://i.loli.net/2019/11/08/jL6xh2YX7OnAHKZ.png) ![UTOOLS1573182474457.png](https://i.loli.net/2019/11/08/6PnoWKIQ2CEdT4l.png) ### 通道 ```shell # Channel: # java.nio.channels 包定义。 # 表示 IO 源于目标打开的连接。 # 类似传统的 "流"。只不过本身不能直接访问数据,只能与 Buffer 进行交互。 ``` ![UTOOLS1573183471709.png](https://i.loli.net/2019/11/08/vusPiVqpd5zF6GM.png) #### 主要实现类 ```shell # FileChannel: # 用于读取、写入、映射和操作文件的通道。 # DatagramChannel: # 通过 UDP 读写网络中的数据通道。 # SocketChannel: # 通过 TCP 读写网络中的数据。 # ServerSocketChannel: # 可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel。 ``` #### 获取通道 ```shell # 获取通道的一种方式是对支持通道的对象调用 getChannel() 方法,支持通道的类有: # FileInputStream # FileOutputStream # RandomAccessFile # DatagramSocket # Socket # ServerSocket # 获取通道的其他方式是使用 Files 类的静态方法,newByteChannel() 获取字节通道。或者通过通道的静态方法 open() 打开并返回指定通道。 ``` #### 通道的数据传输 ```shell # 将 Buffer 中数据写入 Channel # 例如: int bytesWritten = inChannel.write(buf); # 从 Channel 读取数据到 Buffer # 例如: int bytesRead = inChannel.read(buf); ``` #### 分散和聚集 ```shell # 分散读取<Scattering Reads> 是指从 Channel 中读取的数据分散到多个 Buffer 中 # 注意: 按照缓冲区的顺序,从 Channel 中读取的数据依次将 Buffer 填满。 # 聚集写入<Gathering Writes> 是指将多个 Buffer 中的数据"聚集" 到 Channel。 # 注意: 按照缓冲区的顺序,写入 position 和 limit 之间的数据到 Channel。 ``` #### transferFrom() ```shell # 将数据从源通道传输到其他 Channel 中: ``` ```java RandomAccessFile fromFile = new RandomAccessFile("data/fromFile.txt","rw"); FileChannel fromChannel = fromFile.getChannel(); RandomAccessFile toFile = new RandomAccessFile("data/toFile.txt","rw"); FileChannel toChannel = toFile.getChannel(); // 定义传输位置 long position = 0L; // 最多传输的字节数 long count = fromChannel.size(); // 将数据从源通道传输到另一个通道 toChannel.transferFrom(fromChannel, count, position); ``` #### transferTo() ```shell # 将数据从源通道传输到另一个通道 # 上述代码最后一句发生变化: fromChannel.transferTo(position, count, toChannel); ``` #### FileChannel 的常用方法 | 方法 | 描述 | | ----------------------------- | -------------------------------------------- | | int read(ByteBuffer dst) | 从Channel 中读取数据到 ByteBuffer | | long read(ByteBuffer[] dsts) | 将Channel 中的数据"分散"到 ByteBuffer[] | | int write(ByteBuffer src) | 将ByteBuffer 中的数据写入到 Channel | | long write(ByteBuffer[] srcs) | 将ByteBuffer[] 中数据"聚集" 到 Channel | | long position() | 返回此通道的文件位置 | | FileChannel position(long p) | 设置此通道的文件位置 | | long size() | 返回此通道的文件的当前大小 | | FileChannel truncate(long s) | 将此通道的文件截取为给定大小 | | void force(boolean metaData) | 强制将所有对此通道的文件更新写入到存储设备中 | ## NIO 的非阻塞式网络通信 ### 阻塞与非阻塞 ```shell # 传统的 IO 流都是阻塞式的,当一个线程调用 read() 或 write() 时,该线程被阻塞,直到有一些数据被读取或写入,该线程在此期间不能执行其他任务。 # 因此,在完成网络通信进行 IO 操作时,由于线程会阻塞,所以服务器端必须为每个客户端都提供一个独立的线程进行处理,当服务端需要处理大量客户端时,性能急剧下降。 # NIO 是非阻塞模式的。当线程从某通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务。线程通常将非阻塞 IO 的空闲时间用于在其他通道上执行 IO 操作,所以单独的线程可以管理多个输入和输出管道。因此,NIO 可以让服务器端使用一个或有限几个线程来同时处理连接到服务器端的所有客户端。 ``` ### 选择器 ```shell # Selector 是 SelectableChannel 对象的多路复用器,Selector 可以同时监控多个 SelectableChannel 的IO 状况,也就是说,利用 Selector 可使一个单独的线程管理多个 Channel。Selector 是非阻塞 IO 的核心。 ``` #### SelectableChannel 结构图 ![UTOOLS1573197242137.png](https://i.loli.net/2019/11/08/cE4T9qNaxSWor1b.png) #### 选择器的应用 ```java // 创建 Selector Selector selector = Selector.open(); // 向选择器注册通道 // 创建一个 Socket 套接字 Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9898); // 获取 SocketChannel SocketChannel channel = socket.getChannel(); // 将 SocketChannel 切换到非阻塞模式 channel.configureBlocking(false); /** * 向 Selector 注册 Channel * 当调用 register(Selector,int ops) 将通道注册选择器时,选择器对通道的监听事件,需要通过第 * 二个参数 ops 指定。 * 可以监听的事件类型(可使用 SelectionKey 的四个常量表示): * 读: SelectionKey.OP_READ * 写: SelectionKey.OP_WRITE * 连接: SelectionKey.OP_CONNECT * 接收: SelectionKey.OP_ACCEPT * 若注册时不止监听一个事件,则可以使用 | 操作符连接,例: * int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE; */ SelectionKey key = channel.register(selector, SelectionKey.OP_READ); ``` #### SelectionKey ```shell # SelectionKey: # 表示 SelectableChannel 和 Selector 之间的注册关系。每次向选择器注册通道时,就会选择一个事件(选择键)。 # 选择键包含两个表示为整数值的操作集,操作集的每一位都表示该键的通道所支持的一类可选择操作。 ``` | 方法 | 描述 | | --------------------------- | -------------------------------- | | int interestOps() | 获取感兴趣时间集合 | | int readyOps() | 获取通道已经准备就绪的操作的集合 | | SelectableChannel channel() | 获取注册通道 | | Selector selector() | 返回选择器 | | boolean isReadable() | 检测 Channel 中读事件是否就绪 | | boolean isWritable() | 检测 Channel 中写事件是否就绪 | | boolean isConnectable() | 检测 Channel 中连接是否就绪 | | boolean isAcceptable() | 检测 Channel 中接收是否就绪 | #### Selector 的常用方法 | 方法 | 描述 | | ------------------------ | ------------------------------------------------------------ | | Set<SelectionKey> keys() | 所有的 SelectionKey 集合,代表注册在该 Selector 上的 Channel | | selectedKeys() | 被选择的SelectionKey 集合,返回此 Selector 的已选择键集 | | int select() | 监测所有注册的 Channel,当它们中间有需要处理的 IO 操作时,该方法返回,并将对应的 SelectionKey 加入被选择的 SelectionKey 集合中,该方法返回这些 Channel 的数量。 | | int select(long timeout) | 可以设置超时时长的 select() 操作 | | int selectNow() | 执行一个立即返回的 select() 操作,该方法不会阻塞线程 | | Selector wakeup() | 使一个还未返回的 select() 方法立即返回 | | void close() | 关闭该选择器 | ### SocketChannel ```shell # Java NIO 中的 SocketChannel 是一个连接到 TCP 网络套接字的通道。 # 操作步骤: # 打开 SocketChannel # 读写数据 # 关闭 SocketChannel # NIO 中的 ServerSocketChannel 是一个可以监听新进来的 TCP 连接的通道,就像标准 IO 中的 ServerSocket 一样。 ``` ### DatagramChannel ```shell # NIO 中的 DatagramChannel 是一个能收发 UDP 包的通道。 # 操作步骤: # 打开 DatagramChannel # 接收/发送数据 ``` ### 管道 ```shell # NIO 管道是2个线程之间的单向数据连接。 # Pipe 有一个 source 通道和一个 sink 通道。 # 数据会被写到 sink 通道,从 source 通道读取。 ``` ![UTOOLS1573199376680.png](https://i.loli.net/2019/11/08/PD1TC7h3UtV6NQg.png) #### 向管道写数据 ```java @Test public void test1() throws IOException{ String str = "快乐的一只小青蛙"; // 创建管道 Pipe pipe = Pipe.open(); // 向管道写输入 Pipe.SinkChannel sinkChannel = pipe.sink(); ByteBuffer buf = ByteBuffer.allocate(1024); buf.clear(); buf.put(str.getBytes()); buf.flip(); while(buf.hasRemaining()){ sinkChannel.write(buf); } } ``` #### 从管道读取数据 ```java Pipe.SourceChannel sourceChannel = pipe.source(); ByteBuffer buf = ByteBuffer.allocate(1024); sourceChannel.read(buf); ``` ## NIO.2 - Path、Paths、Files ### NIO.2 ```shell # 随着 JDK7 的发布,Java 对 NIO 进行了极大的扩展,增强了对文件处理和文件系统特性的支持,因此被称为 NIO.2。 ``` ### Path 与 Paths ```shell # java.nio.file.Path 接口代表一个平台无关的平台路径,描述了目录结构中文件的位置。 # Paths 提供的 get() 方法用来获取 Path 对象 # Path get(String first,String ...more) : 用于将多个字符串串联成路径。 # Path 常用方法: # boolean endsWith(String path): 判断是否以 path 路径结束 # boolean startsWith(String path): 判断是否以 path 路径开始 # boolean isAbsolute(): 判断是否绝对路径 # Path getFileName(): 返回与调用 Path 对象关联的文件名 # Path getName(int idx): 返回的指定索引位置 idx 的路径名称 # int getNameCount(): 返回 Path 根目录后面元素的数量 # Path getParent(): 返回 Path 对象包含整个路径,不包含 Path 对象指定的文件路径 # Path getRoot(): 返回调用 Path 对象的根路径 # Path resolve(Path p): 将相对路径解析为绝对路径 # Path toAbsolutePath(): 作为绝对路径返回调用 Path 对象 # String toString(): 返回调用 Path 对象的字符串表示形式 ``` ### Files 类 ```shell # java.nio.file.Files 用于操作文件或目录的工具类 # Files 常用方法: # Path copy(Path src, Path dest, CopyOption ...how): 文件的复制 # Path createDirectory(Path path,FileAttribute<?> ...attr): 创建一个目录 # Path createFile(Path path,FileAttribute<?> ...attr): 创建一个文件 # void delete(Path path): 删除一个文件 # Path move(Path src, Path dest, CopyOption ...how): 将 src 移动到 dest位置 # long size(Path path): 返回path 指定文件的大小 # Files 常用方法: 用于判断 # boolean exists(Path path, LinkOption ...opts): 判断文件是否存在 # boolean isDirectory(Path path, LinkOption ...opts): 判断是否是目录 # boolean isExecutable(Path path): 判断是否是可执行文件 # boolean isHidden(Path path): 判断是否是隐藏文件 # boolean isReadable(Path path): 判断文件是否可读 # boolean isWritable(Path path): 判断文件是否可写 # boolean notExists(Path path, LinkOption ...opts): 判断文件是否不存在 # Files 常用方法: 用于操作内容 # SeekableByteChannel newByteChannel(Path path,OpenOption ...how): 获取与指定文件的连接,how 指定打开方式。 # DirectoryStream newDirectoryStream(Path path): 打开 path 指定的目录 # InputStream newInputStream(Path path, OpenOption ...how): 获取 InputStream 对象 # OutputStream newOutputStream(Path path, OpenOption ...how): 获取 OutputStream 对象 ``` ## 自动资源管理 ```shell # JDK7 增加了一个新特性,该特性提供了另外一种管理资源的方式,这种方式能自动关闭文件。 ``` ```java /** * 自动资源管理基于 try 语句的扩展形式 * 当 try 代码块结束时,自动释放资源,因此不需要显示的调用 close() 方法, * 注意: * try 语句中声明的资源被隐式声明为 final,资源的作用局限于带资源的 try 语句 * 可以在一条 try 语句中管理多个资源,每个资源以 ":" 隔开即可 * 需要关闭的资源,必须实现了 AutoCloseable 接口或其子接口 Closeable */ try ("需要关闭的资源声明") { // 可能发生异常的语句 } catch ("异常类型 变量名") { // 异常的处理语句 } ...... finally { // 一定执行的语句 } ``` ###
C#
UTF-8
797
2.875
3
[]
no_license
private async Task<string> ProcessRestMethod(string methodName, string parameters) { string result = ""; using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string strParams = parameters; if ((!String.IsNullOrEmpty(parameters)) && (parameters.IndexOf('?') != 0)) strParams = "?" + parameters; result = await httpClient.GetStringAsync(baseUri + methodName + strParams); } if (result == "") result = "{\"status\":{\"code\":1000,\"message\":\"Unkown Error Ocured\"}}"; return result; }
Markdown
UTF-8
4,197
3.609375
4
[]
no_license
## LeetCode link(Easy) https://leetcode.com/problems/largest-time-for-given-digits/ ## Keyword DFS, Permutation ## Problem description ``` Given an array of 4 digits, return the largest 24 hour time that can be made. The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight. Return the answer as a string of length 5. If no valid time can be made, return an empty string. Example 1: Input: [1,2,3,4] Output: "23:41" Example 2: Input: [5,5,5,5] Output: "" Note: A.length == 4 0 <= A[i] <= 9 ``` ## 8/18/2020 DFS ```java class Solution { String ans; public String largestTimeFromDigits(int[] A) { //compute all permutations of A and find the largest one ans = null; List<Integer> digits = new ArrayList<>(); for (int i : A) { digits.add(i); } dfs(digits, new StringBuilder()); return ans == null ? "" : ans; } private void dfs(List<Integer> digits, StringBuilder sb) { //used all digits if (digits.size() == 0) { //compare with ans String res = sb.toString(); if (ans == null) { ans = res; return; } for (int i = 0; i < 5; ++i) { if (ans.charAt(i) < res.charAt(i)) { ans = res; return; } else if (ans.charAt(i) > res.charAt(i)) { return; } } return; } //':' if (sb.length() == 2) { sb.append(':'); dfs(digits, sb); sb.deleteCharAt(sb.length() - 1); return; } //pick one legal character for this layer for (int i = 0; i < digits.size(); ++i) { //first digit cannot be more than 2 if (sb.length() == 0 && digits.get(i) > 2) { continue; } //first two digits cannot be more than 23 if (sb.length() == 1 && sb.charAt(0) == '2' && digits.get(i) > 3) { continue; } //third digit cannot be more than 5 if (sb.length() == 3 && digits.get(i) > 5) { continue; } // backtracking List<Integer> next = new ArrayList<>(); for (int j = 0; j < digits.size(); ++j) { if (j != i) { next.add(digits.get(j)); } } sb.append(digits.get(i)); dfs(next, sb); sb.deleteCharAt(sb.length() - 1); } } } ``` ## Complexity Analyze Time complexity: O(1)\ Space complexity: O(1) ## Notes Use dfs to enumerate all permutation and find the largest one. ## Key points Corner cases: \ API: ```java class Solution { private int max_time = -1; public String largestTimeFromDigits(int[] A) { this.max_time = -1; permutate(A, 0); if (this.max_time == -1) return ""; else return String.format("%02d:%02d", max_time / 60, max_time % 60); } protected void permutate(int[] array, int start) { if (start == array.length) { this.build_time(array); return; } for (int i = start; i < array.length; ++i) { this.swap(array, i, start); this.permutate(array, start + 1); this.swap(array, i, start); } } protected void build_time(int[] perm) { int hour = perm[0] * 10 + perm[1]; int minute = perm[2] * 10 + perm[3]; if (hour < 24 && minute < 60) this.max_time = Math.max(this.max_time, hour * 60 + minute); } protected void swap(int[] array, int i, int j) { if (i != j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } } ``` ## Complexity Analyze Time complexity: O(1)\ Space complexity: O(1) ## Notes Better permutation. ## Key points Corner cases: \ API:
C#
UTF-8
932
3.09375
3
[ "MIT" ]
permissive
using Asphalt_9_Materials.Annotations; using System; using System.Globalization; using System.Windows.Data; namespace Asphalt_9_Materials.ViewModel.Converters { public class ToLowerCaseConverter : IValueConverter { /// <summary> /// Convert string to lower case. /// </summary> /// <param name="value">Value to convert</param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns>Lower case string</returns> public object Convert([CanBeNull] object value, Type targetType, object parameter, CultureInfo culture) { return (!string.IsNullOrEmpty(value as string)) ? ((string)value).ToLower() : string.Empty; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
Swift
UTF-8
1,070
2.90625
3
[]
no_license
// // ViewController.swift // TextFieldDelegate // // Created by Hongdonghyun on 2019/12/10. // Copyright © 2019 hong3. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var myView: UIView! @IBOutlet weak var myTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() myTextField.delegate = self } } extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { myTextField.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField) { guard let text = textField.text else { return } let textColor: [String:UIColor] = ["red": .red, "black": .black, "blue": .blue] myView.backgroundColor = textColor.keys.contains(text) ? textColor[text] : .gray } // func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // // return true // } }
Python
UTF-8
1,506
2.59375
3
[]
no_license
import RPi.GPIO as GPIO import time from firebase_admin import credentials from firebase_admin import firestore from firebase_admin import messaging import firebase_admin cred = credentials.Certificate( "/home/pi/dev/python/temp_server/check-my-temp-5e3d6-firebase-adminsdk-m5rzd-e70cd0a740.json") firebase_admin.initialize_app(cred) db = firestore.client() GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(8, GPIO.IN) # Read output from PIR motion sensor def get_token(): doc_ref = db.collection(u'tokens').document(u'token') doc = doc_ref.get() tokens = doc.to_dict() token_value = tokens['token'] print(token_value) return token_value def send_to_token(): message = messaging.MulticastMessage( notification=messaging.Notification( title="MY ROOM", body="Motion detected in your room" ), tokens=get_token(), android=messaging.AndroidConfig( priority="high" ), ) try: response = messaging.send_multicast(message) except Exception as error: print(f'Something went wrong: {error}') return False else: print('Successfully sent message:', response) return True while True: i = GPIO.input(8) if i == 1: # When output from motion sensor is HIGH print("movement detected") f = send_to_token() while(f == False): f = send_to_token() time.sleep(2) time.sleep(120)
Java
UTF-8
137
1.679688
2
[ "Apache-2.0" ]
permissive
package com.aditya.meditrack.services; public class ProductService { private final String TAG=this.getClass().getSimpleName(); }
C#
UTF-8
4,365
3.25
3
[]
no_license
using System; using ADCode.Lists.ArrayList; using ADCode.Lists.LinkedList; using ADCode.Lists.Queue; using ADCode.Lists.Stack; namespace ADCode.Lists { internal class ListProgram { public ListProgram() { // MyArrayList<int> arrayList = new MyArrayList<int>(4); // arrayList.Add(1); // arrayList.Add(2); // arrayList.Add(3); // arrayList.Add(4); // arrayList.Print(); // arrayList.CountOccurences(5); // arrayList.Set(2, 5); // arrayList.Print(); // arrayList.Clear(); // arrayList.Add(5); // arrayList.Print(); // // MyLinkedList<int> linkedList = new MyLinkedList<int>(); // linkedList.AddFirst(1); // linkedList.AddFirst(2); // linkedList.AddFirst(3); // linkedList.Print(); // linkedList.Insert(3, 5); // linkedList.Print(); // // linkedList.RemoveFirst(); // linkedList.Print(); // linkedList.RemoveFirst(); // linkedList.Print(); // linkedList.RemoveFirst(); // linkedList.Print(); // linkedList.RemoveFirst(); // linkedList.Print(); // // Console.WriteLine(CheckBrackets("((()))")); // Console.WriteLine(CheckBrackets("(()")); // Console.WriteLine(CheckBrackets2("([][])()")); // Console.WriteLine(CheckBrackets2("[()")); MyQueue<int> myQueue = new MyQueue<int>(); myQueue.Enqueue(4); myQueue.Enqueue(3); myQueue.Enqueue(2); myQueue.Enqueue(1); Console.WriteLine(myQueue); myQueue.Dequeue(); Console.WriteLine(myQueue); myQueue.Enqueue(6); Console.WriteLine(myQueue); Console.WriteLine(myQueue.Size()); myQueue.Enqueue(7); myQueue.Enqueue(8); myQueue.Enqueue(8); myQueue.Enqueue(8); Console.WriteLine(myQueue); Console.WriteLine(myQueue.Size()); } // Week 2 - Opdracht 4a private static bool CheckBrackets(string s) { MyStack<char> stack = new MyStack<char>(); bool balanced = true; for (int i = 0; i < s.Length && balanced; i++) { char c = s[i]; if (c == '(') { stack.Push(c); } else { try { stack.Pop(); } catch (NullReferenceException) { balanced = false; } } } try { stack.Top(); } catch (NullReferenceException) { return balanced; } return false; } // Week 2 - Opdracht 4b private static bool CheckBrackets2(string s) { MyStack<char> stack = new MyStack<char>(); bool balanced = true; for (int i = 0; i < s.Length && balanced; i++) { char c = s[i]; if ("[(".IndexOf(c) != -1) { stack.Push(c); } else { try { var top = stack.Pop(); balanced = SameBracket(top, c); } catch (NullReferenceException) { balanced = false; } } } try { stack.Top(); } catch (NullReferenceException) { return balanced; } return false; } private static bool SameBracket(char first, char end) { const string firsts = "[("; const string ends = "])"; return firsts.IndexOf(first) == ends.IndexOf(end); } } }
PHP
UTF-8
1,034
3.09375
3
[]
no_license
<html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <?php define("DB_SERVER", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB_NAME", "ny_db"); $dbh = new PDO('mysql:dbname=' . DB_NAME . ';host=' . DB_SERVER . ';charset=utf8', DB_USER, DB_PASSWORD); $array = array("Hus", "Pinne", "Gran", "Toalett","Pilbåge","Dator","Hund","Rymdskepp","Tangentbord","U-båt","Papperskorg","Fedora"); $index = rand(0, 11 ); $sql = "INSERT INTO `Saker`(`id`, `Namn`) VALUES ('','$array[$index]')"; $stmt = $dbh->prepare($sql); $stmt->execute(); $sql = "SELECT * FROM Saker"; $stmt = $dbh->prepare($sql); $stmt->execute(); $saker = $stmt->fetchAll(); foreach ($saker as $sak) { echo $sak["Namn"]; echo "<br>"; } ?> </body> </html>
Python
UTF-8
1,466
3.625
4
[]
no_license
import clipboard import string import random lower_case = string.ascii_lowercase upper_case = string.ascii_uppercase digits = string.digits symbols = string.punctuation password_length = input("How long do you want your password to be?\n") #colored warning choice = input("""Seperate Using Space Press 1 for lowercase Press 2 for uppercase Press 3 for digits Press 4 for symbols Press 5 for everything\n""") def listbuilder(): global list list= '' if '1' in choice: list += lower_case if '2' in choice: list += upper_case if '3' in choice: list += digits if '4' in choice: list += symbols if '5' in choice: list = lower_case + upper_case + digits + symbols def passwordgenerator(list, password_length): global password password = '' try: for i in range(int(password_length)): index = random.randint(0, int(len(list))) password += list[index - 1] except: print('Something went wrong, check the length you have provided') def passwordretriever(): print('Here is your password : {}'.format(password)) copy = input("Do you want to copy it to your clipboard y or n\n") if 'y' in copy: #copy to clipboard clipboard.copy(password) elif 'Y' in copy: clipboard.copy(password) #copy to clipboard else: quit() listbuilder() passwordgenerator(list, password_length) passwordretriever()
Java
UTF-8
1,251
2.1875
2
[]
no_license
package com.felipeska.banking.presenter; import java.util.List; import com.felipeska.banking.interactor.FindHistoryTransactionInteractor; import com.felipeska.banking.interactor.FindHistoryTransactionInteractorImpl; import com.felipeska.banking.listener.OnFinisLoadHistoryTransactionsListener; import com.felipeska.banking.model.Transaction; import com.felipeska.banking.view.TransactionHistoryView; public class TransactionHistoryPresenterImpl implements TransactionHistoryPresenter, OnFinisLoadHistoryTransactionsListener { private TransactionHistoryView transactionHistoryView; private FindHistoryTransactionInteractor findHistoryTransactionInteractor; public TransactionHistoryPresenterImpl( TransactionHistoryView transactionHistoryView) { this.transactionHistoryView = transactionHistoryView; this.findHistoryTransactionInteractor = new FindHistoryTransactionInteractorImpl(); } @Override public void findHistory(String accountNumber) { this.transactionHistoryView.showProgress(); this.findHistoryTransactionInteractor.findAccounts(accountNumber, this); } @Override public void onFinished(List<Transaction> items) { this.transactionHistoryView.hideProgress(); this.transactionHistoryView.setClients(items); } }
Java
UTF-8
2,159
2.515625
3
[]
no_license
package com.sitech.paas.javagen.benchmark.interpret; import org.apache.commons.io.IOUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import java.io.IOException; import java.io.OutputStream; import java.io.StringWriter; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * 生成对应模板的代码 * @author liwei_paas * @date 2020/3/24 */ public class TemplateUtil { /** * 生成代码 * * @return 数据 */ public static void generatorCode(OutputStream outputStream, Map<String,Object> map,List<String> templates) { ZipOutputStream zip = new ZipOutputStream(outputStream); // 生成代码 generator(zip,map,templates); IOUtils.closeQuietly(zip); } /** * 生成代码 */ public static void generator(ZipOutputStream zip,Map<String,Object> map,List<String> templates){ VelocityInitializer.initVelocity(); VelocityContext context = new VelocityContext(); context.put("author", "liwei_paas"); map.forEach((k,v)->context.put(k,v)); String filePrefix = "main/java/com/sitech/paas/javagen/demo/"; for (String template : templates){ // 渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, "utf-8"); tpl.merge(context, sw); try{ String tname = template.substring(template.indexOf("/") + 1, template.length()); if (tname.endsWith(".vm")){ tname = tname.substring(0,tname.lastIndexOf(".")); } String filename = filePrefix + tname; // 添加到zip zip.putNextEntry(new ZipEntry(filename)); IOUtils.write(sw.toString(), zip, "utf-8"); IOUtils.closeQuietly(sw); zip.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
UTF-8
5,562
1.640625
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.flipkart.android.utils; import android.content.Context; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; import com.flipkart.android.fragments.model.InAppNotificationModel; import com.flipkart.android.response.customwidgetitemvalue.Action; import java.util.Map; // Referenced classes of package com.flipkart.android.utils: // StringUtils public class InAppNotificationItemBuilder { public InAppNotificationItemBuilder() { } public static View buildInAppNotificationItem(InAppNotificationModel inappnotificationmodel, View view, ImageLoader imageloader, android.view.View.OnClickListener onclicklistener, Context context) { RelativeLayout relativelayout; if (inappnotificationmodel == null) { return new View(context); } LayoutInflater layoutinflater = LayoutInflater.from(context); if (inappnotificationmodel.isShareable() && !StringUtils.isNullOrEmpty(inappnotificationmodel.getShareUrl())) { relativelayout = (RelativeLayout)layoutinflater.inflate(0x7f030055, null); } else { relativelayout = (RelativeLayout)layoutinflater.inflate(0x7f030054, null); } if (relativelayout == null) { return new View(context); } TextView textview; TextView textview1; ImageView imageview; TextView textview2; NetworkImageView networkimageview; TextView textview3; View view1; String s; textview = (TextView)relativelayout.findViewById(0x7f0a0111); textview1 = (TextView)relativelayout.findViewById(0x7f0a0112); imageview = (ImageView)relativelayout.findViewById(0x7f0a011a); textview2 = (TextView)relativelayout.findViewById(0x7f0a0118); networkimageview = (NetworkImageView)relativelayout.findViewById(0x7f0a0110); textview3 = (TextView)relativelayout.findViewById(0x7f0a0119); view1 = relativelayout.findViewById(0x7f0a010e); s = inappnotificationmodel.getImageUrl(); if (StringUtils.isNullOrEmpty(s)) goto _L2; else goto _L1 _L1: networkimageview.setImageUrl(s, imageloader); _L14: textview.setText(inappnotificationmodel.getTitle()); if (!inappnotificationmodel.getNotificationType().equals("UPGRADE_APP")) goto _L4; else goto _L3 _L3: textview2.setVisibility(8); textview1.setText(Html.fromHtml(inappnotificationmodel.getSubTitle())); _L8: if (inappnotificationmodel.isShareable() && !StringUtils.isNullOrEmpty(inappnotificationmodel.getShareUrl())) { TextView textview4 = (TextView)relativelayout.findViewById(0x7f0a011e); textview4.setOnClickListener(onclicklistener); textview4.setTag((new StringBuilder("share:")).append(inappnotificationmodel.getNotificationType()).append(":").append(inappnotificationmodel.getShareUrl()).toString()); } if (!inappnotificationmodel.isNew()) goto _L6; else goto _L5 _L5: textview3.setVisibility(0); view1.setVisibility(0); _L9: String s1 = inappnotificationmodel.getNotificationType(); if (!StringUtils.isNullOrEmpty(s1)) { if (!s1.equals("TARGETED_OFFERS") && !s1.equals("SANTA_OFFERS")) { break MISSING_BLOCK_LABEL_494; } imageview.setVisibility(0); } _L10: Action action = inappnotificationmodel.getAction(); if (action == null) { break MISSING_BLOCK_LABEL_430; } Map map = action.getParams(); if (map == null) { break MISSING_BLOCK_LABEL_423; } map.put("notificationType", inappnotificationmodel.getNotificationType()); map.put("notificationId", inappnotificationmodel.getNotificationId()); map.put("notificationTimeStamp", Long.valueOf(inappnotificationmodel.getTimeStamp())); action.setParams(map); relativelayout.setTag(action); break MISSING_BLOCK_LABEL_504; _L2: try { networkimageview.setDefaultImageResId(0x7f020189); continue; /* Loop/switch isn't completed */ } catch (Exception exception) { } goto _L7 _L4: textview1.setText(inappnotificationmodel.getSubTitle()); textview2.setVisibility(0); textview2.setText(inappnotificationmodel.getTime()); goto _L8 _L6: textview3.setVisibility(8); view1.setVisibility(8); goto _L9 imageview.setVisibility(8); goto _L10 _L12: return relativelayout; _L7: if (true) goto _L12; else goto _L11 _L11: if (true) goto _L14; else goto _L13 _L13: } public static View buildRefreshingListitem(View view, ImageLoader imageloader, android.view.View.OnClickListener onclicklistener, Context context, boolean flag) { if (!flag) { return new View(context); } else { return (RelativeLayout)LayoutInflater.from(context).inflate(0x7f03005d, null); } } }
Markdown
UTF-8
586
2.6875
3
[]
no_license
# Image Processing With Java ## Introduction In this lecture we continue our tour of cool stuff you can do with Java. This lecture is particularly important because we cover the exact material that will be on your final exam. We are using all we learned about java and computers in general to do a cool trick. We are going to embed a 4 bit ASCII message in a ppm file and then write some Java to extract it. The code for this lesson is in the SampleCode directory below here. ## References [1] About PPM files https://www.cs.swarthmore.edu/~soni/cs35/f12/Labs/extras/01/ppm_info.html
C
UTF-8
550
2.9375
3
[]
no_license
/************************************************************************* > File Name: F.c > Author: zxw > Mail: > Created Time: 2017年10月17日 星期二 21时49分07秒 ************************************************************************/ #include<stdio.h> #include<string.h> int main(void){ int N; int num; int temp,sum; while(EOF != scanf("%d",&N)){ sum = 0; for(temp=0;temp<N;temp++){ scanf("%d",&num); sum = sum+num; } printf("%d\n",sum); } }
PHP
UTF-8
2,792
3.03125
3
[ "MIT" ]
permissive
<?php namespace Concrete\Package\Sequence\Src\Traits { date_default_timezone_set('UTC'); use Database; use DateTime; use DateTimeZone; /** * Class Persistable * @package Concrete\Package\Sequence\Src\Traits * @todo: Installation test to ensure support for prepersist callbacks! */ trait Persistable { /** * @Id @Column(type="integer") @GeneratedValue * @var int */ protected $id; /** * @Column(type="datetime") * @var DateTime */ protected $createdUTC; /** * @Column(type="datetime") * @var DateTime */ protected $modifiedUTC; /** * @PrePersist */ public function setCreatedUTC(){ if( !($this->createdUTC instanceof DateTime) ){ $this->createdUTC = new DateTime('now', new DateTimeZone('UTC')); } } /** * @PrePersist * @PreUpdate */ public function setModifiedUTC(){ $this->modifiedUTC = new DateTime('now', new DateTimeZone('UTC')); } /** * @return int|null */ public function getID(){ return $this->id; } /** * @return DateTime */ public function getModifiedUTC(){ return $this->modifiedUTC; } /** * @return DateTime */ public function getCreatedUTC(){ return $this->createdUTC; } /** * @param array $properties * @return mixed */ public static function create( array $properties = array() ){ $instance = new self(); $instance->setPropertiesFromArray( $properties ); $instance->save(); return $instance; } /** * Update the instance with the given properties * @param array $properties */ public function update( array $properties = array() ){ $this->setPropertiesFromArray( $properties ); $this->save(); } /** * Delete a record */ public function delete(){ $this->entityManager()->remove($this); $this->entityManager()->flush(); } /** * Persist to the database * @return void */ protected function save(){ $this->entityManager()->persist( $this ); $this->entityManager()->flush(); } /** * @return \Doctrine\ORM\EntityManager */ protected static function entityManager(){ return Database::get()->getEntityManager(); } } }
C#
UTF-8
2,440
2.53125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using SwiftReflector.Inventory; using SwiftRuntimeLibrary; namespace DylibBinder { internal class InnerX { // This class will be responsible for creating a dictionary // telling us if a TypeDeclaration is on the top level or // which TypeDeclaration it is an innerType for public Dictionary<string, List<ClassContents>> InnerXDict { get; } = new Dictionary<string, List<ClassContents>> (); public Dictionary<string, List<ClassContents>> AddClassContentsList (params SortedSet<ClassContents>[] contents) { foreach (var classContentsList in contents) { foreach (var classContent in classContentsList) { AddItem (classContent); } } return InnerXDict; } void AddItem (ClassContents c) { Exceptions.ThrowOnNull (c, nameof (c)); var nestingNames = c.Name.NestingNames.ToList (); if (nestingNames.Count == 0) return; var nestingNameString = c.Name.ToFullyQualifiedName (); if (nestingNameString == null) return; if (nestingNames.Count == 1) { AddKeyIfNotPresent (nestingNameString); return; } var parentNestingNameString = GetParentNameString (nestingNameString); if (parentNestingNameString == null) return; AddKeyIfNotPresent (parentNestingNameString); var value = InnerXDict [parentNestingNameString]; value.Add (c); InnerXDict [parentNestingNameString] = value; } void AddKeyIfNotPresent (string key) { Exceptions.ThrowOnNull (key, nameof (key)); if (InnerXDict.ContainsKey (key)) return; InnerXDict.Add (key, new List<ClassContents> ()); } string GetParentNameString (string childName) { Exceptions.ThrowOnNull (childName, nameof (childName)); MatchCollection matches = Regex.Matches (childName, @"\."); if (matches.Count == 0) return null; return childName.Substring (0, matches [matches.Count - 1].Index); } public static bool IsInnerType (DBTypeDeclaration typeDeclaration) { Exceptions.ThrowOnNull (typeDeclaration, nameof (typeDeclaration)); var name = typeDeclaration.Name; // if the name begins with the module and a period, we do not take that into consideration if (name.StartsWith ($"{typeDeclaration.Module}.")) name = typeDeclaration.Name.Substring (typeDeclaration.Module.Length + 1); return Regex.Matches (name, @"\.").Count > 0; } } }
Python
UTF-8
731
3.171875
3
[]
no_license
''' Created on 12-Mar-2018 @author: Titan ''' if __name__ == '__main__': pass import sqlite3 data_person_name = [('Michael', 'Fox'), ('Adam', 'Miller'), ('Andrew', 'Peck'), ('James', 'Shroyer'), ('Eric', 'Burger')] con = sqlite3.connect(":memory:") c = con.cursor() c.execute('''CREATE TABLE q1_person_name (name_id INTEGER PRIMARY KEY, first_name varchar(40) NOT NULL, last_name varchar(20) NOT NULL)''') c.executemany('INSERT INTO q1_person_name(first_name, last_name) VALUES (?,?)', data_person_name) for row in c.execute('SELECT * FROM q1_person_name'): print(row)
TypeScript
UTF-8
965
2.53125
3
[ "MIT" ]
permissive
import { Body, Get, Controller, Res, Post, Query } from '@nestjs/common'; import { ApiBody } from '@nestjs/swagger'; import { LogoutDto } from '@user/dto/logout.dto'; import { UsersService } from '@user/users.service'; @Controller('User') export class UserController { constructor(private readonly userService: UsersService) {} @Get('getProfile') async getProfile(@Query('id') id: number, @Res() res) { const user = await this.userService.findOneById(id); return res.json(user); } @Post('logout') @ApiBody({ type: LogoutDto }) async logout(@Body() data: LogoutDto, @Res() res) { const result = await this.userService.removeFCMToken( data.userID, data.fcmToken, ); if (result === true) return res.json({ valid: true, message: 'User has been logged out successfully !', }); else return res.json({ valid: false, message: 'An unknown error occured', }); } }
Markdown
UTF-8
1,779
3.078125
3
[]
no_license
# 1931번 회의실 배정 [문제 보러가기](https://www.acmicpc.net/problem/1931) 🚩 `그리디` <br> ## 🅰 설계 `[SWEA] 5202-화물 도크` 랑 똑같은 문제여서 같은 방식으로 풀었다. 시작-끝 시간을 리스트로 받은 다음, **끝나는 시간 순**으로 정렬한다. 전회차의 끝 시간보다 다음회차 시작 시간이 같거나 크면 카운팅을 해주면 된다. 시간 때문에 `pop(0)` 을 안하고 `pop()` 을 하고 싶어서 내림차순으로 정렬했다. ```python # sorted(a, key=lambda x: (-x[1], -x[0])) 정렬결과 [[12, 14], [2, 13], [8, 12], [8, 11], [6, 10], [5, 9], [3, 8], [5, 7], [0, 6], [3, 5], [1, 4]] ``` <br> ## 🅱 최종 코드 ```python import sys N = int(sys.stdin.readline()) # 회의의 수 a = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] a = sorted(a, key=lambda x: (-x[1], -x[0])) cnt = 1 f1, f2 = a.pop() # 뒤에서부터 체크 while a: n1, n2 = a.pop() if n1 >= f2: # 다음 시작이 전회차 끝보다 크거나 같으면 갱신 f1, f2 = n1, n2 cnt += 1 print(cnt) ``` <br> ## ✅ 후기 ### 새롭게 알게 된 점 (새롭게 알게 된 점이 아니라 옛날에 알아놓고 까먹은 것..😅) ⭐ `input()`은 매우 느리다. 입력이 **10만줄 이상** 되면 `stdin.readline`을 사용하는 것이 좋다. - 참고 : [파이썬 입력 받기 (sys.stdin.readline)](https://velog.io/@yeseolee/Python-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%9E%85%EB%A0%A5-%EC%A0%95%EB%A6%ACsys.stdin.readline) <br> ✔ 위가 `stdin.readline` 을 사용한 것이고, 아래가 `input()`을 사용한 것이다. ![221839](https://user-images.githubusercontent.com/77573938/116880911-919f3c00-ac5d-11eb-8203-10074de4ddbe.png)
Python
UTF-8
310
2.984375
3
[]
no_license
#M st="" for r in range(7): for c in range(0,7): if ((c==0)or(c==6)or (r==1 and c!=2 and c!=3 and c!=4) or (r==2 and c!=1 and c!=3 and c!=5 )or(r==3 and c!=1 and c!=2 and c!=4 and c!=5 ) ): st=st+"*" else: st=st+" " st=st+"\n" print(st)
PHP
UTF-8
2,701
2.609375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: alexwinter * Date: 23.08.18 * Time: 18:19 */ namespace Ginero\GineroPhp\Model\Response; use JMS\Serializer\Annotation as Serializer; use Psr\Http\Message\ResponseInterface; /** * Class BaseResponse * @package Ginero\GineroPhp\Model\Response */ abstract class BaseResponse { /** * @var string * * @Serializer\Type("string") * @Serializer\SerializedName("message") */ private $message; /** * @var int * * @Serializer\Type("integer") * @Serializer\SerializedName("code") */ private $code = 200; /** * @var Error * * @Serializer\Type("Ginero\GineroPhp\Model\Response\Error") * @Serializer\SerializedName("error") */ private $error; /** * @var Errors * * @Serializer\Type("Ginero\GineroPhp\Model\Response\Errors") * @Serializer\SerializedName("errors") */ private $errors; /** * @var ResponseInterface */ private $response; /** * @return string */ public function getMessage() { return $this->message; } /** * @return int */ public function getCode() { return $this->code; } /** * @return Error */ public function getError() { return $this->error; } /** * @return Errors */ public function getErrors() { return $this->errors; } /** * @return ResponseInterface */ public function getResponse() { return $this->response; } /** * @param int $code * @return BaseResponse */ public function setCode($code) { $this->code = $code; return $this; } /** * @param ResponseInterface $response * @return BaseResponse */ public function setResponse(ResponseInterface $response) { $this->response = $response; return $this; } /* HELPERS */ /** * @return bool */ public function isOk() { return null === $this->error && null === $this->errors && 2 == substr($this->code, 0, 1); } /** * @return string|null */ public function getFirstError() { if (null !== $this->error) { return $this->error; } if ($this->errors instanceof Errors) { foreach ($this->errors->getChildren() as $child) { if (count($child->getErrors()) > 0) { foreach ($child->getErrors() as $error) { return $error; } } } } return null; } }
Markdown
UTF-8
1,332
2.5625
3
[ "MIT" ]
permissive
# 탭 ## 데모 <client-only> <demo-block> <examples-tab-index/> </demo-block> </client-only> 단순하면 재미가 없으므로, 트랜지션을 사용해서 슬라이드 하게 만들었습니다. ## 사용하고 있는 주요 기능 <page-info page="62">클래스 데이터 바인딩하기</page-info> <page-info page="64">여러 속성 데이터 바인딩하기</page-info> <page-info page="120">산출 속성(computed)</page-info> <page-info page="146">컴포넌트</page-info> <page-info page="153">컴포넌트와 컴포넌트 끼리의 통신</page-info> <page-info page="194">트랜지션</page-info> ## 소스 코드 - [소스 코드](https://github.com/mio3io/cr-vue/tree/master/docs/.vuepress/components/examples/tab) <code-caption>index.vue</code-caption> {include:examples/tab/index.vue} <code-caption>TabItem.vue</code-caption> {include:examples/tab/TabItem.vue} ::: tip 탭 요소 컴포넌트의 액티브 상태를 스스로 판단하게 하기 어떤 컴포넌트가 선택되어 있는 상태인지 판단해야 하는 상황은 굉장히 많습니다. 현재 샘플에서는 부모로부터 전달받은 `currentId` 속성을 자신의 ID와 비교해서, 자신이 액티브 상태(선택되어 있는 상태)인지 확인하고 있습니다. 굉장히 자주 사용하는 형태입니다. :::
Java
UTF-8
678
2.15625
2
[]
no_license
package leapfrog_inc.icchi.Fragment; import android.support.v4.app.Fragment; import android.view.View; import android.view.ViewGroup; /** * Created by Leapfrog-Software on 2018/01/25. */ public class BaseFragment extends Fragment { @Override public void onStart() { super.onStart(); View view = getView(); if (view == null) { return; } ViewGroup.LayoutParams params = view.getLayoutParams(); if (params != null) { params.width = ViewGroup.LayoutParams.MATCH_PARENT; params.height = ViewGroup.LayoutParams.MATCH_PARENT; view.setLayoutParams(params); } } }