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-unknown-license-reference", "LicenseRef-scancode-generic-cla" ]
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); } } }