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
TypeScript
UTF-8
3,379
3.109375
3
[]
no_license
const isString = require('lodash/isString'); const isNumber = require('lodash/isNumber'); const isObject = require('lodash/isObject'); import Logger from '@terrestris/base-util/dist/Logger'; import { ADD_ACTIVEMODULE, REMOVE_ACTIVEMODULE, SET_INITIALLY_ACTIVE_MODULE } from '../constants/ActiveModules'; /** * Returns the ADD_ACTIVEMODULE action. * * Note: This is a private method that should be called by the public * `addActiveModule()`` method only. * * @param {Object} activeModule The (unique) module to add to the active * modules state. * @return {Object} The ADD_ACTIVEMODULE action. */ function addUniqueActiveModule(activeModule: any) { return { type: ADD_ACTIVEMODULE, activeModule }; } /** * Returns the REMOVE_ACTIVEMODULE action. * * Note: This is a private method that should be called by the public * `removeActiveModule()`` method only. * * @param {Number} activeModuleIdx The index of the active module to delete. * @return {Object} The REMOVE_ACTIVEMODULE action. */ function removeActiveModuleByIndex(activeModuleIdx: number) { return { type: REMOVE_ACTIVEMODULE, activeModuleIdx }; } /** * Dispatches the ADD_ACTIVEMODULE, but only if the provided activeModule * isn't available in the state already. * * @param {Object} activeModule The module to add to the active modules state. */ export function addActiveModule(activeModule: any) { return function(dispatch: any, getState: any) { const activeModules = getState().activeModules; const containsModule = activeModules.some((module: any) => module.name === activeModule.name); if (containsModule) { Logger.debug('Active module already exists in state.'); return; } dispatch(addUniqueActiveModule(activeModule)); }; } /** * Dispatches the REMOVE_ACTIVEMODULE, but only if the provided activeModule * could be found in the state. * * @param {String|Number|Object} activeModule The activeModule to remove. * Possible input values are the * name, index or full object of the * module to remove. */ export function removeActiveModule(activeModule: any) { return function(dispatch: any, getState: any) { const activeModules = getState().activeModules; let activeModuleIdx; if (isString(activeModule)) { activeModuleIdx = activeModules.findIndex((module: any) => module.name === activeModule); } else if (isNumber(activeModule)) { activeModuleIdx = activeModule; } else if (isObject(activeModule)) { activeModuleIdx = activeModules.indexOf(activeModule); } else { Logger.debug('Invalid input type given.'); return; } if (activeModuleIdx === -1) { Logger.debug('Could not find the provided activeModule in state.'); return; } dispatch(removeActiveModuleByIndex(activeModuleIdx)); }; } /** * Returns the SET_INITIALLY_ACTIVE_MODULE action. * * * @param {Number} initiallyActiveModuleIdx The index of the active module to set active initially * @return {Object} The REMOVE_ACTIVEMODULE action. */ export function setInitiallyActiveModule(initiallyActiveModuleIdx: number) { return { type: SET_INITIALLY_ACTIVE_MODULE, initiallyActiveModuleIdx }; }
C++
GB18030
4,980
3.15625
3
[]
no_license
//==================================================================================== //SOFTWARE: Non-local Elasto-plastic Continuum Analysis (NECA) //CODE FILE: Geometry_2D.h //OBJECTIVE: The definitions of point, line and shape in 2D //AUTHOR: Fei Han //E-MAIL: fei.han@kaust.edu.sa //==================================================================================== #ifndef GEOMETRY_2D_H #define GEOMETRY_2D_H #include<cmath> #include<stdlib.h> #include<vector> #include "Hns.h" using namespace hns; #include "MathMatrix.h" //--------------------------------------------------------------------------- //άռ class Point_2D { public: //ݳԱ double x, y; int flag; //캯 Point_2D(){}; Point_2D( double px, double py ); //Ա Point_2D operator+( Point_2D &pt ); Point_2D operator+( const Point_2D &pt ); Point_2D operator+( double d ); Point_2D operator-( double d ); Point_2D operator-( Point_2D &pt ); Point_2D operator-( const Point_2D &pt ); Point_2D operator*( double d ); Point_2D operator/( double d ); bool operator==( Point_2D &pt ); bool operator!=( Point_2D &pt ); double distance_to(const Point_2D &pt)const; double distance_to(const double &px, const double &py)const; }; //--------------------------------------------------------------------------- //ά() class Line_2D { public: //ݳԱ Point_2D point[2]; //ʾ߶ε˵ double len; //ʾ߶εij bool virtual_line; //ʾ߶Ƿ϶Ϊ߶(fase:߶ΣΪһ㣩; true:߶) //캯 Line_2D(){}; Line_2D(Point_2D p0, Point_2D p1); //Ա double length(); //߶εij double distance_point_to_line(const Point_2D *point_temp)const; //㵽ֱߵľ double distance_point_to_line(const Point_2D &point_temp)const; //㵽ֱߵľ double distance_point_to_line(double dx, double dy)const; //㵽ֱߵľ double path_point_to_line(const Point_2D &point_temp)const; //㵽ֱߵ·жϵֱߵһ໹һ int contain(const Point_2D &point_temp)const; //ж߶ΰһ int contain(const double &px, const double &py)const; //ж߶ΰһ private: //ݳԱ double A, B, D ; //ֱ߷̵ϵ Ax+By+D=0 }; //--------------------------------------------------------------------------- // class Rectangle { public: //ݳԱ Point_2D point[4]; //ĸǵ㣬½ǿʼ˳ʱת double length; //ij double width; //Ŀ double area; //ʾε int virtual_rect; //ʾǷ϶Ϊ(0:; 1:) //캯 Rectangle(){}; Rectangle (Point_2D p0, Point_2D p1, Point_2D p2, Point_2D p3); Rectangle (Point_2D p0, double len, double wid); Rectangle (Point_2D p0, Point_2D p2); //Ա double calculate_area(); //ε int contain(const Point_2D &poi)const; //жϾǷһ㣨ֵ0û1 int contain_in(const Point_2D &poi)const;//жһǷ񱻰ھڲ(߽)ֵ0û1 int contain(const Line_2D &line)const; //жϾǷһ߶Σֵ0û1 int contain(const Rectangle &rect)const; //жϾǷһΣֵ0û1 int contain_in(const Line_2D &line)const; //жһ߶Ƿ񱻰ھڲھб߽ϲ㣨ֵ0û1 int overlap(const Line_2D &line)const; //ж߶Ƿ;ཻཻ߶ε˵㶼ھεı߽ϣһ˵ھ //һ˵ھα߽ϣһ˵ھⲿཻ)(ֵ0ཻ1ཻ) void output_parameters(); //εȫϢĸ꣬αǣ int rectangles_overlapping(const Rectangle &Rect1, const Rectangle &Rect2); //Rect1Rect2ص int make_nine_grids_by(const Rectangle rect, vector<Rectangle> &grids); //ڲСΪŹָ }; //--------------------------------------------------------------------------- //¼Ԫ12ཻԪཻС struct Relative_Ele_Rect { vector<int> relative_ele_num[2]; vector<Rectangle> relative_rect[2]; }; #endif //===========================================================================
Markdown
UTF-8
7,038
2.640625
3
[]
no_license
<div id="hypercomments_widget" class="js-hypercomments-widget invisible"></div> # Тема 2. Надорганізмові рівні організації живої природи: популяція, екосистема, біосфера (11 год.) <table> <tr> <td width="50%" align="center"><b>Зміст навчального матеріалу</b></td> <td width="50%" align="center"><b>Навчальні досягнення учнів</b></td> </tr> <tr> <td width="50%" style="vertical-align:top !important;"> <p>Поняття про середовище існування, шляхи пристосувань до нього організмів. Біологічні адаптивні ритми організмів. Пояснення їх на основі ЗЗП.<br><br>Популяції, їх характеристика. Екологічні фактори, які впливають на чисельність популяції, їх пояснення на основі ЗЗП.<br><br>Угруповання організмів у природі. Екосистеми.<br><br>Взаємодії організмів в екосистемах. Прояв у них ЗЗП.<br><br>Різноманітність екосистем, їх розвиток та зміни.<br><br>Колообіг речовин і потік енергії в екосистемах, їх зв’язок з ЗЗП.<br><br>Продуктивність екосистем.<br><br>Загальна характеристика біосфери. Вчення В.І. Вернадського про біосферу.<br><br>Вплив діяльності людини на стан біосфери. <br><br>Збереження біорізноманіття.<br><br>Узагальнення знань з теми на основі ЗЗП. Моделювання цілісності знань (СЛС).</p> </td> <td width="50%" style="vertical-align:top !important;"> <p><b>Учень:</b><br> <b><i>називає:</i></b><br> <ul> <li>надорганізмові системи;</li> <li>основні характеристики популяції;</li> <li>екологічні фактори;</li> <li>природоохоронні території; </li> <li>основні екологічні проблеми сучасності;</li> </ul> <b><i>наводить приклади:</i></b><br> <ul> <li>угруповань, екосистем;</li> <li>пристосованості організмів до умов життя;</li> <li>біологічних ритмів;</li> <li>різних типів взаємозв’язків між організмами, ланцюгів живлення;</li> </ul> <b><i>характеризує із застосуванням знань про ЗЗП:</i></b><br> <ul> <li>середовища існування організмів;</li> <li>екологічні фактори;</li> <li>добові, сезонні, річні адаптивні біологічні ритми організмів; </li> <li>структуру і функціонування надорганізмових систем;</li> <li>взаємодію організмів в екосистемах;</li> <li>ланцюги живлення;</li> <li>правило екологічної піраміди;</li> <li>біосферу, функціональні компоненти і межі біосфери; </li> <li>можливі шляхи подолання екологічної кризи;</li> </ul> <b><i>обґрунтовує, застосовуючи природничо-наукову компетентність:</i></b><br> <ul> <li>значення колообігу речовин у збереженні екосистем;</li> <li>вплив діяльності людини на видову різноманітність рослин і тварин, на середовище життя, наслідки цієї діяльності;</li> <li>необхідність застосування альтернативних джерел енергії; </li> </ul> <b><i>пояснює, використовуючи фундаментальні природничі ідеї:</i></b><br> <ul> <li>основні закономірності дії екологічних факторів на живі організми;</li> <li>шляхи пристосування організмів до умов існування; </li> <li>значення організмів продуцентів, консументів, редуцентів і людини в штучних і природних екосистемах;</li> <li>роль заповідних територій у збереженні біологічного різноманіття, рівноваги в біосфері; </li> </ul> <b><i>порівнює:</i></b><br> <ul> <li>природні та штучні екосистеми;</li> <li>різні середовища життя; </li> </ul> <b><i>робить висновок:</i></b><br> <ul> <li>про цілісність і саморегуляцію живих систем на основі ЗЗП;</li> <li>про роль біологічного різноманіття, регулювання чисельності видів, охорони природних угруповань для збереження стійкості у біосфері;</li> <li>про необхідність об’єднання знань з теми в цілісність на основі ЗЗП, фундаментальних природничих ідей.</li> </ul> </p> </td> </tr> <tr> <td colspan="2" style="vertical-align:top !important;"> <p><b>Демонстрації:</b><br> <ol> <li>Колекцій.</li> <li>Гербарних матеріалів. </li> <li>Живих об’єктів, які ілюструють вплив різних екологічних факторів на рослини і тварини.</li> <li>Моделей екосистем.</li> <li>Фільмів про охорону природи.</li> </ol></p> <p><b>Урок у довкіллі №6.</b> Спостереження за взаємодією організмів в екосистемі вашої місцевості. </p> <p><b>Систематизуємо знання:</b><br> <ol> <b>Семінар №5.</b> Причини та можливі шляхи подолання екологічної кризи в Україні.</p> </td> </tr> </table> <div class="js-hypercomments-container"> <a href="http://hypercomments.com" class="hc-link" title="comments widget">comments powered by HyperComments</a> </div>
Java
UTF-8
890
2.9375
3
[]
no_license
import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class CDPlayerTest { private CDPlayer player; private String cd; @Before public void before(){ player = new CDPlayer("Sony", "SE5", 4); cd = "Abba Gold"; } @Test public void hasModel(){ assertEquals("SE5", player.getModel()); } @Test public void hasMake(){ assertEquals("Sony", player.getMake()); } @Test public void hasNumberOfCDs(){ assertEquals(4, player.getNumberOfCDs()); } @Test public void canPlayCD(){ assertEquals("Playing Abba Gold", player.play(cd)); } @Test public void canStopCD(){ assertEquals("Music Stopped", player.stop()); } @Test public void canPauseCD(){ assertEquals("Music Paused", player.pause()); } }
Python
UTF-8
289
2.953125
3
[]
no_license
#!/usr/bin/env python import re, sys convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] if __name__ == "__main__": sys.stdout.write(''.join(sorted(sys.stdin.readlines(), key=alphanum_key)))
C++
UTF-8
1,330
2.703125
3
[ "MIT" ]
permissive
#ifndef COthello_H #define COthello_H enum COthelloPieceValue { COTHELLO_PIECE_BORDER, COTHELLO_PIECE_NONE, COTHELLO_PIECE_WHITE, COTHELLO_PIECE_BLACK }; class COthelloPiece { public: static COthelloPieceValue otherPiece(COthelloPieceValue piece); }; class COthelloBoard { public: COthelloBoard(); void init(); bool canMoveAnywhere(COthelloPieceValue piece); bool canMove(int x, int y, COthelloPieceValue piece); void doMove (int x, int y, COthelloPieceValue piece); COthelloPieceValue getPiece(int x, int y); int getNumWhite(); int getNumBlack(); int getNum(); int getMoves(); int score(COthelloPieceValue piece); static void copy(const COthelloBoard &board1, COthelloBoard &board2); bool getBestMove(COthelloPieceValue piece, int depth, int *x, int *y); private: bool canMoveDirection(int x, int y, int dx, int dy, COthelloPieceValue piece, COthelloPieceValue other_piece); void doMoveDirection (int x, int y, int dx, int dy, COthelloPieceValue piece, COthelloPieceValue other_piece); int getNum(COthelloPieceValue piece); bool getBestMove1(COthelloPieceValue piece, int depth, int *x, int *y, int *score); bool flipCoin(); private: COthelloPieceValue board_[8][8]; static int board_score_[8][8]; }; #endif
C#
UTF-8
744
2.5625
3
[]
no_license
using AdventOfCode2020.Days.Day05.Calculator; using AdventOfCode2020.Days.Day05.Decoders; using AdventOfCode2020.Puzzles; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AdventOfCode2020.Days.Day05 { [Puzzle(5, 2)] public class Task2 : Day05 { protected override int SelectValue(List<int> values) { values.Sort(); for (var idx = 1; idx + 1 < values.Count; ++idx) { var previous = values[idx - 1]; var next = values[idx + 1]; if (next - previous > 2) { return next - 1; } } return -1; } } }
Python
UTF-8
36,302
2.84375
3
[]
no_license
#---------------------------------------------------------------------- # Name: DOTS AND BOXES GAME # Purpose: PROJECT # # Author: SUSHEELA # # Created: 14/06/2015 # Copyright: (c) user 2015 # Licence: <your licence> #------------------------------------------------------------------------------- import pygame import math import easygui import random class BoxesGameVersion2(): def initGraphics(self): self.normallinev=pygame.image.load("normalline.png") self.normallineh=pygame.transform.rotate(pygame.image.load("normalline.png"), -90) self.bar_donev=pygame.image.load("bar_done.png") self.bar_doneh=pygame.transform.rotate(pygame.image.load("bar_done.png"), -90) self.hoverlinev=pygame.image.load("hoverline.png") self.hoverlineh=pygame.transform.rotate(pygame.image.load("hoverline.png"), -90); self.separators=pygame.image.load("separators.png") self.redindicator=pygame.image.load("redindicator.png") self.greenindicator=pygame.image.load("greenindicator.png") self.greenplayer=pygame.image.load("greenplayer.png") self.blueplayer=pygame.image.load("blueplayer.png") self.winningscreen=pygame.image.load("youwin.png") self.gameover=pygame.image.load("gameover.png") self.score_panel=pygame.image.load("score_panel.png") def __init__(self): pass #1 pygame.init() self.dimensions=int(input("enter the dimensions")) #pygame.font.init() self.turn=0 width, height = 500,500 self.boardh = [[False for x in range(self.dimensions)] for y in range(self.dimensions+1)] self.boardv = [[False for x in range(self.dimensions+1)] for y in range(self.dimensions)] self.box=[[0 for x in range(self.dimensions) ] for y in range(self.dimensions)] self.boxcount=[[0 for x in range(self.dimensions) ] for y in range(self.dimensions)] self.no_of_boxes=0 #2 #initialize the screen self.screen = pygame.display.set_mode((width, height)) self.result=pygame.display.set_mode((width, height)) pygame.display.set_caption("Boxes") #3 #initialize pygame clock self.clock=pygame.time.Clock() self.initGraphics() self.me=0 self.otherplayer=0 self.didiwin=False #self.owner = [[0 for x in range(6)] for y in range(6)] self.xbox=0 self.ybox=0 self.newbox=0 self.turn=0 self.switch=0 ##print "self.turn in init()",self.turn self.total=0 def drawHUD(self): #draw the background for the bottom: #create font myfont = pygame.font.SysFont("freesansbold", 32) #create text surface label = myfont.render("Your Turn:", 1, (255,255,255)) #draw surface #self.screen.blit(label, (35, 500)) myfont64 = pygame.font.SysFont("freesansbold", 64) myfont20 = pygame.font.SysFont("freesansbold", 20) self.scoreme = myfont64.render(str(self.me), 1, (255,255,255)) self.scoreother = myfont64.render(str(self.otherplayer), 1, (255,255,255)) self.labelwin= myfont20.render("You win", 1, (255,255,255)) self.computerwin=myfont20.render("computer win",1,(255,255,255)) scoretextme = myfont20.render("You", 1, (255,255,255)) scoretextother = myfont20.render("Other Player", 1, (255,255,255)) self.screen.blit(self.score_panel,(650,10)) self.screen.blit(scoretextme, (700, 10)) self.screen.blit(self.scoreme, (700, 50)) self.screen.blit(scoretextother, (900, 10)) self.screen.blit(self.scoreother, (900, 50)) self.screen.blit(self.greenindicator,(650,30)) self.screen.blit(self.redindicator,(850,30)) def drawBoard(self): for x in range(self.dimensions): for y in range(self.dimensions+1): if not self.boardh[y][x]: self.screen.blit(self.normallineh, [(x)*64+5, (y)*64]) else: self.screen.blit(self.bar_doneh, [(x)*64+5, (y)*64]) for x in range(self.dimensions+1): for y in range(self.dimensions): if not self.boardv[y][x]: self.screen.blit(self.normallinev, [(x)*64, (y)*64+5]) else: self.screen.blit(self.bar_donev, [(x)*64, (y)*64+5]) #draw separators for x in range(self.dimensions+1): for y in range(self.dimensions+1): self.screen.blit(self.separators, [x*64, y*64]) def check_four(self): self.newbox=0 ##print "self.turn in check_four:",self.turn for x in range(self.dimensions): for y in range(self.dimensions): if self.boardh[y][x] and self.boardv[y][x] and self.boardh[y+1][x] and self.boardv[y][x+1]: if self.box[y][x]==0: if self.turn==1: if self.box[y][x]=="G": continue else: self.box[y][x]="B" self.newbox+=1 #self.turn=0 self.no_of_boxes+=1 self.me+=1 self.turn=0 #print "your score",self.me #print "you got another turn" if self.turn==0: if self.box[y][x]=="B": continue else: self.box[y][x]="G" #self.turn=1 self.no_of_boxes+=1 self.newbox+=1 #self.otherplayer+=1 #print "other player's turn" #print "self.otherplayer",self.otherplayer def drawBox(self): ##print "enter drawBox" for x in range(self.dimensions): for y in range(self.dimensions): if self.box[y][x]=="B": self.screen.blit(self.blueplayer, (x*64+5,y*64+5)) me=1 if self.box[y][x]=="G": self.screen.blit(self.greenplayer, (x*64+5,y*64+5)) other=1 def mouse_event(self): ##print "entered mouse_event" mouse = pygame.mouse.get_pos() crash=False pressed=0 xpos = int(math.ceil((mouse[0]-32)/64.0)) ypos = int(math.ceil((mouse[1]-32)/64.0)) is_horizontal = abs(mouse[1] - ypos*64) < abs(mouse[0] - xpos*64) ypos = ypos - 1 if mouse[1] - ypos*64 < 0 and not is_horizontal else ypos xpos = xpos - 1 if mouse[0] - xpos*64 < 0 and is_horizontal else xpos board=self.boardh if is_horizontal else self.boardv isoutofbounds=False try: if not board[ypos][xpos]: self.screen.blit(self.hoverlineh if is_horizontal else self.hoverlinev, [xpos*64+5 if is_horizontal else xpos*64, ypos*64 if is_horizontal else ypos*64+5]) except: isoutofbounds=True pass if not isoutofbounds: alreadyplaced=board[ypos][xpos] else: alreadyplaced=False if pygame.mouse.get_pressed()[0] and not alreadyplaced and not isoutofbounds: if is_horizontal: self.boardh[ypos][xpos]=True else: self.boardv[ypos][xpos]=True if self.turn==0: self.turn=1 else: ##print "turn changed",self.turn self.turn=0 if is_horizontal: if ypos>0: self.boxcount[ypos-1][xpos]+=1 if ypos<self.dimensions: self.boxcount[ypos][xpos]+=1 else: if xpos>0: self.boxcount[ypos][xpos-1]+=1 if xpos<self.dimensions: self.boxcount[ypos][xpos]+=1 #print "self.boxcount in mouseclick():",self.boxcount self.check_four() ##print "entered user drawbox()" self.drawBox() pygame.display.flip() #computer move def computermove(self): print ("computermove()") self.takesafe3s() if self.sides3()==True:#sides3 uses u,v print ("sides03 exist") if self.sides01()==True:#sides01 uses x,y print ("sides3 TRUE sides01 TRUE ") self.takeall3s()#takeall3s() uses u,v self.takeedge()#takeedge() uses x,y,z else: print ("sides3 TRUE sides01 FALSE") self.takeall3s() self.makeanymove() if self.me+self.otherplayer==self.dimensions*self.dimensions: #print "your score:",self.me #print "other player score",self.otherplayer if self.me>self.otherplayer: print ("you win") #self.result.blit(self.winningscreen, [0,0]) self.screen.blit(self.labelwin,(650,300)) easygui.msgbox("You win") elif self.me==self.otherplayer: print ("Draw") # self.result.blit(self.gameover, [0,0]) self.screen.blit(self.computerwin,(650,100)) easygui.msgbox("Draw") else: print ("you lose") easygui.msgbox("You lose") self.update() elif self.sides01()==True: print ("sides01 TRUE") self.takeedge() elif self.singleton()==True: print ("singleton TRUE") self.takeedge() elif self.doubleton()==True: print ("Doubleton") self.takeedge() else: print ("makeanymove") self.makeanymove() print ("end of computermove()") #takesafe3s function def takesafe3s(self): print ("entered takesafe3s()") for i in range(0,self.dimensions): for j in range(0,self.dimensions): if self.boxcount[i][j]==3: if self.boardv[i][j]==False: if j==0 or self.boxcount[i][j-1]!=2: print ("set the positions safely") self.x=i self.y=j #print "called setvedge()" self.setvedge() elif self.boardh[i][j]==False: if i==0 or self.boxcount[i-1][j]!=2: print ("set the positions safely") self.x=i self.y=j #print "called sethedge()" self.sethedge() elif self.boardv[i][j+1]==False: if j==self.dimensions-1 or self.boxcount[i][j+1]!=2: print ("set the positions safely") self.x=i self.y=j+1 #print "setvedge()" self.setvedge() elif self.boardh[i+1][j]==False: if i==self.dimensions-1 or self.boxcount[i+1][j]!=2: print ("set the positions safely") self.x=i+1 self.y=j #print "sethedge()" self.sethedge() print ("takesafe3s() exit") #sethedge() def sethedge(self): #print "entered sethedge() with self.x and self.y values as: ",self.x,self.y self.boardh[self.x][self.y]=True if self.x>0: self.boxcount[self.x-1][self.y]+=1 if self.x<self.dimensions: self.boxcount[self.x][self.y]+=1 #print "self.boxcount in sethedge:",self.boxcount #print "self.boardh,",self.boardh self.screen.blit(self.hoverlineh,(self.x*64+5,self.y*64)) self.checkh() if self.me+self.otherplayer==self.dimensions*self.dimensions: self.update() self.turn=1-self.turn #setvedge def setvedge(self): #print "entered setvedge with self.x and self.y as ",self.x,self.y self.boardv[self.x][self.y]=True if self.y>0: self.boxcount[self.x][self.y-1]+=1 if self.y<self.dimensions: self.boxcount[self.x][self.y]+=1 self.screen.blit(self.hoverlinev,(self.x*64,self.y*64+5)) self.checkv() if self.me+self.otherplayer==self.dimensions*self.dimensions: self.update() self.turn=1-self.turn #checkh() def checkh(self): #print "entered checkh() with self.x and self.y as,",self.x,self.y hit=0 if self.x>0: if self.boxcount[self.x-1][self.y]==4 : #print "color box" self.box[self.x-1][self.y]="G" #self.drawBox() self.screen.blit(self.greenplayer, (self.x*64+5,self.y*64+5)) self.otherplayer+=1 hit=1 if self.x<self.dimensions: if self.boxcount[self.x][self.y]==4 : #print "color box" self.box[self.x][self.y]="G" #self.drawBox() self.screen.blit(self.greenplayer, (self.x*64+5,self.y*64+5)) self.otherplayer+=1 hit=1 #print "computer score:",self.otherplayer if hit>0: if self.me+self.otherplayer<self.dimensions*self.dimensions: self.turn=1-self.turn #checkv() def checkv(self): #print "entered checkv() with self.x and self.y as",self.x,self.y hit=0 if self.y>0: if self.boxcount[self.x][self.y-1]==4 : #print "color box" self.box[self.x][self.y-1]="G" self.screen.blit(self.greenplayer, (self.x*64+5,self.y*64+5)) self.otherplayer+=1 hit=1 if self.y<self.dimensions: if self.boxcount[self.x][self.y]==4 : #print "color box" self.box[self.x][self.y]="G" self.screen.blit(self.greenplayer, (self.x*64+5,self.y*64+5)) self.otherplayer+=1 hit=1 #print "computer score:",self.otherplayer if hit>0: if self.me+self.otherplayer<self.dimensions*self.dimensions: self.turn=1-self.turn #sides3() def sides3(self): #print "sides3()" #print "#print boxcount: in sides03():",self.boxcount for i in range(0,self.dimensions): for j in range(0,self.dimensions): if self.boxcount[i][j]==3: self.u=i self.v=j return True return False #sides01() def sides01(self): #print "entered sides01" self.x=0 self.y=0 self.z=random.randint(1,2) is_horizontal=False is_vertical=False if self.z==1: # #print "self.z=1" self.x=random.randint(0, self.dimensions) self.y=random.randint(0,self.dimensions-1) ##print "entering into self.randhedge" if self.randhedge()==True: return True else: self.z=2 self.x=random.randint(0, self.dimensions-1) self.y=random.randint(0,self.dimensions) if self.randvedge()==True: return True else: # #print "self.z==2" self.x=random.randint(0, self.dimensions-1) self.y=random.randint(0,self.dimensions) # #print "entering into self.randvedge" if self.randvedge()==True: return True else: self.z=1 self.x=random.randint(0, self.dimensions) self.y=random.randint(0,self.dimensions-1) #print "entered into self.randhedge2" if self.randhedge()==True: return True return False #randhedge() def randhedge(self): m=self.x n=self.y #print "entered randhedge" ##print "self.x,self.y before callinf safehedge for 1st time" if self.safehedge(): return True else: self.y+=1 if self.y==self.dimensions: self.y=0 self.x+=1 if self.x>self.dimensions: self.x=0 while self.x!=m or self.y!=n: #print "self.x,self.y before calling safehedge:",self.x,self.y if self.safehedge(): return True else: self.y+=1 #print "self.y:",self.y if self.y==self.dimensions: self.y=0 self.x+=1 #print "self.x:",self.x if self.x>self.dimensions: #print "self.x=>" self.x=0 return False #randvedge() def randvedge(self): m=self.x n=self.y #print "entered randvedge() with self.x and self.y as,",self.x,self.y if self.safevedge(): return True else: self.y+=1 if self.y>self.dimensions: self.y=0 self.x+=1 if self.x==self.dimensions: self.x=0 while self.x!=m or self.y!=n: if self.safevedge(): return True else: self.y+=1 if self.y>self.dimensions: self.y=0 self.x+=1 if self.x==self.dimensions: self.x=0 return False #safehedge() def safehedge(self): #print "entered safehedge with self.x and self.y as,",self.x,self.y if self.boardh[self.x][self.y]==False: if self.x==0: if self.boxcount[self.x][self.y]<2: #print "safehedge returns TRUE" return True elif self.x==self.dimensions: if self.boxcount[self.x-1][self.y]<2: #print "safehedge returns TRUE" return True elif self.boxcount[self.x][self.y]<2 and self.boxcount[self.x-1][self.y]: #print"safehedge returns TRUE" return True #print"safehedge returns FALSE" return False #safevedge() def safevedge(self): #print "entered safevedge with self.x and self.y as, ",self.x,self.y if self.boardv[self.x][self.y]==False: if self.y==0: #print "self.x,self.y",self.x,self.y if self.boxcount[self.x][self.y]<2: return True elif self.y==self.dimensions: if self.boxcount[self.x][self.y-1]<2: return True elif self.boxcount[self.x][self.y]<2 and self.boxcount[self.x][self.y-1]<2: return True return False #takeall3s() def takeall3s(self): #print "entered takeall3s" while self.sides3(): #print "in take all 3s() sides3()==True" self.takebox() #print "left takeall3s" #takebox() def takebox(self): self.e=self.x self.f=self.y #print"entered takebox with self.u self.v",self.u,self.v if self.boardh[self.u][self.v]==False: self.x=self.u self.y=self.v #print "sethedge() with self.x and self.y as",self.x,self.y self.sethedge() elif self.boardv[self.u][self.v]==False: self.x=self.u self.y=self.v #print "setvedge() with self.x and self.y as",self.x,self.y self.setvedge() elif self.boardh[self.u+1][self.v]==False: self.x=self.u+1 self.y=self.v #print "sethedge() with self.x and self.y as",self.x,self.y self.sethedge() elif self.boardv[self.u][self.v+1]==False: self.x=self.u self.y=self.v+1 #print "setvedge() with self.x and self.y as",self.x,self.y self.setvedge() self.x=self.e self.y=self.f #print "left takebox()" #takeedge def takeedge(self): #print "entered takeedge() with self.x and self.y as",self.x,self.y if self.z==2: #print "setvedge() with self.x and self.y as",self.x,self.y self.setvedge() elif self.z==1: #print "sethedge() with self.x and self.y as",self.x,self.y self.sethedge() #print "left takedge()" #incount def incount(self): ##print "incount" #print "self.u and self.v",self.u,self.v self.count=self.count+1 if self.k!=1 and self.boardv[self.u][self.v]==False: if self.v>0: if self.boxcount[self.u][self.v-1]>2: self.count+=1 self.loop=True elif self.boxcount[self.u][self.v-1]>1: self.k=3 self.v=self.v-1 self.incount() elif self.k!=2 and self.boardh[self.u][self.v]==False: if self.u>0: if self.boxcount[self.u-1][self.v]>2: self.count+=1 self.loop=True elif self.boxcount[self.u-1][self.v]>1: self.k=4 self.u=self.u-1 self.incount() elif self.k!=3 and self.boardv[self.u][self.v+1]==False: if self.v<self.dimensions-1: if self.boxcount[self.u][self.v+1]>2: self.count+=1 self.loop=True elif self.boxcount[self.u][self.v+1]>1: self.k=1 self.v=self.v+1 self.incount() elif self.k!=4 and self.boardh[self.u+1][self.v]==False: if self.u<self.dimensions-1: if self.boxcount[self.u+1][self.v]>2: self.count+=1 self.loop=True elif self.boxcount[self.u+1][self.v]>1: self.u==self.u+1 self.k=2 self.incount() #print "count: at end of incount():",self.count #sac() def sac(self): #print "entered sac" self.count=0 self.loop=False self.k=0 self.incount() print ("count:",self.count) if self.loop==False: self.takeallbut() if self.count+self.me+self.otherplayer==self.dimensions*self.dimensions: self.takeall3s() else: if self.loop==True: self.count=self.count-2 self.k=0 self.outcount() self.u=self.dimensions self.v=self.dimensions #print "left sac()" #incount() #takeallbut() def takeallbut(self): #print "entered takeallbut()" while self.sides3not(): self.takebox() #print "left takeallbut" #sides3not() def sides3not(self): #print "entered sides3not()" for i in range(0,self.dimensions): for j in range(0,self.dimensions): if self.boxcount[i][j]==3: if i!=self.u or j!=self.v: self.u=i self.v=j #print "left sides3not()" return True #print "left sides3not()" return False #outcount() def outcount(self): #print "entered outcount" if self.count>0: if self.k!=1 and self.boardv[self.u][self.v]==False: if self.count!=2: self.x=self.u self.y=self.v self.setvedge() self.count=self.count-1 self.k=3 self.v=self.v-1 self.outcount() if self.k!=2 and self.boardh[self.u][self.v]==False: if self.count!=2: self.x=self.u self.y=self.v self.sethedge() self.count=self.count-1 self.k=4 self.u=self.u-1 self.outcount() if self.k!=3 and self.boardv[self.u][self.v+1]==False: if self.count!=2: self.x=self.u self.y=self.v+1 self.setvedge() self.count=self.count-1 self.k=1 self.v=self.v+1 self.outcount() if self.k!=4 and self.boardh[self.u+1][self.v]==False: if self.count!=2: self.x=self.u+1 self.y=self.v sethedge(self.u+1,self.v) self.count=self.count-1 self.k=2 self.u=self.u+1 self.outcount() #print "left outcount()" #singleton() def singleton(self): print ("entered singleton") for i in range(0,self.dimensions): for j in range(0,self.dimensions): if self.boxcount[i][j]==2: numb=0 if self.boardh[i][j]==False: if i<1 or self.boxcount[i-1][j]<2: numb+=1 self.z=2 if self.boardv[i][j]==False: if j<1 or self.boxcount[i][j-1]<2: numb+=1 if numb>1: self.x=i self.y=j return True if self.boardv[i][j+1]==False: if j+1==self.dimensions or self.boxcount[i][j+1]<2: numb+=1 if numb>1: self.x=i self.y=j+1 return True self.z=1 if self.boardh[i+1][j]==False: if i+1==self.dimensions or self.boxcount[i+1][j]<2: numb+=1 if numb>1: self.x=i+1 self.y=j return True return False #doubleton() def doubleton(self): print ("entered doubleton") self.z=2 for i in range(0,self.dimensions): for j in range(0,self.dimensions-1): if self.boxcount[i][j]==2 and self.boxcount[i][j+1]==2 and self.boardv[i][j+1]==False: self.k=i self.l=j if self.ldub() and self.rdub(): self.x=self.k self.y=self.l+1 print ("self.x and self.y in doubleton:",self.x,self.y) return True self.z=1 for j in range(0,self.dimensions): for i in range(0,self.dimensions-1): if self.boxcount[i][j]==2 and self.boxcount[i+1][j]==2 and self.boardh[i+1][j]==False: self.k=i self.l=j if self.udub() and self.ddub(): self.x=self.k+1 self.y=self.l print ("self.x and self.y in doubleton:",self.x,self.y) return True return False #ldub() def ldub(self): #print "entered ldub" if self.boardv[self.k][self.l]==False: if self.l<1 or self.boxcount[self.k][self.l-1]<2: return True elif self.boardh[self.k][self.l]==False: if self.k<1 or self.boxcount[self.k-1][self.l]<2: return True elif self.k==self.dimensions or self.boxcount[self.k-1][self.l]<2: return True return False def rdub(self): #print "entered rdub" if self.boardv[self.k][self.l+1+1]==False: if self.k+1+1==self.dimensions or self.boxcount[self.k][self.l+1]<2: return True elif self.boardh[self.k][self.l+1]==False: if self.k<1 or self.boxcount[self.k-1][self.l+1]<2: return True elif self.k+1==self.dimensions or self.boxcount[self.k+1][self.l+1]<2: return True return False def udub(self): #print "entered udub" if self.boardh[self.k][self.l]==False: if self.k<1 or self.boxcount[self.k-1][self.l]<2: return True elif self.boardv[self.k][self.l]==False: if self.l<1 or self.boxcount[self.k][self.l-1]<2: return True elif self.l==self.dimensions-1 or self.boxcount[self.k][self.l+1]<2: return True return False def ddub(self): #print "entered ddub" if self.boardh[self.k+1+1][self.l]==False: if self.k+1==self.dimensions-1 or self.boxcount[self.k+1][self.l]<2: return True elif self.boardv[self.k+1][self.l]==False: if self.l<1 or self.boxcount[self.k+1][self.l-1]<2: return True elif self.l==self.dimensions-1 or self.boxcount[self.k+1][self.l+1]<2: return True return False #makeanymove() def makeanymove(self): #print "entered makeanymove()" self.x=-1 for i in range(0,self.dimensions+1): for j in range(0,self.dimensions): #print "self.x and self.y in makeanymove as",self.x,self.y #print #print "self.boardh[i][j]",self.boardh if self.boardh[i][j]==False: self.x=i self.y=j i=self.dimensions+1 j=self.dimensions break if self.x<0: for i in range(0,self.dimensions): for j in range(0,self.dimensions+1): #print "self.x and self.y in makeanymove as",self.x,self.y #print "self.boardv[i][j]: for dimensions",self.boardv,self.dimensions if self.boardv[i][j]==False: self.x=i self.y=j i=self.dimensions j=self.dimensions+1 self.setvedge() else: self.sethedge() if self.turn==1 and self.me+self.otherplayer<self.dimensions*self.dimensions: self.computermove() def update(self): ##print "entered update()" #sleep to make the game 60 fps #self.clock.tick(60) white=(240,100,50) white1=(255,255,255) black=(0,0,0) #clear the screen self.screen.fill(white) self.drawBoard() self.drawHUD() crashed=False # #print "self.turn in update",self.turn if self.me+self.otherplayer==self.dimensions*self.dimensions: #self.drawBox() self.result="you scored "+str(self.me)+" computer scored "+str(self.otherplayer) myfont64 = pygame.font.SysFont("", 64) myfont20 = pygame.font.SysFont("", 20) self.scoreme = myfont64.render(str(self.me), 1, (255,255,255)) self.scoreother = myfont64.render(str(self.otherplayer), 1, (255,255,255)) self.screen.blit(self.scoreme, (700, 50)) self.screen.blit(self.scoreother, (900, 50)) #print "your score:",self.me #print "other player score",self.otherplayer if self.me>self.otherplayer: #print "you win" #self.result.blit(self.winningscreen, [0,0]) self.screen.blit(self.labelwin,(650,300)) easygui.msgbox("You win") elif self.me==self.otherplayer: #print "Draw" #self.result.blit(self.gameover, [0,0]) self.screen.blit(self.computerwin,(650,100)) easygui.msgbox("Draw") else: #print "you lose" easygui.msgbox("computer wins") easygui.msgbox(str(self.result)) pygame.quit() quit() for event in pygame.event.get(): #quit if the quit button was pressed if event.type == pygame.QUIT: if self.me>self.otherplayer: #print "you win" #self.result.blit(self.winningscreen, [0,0]) easygui.msgbox("You win") elif self.me==self.otherplayer: #print "Draw" #self.result.blit(self.gameover, [0,0]) easygui.msgbox("Draw") else: #print "you lose" easygui.msgbox("computer wins") crashed=True pygame.quit() quit() #jhturn=self.mouse_event() ##print "mouse_event is called" if self.turn==0: self.mouse_event() ##print "got back to update after mouse event" elif self.turn==1: self.computermove() # #print "mouse_event is returned" #self.drawBox() bg=BoxesGameVersion2() #__init__ is called right here while 1: bg.update()
Python
UTF-8
981
2.9375
3
[ "MIT" ]
permissive
import unittest from simple_ws import RequestParser class RequestParserTestMethods(unittest.TestCase): def test_valid_request(self): rp = RequestParser() input_head = "GET / HTTP/1.1\r\n" \ "Host: localhost:8080\r\n" \ "Connection: Upgrade\r\n" \ "Pragma: no-cache\r\n" \ "Cache-Control: no-cache\r\n" \ "Upgrade: websocket\r\n" rp.parse_request(input_head) print(rp.headers) self.assertEqual(rp.headers["Host"], "localhost:8080", "Asserting correct host") self.assertEqual(rp.headers["Connection"], "Upgrade", "Asserting correct connection") self.assertEqual(rp.headers["Pragma"], "no-cache", "Asserting correct pragma") self.assertEqual(rp.headers["Cache-Control"], "no-cache", "Asserting correct cache-control") self.assertEqual(rp.headers["Upgrade"], "websocket", "Asserting correct upgrade")
Java
UTF-8
2,872
1.710938
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.impl; import com.jetbrains.python.PyNames; import com.jetbrains.python.psi.Property; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.PyFunction; import consulo.annotation.component.ExtensionImpl; import consulo.application.AllIcons; import consulo.language.icon.IconDescriptor; import consulo.language.icon.IconDescriptorUpdater; import consulo.language.psi.PsiDirectory; import consulo.language.psi.PsiElement; import consulo.module.content.ProjectRootManager; import consulo.ui.image.Image; import consulo.util.lang.Comparing; import consulo.virtualFileSystem.VirtualFile; import javax.annotation.Nonnull; /** * @author yole */ @ExtensionImpl public class PyIconDescriptorUpdater implements IconDescriptorUpdater { @Override public void updateIcon(@Nonnull IconDescriptor iconDescriptor, @Nonnull PsiElement element, int i) { if (element instanceof PsiDirectory) { final PsiDirectory directory = (PsiDirectory)element; if (directory.findFile(PyNames.INIT_DOT_PY) != null) { final VirtualFile vFile = directory.getVirtualFile(); final VirtualFile root = ProjectRootManager.getInstance(directory.getProject()).getFileIndex().getSourceRootForFile(vFile); if (!Comparing.equal(root, vFile)) { iconDescriptor.setMainIcon(AllIcons.Nodes.Package); } } } else if (element instanceof PyClass) { iconDescriptor.setMainIcon(AllIcons.Nodes.Class); } else if (element instanceof PyFunction) { Image icon = null; final Property property = ((PyFunction)element).getProperty(); if (property != null) { if (property.getGetter().valueOrNull() == this) { icon = PythonIcons.Python.PropertyGetter; } else if (property.getSetter().valueOrNull() == this) { icon = PythonIcons.Python.PropertySetter; } else if (property.getDeleter().valueOrNull() == this) { icon = PythonIcons.Python.PropertyDeleter; } else { icon = AllIcons.Nodes.Property; } } if (icon != null) { iconDescriptor.setMainIcon(icon); } else { iconDescriptor.setMainIcon(AllIcons.Nodes.Method); } } } }
Python
UTF-8
78
3.03125
3
[]
no_license
def encontra_cateto(hip,cto): cta=((hip**2)-(-cto**2))**1/2 return cta
C#
UTF-8
3,228
2.890625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EntityMap; using PayCare.Model; using PayCare.Repository.Mapping; namespace PayCare.Repository { public interface ICompanyRepository { Company GetById(Guid id); Company GetAll(); List<Company> Search(string column, string value); void Update(Company company); } public class CompanyRepository : ICompanyRepository { private string tableName = "Company"; private DataSource ds; public CompanyRepository(DataSource ds) { this.ds = ds; } public Company GetById(Guid id) { Company company = null; using (var em = EntityManagerFactory.CreateInstance(ds)) { var q = new Query().From(tableName).Where("ID").Equal("{" + id + "}"); company = em.ExecuteObject<Company>(q.ToSql(), new CompanyMapper()); } return company; } public Company GetAll() { Company companies = new Company(); using (var em = EntityManagerFactory.CreateInstance(ds)) { var q = new Query().From(tableName); companies = em.ExecuteObject<Company>(q.ToSql(), new CompanyMapper()); } return companies; } public List<Company> Search(string column, string value) { List<Company> companies = new List<Company>(); using (var em = EntityManagerFactory.CreateInstance(ds)) { var q = new Query().From(tableName).Where(column).Equal(value); companies = em.ExecuteList<Company>(q.ToSql(), new CompanyMapper()); } return companies; } public void Update(Company company) { try { using (var em = EntityManagerFactory.CreateInstance(ds)) { string[] columns = {"CompanyCode", "CompanyName","Address", "Phone", "Fax", "Email", "Notes", "BankName", "SalaryCutOffDate", "MainSalaryDivider", "OverTimeHourDivider", "OverTimeMaximumHour", "OverTimeMultiply", "OverTimeMultiplyHoliday"}; object[] values = {company.CompanyCode, company.CompanyName, company.Address, company.Phone, company.Fax, company.Email, company.Notes, company.BankName, company.SalaryCutOffDate, company.MainSalaryDivider, company.OverTimeHourDivider, company.OverTimeMaximumHour, company.OverTimeMultiply, company.OverTimeMultiplyHoliday}; var q = new Query().Select(columns).From(tableName).Update(values).Where("ID").Equal("{" + company.ID + "}"); em.ExecuteNonQuery(q.ToSql()); } } catch (Exception ex) { throw ex; } } } }
Markdown
UTF-8
3,114
3.0625
3
[ "MIT" ]
permissive
** **Practica 9: POO.Módulos** =========== **Autor:Alberto Martínez Chincho** ----------- **Introducción:** ------------- En esta practica vamos a desarrollar los módulos Mixin Enumerable y Comparable. Usaremos el modulo Comprable para la jerarquía de clases que desarrollamos en la practica anterior con algunas modificacion para poder usar correctamente este modulo. Usaremos el modulo Enumerable para la parte de la lista doblemente enlazada de nuestra practica anterior con alguna modificación para el buen uso de este modulo. Por último desarrollaremos un código de TDD para realizar las pruebas y comprobar que los códigos que vamos desarrollando tanto de la jerarquía de clases como de la lista están bien desarrollados. ## **Ficheros:** ## En nuestra practicas podrás encontrar los ficheros necesarios para la resolución de dicha practica , los cuales se especifican a continuación: 1.**.gitignore** --> Contiene todas las extensiones de los ficheros que queremos ignorar durante nuestro trabajo. 2.**Readme.md** --> Contiene la explicación e informe de nuestra practica. 3.**double_lista**-->Contiene la implementación de la lista.doblemente enlazada, ademas de incluido el modulo Enumerable. 4.**bibliografia**-->Contiene la clase padre para la jerarquía de clases que estamos realizando,además del modulo Comparable incluido y las clases de **<=>** ,**==** para poder usarlo en las pruebas. 5.**ref_libro**-->Contiene la clase hija de la clase bibliografia, esta clase contiene lo necesario para realizar una referencia de un libro. 6.**ref_revitas**-->Contiene la clase hija de la clase bibliografia, esta clase contiene lo necesario para realizar una referncias de una revista. 7.**prct_09_spec**-->Fichero que contiene las TDD necesarias para la clase hijas y listas. 8.**.travis.yml**-->Fichero que contiene las versiones con las que queremos comprobar si nuestro código es compatible y funciona. ## **Resolución de la practica:** ## En esta practica hemos reciclado un poco de código de la practica que realizamos la semana pasada, además le añadimos los módulos de Comparable y Enumerable que era lo que nos pedía esta práctica, tuvimos que modificar la clase padre **Bibliografias** añadiéndole dos clases nuevas para poder usarla en las pruebas y comprobar que el modulo Comparable funcionaba correctamente. En la clase **Doble_lista** añadimos el modulo Enumerable para luego comprobar su funcionamiento en las TDD. Dejando aun lado la explicación de la parte principal de la practica, hemos de decir que modificamos otra serie de ficheros como son, el **.gitignore** para ignorar los ficheros que no queremos que suban a nuestro repositorio, **README.md** el cual contiene el informe de la practica que hemos realizado y el **Rakefile** el cual usamos para poder ejecutar de manera automática las pruebas (TDD) escribiendo en la consola el comando **rake** . Volviendo al desarrollo principal de la practica lo que modificamos y desarrollamos fueron las TDD necesarias para ver como ir desarrollando nuestro código en función a la salida de las pruebas .
Java
UTF-8
1,267
1.757813
2
[]
no_license
package org.young.sso.server.service; import org.young.sso.sdk.resource.LoginUser; import org.young.sso.sdk.resource.SsoResult; import org.young.sso.server.beans.IdInfo; import org.young.sso.server.controller.form.PasswordForgetForm; import org.young.sso.server.controller.form.ValidateForm; import org.young.sso.server.model.UserInfo; public interface UserInfoService extends BaseService<UserInfo, Long> { LoginUser poToLoginUser(UserInfo po); /** * 登录 * @param id * @return */ SsoResult signIn(IdInfo id); /** * 登录校验 * @param form * @return */ SsoResult validate(ValidateForm form); SsoResult sendCodeToPhone(LoginUser loginUser); SsoResult sendCodeToEmail(LoginUser loginUser); SsoResult forgetPassword(PasswordForgetForm form); SsoResult updatePassword(LoginUser loginUser, String code, String password); /** * check唯一性 * @param res * @param id * @param username * @param phone * @param email */ void checkExist(SsoResult res, Long userId, String username, String phone, String email); String generateTGT(LoginUser loginUser, String tgc); String generateRequestKey(String remoteAddr); long countRequestKey(String prefix); SsoResult checkRequestKey(String key, String remoteAddr); }
Java
UTF-8
2,214
2.734375
3
[]
no_license
package info.esblurock.reaction.chemconnect.core.base.contact; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Index; import info.esblurock.reaction.chemconnect.core.base.DatabaseObject; import info.esblurock.reaction.chemconnect.core.base.dataset.ChemConnectCompoundDataStructure; @SuppressWarnings("serial") @Entity public class ContactInfoData extends ChemConnectCompoundDataStructure { @Index String contactType; @Index String contact; public ContactInfoData() { super(); this.contactType = ""; this.contact = ""; } /** * @param identifier The id of contact info * @param owner The owner of contact info * @param access The accessibility of contact info * @param email The full email address * @param topSite The http address of the encompasing structure of the contact * @param hasSite The web-site associated with the contact */ public ContactInfoData(ChemConnectCompoundDataStructure obj, String contactType, String contact) { fill(obj,contactType,contact); } public void fill(ChemConnectCompoundDataStructure obj, String contactType, String contact) { super.fill(obj); this.contactType = contactType; this.contact = contact; } @Override public void fill(DatabaseObject object) { super.fill(object); ContactInfoData contact = (ContactInfoData) object; this.contactType = contact.getContactType(); this.contact = contact.getContact(); } public String getContactType() { return contactType; } public String getContact() { return contact; } public void setContactType(String contactType) { this.contactType = contactType; } public void setContact(String contact) { this.contact = contact; } public String toString() { return toString(""); } public String toString(String prefix) { StringBuilder builder = new StringBuilder(); builder.append(super.toString(prefix)); builder.append(prefix + "contactType: " + contactType + "\n"); builder.append(prefix + "contact: " + contact + "\n"); return builder.toString(); } }
Java
UTF-8
1,363
3.484375
3
[ "MIT" ]
permissive
package com.holub; enum Currency{ USD, EURO; public double conversionRateTo(Currency target){ return 1.0; } } public class Money{ private double value; private Currency currency; public Money(double value, Currency currency){ this.value = value; this.currency = currency; } private double normalized(){ return currency == Currency.USD ? value : value * currency.conversionRateTo(Currency.USD); } public boolean isGreaterThan(Money op){ return (normalized() > op.normalized()); } } class Test{ private static void dispenseFunds(Money amount){ /*...*/ } private static void test(){ Money balance = new Money(1.0, Currency.EURO); Money request = new Money(3.0, Currency.USD); if(balance.isGreaterThan(request)){ dispenseFunds(request); } /* if(balance.getValue() > request.getValue()){ dispenseFunds(request); } */ /* double normalizedBalance = balance.getValue() * balance.getCurrency().conversionRateTo(Currency.USD); double normalizedRequest = request.getValue() * request.getCurrency().conversionRateTo(Currency.USD); if(normalizedBalance > normalizedRequest) dispenseFunds(request); */ } }
Markdown
UTF-8
1,155
3.953125
4
[]
no_license
# 我所理解的js扁平化(拍平)数组的方法有哪些 **需求**: 将给定的数组拍平,即变成一维数组,你能想到哪几种方法。 ```js var arr = [1,2,[3,[4,5,[6]],7],8]; ``` ```js //第一种处理方法 var tempArr = JSON.stringify(arr).split(''); var arrFlat = []; for(var i=0;i<tempArr.length;i++){ if(!isNaN(Number(tempArr[i]))) arrFlat.push(Number(tempArr[i])) } ``` ```js //第二种方法 var arrFlat = arr.flat(Infinity) ``` ```js //第三种方法 var arrFlat = arr.join(',').split(',').map(item => Number(item)); ``` ```js //第四种方法 var arrFlat = []; function flatFn(ary){ for(var i=0,l=ary.length;i<l;i++){ if(Array.isArray(ary[i])){ flatFn(ary[i]) }else{ arrFlat.push(ary[i]) } } } ``` ```js //第五种方法 while(arr.find(item => Array.isArray(item))){ arr = [].concat(...arr) } ``` ```js //第六种方法 function arrFlat(arr){ return arr.reduce(function fn(pre,cur){ return pre.concat(Array.isArray(cur)?arrFlat(cur):cur) },[]) } ``` 利用数组的map方法我试过了,基本上跟遍历差不多。<br /> 欢迎评论指出不足以及更多方法。
Java
UTF-8
2,032
2.703125
3
[]
no_license
package com.hepolite.racialtraits.ability; import org.bukkit.ChatColor; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import com.hepolite.coreutility.apis.damage.Damage; import com.hepolite.coreutility.apis.damage.DamageAPI; import com.hepolite.coreutility.apis.damage.DamageType; import com.hepolite.coreutility.apis.entites.EntityLocater.ConeLocater; import com.hepolite.racialtraits.ability.components.ComponentResourceCost; import com.hepolite.racialtraits.race.Race; import com.sucy.skill.api.player.PlayerSkill; public class AbilityKick extends Ability { private final ComponentResourceCost resourceCost; public AbilityKick(Race race) { super(race, "Kick"); resourceCost = new ComponentResourceCost(race.getResource()); } @Override public final boolean onCast(Player player, PlayerSkill skill) { int level = skill.getLevel(); float angle = getSettings().getFloat("Level " + level + ".angle"); float radius = getSettings().getFloat("Level " + level + ".radius"); float damage = getSettings().getFloat("Level " + level + ".damage"); float knockback = getSettings().getFloat("Level " + level + ".knockback"); float lift = getSettings().getFloat("Level " + level + ".lift"); float cost = getSettings().getFloat("Level " + level + ".cost"); if (!resourceCost.has(player, cost)) { player.sendMessage(ChatColor.RED + "You are too tired to do this!"); return false; } ConeLocater cone = new ConeLocater(player.getLocation(), player.getEyeLocation() .getDirection().multiply(-radius), angle); boolean hitSomething = false; for (LivingEntity entity : cone.getUnobstructed(player.getEyeLocation(), false, LivingEntity.class)) { if (entity == player) continue; if (DamageAPI.damage(entity, player, new Damage(DamageType.BLUNT, damage))) { DamageAPI.applyKnockback(entity, player.getLocation(), knockback, lift); hitSomething = true; } } if (hitSomething) resourceCost.consume(player, cost); return hitSomething; } }
PHP
UTF-8
553
3.484375
3
[]
no_license
<?php //Super class qui sera appliqué par les classes qui l'etendent abstract class Stats { //Initialisation de nos propriétes qui a une visibilité protected protected $nom = "test"; protected $pdv = 0; protected $atk = 0; protected $def = 0; //Initialisation de notre accesseur qui retourne notre propriéte nom public function getNom(){ return $this->nom; } //Initialisation de notre accesseur qui permet d'attribuer une valeur //à notre propriété nom public function setNom($nom){ $this->nom = $nom; } }
Python
UTF-8
812
3
3
[]
no_license
import sys stdin = sys.stdin ixs = range(4) for i in xrange(int(stdin.readline())): print "Case #%i: " % (i+1), rows = [stdin.readline()[:4] for i in ixs] cols = [[row[i] for row in rows] for i in ixs] diags = [ [rows[i][i] for i in ixs], [rows[i][3-i] for i in ixs] ] notdone = False for row in rows + cols + diags: x = None for t in row: if t == '.': notdone = True break elif t == 'T': continue elif x is not None and x != t: break else: x = t else: print x, "won" break else: if notdone: print "Game has not completed" else: print "Draw" stdin.readline()
Java
UTF-8
1,711
2.796875
3
[]
no_license
package pro.woz.swarm.clients.producers; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; /** * Sends messages to kafka in round robin manner regarding partitions. * * @author pwozniak */ public class SimpleMessagesProducer { public static final Logger LOGGER = LogManager.getLogger(SimpleMessagesProducer.class.getName()); private Producer producer; private String topicName; public SimpleMessagesProducer(Producer kafkaProducer, String topicName) { this.producer = kafkaProducer; this.topicName = topicName; } public void produceMessage(String key, String value) throws ExecutionException, InterruptedException { ProducerRecord<String, String> message = new ProducerRecord<>(topicName, key, value); sendMessage(message); } public void produceMessage(String value) throws ExecutionException, InterruptedException { ProducerRecord<String, String> message = new ProducerRecord<>(topicName, value); sendMessage(message); } private void sendMessage(ProducerRecord<String, String> message) throws ExecutionException, InterruptedException { Future<RecordMetadata> meta = producer.send(message); RecordMetadata recordMetadata = meta.get(); LOGGER.info("Message sent to broker. Topic " + recordMetadata.topic() + ", partition: " + recordMetadata.partition() + ", offset: " + recordMetadata.offset()); } }
Java
UTF-8
426
2.453125
2
[]
no_license
package framework.exceptions; public class ServiceNotFoundException extends Exception { private static final long serialVersionUID = 5650216591219543299L; private String service; public ServiceNotFoundException(String msg, String resourceName) { super(msg); setService(resourceName); } public void setService(String service) { this.service = service; } public String getService() { return service; } }
Java
UTF-8
147
1.929688
2
[]
no_license
package service; import model.Person; public interface EditService { public Person getPerson(); public void savePerson(Person person); }
Markdown
UTF-8
3,131
3.34375
3
[]
no_license
### 2019 年 10 月 14 日-2019 年 10 月 18 日的作业答案 #### 1. 计算机包含哪些部分,至少写出 2 个,不局限分类方式。 #### A1CN1. 软件和硬件 #### A1EN1. Software and Hardware #### A1CN2. 控制器,运算器,存储器,输入设备,输出设备 #### A1EN2. Control Unit, Arithmetical Unit, Memory Unit, Input Devices, Output Devices #### A1CN3. 系统和应用 #### A1EN3. System and Application #### A1CN4. 中央处理器,随机存取内存/内存,只读内存/硬盘,显卡,主板,声卡,等等 #### A1EN4. Central Processing Unit (CPU), Random Access Memory (RAM), Read-Only Memory (ROM)/Hard Disk, Video Card/Graphics Card, Motherboard, Sound Card/Audio Card, etc #### 2. 目前常见的计算机位数/字长有哪些?他们的区别是什么? #### A2CN. 家用机:32 位,64 位;服务器:128 位,256 位,512 位,等等;位数/字长指的是计算机一次性可以处理/读取的数据宽度,所以他们的区别就是位数越大的计算机处理性能越好,因为一次性处理的数据量提升了。 #### A2EN. Personal Computer: 32 Bit, 64 Bit; Server: 128 Bit, 256 Bit, 512 Bit, etc; Bit Number/ Byte Length is the width of the data which a computer can process once so the bigger bit number means the better performance of the computer. #### 扩展: 32 位系统中最大内存是 4GB。请给出原因。 #### Extension: The max memory is 4GB in 32-bit system. Please give the reason. #### ExtACN: 内存的每个字节都需要被寻址,所以内存的最小单位是字节。1 字节是 8 位。所以计算公式就是 (2^32) × 8 位 = 2^32 字节 = 2^22 千比特 = 2^12 兆比特 = 2^2 吉比特 = 4 吉比特 #### ExtAEN: Every byte of memory needs to be addressed so the min unit of memory is byte. A byte is 8 bit. So the formula is (2^32) × 8 bit = 2^32 byte = 2^22 kilobyte(KB) = 2^12 megabyte(MB) = 2^2 gigabyte(GB) = 4 gigabyte(GB) #### 3. 常见的计算机进制有哪些?至少讲出 2 个。写出任意两个之间转换的计算方法。现实生活中人类使用的进制是什么,同时自己设计一个进制以及它和该进制之间的转换方法,可类比常见进制。 #### A3CN: 2 进制,8 进制,10 进制,16 进制。最简单通用转换方式是 A 进制->10 进制->B 进制。10 进制。 #### A3EN: Binary Number System, Octonary Number System, Decimal Number System, Hexadecimal Number System. The simplest way is convert A number system to decimal number system and then convert decimal number system to B number system. #### 4. 了解常见的解释型编程语言和编译型编程语言,每个类别至少写出 3 个。C 语言属于哪一类?这种类型有何优缺点? #### A4CN: 解释型:Javascript,Python,Ruby。编译型:C,C++,Java,Golang,Swift,Kotlin,Dart。编译型。优点:性能好。缺点:不利于调试。 #### A4EN: Interpreted Language: Javascript, Python, Ruby. Compiled Language: C, C++, Java, Golang, Swift, Kotlin, Dart. Compiled Language. Advantage: Best Performance. Disadvantage: Poor In Debug
C#
UTF-8
281
2.921875
3
[ "MIT" ]
permissive
using System; namespace T { public class Test { public static int Main () { int i = 12; object o = i; if (i.ToString () != "12") return 1; if (((Int32)o).ToString () != "12") return 2; if (o.ToString () != "12") return 3; return 0; } } }
Python
UTF-8
7,002
2.921875
3
[ "MIT" ]
permissive
#!/usr/bin/python ############################################################################### # # This script generates dihedral populations of passed columns in the # rotamer datafile. It also parses the survival probabilities of dunking states # and outputs histograms of dunking survival. The name is kind of a lie # since it makes 2D histograms as well, but I didn't feel like changing my # naming convention. # # Example: For 10-column data with this type (described elsewhere): # 24.0 170.2 63.7 -74.5 -74.4 -143.9 -88.4 -143.6 -73.7 10.0 # 25.0 157.4 78.0 -88.5 -73.3 -144.4 -73.7 -151.2 -55.1 10.0 # # The following command would remove 2000 lines from the input # and produce a large number of 1D Histograms to be plotted # in an external plotting program: # python Rotamer_Histograms.py -f f1.out f2.out -t 9 # -x1 0 2 3 4 -x2 1 3 4 5 # -remove 2000 # # By Chris Ing, 2013 for Python 2.7 # ############################################################################### from argparse import ArgumentParser from numpy import histogram, histogram2d, log from ChannelAnalysis.RotamerAnalysis.Preprocessor import * from collections import defaultdict # This returns the sort_column as a time series, useful # for making scatterplot time series of ionic positions. def compute_dihedral_timeseries(data_lines, dihedral_cols, traj_col, prefix=None): # These are dictionaries of dict where the key is the traj_number # and the subdict is res_number and the value is a LIST of dihedral vals, # or associated time values in the case of the associated time_per_traj dihedral_per_traj = defaultdict(dict) time_per_traj = defaultdict(dict) dihedral_vals = [] for line in data_lines: traj_id = line[traj_col] for res_id, col in enumerate(dihedral_cols): if res_id not in dihedral_per_traj[traj_id]: dihedral_per_traj[traj_id][res_id] = [line[col]] time_per_traj[traj_id][res_id] = [line[0]] else: dihedral_per_traj[traj_id][res_id].append(line[col]) time_per_traj[traj_id][res_id].append(line[0]) return (dict(dihedral_per_traj), dict(time_per_traj)) # This writes chi1 or chi2 population densities in 1D # (kind of a weaker version of write_rotamer_rotamer_histogram below) # Note that it's unnormalized, but that's easy to change. def compute_rotamer_histogram(data_lines, dihedral_cols, histmin=0, histmax=360, histbins=250, prefix=None): dihedral_vals = [] for line in data_lines: dihedral_vals.extend([line[col] for col in dihedral_cols]) histo, edges = histogram(dihedral_vals, range=[histmin, histmax], bins=histbins, normed=False) if prefix != None: with open(prefix+"_dihedrals","w") as out: for xval, yval in zip(edges,histo): out.write(str(xval)+" "+str(yval)+"\n") return (histo, edges) # This writes Chi1 vs Chi2 distributions (or vice versa) in the form of a # 2D histogram. def compute_rotamer_rotamer_histogram(data_lines, chi1_cols, chi2_cols, kBT=0.596, max_eng=7.0, histmin=0, histmax=360, histbins=180, prefix=None): dihedral_vals_x = [] dihedral_vals_y = [] for line in data_lines: dihedral_vals_x.extend([line[col] for col in chi1_cols]) dihedral_vals_y.extend([line[col] for col in chi2_cols]) histo, xedges, yedges = histogram2d(dihedral_vals_x, dihedral_vals_y, range=[[histmin,histmax], [histmin,histmax]], bins=[histbins,histbins], normed=True) # Since we're taking the log, remove all 0.0 values. low_val_indices = histo <= 0.0 high_val_indices = histo > 0.0 histo[low_val_indices] = max_eng histo[high_val_indices] = -kBT*log(histo[high_val_indices]) # Everything must be shifted such that 0 is the true minimum value. min_val = min(histo[high_val_indices]) histo[high_val_indices] = histo[high_val_indices] - abs(min_val) if prefix != None: with open(prefix + "_rotamer","w") as out: for xval, yval, zval in zip(xedges, yedges, histo): out.write(str(xval) + " " + str(yval) + " " + str(zval) + "\n") return (histo, xedges, yedges) if __name__ == '__main__': parser = ArgumentParser( description='This script parses dihedral angles for multiple subunits, \ preparing input for subsequent rotameric analysis.') parser.add_argument( '-f', dest='filenames', type=str, nargs="+", required=True, help='a filename of coordination data from MDAnalysis trajectory data') parser.add_argument( '-x1', dest='chi1_cols', type=int, nargs="+", required=True, help='column numbers in the input that denote chi1 values') parser.add_argument( '-x2', dest='chi2_cols', type=int, nargs="+", required=True, help='column numbers in the input that denote chi2 values') parser.add_argument( '-remove', dest='remove_frames', type=int, default=0, help='this is a number of frames to remove from the start of the data') parser.add_argument( '-div', dest='dividers', type=float, nargs="+", default=[180], help='slices in angle space that label dunking states (<180 = 0, >180 = 1') parser.add_argument( '-t', dest='traj_col', type=int, default=11, help='a zero inclusive column number that contains the run number') parser.add_argument( '-o', dest='outfile', type=str, default=None, help='the file to output the sorted padding output of all input files') args = parser.parse_args() data_f_dunk = process_rotamers(filenames=args.filenames, chi1_cols=args.chi1_cols, chi2_cols=args.chi2_cols, remove_frames=args.remove_frames, traj_col=args.traj_col) print "Writing 1D histograms chi2 population" chi1s = compute_rotamer_histogram(data_f_dunk, args.chi1_cols, prefix=args.outfile+"_chi1_") chi2s = compute_rotamer_histogram(data_f_dunk, args.chi2_cols, prefix=args.outfile+"_chi2_") print "Writing 2D histograms chi2 vs chi1 population" chi1_chi2s = compute_rotamer_rotamer_histogram(data_f_dunk, args.chi1_cols, args.chi2_cols, prefix=args.outfile+"_chi1_chi2_")
Java
WINDOWS-1250
822
3.375
3
[]
no_license
public class cadenas{ public static void main(String[] args){ String telefono = "72-25-14-23-62"; int indice1 = telefono.indexOf('1'); System.out.println("El ndice del carcter buscado es: "+ indice1); int indice2 = telefono.indexOf('-', 4); System.out.println("El segundo ndice es: "+indice2); System.out.println(telefono.charAt(8)); System.out.println(telefono.charAt(13)); String subcadena1 = telefono.substring(0, 5); String subcadena2 = telefono.substring(8, 12); String subcadena3 = telefono.substring(7); System.out.println(subcadena1); System.out.println(subcadena2); System.out.println(subcadena3); String cambio = telefono.replace("-","@"); System.out.println(cambio); String reemplazo = telefono.replaceFirst("72-2","Toluca"); System.out.println(reemplazo); } }
JavaScript
UTF-8
2,033
2.78125
3
[]
no_license
var intervalID; $("#registerSubmit").on("click", function () { console.log("Pressed submit button!"); let email = $(".email").val() ; let password = $(".password").val(); var text = '{ "email" : "' + email + '", "password" : "' + password + '"}'; console.log("Trying register with email: " + email); $.ajax({ method: "POST", // Declare request type url: getEndpoint() + "/idm/register", datatype: "json", contentType:"application/json", data: text, success: handleRegisterResult, // Bind event handler as a success callback }); }); function handleRegisterResult(res, status, xhr) { console.log("res = " + res); console.log("status = " + status); console.log("xhr = " + xhr.getAllResponseHeaders()); let transactionID = xhr.getResponseHeader("transactionID"); let delay = xhr.getResponseHeader("requestDelay"); console.log("transactionID = " + transactionID); console.log("requestDelay = " + delay); let requestDelay = parseInt(delay, 10); intervalID = setInterval(getRegisterResponse, requestDelay, transactionID); } function getRegisterResponse(transactionID) { console.log("Trying to retrieve data tId: " + transactionID); let resultDom = $('#result'); resultDom.empty(); $.ajax({ method: "GET", url: getEndpoint() + "/report", headers:{"transactionID":transactionID}, datatype:"json", success: function(json, resultCode, xhr){ if(resultCode == "nocontent"){ console.log("The status was 204"); return; } else { console.log("Status = " + resultCode); let res2 = json.message; console.log("json message = " + res2); let rowHTML = "<p>"; rowHTML += res2; rowHTML += "</p>"; resultDom.append(rowHTML); clearInterval(intervalID); } } }); }
PHP
UTF-8
4,243
2.546875
3
[]
no_license
<?php include('mysql.php'); date_default_timezone_set('UTC'); $req_liste_inscrit = $bdd->prepare('SELECT id, caem FROM inscrits WHERE val_email_j = ? AND valeur_inscrit = ?'); $req_liste_inscrit->execute(array(1, 1)); $donnees_liste_inscrit = $req_liste_inscrit->fetch(); $jour = time() - 60*60*18; $jour1 = time() - 60*60*16; $joursuivant = $jour + 60*60*24; $joursuivant1 = $jour1 + 60*60*24; if(isset($donnees_liste_inscrit['id'])) { do { $n = 0; $m = 0; $req_liste_sortie = $bdd->prepare('SELECT id_sortie FROM inscrits_sortie WHERE id_membre = ? AND valeur_membre < ?'); $req_liste_sortie->execute(array($donnees_liste_inscrit['id'], 3)); $donnees_liste_sortie = $req_liste_sortie->fetch(); if(isset($donnees_liste_sortie['id_sortie'])) { do { $req_liste_donnees_s = $bdd->prepare('SELECT date, heure, s_privative, valeur_sortie FROM sortie WHERE id_sortie = ?'); $req_liste_donnees_s->execute(array($donnees_liste_sortie['id_sortie'])); $donnees_s = $req_liste_donnees_s->fetch(); if($donnees_s['valeur_sortie'] == 0) { if($donnees_s['s_privative'] == 1) { if($donnees_s['date'] > $jour AND $donnees_s['date'] < $jour1) { if($donnees_s['heure'] >= 17) { $n++; } }elseif($donnees_s['date'] > $joursuivant AND $donnees_s['date'] < $joursuivant1) { if($donnees_s['heure'] < 17) { $n++; } } }elseif($donnees_s['s_privative'] == 2) { if($donnees_s['date'] > $jour AND $donnees_s['date'] < $jour1) { if($donnees_s['heure'] >= 17) { $m++; } }elseif($donnees_s['date'] > $joursuivant AND $donnees_s['date'] < $joursuivant1) { if($donnees_s['heure'] < 17) { $m++; } } } } }while($donnees_liste_sortie = $req_liste_sortie->fetch()); } $req_liste_donnees_spu_1 = $bdd->prepare('SELECT date, heure FROM sortie WHERE date < ? AND s_privative = ? AND valeur_sortie = ?'); $req_liste_donnees_spu_1->execute(array($jour1,2,0)); $donnees_spu_1 = $req_liste_donnees_spu_1->fetch(); $spu1 = 0; if(isset($donnees_spu_1['date'])) { do { if($donnees_spu_1['date'] > $jour) { if($donnees_spu_1['heure'] >= 17) { $spu1++; } } }while($donnees_spu_1 = $req_liste_donnees_spu_1->fetch()); } $req_liste_donnees_spu_2 = $bdd->prepare('SELECT date, heure FROM sortie WHERE date < ? AND s_privative = ? AND valeur_sortie = ?'); $req_liste_donnees_spu_2->execute(array($joursuivant1,2,0)); $donnees_spu_2 = $req_liste_donnees_spu_2->fetch(); $spu2 = 0; if(isset($donnees_spu_2['date'])) { do { if($donnees_spu_2['date'] > $joursuivant) { if($donnees_spu_1['heure'] < 17) { $spu2++; } } }while($donnees_spu_2 = $req_liste_donnees_spu_2->fetch()); } $spu = $spu1+ $spu2; if($spu == 0) { $m = "aucune sortie publique aura lieu."; }elseif($spu == 1) { if($m == 0) { $m = "une sortie publique aura lieu."; }elseif($m == 1) { $m = "une sortie publique aura lieu, et l'organisateur vous a invité."; }else { $m = "une sortie publique aura lieu."; } }else { if($m == 0) { $m = $spu." sorties publiques auront lieu."; }elseif($m == 1) { $m = $spu." sorties publiques auront lieu, et vous êtes invité à l'une d'entre elles."; }else { $m = $spu." sorties publiques auront lieu, et vous êtes invité à " .$m. " d'entre elles."; } } if($n == 0) { $n = "aucune sortie privée vous attend."; }elseif($n == 1) { $n = "une sortie privée vous attend."; }else { $n = $n." sorties privées vous attendent."; } $to = $donnees_liste_inscrit['caem']; $subject = "Annonce des prochaines sorties sur Les Nouveaux Arrivants"; $message = "Dans les prochaines 24h, " .$m. " Et, en ce qui concerne les sorties privées, " .$n. " N'hésitez pas à proposer des sorties, c'est gratuit ! Cliquez sur le lien suivant pour vous connecter: https://www.lesnouveauxarrivants.fr. Bonne soirée !"; $message = wordwrap($message, 70, "\r\n", true); }while($donnees_liste_inscrit = $req_liste_inscrit->fetch()); } ?>
JavaScript
UTF-8
2,931
2.59375
3
[ "MIT" ]
permissive
/** * Created by yinziwei on 2018/4/7. */ function enterCerticateDatil(id) { var data = {}; data.certificateId = id; $.ajax({ type:"POST", url:"/certificate/certificateOnclick/certificateDetail", data:JSON.stringify(data), contentType:"application/json", dataType:"json", success:function (data) { console.log(data); window.parent.location.href = "index3.html" } }) } function enterCollegeDatil(id) { var data = {}; data.collegeId = id; $.ajax({ type:"POST", url:"/certificate/collegeDirection/collegeDirectionDetail", //这个其实要访问certificate表, data:JSON.stringify(data), contentType:"application/json", dataType:"json", success:function (data) { console.log(data); window.parent.location.href = "index2.html" } }) } function changeCollegeDatil(id){ var data = {}; data.collegeId = id; $.ajax({ type:"POST", url:"/certificate/certificatePush/certificatePhoto", //这个其实要访问certificate表, data:JSON.stringify(data), contentType:"application/json", dataType:"json", success:function (data) { console.log(data); $("#majordetail").append( " <li class=\"direction-0 floatLeft \" ><a href=\"#\">全部</a></li>") //这里的全部是否被选中,会根据上个页面传过来的参数进行 $.each(data.data, function (i, item) { /*此时要限定出现的个数*/ $("#cerficatepush").append( "<div class=\"allcontent floatLeft\" onclick='enterCerticateDatil("+item.certificateId +")'>"+ " <a href=\"\">"+ " <div class=\"pic\">"+ " <img src="+item.certificatePhoto+" alt="+item.certificateTitle+" class=\"imgcontent\"/>"+ " <div class=\"label\">"+ /* " <label >ios</label>"+*/ //这个标签现在数据库中没有 " </div>"+ " </div>"+ " <div class=\"picontent\"><a href=\"#\">"+ " <span>" +item.certificateTitle+"</span>"+ " <p>"+item.introduceSmall+"</p>"+ " </a></div>"+ " </a>"+ " </div>" ) }); } }) } }
C#
UTF-8
517
3.0625
3
[]
no_license
using System; class Program { static void Main() { var thankyou = new List <string>() {"Thank", "You"} Console.WriteLine(string.Join("", Method()));. } //<sumary> //Methid create arrays //</summary> //<returns> An array. </returnd> static string[] Method() { string[] array = {"Thank", "You"}; int length = array.Length; Console.WriteLine(length); return array; } }
C++
UTF-8
1,397
3.625
4
[]
no_license
#include <iostream> #include <vector> class Solution { public: std::vector<std::vector<int>> permuteUnique(std::vector<int> &nums) { std::vector<int> base; std::sort(nums.begin(), nums.end()); return permute_recursively(nums, base); } std::vector<std::vector<int>> permute_recursively(std::vector<int>& nums, std::vector<int>& base) { std::vector<std::vector<int>> ret; if (nums.empty()) { return std::vector<std::vector<int>> {base}; } for (int i = 0 ; i < nums.size() ; i++) { if (i > 0 && nums[i] == nums[i-1]) { continue; } std::vector<int> next_base(base); next_base.push_back(nums[i]); std::vector<int> next_nums; for (int j = 0 ; j < nums.size() ; j++) { if (j != i) { next_nums.push_back(nums[j]); } } auto list = permute_recursively(next_nums, next_base); std::copy(list.begin(), list.end(), std::back_inserter(ret)); } return ret; } }; int main() { Solution s; std::vector<int> v = {0,0,0,1,9}; auto permutations = s.permuteUnique(v); for (auto p : permutations) { for (int n : p) { std::cout << n << " "; } std::cout << std::endl; } return 0; }
C#
UTF-8
2,668
2.765625
3
[]
no_license
using System.IO; using System.Linq; using CCDPlanetHelper.Database; using CCDPlanetHelper.Models; using Fooxboy.NucleusBot.Interfaces; using Fooxboy.NucleusBot.Models; using Newtonsoft.Json; namespace CCDPlanetHelper.Commands { public class RemindersCommand:INucleusCommand { public string Command => "reminders"; public string[] Aliases => new[] {"напоминания"}; public void Execute(Message msg, IMessageSenderService sender, IBot bot) { //проверка и подписка на рассылку, если пользователь пользуется ботом первый раз. var usrs1 = JsonConvert.DeserializeObject<MailingModel>(File.ReadAllText("MailingUsers.json")); if (usrs1.Users.All(u => u.UserId != msg.MessageVK.FromId.Value)) { usrs1.Users.Add(new ValuesMail() { IsActive = true, UserId = msg.MessageVK.FromId.Value }); File.WriteAllText("MailingUsers.json", JsonConvert.SerializeObject(usrs1)); } var text = "✔ Ваши напоминания:\n"; using (var db = new BotData()) { var reminders = db.Reminders.Where(r => r.UserId == msg.MessageVK.FromId.Value); foreach (var reminder in reminders) { var mouth = reminder.Mouth; var mouthStr = string.Empty; if (mouth == 1) mouthStr = "Января"; else if (mouth == 2) mouthStr = "Февраля"; else if (mouth == 3) mouthStr = "Марта"; else if (mouth == 4) mouthStr = "Апреля"; else if (mouth == 5) mouthStr = "Мая"; else if (mouth == 6) mouthStr = "Июня"; else if (mouth == 7) mouthStr = "Июля"; else if (mouth == 8) mouthStr = "Августа"; else if (mouth == 9) mouthStr = "Сентября"; else if (mouth == 10) mouthStr = "Октября"; else if (mouth == 11) mouthStr = "Ноября"; else if (mouth == 12) mouthStr = "Декабря"; text += $"▶ ID: {reminder.ReminderId}. {reminder.Day} {mouthStr} напомнить {reminder.Text} \n"; } } sender.Text(text, msg.ChatId); } public void Init(IBot bot, ILoggerService logger) { } } }
Java
UTF-8
3,071
2.09375
2
[]
no_license
package io.codelirium.examples.facade; import io.codelirium.examples.facade.controller.GreetingsController; import io.codelirium.examples.facade.controller.UrlMappings; import io.codelirium.examples.facade.service.FacadeService; import io.codelirium.examples.facade.service.GreetingsFacadeServiceImpl; import io.codelirium.examples.facade.service.core.EveningGreetingsServiceImpl; import io.codelirium.examples.facade.service.core.GreetingsService; import io.codelirium.examples.facade.service.core.MorningGreetingsServiceImpl; import io.codelirium.examples.facade.service.core.NightGreetingsServiceImpl; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) public class ApplicationControllerTests { private GreetingsController greetingsController; private FacadeService<List<String>> greetingsFacadeService; private GreetingsService morningGreetingsService; private GreetingsService eveningGreetingsService; private GreetingsService nightGreetingsService; private MockMvc mockMvc; @Before public void setUp() { morningGreetingsService = new MorningGreetingsServiceImpl(); eveningGreetingsService = new EveningGreetingsServiceImpl(); nightGreetingsService = new NightGreetingsServiceImpl(); greetingsFacadeService = new GreetingsFacadeServiceImpl(morningGreetingsService, eveningGreetingsService, nightGreetingsService); greetingsController = new GreetingsController(greetingsFacadeService); mockMvc = MockMvcBuilders.standaloneSetup(greetingsController).build(); } @Test public void testGreetingsControllerGetGreetingsIsOkWithContent() throws Exception { mockMvc.perform(get(UrlMappings.API_BASE_MAPPING + UrlMappings.API_GET_GREETINGS) .param("name", getGreetingName())) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.TEXT_PLAIN)) .andExpect(content().string(containsString(morningGreetingsService.getGreetings(getGreetingName())))) .andExpect(content().string(containsString(eveningGreetingsService.getGreetings(getGreetingName())))) .andExpect(content().string(containsString(nightGreetingsService.getGreetings(getGreetingName())))); } private String getGreetingName() { return "codelirium"; } }
C++
UTF-8
4,946
2.90625
3
[]
no_license
//Modified the starting code of a button from http://www.instructables.com/id/How-to-control-your-TV-with-an-Arduino/ //Tutorials and examples from https://www.arduino.cc/en/Tutorial/Button were used to help with the code int IRledPin = 13; // LED connected to digital pin 13 int buttonPin = 3; //Button connected to pin 3 //int delayNum[]={790,1680,740}; //initializes the array of the delay numbers --> these numbers are currently place holders //int pulseNum[]={450,760,940}; //initializes the array of the pulse numbers --> these numbers are currently place holders int favChannels [] = {4, 5}; int i = 0; //initializes the counter i to 0 int buttonState; //initializes the button reader variable struct channelSignals { long [][] four; long [][] five; } long four [2][5] = {{10000, 200, 300, 400, 500}, {100, 200, 300, 400, 500}}; //1st array is delays, 2nd array is pulses long five [2][5] = {{10000, 200, 300, 400, 500}, {100, 200, 300, 400, 500}}; // The setup() method runs once, when the sketch starts void setup() { // initialize the IR digital pin as an output: channelSignals signals = {four, five};//Modified the starting code of a button from http://www.instructables.com/id/How-to-control-your-TV-with-an-Arduino/ //Tutorials and examples from https://www.arduino.cc/en/Tutorial/Button were used to help with the code int IRledPin = 13; // LED connected to digital pin 13 int buttonPin = 3; //Button connected to pin 3 int channel1[]={740,1680,740}; //Channel Example int channel2[]={300,10,300,10,300}; //Channel Example 2 int channel3[]={100,100,100,100,100}; //Channel Example 3 int i=0; //initializes the counter i to 0 int buttonState; //initializes the button reader variable // The setup() method runs once, when the sketch starts void setup() { // initialize the IR digital pin as an output: pinMode(IRledPin, OUTPUT); pinMode(buttonPin, INPUT); digitalWrite(buttonPin, HIGH); Serial.begin(9600); } void loop() { buttonState=digitalRead(buttonPin); if(buttonState==LOW){ if(i==1){ for(int c = 0; c<sizeof(channel1); i++){ if(c%2==0){ pulseIR(channel1[c]); } else{ delayMicroseconds(channel1[c]); } } i++; } if(i==2){ for(int c = 0; c<sizeof(channel1); i++){ if(c%2==1){ pulseIR(channel2[c]); } else{ delayMicroseconds(channel2[c]); } } i++; } else{ for(int c = 0; c<sizeof(channel1); i++){ if(c%2==1){ pulseIR(channel3[c]); } else{ delayMicroseconds(channel3[c]); } } i=0; } } } // This procedure sends a 38KHz pulse to the IRledPin // for a certain # of microseconds. We'll use this whenever we need to send codes void pulseIR(long microsecs) { // we'll count down from the number of microseconds we are told to wait cli(); // this turns off any background interrupts while (microsecs > 0) { // 38 kHz is about 13 microseconds high and 13 microseconds low digitalWrite(IRledPin, HIGH); // this takes about 3 microseconds to happen delayMicroseconds(10); // hang out for 10 microseconds digitalWrite(IRledPin, LOW); // this also takes about 3 microseconds delayMicroseconds(10); // hang out for 10 microseconds // so 26 microseconds altogether microsecs -= 26; } sei(); // this turns them back on } pinMode(IRledPin, OUTPUT); pinMode(buttonPin, INPUT); digitalWrite(buttonPin, HIGH); Serial.begin(9600); } void loop() { } // This procedure sends a 38KHz pulse to the IRledPin // for a certain # of microseconds. We'll use this whenever we need to send codes void pulseIR(long microsecs) { // we'll count down from the number of microseconds we are told to wait cli(); // this turns off any background interrupts while (microsecs > 0) { // 38 kHz is about 13 microseconds high and 13 microseconds low digitalWrite(IRledPin, HIGH); // this takes about 3 microseconds to happen delayMicroseconds(10); // hang out for 10 microseconds digitalWrite(IRledPin, LOW); // this also takes about 3 microseconds delayMicroseconds(10); // hang out for 10 microseconds // so 26 microseconds altogether microsecs -= 26; } sei(); // this turns them back on } void favoriteLoop () { buttonState = digitalRead(buttonPin); if (buttonState == LOW) { if (i < sizeof(favChannels) - 1) { sendChannel(favChannels[i]); i++; } else { sendChannel(favChannels[i]); i = 0; } } } void sendChannel(int channel) { long [][] signal = channelSignals[channel]; for (int i = 0; i < sizeof(signal[0]); i++) { delayMicroseconds(signal[0][i]); pulseIR(signal[1][i]); } delay(100); }
Java
UTF-8
13,771
2.28125
2
[]
no_license
package by.epam.dao; import by.epam.entity.Company; import by.epam.entity.User; import by.epam.entity.UserHistory; import by.epam.entity.UserType; import by.epam.exception.DAOException; import by.epam.pool.ConnectionPool; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import org.apache.log4j.Logger; /** * UserDAO class is a DAO class for user db operations. * * @author Siarhei Huba. */ public class UserDAO extends AbstractDAO<User> { private final static Logger LOG = Logger.getLogger("UserDAO"); private final static ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("resources/mysqlStatements"); private String getUserQuery = RESOURCE_BUNDLE.getString("GET_USER_ENTITY"); private String getAdminInfo = RESOURCE_BUNDLE.getString("GET_ADMIN_ENTITY"); private String queryRegister = RESOURCE_BUNDLE.getString("REGISTER_COMMAND"); private String queryAddHRHEADInfo = RESOURCE_BUNDLE.getString("ADD_HRHEAD_INFO_COMMAND"); private String queryUpdateHrheadInfo = RESOURCE_BUNDLE.getString("UPDATE_HRHEAD_INFO"); private String queryUpdateHrheadCred = RESOURCE_BUNDLE.getString("UPDATE_HRHEAD_CRED"); private String queryGetUserId = RESOURCE_BUNDLE.getString("GET_USER_ID"); private String querySetNewPassword = RESOURCE_BUNDLE.getString("SET_NEW_PASS"); private String queryGetEmplBySSN = RESOURCE_BUNDLE.getString("GET_EMPLOYEE_BY_SSN"); private String queryGetEmplIdBySSN = RESOURCE_BUNDLE.getString("GET_EMPLOYEE_ID_BY_SSN"); private String queryGetEmplHistById = RESOURCE_BUNDLE.getString("GET_EMPLOYEE_HISTORY_BY_ID"); private String queryAddReview = RESOURCE_BUNDLE.getString("ADD_REVIEW"); private String queryGetHrByName = RESOURCE_BUNDLE.getString("GET_HR_BY_NAME"); private String queryGetHrById = RESOURCE_BUNDLE.getString("GET_HR_BY_ID"); private String queryAddEmployeeBySSN = RESOURCE_BUNDLE.getString("ADD_EMPLOYEE_BY_SSN"); private String getReviewsOfSingleHrById = RESOURCE_BUNDLE.getString("GET_REVIEWS_OF_SINGLE_HR_BY_ID"); private String getAVGReviewsOfSingleHrById = RESOURCE_BUNDLE.getString("GET_AVG_REVIEWS_OF_SINGLE_HR_BY_ID"); private String querySetCompanyId = RESOURCE_BUNDLE.getString("SET_COMPANY_TO_USER"); public UserDAO() { } /** * Login query checks for existence of login and password combinations and tries to get user information based * on this data * * @param params - params for login * @return {@link User} */ public User login(Object... params) throws DAOException { Connection conn = ConnectionPool.getInstance().getConnection(); User user; try (PreparedStatement ps = conn.prepareStatement(getUserQuery)) { ps.setObject(1, params[0]); //login ps.setObject(2, params[1]); //password try (ResultSet rs = ps.executeQuery()) { user = new User(); LOG.info("Login check point 1"); Company company; while (rs.next()) { UserType role = rs.getInt("role") == 0 ? UserType.ADMIN : UserType.HR; user.setId(rs.getInt("idLogin")); user.setType(role); LOG.info("Login check point 2"); if (role == UserType.HR) { user.setEmail(rs.getString("email")); user.setPass(rs.getString("pass")); user.setfName(rs.getString("fName")); user.setlName(rs.getString("lName")); LOG.info("Login check point 3"); company = new Company(); company.setName(rs.getString("name")); company.setId(rs.getInt("idCompany")); company.setNiche(rs.getString("niche")); LOG.info("Login check point 4"); company.setLocation(rs.getString("location")); company.setHeadcount(rs.getInt("headcount")); company.setCompanyOfficialId(rs.getInt("offCompId")); user.setCompany(company); LOG.info("Login check point 5"); } if (role == UserType.ADMIN) { String fullName = executeForSingleResult(getAdminInfo, user.getId()).toString(); user.setfName(fullName); LOG.info("Admin: " + user.getfName() + ", id:" + user.getId()); } } return user; } } catch (SQLException e) { LOG.info("SQL Exception during login entity retrieval from db" + e); throw new DAOException("User can't be found", e); } finally { ConnectionPool.getInstance().returnConnection(conn); } } public void setNewPassword(String login, String pass) throws DAOException { if ((updateQuery(querySetNewPassword, pass, login)) == 0) throw new DAOException("Such login does not exist"); } public void addNewEmployee(User user) throws DAOException { executeQuery(queryAddEmployeeBySSN); } private void registerUser(User user) throws DAOException { executeQuery(queryRegister, user.getEmail(), user.getPass()); } public void setUserIdByEmailAndPass(User user) throws DAOException { int userId = (int) executeForSingleResult(queryGetUserId, user.getEmail(), user.getPass()); user.setId(userId); } public void updateUserInfo(User user) throws DAOException { updateQuery(queryUpdateHrheadInfo, user.getfName(), user.getlName(), user.getCompany().getCompanyOfficialId(), user.getId()); updateQuery(queryUpdateHrheadCred, user.getEmail(), user.getId()); } private void addHrHeadInfo(User user) throws DAOException { updateQuery(queryAddHRHEADInfo, user.getId(), user.getfName(), user.getmName(), user.getlName()); } public void register(User user) throws DAOException { registerUser(user); LOG.info("New user registration is done, user login: " + user.getEmail()); setUserIdByEmailAndPass(user); addHrHeadInfo(user); LOG.info("New user is added:" + user.getEmail()); } private int getEmployeeIdBySSN(int SSN) throws DAOException { if (executeForSingleResult(queryGetEmplIdBySSN, SSN) == null) { return 0; } else return (int) executeForSingleResult(queryGetEmplIdBySSN, SSN); } public User getEmployeeBySSN(int SSN) throws DAOException { Connection conn = ConnectionPool.getInstance().getConnection(); User employee = new User(); try (PreparedStatement ps = conn.prepareStatement(queryGetEmplBySSN)) { ps.setInt(1, SSN); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { employee.setId(rs.getInt("idEmployee")); employee.setfName(rs.getString("fName")); employee.setlName(rs.getString("lName")); employee.setSSN(SSN); } } LOG.info("Employee " + employee.getfName() + " is retrieved from db."); } catch (SQLException e) { LOG.info("SQL Exception during getEmployeeBySSN method in UserDAO" + e); throw new DAOException("Can't get user Id by SSN", e); } finally { ConnectionPool.getInstance().returnConnection(conn); } return employee; } private List<User> getHrWithCompanyDataList(String query, Object... params) throws DAOException { Connection conn = ConnectionPool.getInstance().getConnection(); List<User> userList = new ArrayList<>(); User user; try (PreparedStatement ps = conn.prepareStatement(query)) { for (int i = 0; i < params.length; i++) { ps.setObject(i + 1, params[i]); LOG.info("param " + (i + 1) + " equals to: " + params[i]); } try (ResultSet rs = ps.executeQuery()) { Company company; while (rs.next()) { user = new User(); user.setId(rs.getInt("idHRhead")); user.setfName(rs.getString("fName")); user.setmName(rs.getString("mName")); user.setlName(rs.getString("lName")); company = new Company(); company.setName(rs.getString("name")); company.setId(rs.getInt("idCompany")); company.setNiche(rs.getString("niche")); company.setLocation(rs.getString("location")); company.setHeadcount(rs.getInt("headcount")); company.setCompanyOfficialId(rs.getInt("offCompId")); company.setId(rs.getInt("idCompany")); user.setCompany(company); userList.add(user); } } } catch (SQLException e) { LOG.info("SQL Exception during getHr method in UserDAO"); throw new DAOException("SQL Exception during getHr command execution", e); } finally { ConnectionPool.getInstance().returnConnection(conn); } return userList; } public User getEntityBySSN(int SSN) throws DAOException { User employee = getEmployeeBySSN(SSN); LOG.info("Passed getEntityBySSN in UserDAO, id: " + employee.getId()); List<UserHistory> userHistory = getReviews(queryGetEmplHistById, employee.getId()); for (UserHistory hist : userHistory) employee.addHistory(hist); return employee; } public void setCompanyId(Company company, User user) throws DAOException { updateQuery(querySetCompanyId, company.getId(), user.getId()); } public void registerEmployee(User employee) throws DAOException { updateQuery(queryAddEmployeeBySSN, employee.getfName(), employee.getlName(), employee.getmName(), employee.getSSN()); employee.setId(getEmployeeIdBySSN(employee.getSSN())); } public void addReview(User hrHead, User employee, UserHistory userHistory) throws DAOException { double aveRating = (userHistory.getRating1() + userHistory.getRating2() + userHistory.getRating3() + userHistory.getRating4() + userHistory.getRating5()) / 5.0; int getHireAgain = userHistory.getHireAgain(); Company company = hrHead.getCompany(); LOG.info("Company data: " + company); CompanyDAO companyDAO = new CompanyDAO(); int companyId = companyDAO.getCompanyIdByOfficialId(company.getCompanyOfficialId()); LOG.info("company id: " + companyId + ", hr head id: " + hrHead.getId()); updateQuery(queryAddReview, companyId, hrHead.getId(), employee.getId(), userHistory.getYearEmployed(), userHistory.getYearTerminated(), userHistory.getRating1(), userHistory.getRating2(), userHistory.getRating3(), userHistory.getRating4(), userHistory.getRating5(), aveRating, getHireAgain); } public User getHrById(int hrId) throws DAOException { User user; try { user = getHrWithCompanyDataList(queryGetHrById, hrId).get(0); } catch (IndexOutOfBoundsException e) { throw new DAOException("Data is empty"); } return user; } public List<User> getHrByName(String fName, String lName) throws DAOException { return getHrWithCompanyDataList(queryGetHrByName, fName, lName); } public List<Integer> getReviewsRateForHrById(int idHR) throws DAOException { Connection conn = ConnectionPool.getInstance().getConnection(); List<Integer> ratingList = new ArrayList<>(); try (PreparedStatement ps = conn.prepareStatement(getReviewsOfSingleHrById)) { ps.setInt(1, idHR); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { ratingList.add(rs.getInt("rating1")); ratingList.add(rs.getInt("rating2")); ratingList.add(rs.getInt("rating3")); ratingList.add(rs.getInt("rating4")); ratingList.add(rs.getInt("rating5")); } } } catch (SQLException e) { LOG.info("SQL Exception during getReviewsRateForHrById method in UserDAO"); throw new DAOException("SQL Exception during getReviewsRateForHrById command execution", e); } finally { ConnectionPool.getInstance().returnConnection(conn); } return ratingList; } public List<Double> getAVGReviewsRateForHrById(int idHR) throws DAOException { Connection conn = ConnectionPool.getInstance().getConnection(); List<Double> ratingAVGSList = new ArrayList<>(); try (PreparedStatement ps = conn.prepareStatement(getAVGReviewsOfSingleHrById)) { ps.setInt(1, idHR); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { ratingAVGSList.add(rs.getDouble("totalRating")); } } } catch (SQLException e) { LOG.info("SQL Exception during getAVGReviewsRateForHrById method in UserDAO"); throw new DAOException("SQL Exception during getAVGReviewsRateForHrById command execution", e); } finally { ConnectionPool.getInstance().returnConnection(conn); } return ratingAVGSList; } }
Java
UTF-8
255
2.765625
3
[]
no_license
class Test { public static void main(String[] args){ new Test().m(); } public void m(){ class Inner { public void sum(int x, int y){ System.out.println(x+y); } } Inner inner = new Inner(); inner.sum(1,2); inner.sum(2,3); } }
C++
UTF-8
1,373
3.609375
4
[]
no_license
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { ListNode *p, *q, *x; int i, rots; if (head == NULL || m == n) return head; if (m == 1) { rots = n - m - 1; p = q = head; for (i = 0; i < rots; ++i) p = p->next; head = p->next; p->next = head->next; head->next = q; p = head; } else { rots = n - m; p = head; for (i = 0; i < m - 2; ++i) p = p->next; q = p->next; } for (i = 0; i < rots; ++i) { x = p->next; p->next = q->next; q->next = p->next->next; p->next->next = x; } return head; } }; int main() { ListNode l1(1); ListNode l2(2); ListNode l3(3); ListNode l4(4); ListNode l5(5); l1.next = &l2; l2.next = &l3; l3.next = &l4; l4.next = &l5; l5.next = NULL; Solution s; ListNode *ret = s.reverseBetween(&l1, 1, 4); while (ret != NULL) { cout << ret->val << " "; ret = ret->next; } cout << endl; return 0; }
C#
UTF-8
1,722
3.015625
3
[]
no_license
// Copyright (c) 2014 Jonathan Magnan (http://zzzportal.com) // All rights reserved. // Licensed under MIT License (MIT) // License can be found here: https://zextensionmethods.codeplex.com/license using System.IO; public static partial class StringExtension { /// <summary> /// A string extension method that converts the @this to a directory information. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>@this as a DirectoryInfo.</returns> /// <example> /// <code> /// using System; /// using System.IO; /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// using Z.ExtensionMethods; /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_String_ToDirectoryInfo /// { /// [TestMethod] /// public void ToDirectoryInfo() /// { /// // Type /// string @this = AppDomain.CurrentDomain.BaseDirectory; /// /// // Examples /// DirectoryInfo value = @this.ToDirectoryInfo(); // return a DirectoryInfo from the specified path. /// /// // Unit Test /// Assert.AreEqual(@this, value.FullName); /// } /// } /// } /// </code> /// </example> public static DirectoryInfo ToDirectoryInfo(this string @this) { return new DirectoryInfo(@this); } }
C++
UTF-8
1,886
3.1875
3
[]
no_license
#pragma once #include <iostream> class Derived; class Base { public: friend class Test; Base() :m_Id(++s_CurrentId) { std::cout << "Base Constructor" << std::endl; } //Base(const Base& i_Other) = delete; virtual void Print() const { std::cout << "Base Print" << std::endl; } virtual void PrintInt(int i) const { std::cout << "Printing from Base INTEGER :" << i << std::endl; } void callPrivate() { PrintPrivate(); } virtual ~Base() { std::cout << "Base Destructor" << std::endl; } protected: void PrintProt() const { std::cout << "Pro" << std::endl; } private: virtual void PrintPrivate() // a private pure virtual function { std::cout << "Virtual Private in Base" << std::endl; } static int s_CurrentId; int m_Id; }; class Derived : public Base { friend class Test; public: Derived(const std::string& i_Name="Derived") :m_Name(i_Name) { std::cout << "Derived Constructor" << std::endl; } void Print() const override { std::cout << "Derived Print" << std::endl; } void PrintDer() { std::cout << "Name:" <<m_Name<< std::endl; } ~Derived() { std::cout << "Derived Destructor" << std::endl; } int* m_Array; private: void PrintPrivate() override //overiding a private virtual function { std::cout << "Virtual Private in Derived" << std::endl; } std::string m_Name; }; class DerivedDerived : public Derived { public: DerivedDerived(uint32_t i_Category=0):m_Cateogry(i_Category) { std::cout << "Derived Derived Constructor" << std::endl; } void Print() const override { std::cout << "DerivedDerived Print" << std::endl; } /*void PrintInt(int i) override { std::cout << "Printing from Derived Derived INTEGER :" << i << std::endl; }*/ ~DerivedDerived() { std::cout << "Derived Derived Destructor" << std::endl; } private: uint32_t m_Cateogry; };
PHP
UTF-8
5,203
2.59375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php class Spaces_model extends CI_Model { function __construct() { parent::__construct(); $this->load->database(); } function loadFeaturedSpaces() { return $this->db->query("SELECT * FROM areas_information WHERE featured = 1 ORDER BY area_name")->result_array(); } function loadAllSpaces() { return $this->db->query("SELECT * FROM areas_information ORDER BY area_name")->result_array(); } function fetchAreasCategory($spacesId) { return $this->db->query("SELECT area_name FROM areas_information WHERE area_id = ".$spacesId)->row_array()['area_name']; } function fetchDataForMaps($spacesId, $filters, $page = 1) { $distance = $filters['distanceFromUser']; $filters['category'] = $this->db->escape($filters['category']); // echo "<pre>".print_r($filters,1)."</pre>"; $distanceWhere = ' 1 = 1 '; $orderBy = ' '; if($filters['userLocation']['latitude'] < 0) $filters['userLocation']['latitude'] *= (-1); $distanceLatString = ''; $distanceLongString = ''; if($filters['userLocation']['latitude'] == 0){ $distanceWhere = ' 1 = 1 '; } else{ if($distance == '100') $distanceWhere = ' ABS(ABS(t.lat) - '.$filters['userLocation']['latitude'].') < 2 AND ABS(ABS(t.long) - '.$filters['userLocation']['longitude'].') < 2 '; else if($distance == '50') $distanceWhere = ' ABS(ABS(t.lat) - '.$filters['userLocation']['latitude'].') < 0.5 AND ABS(ABS(t.long) - '.$filters['userLocation']['longitude'].') < 0.5 '; else if($distance == '10') $distanceWhere = ' ABS(ABS(t.lat) - '.$filters['userLocation']['latitude'].') < 0.1 AND ABS(ABS(t.long) - '.$filters['userLocation']['longitude'].') < 0.1 '; else if ($distance == '5') $distanceWhere = ' ABS(ABS(t.lat) - '.$filters['userLocation']['latitude'].') < 0.05 AND ABS(ABS(t.long) - '.$filters['userLocation']['longitude'].') < 0.05 '; else if ($distance == '1') $distanceWhere = ' ABS(ABS(t.lat) - '.$filters['userLocation']['latitude'].') < 0.01 AND ABS(ABS(t.long) - '.$filters['userLocation']['longitude'].') < 0.01 '; $distanceLatString = ' ,ABS(t.lat) - '.$filters['userLocation']['latitude'].' as latString'; $distanceLongString = ' ,ABS(t.long) - '.$filters['userLocation']['longitude'].' as longString'; $orderBy = ' ORDER BY latString asc, longString asc '; } $categoryWhere = ' 1 = 1 '; if($filters['category'] != "'All'" && !empty($filters['category'])) $categoryWhere = ' os.OSCATEGORY = '.$filters['category'].' '; $tableName = $this->db->query("SELECT table_name FROM areas_information WHERE area_id = ".$spacesId)->row_array()['table_name']; $queryString = "SELECT t.*, os.OSCATEGORY ".$distanceLatString.$distanceLongString." FROM ".$tableName." t LEFT OUTER JOIN open_space os ON os.lat = t.lat AND os.long = t.long WHERE ".$categoryWhere." AND ".$distanceWhere.$orderBy."LIMIT ".(($page-1)*10).",10"; // echo $queryString;die(); return $this->db->query($queryString)->result_array(); // echo "<pre>".print_r($this->db->query($queryString)->result_array(),1);die(); } function fetchPageCount($spacesId, $filters) { $distance = $filters['distanceFromUser']; $filters['category'] = $this->db->escape($filters['category']); $distanceWhere = ' 1 = 1 '; if($distance == '100') $distanceWhere = ' ABS(t.lat - '.$filters['userLocation']['latitude'].') < 2 AND ABS(t.long - '.$filters['userLocation']['longitude'].') < 2 '; else if($distance == '50') $distanceWhere = ' ABS(ABS(t.lat) - '.$filters['userLocation']['latitude'].') < 0.5 AND ABS(ABS(t.long) - '.$filters['userLocation']['longitude'].') < 0.5 '; else if($distance == '10') $distanceWhere = ' ABS(t.lat - '.$filters['userLocation']['latitude'].') < 0.1 AND ABS(t.long - '.$filters['userLocation']['longitude'].') < 0.1 '; else if ($distance == '5') $distanceWhere = ' ABS(t.lat - '.$filters['userLocation']['latitude'].') < 0.05 AND ABS(t.long - '.$filters['userLocation']['longitude'].') < 0.05 '; else if ($distance == '1') $distanceWhere = ' ABS(t.lat - '.$filters['userLocation']['latitude'].') < 0.01 AND ABS(t.long - '.$filters['userLocation']['longitude'].') < 0.01 '; $categoryWhere = ' 1 = 1 '; if($filters['category'] != "'All'" && !empty($filters['category'])) $categoryWhere = ' os.OSCATEGORY = '.$filters['category'].' '; $tableName = $this->db->query("SELECT table_name FROM areas_information WHERE area_id = ".$spacesId)->row_array()['table_name']; $queryString = "SELECT count(*) as c FROM ".$tableName." t LEFT OUTER JOIN open_space os ON os.lat = t.lat AND os.long = t.long WHERE ".$categoryWhere." AND ".$distanceWhere; return $this->db->query($queryString)->row_array()['c']; } }
Java
UTF-8
668
1.953125
2
[]
no_license
package com.site.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.site.core.base.AbstractManagerImpl; import com.site.core.mybatis.Dao; import com.site.dao.PosTPayflowDao; import com.site.entity.PosTPayflow; import com.site.service.PosTPayflowService; /** * 对象功能:PosTPayflow Service Impl 对象 * 开发公司:SZUNIC * 开发人员:LZM */ @Service("PosTPayflowService") public class PosTPayflowServiceImpl extends AbstractManagerImpl<Long, PosTPayflow> implements PosTPayflowService { @Resource PosTPayflowDao dao; @Override protected Dao<Long, PosTPayflow> getDao() { return dao; } }
Java
UTF-8
2,995
2.796875
3
[]
no_license
package org.test.junit; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class EmpParamTests { static EmpBussinessLogic empLogic = new EmpBussinessLogic(); /** The monthly salary. */ private final double monthlySalary; /** The expected yearly salary. */ private final double expectedYearlySalary; /** The expected appraisal. */ private final double expectedAppraisal; enum TYPE {YES, NO}; /** The type. */ private TYPE type; /** * @param monthlySalary * @param expectedYearlySalary * @param expectedAppraisal */ public EmpParamTests(TYPE type, final double monthlySalary, final double expectedYearlySalary, final double expectedAppraisal) { super(); this.type = type; this.monthlySalary = monthlySalary; this.expectedYearlySalary = expectedYearlySalary; this.expectedAppraisal = expectedAppraisal; } @Parameters public static List<Object[]> data() { Object[][] object = new Object[][] { {TYPE.YES, 20000, 20000 * 12, 1000 }, { TYPE.YES, 2000, 2000 * 12, 500 }, {TYPE.YES, -20000, -20000 * 12, 500 }, {TYPE.YES, -2000, -2000 * 12, 500 }, {TYPE.YES, 0, 0 * 12, 500 }, {TYPE.YES, 0, 0 * 12, 500 }}; return Arrays.asList(object); } @BeforeClass public static void before() { empLogic = new EmpBussinessLogic(); } @AfterClass public static void after() { empLogic = null; } // @Test(expected = RuntimeException.class) // public void testCalculateAppraisalIfMonthlySalaryIsNull() { // Assume.assumeTrue(type == TYPE.NO); // EmployeeDetails empDetail = new EmployeeDetails(); // empDetail.setMonthlySalary((Double) null); // Double result = empLogic.calculateAppraisal(empDetail); // } @Test public void calculateAppraisal_Zero_Salary() { //System.out.println("Before" + type); Assume.assumeTrue(type == TYPE.NO); System.out.println("After" + type); EmployeeDetails empDetail = new EmployeeDetails(); empDetail.setMonthlySalary(monthlySalary); double result = empLogic.calculateAppraisal(empDetail); System.out.println(result); assertEquals("Correct", expectedAppraisal, result, 0); } @Test public void calculateYearlySalary_Positive_salary() { EmployeeDetails empDetail = new EmployeeDetails(); empDetail.setMonthlySalary(monthlySalary); double result = empLogic.calculateYearlySalary(empDetail); System.out.println(result); assertEquals("Correct", expectedYearlySalary, result, 0); } }
JavaScript
UTF-8
1,335
3.015625
3
[]
no_license
const quotes = [ { quote: "Travel expands the mind and fills the gap1.", author: "Sheda Savage" }, { quote: "Travel expands the mind and fills the gap2.", author: "Sheda Savage" }, { quote: "Travel expands the mind and fills the gap3.", author: "Sheda Savage" }, { quote: "Travel expands the mind and fills the gap4.", author: "Sheda Savage" }, { quote: "Travel expands the mind and fills the gap5.", author: "Sheda Savage" }, { quote: "Travel expands the mind and fills the gap6.", author: "Sheda Savage" }, { quote: "Travel expands the mind and fills the gap7.", author: "Sheda Savage" }, { quote: "Travel expands the mind and fills the gap8.", author: "Sheda Savage" }, { quote: "Travel expands the mind and fills the gap9.", author: "Sheda Savage" }, { quote: "Travel expands the mind and fills the gap10.", author: "Sheda Savage" } ]; const quote = document.querySelector("#quote span:first-child"); const author = document.querySelector("#quote span:last-child"); // Math.round(1) // 반올림 const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)]; quote.innerText = todaysQuote.quote; author.innerText = `-${todaysQuote.author}-`;
Java
UTF-8
498
2.4375
2
[]
no_license
package com.huangpan; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; public class MyAdvice { public void mybefor(JoinPoint jp) { System.out.println("前..."); } public void myafer(JoinPoint jp) { System.out.println("后..."); } public Object myaround(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("前"); //手动执行目标方法 Object obj = joinPoint.proceed(); System.out.println("后"); return obj; } }
Java
UTF-8
1,663
2.640625
3
[]
no_license
package ca.judacribz.week5day1_test; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import java.util.Map; public class MainActivity extends AppCompatActivity { EditText etQ1, etQ2; TextView tvQ1, tvQ2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etQ1 = findViewById(R.id.etQ1); etQ2 = findViewById(R.id.etQ2); tvQ1 = findViewById(R.id.tvQ1); tvQ2 = findViewById(R.id.tvQ2); } public void encodeString(View view) { String str = checkEditText(etQ1); if (!str.isEmpty()) { tvQ1.setText(Algorithms.encodeString(str)); } } public void getFrequency(View view) { String str = checkEditText(etQ2); if (!str.isEmpty()) { tvQ2.setText(flattenMap(Algorithms.getCharFrequency(str))); } } String checkEditText(EditText et) { String str = et.getText().toString().trim(); if (str.isEmpty()) { et.setError("Error: Empty String"); } return str; } String flattenMap(Map<Character, Integer> map) { StringBuilder sb = new StringBuilder(); int val; for (char key : map.keySet()) { val = map.get(key); if (val != 0) { sb.append(key).append(": ").append(val).append("\n"); } } return sb.toString(); } }
Python
UTF-8
2,701
3.109375
3
[ "BSD-3-Clause" ]
permissive
""" Interpolation of an SVF generated by a function and 3 of its integral curves for given initial points computed with the scipy integration method. """ import copy import matplotlib.pyplot as plt import numpy as np from scipy.integrate import ode from calie.fields import compose as cp from calie.fields import generate_identities as gen_id # Function input: def function_1_bis(t, x): t = float(t); x = [float(y) for y in x] return list([0.5*x[1], -0.5 * x[0] + 0.8 * x[1]]) def function_1(t, x): # complex (conjugate) eigenvalues: spirals. t = float(t) x = [float(z) for z in x] a, b, c, d = 0.7, -3, 3, -0.4 alpha = 0.1 return alpha * (a*x[0] + b*x[1] + 30), alpha * (c*x[0] + d*x[1] - 15) if __name__ == '__main__': # Initialize the field with the function input: field_0 = np.zeros((20, 20, 1, 1, 2)) for ix in range(0, 20): for jy in range(0, 20): field_0[ix, jy, 0, 0, :] = function_1(1, [ix, jy]) x1 = 5.22 y1 = 1.2 print('ground truth = ' + str(function_1(1, [x1, y1]))) print('values interpolated nearest = ' + str(cp.one_point_interpolation( field_0, point=(x1, y1), method='nearest'))) print('values interpolated linear = ' + str(cp.one_point_interpolation( field_0, point=(x1, y1), method='linear'))) print('values interpolated cubic = ' + str(cp.one_point_interpolation( field_0, point=(x1, y1), method='cubic'))) # Vector field function: def vf(t, x): global field_0 return list(cp.one_point_interpolation(field_0, point=x, method='cubic')) t0, tEnd, dt = 0, 50, 0.5 ic = [[5, 7], [6, 8], [8, 8]] colors = ['r', 'b', 'g'] r = ode(vf).set_integrator('vode', method='bdf', max_step=dt) fig = plt.figure(num=1) ax = fig.add_subplot(111) # Plot integral curves for k in range(len(ic)): Y, T = [], [] r.set_initial_value(ic[k], t0).set_f_params() while r.successful() and r.t + dt < tEnd: r.integrate(r.t+dt) Y.append(r.y) S = np.array(np.real(Y)) ax.plot(S[:, 0], S[:, 1], color=colors[k], lw=1.25) # Plot vector field id_field = gen_id.id_eulerian_like(field_0) input_field_copy = copy.deepcopy(field_0) ax.quiver(id_field[..., 0, 0, 0], id_field[..., 0, 0, 1], input_field_copy[..., 0, 0, 0], input_field_copy[..., 0, 0, 1], linewidths=0.01, width=0.03, scale=1, scale_units='xy', units='xy', angles='xy', ) plt.xlim([0, 20]) plt.ylim([0, 20]) plt.xlabel(r"$x$") plt.ylabel(r"$y$") print('finish!') plt.show()
C++
UTF-8
761
2.890625
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> #include<math.h> using namespace std; int main() { vector<vector<int>> vect,vectf; cout<<"enter the capacity"; int x; cin>>x; for(int i=0;i<x;i++) { vector<int> vect1; for(int i=0;i<2;i++) { int temp; cin>>temp; vect1.push_back(temp); } vect.push_back(vect1); } int t=0; while(true) { if(t>x) break; cout<<t; if(vect[t][1]>vect[t+1][0]) { cout<<"["<<vect[t][0]<<","<<vect[t+1][1]<<"]"; t=t+2; } else{ cout<<"["<<vect[t][0]<<","<<vect[t][1]<<"]"; t++; } } }
Ruby
UTF-8
122
2.609375
3
[]
no_license
# frozen_string_literal: true # Gigasecond time from X class Gigasecond def self.from(time) time + 10**9 end end
C
UTF-8
473
3.25
3
[]
no_license
/** Gabiel Augusto Requena dos Reis - 16.2.8105 Sistemas de informacao - CSI030 */ #include <stdio.h> int main(void){ float a,b; printf("Insira o valor da base do retangulo: "); scanf("%f",&a); printf("Insira a altura do retangulo: "); scanf("%f",&b); system ("cls"); printf("\nPara o retangulo de base %.2f e altura %.2f\n",a,b); printf("A area equivale a %.2f e\n",a*b); printf("O perimetro equivale a: %.2f\n\n\n", a+a+b+b); return 0; }
Python
UTF-8
218
3.140625
3
[]
no_license
N = int(input()) a = sorted((int(i) for i in input().split()), reverse=True) alice = 0 bob = 0 for i in range(0, N, 2): try: alice += a[i] bob += a[i+1] except: pass print(alice - bob)
JavaScript
UTF-8
2,810
4.46875
4
[]
no_license
// Create a function that takes a string and returns true or false, depending on whether the characters are in order or not. function isInOrder(str) { str = str.split('') let comparator = str.slice() comparator = comparator.sort() return str.join() === comparator.join()? true: false } // isInOrder("abc") //➞ true // console.log(isInOrder("123")); //➞ false // isInOrder("123") //➞ true // isInOrder("xyzz") //➞ true // Write a function that returns true if a word can be found in between the start and end word in a dictionary. function isBetween(first, last, word) { return [...arguments].sort()[1] === word; } isBetween("apple", "banana", "azure") //➞ true isBetween("monk", "monument", "monkey") //➞ true isBetween("bookend", "boolean", "boost") //➞ false // Your friend is trying to write a function that removes all vowels from a string. They write: // Fix this incorrect code, so that all tests pass! // However, it seems that it doesn't work? Fix your friend's code so that it actually does remove all vowels function removeVowels(str) { return str.replace(/[aeiou]/g, '') } removeVowels("candy") //➞ "cndy" removeVowels("hello") //➞ "hllo" // The "e" is removed, but the "o" is still there! removeVowels("apple") //➞ "pple" // Write two functions: // firstArg() should return the first parameter passed in. // lastArg() should return the last parameter passed in. // Return undefined if the function takes no parameters. function firstArg(...arr) { if (arr !== undefined) { return arr.shift(); } else if (arr == ""){ return undefined } } function lastArg(...arr) { if (arr !== undefined) { return arr.pop(); } else if (arr == ""){ return undefined } } firstArg(1, 2, 3)//➞ 1 lastArg(1, 2, 3) //➞ 3 firstArg(8) //➞ 8 lastArg() //➞ 8 // Create a function that returns the next element in an arithmetic sequence. In an arithmetic sequence, each element is formed by adding the same constant to the previous element. function nextElement(arr) { let add = arr[arr.length -1] - arr[arr.length -2]; return add > 0 || add < -0? arr[arr.length -1] + add :arr[arr.length -1] } nextElement([3, 5, 7, 9]); //➞ 11 nextElement([-5, -6, -7]); //➞ -8 nextElement([2, 2, 2, 2, 2]); //➞ 2 // Create a function which filters out strings from an array and returns a new array containing only integers. function filterList(l) { let newArr = []; l=l.filter(arr =>{ if (typeof arr === "number") { newArr.push(arr) } }) return newArr } filterList([1, 2, 3, "x", "y", 10]); //➞ [1, 2, 3, 10] filterList([1, "a", 2, "b", 3, "c"]) //➞ [1, 2, 3] filterList([0, -32, "&@A", 64, "99", -128]) //➞ [0, -32, 64, -128]
C#
UTF-8
1,885
3.109375
3
[]
no_license
using System; using System.Globalization; using System.IO; using System.Windows.Data; using System.Windows.Media.Imaging; namespace Video03 { /// <summary> /// Converts a full path to a specific image type of a drive, folder or file. /// </summary> // attribute for easier findings [ValueConversion(typeof(DirectoryItemType), typeof(BitmapImage))] public class HeaderToImageConverter : IValueConverter { public static HeaderToImageConverter Instance = new HeaderToImageConverter(); public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { // default string image = "Images/Document-Blank-icon.png"; switch ((DirectoryItemType)value) { case DirectoryItemType.Drive: image = "Images/Home-icon.png"; break; case DirectoryItemType.File: image = "Images/Document-Blank-icon.png"; break; case DirectoryItemType.Folder: image = "Images/Folder-icon.png"; break; default: image = "Images/Document-Blank-icon.png"; break; } return new BitmapImage(new Uri($"pack://application:,,,/{image}")); // a direct path works too, but since the app can be located diffrently on another mashine // a refrence to the refrences packeges is better, as those follow the app //return new BitmapImage(new Uri("D:\\PrgTek13\\ADO02\\AngelSixWPFtut\\Video02\\Images\\Folder-icon.png")); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
Java
UTF-8
709
2.265625
2
[ "Apache-2.0" ]
permissive
package com.example.restaurant.bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @AllArgsConstructor @NoArgsConstructor @Data public class User { private Integer user_id; private String user_name; private String user_password; private String user_address; private String user_telephone; public User(String name, String password) { this.user_name = name; this.user_password = password; } public User(String user_name,String user_address,String user_telephone){ this.user_name=user_name; this.user_address=user_address; this.user_telephone= user_telephone; } }
Shell
UTF-8
408
2.9375
3
[]
no_license
if [ "$USE_UNICODE_GLYPHS" = "y" ] then GIT="\ue725" GITHUB="\uf113 " GITLAB="\uf296 " DIRTY="!" NEW="?" UP="\uf63e" DOWN="\uf63b" FOLDER="\uf07c " AWS="\uf0c2 " ERROR="\uf46e" ARROW=">" else GIT="branch:" GITHUB="GH" GITLAB="GL" DIRTY="!" NEW="?" UP="^" DOWN="v" FOLDER="" AWS="aws" ERROR="!" ARROW=">" fi
C++
ISO-8859-1
198
3.390625
3
[]
no_license
//Construa um algoritmo que apresente na tela os nmeros de 1 a 30. #include <iostream> using namespace std; main() { int x=1; while (x<=30) { cout << x <<"\n"; x++; } }
JavaScript
UTF-8
3,955
3.140625
3
[]
no_license
var canvas = document.getElementById("monCanvas"); var wW = canvas.width = 800; var wH = canvas.height = 800; var context = canvas.getContext('2d'); var cellSize = 50; var cells = []; var fps = 2; var COLUMN = 11; var ROWS = COLUMN; var lecture = false; function drawGrid(){ for (var i = 0; i < COLUMN; i++) { for (var y = 0; y < ROWS; y++) { context.beginPath(); context.rect(i*cellSize,y*cellSize,cellSize,cellSize); context.stroke(); } } } var Cell = function(x,y){ var _self = this; _self.x = x; _self.y = y; _self.isAlive = false; _self.willBeAlive = false; _self.check = function(){ var compteur = 0; for (var i = 0; i < cells.length; i++) { var cell = cells[i]; //top left if(_self.x - cellSize == cell.x && _self.y - cellSize == cell.y){ if(cell.isAlive){ compteur++; } } //top if(_self.x == cell.x && _self.y - cellSize == cell.y){ if(cell.isAlive){ compteur++; } } //top right if(_self.x + cellSize == cell.x && _self.y - cellSize == cell.y){ if(cell.isAlive){ compteur++; } } //left if(_self.x - cellSize == cell.x && _self.y == cell.y){ if(cell.isAlive){ compteur++; } } //right if(_self.x + cellSize == cell.x && _self.y == cell.y){ if(cell.isAlive){ compteur++; } } //bottom left if(_self.x - cellSize == cell.x && _self.y + cellSize == cell.y){ if(cell.isAlive){ compteur++; } } //bottom if(_self.x == cell.x && _self.y + cellSize == cell.y){ if(cell.isAlive){ compteur++; } } //bottom right if(_self.x + cellSize == cell.x && _self.y + cellSize == cell.y){ if(cell.isAlive){ compteur++; } } if(compteur == 2 || compteur == 3 ){ _self.willBeAlive = true; } else{ _self.willBeAlive = false; } } } _self.draw = function(){ /* si vivant - si vivant au suivant -> vert - sinon rouge si mort - si vivant au prochain - > gris - sinon blancs */ if (_self.isAlive) { if (_self.willBeAlive){ context.fillStyle = "green"; }else{ context.fillStyle = "red"; } }else{ if(_self.willBeAlive){ context.fillStyle = "gray"; }else{ context.fillStyle = "white"; } } _self.isAlive = _self.willBeAlive; context.beginPath(); context.rect(_self.x,_self.y,cellSize,cellSize); context.fill(); context.stroke(); } } init(); drawCell(); function animate(){ setTimeout(function() { window.requestAnimationFrame(animate); if(lecture){ checkCell(); drawCell(); } }, 1000 / fps); } function init(){ for (var x = 0; x < COLUMN; x++) { for (var y = 0; y < ROWS; y++) { cells.push(new Cell(x*cellSize,y*cellSize)); } } } function checkCell(){ for(var idx in cells){ cells[idx].check(); } } function drawCell(){ for(var idx in cells){ cells[idx].draw(); } } function drawCube(event){ var clickX = event.offsetX / cellSize; var clickY = event.offsetY / cellSize; var x = Math.floor(clickX); var y = Math.floor(clickY); for(var i = 0 ; i < cells.length ; i++){ var cell = cells[i]; if(x*cellSize == cell.x && y*cellSize == cell.y){ cell.isAlive = true; cell.willBeAlive = true; cell.draw(); } } } function startDrawing(){ lecture = true; animate(); } function stopDrawing(){ lecture = false; } /* HANDLER */ canvas.addEventListener('click',drawCube); var btnStart = document.getElementById('start'); var btnStop = document.getElementById('stop'); btnStop.addEventListener('click',stopDrawing); btnStart.addEventListener('click',startDrawing);
Java
UTF-8
2,830
1.84375
2
[]
no_license
package com.ihk.saleunit.action.new_; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.ihk.property.data.pojo.PropertyDeveloper; import com.ihk.property.data.pojo.PropertyProject; import com.ihk.property.data.services.IPropertyDeveloperServices; import com.ihk.property.data.services.IPropertyProjectServices; import com.ihk.saleunit.data.pojo.PropertyProjectPlan; import com.ihk.saleunit.data.pojo.PropertyProjectPlanCond; import com.ihk.saleunit.data.services.IPropertyProjectPlanServices; import com.ihk.utils.SupperAction; /** * 楼盘项目 * */ public class PropertyProjectInfoAction extends SupperAction{ private static final long serialVersionUID = 1L; @Autowired IPropertyProjectServices propertyProjectServices; @Autowired IPropertyDeveloperServices propertyDeveloperServices; @Autowired IPropertyProjectPlanServices propertyProjectPlanServices; private List<PropertyProjectPlan> propertyProjectPlanList; private PropertyProjectPlanCond propertyProjectPlanCond; public List<PropertyProjectPlan> getPropertyProjectPlanList() { return propertyProjectPlanList; } public void setPropertyProjectPlanList( List<PropertyProjectPlan> propertyProjectPlanList) { this.propertyProjectPlanList = propertyProjectPlanList; } /** * 项目信息 * */ public String proInfo(){ propojo = propertyProjectServices.findPropertyProjectById(proId); if(propojo.getDeveloperId() == 0){ devpojo = new PropertyDeveloper(); }else{ devpojo = propertyDeveloperServices.findPropertyDeveloperById(propojo.getDeveloperId()); } propertyProjectPlanCond = new PropertyProjectPlanCond(); propertyProjectPlanCond.setPropertyId(String.valueOf(propojo.getId())); propertyProjectPlanList = propertyProjectPlanServices.findPropertyProjectPlan(propertyProjectPlanCond); return "suc"; } /** * 项目信息 销控中心用 * */ public String proInfoBySaleUnit(){ propojo = propertyProjectServices.findPropertyProjectById(proId); if(propojo.getDeveloperId() == 0){ devpojo = new PropertyDeveloper(); }else{ devpojo = propertyDeveloperServices.findPropertyDeveloperById(propojo.getDeveloperId()); } return "suc"; } private int proId; private PropertyProject propojo; private PropertyDeveloper devpojo; public int getProId() { return proId; } public void setProId(int proId) { this.proId = proId; } public PropertyProject getPropojo() { return propojo; } public void setPropojo(PropertyProject propojo) { this.propojo = propojo; } public PropertyDeveloper getDevpojo() { return devpojo; } public void setDevpojo(PropertyDeveloper devpojo) { this.devpojo = devpojo; } }
Markdown
UTF-8
1,902
2.84375
3
[]
no_license
# File Transfer Application ## Introduction File Transfer Application between one main.Server and one main.Client with Authentication system built-in. The problem is to create a file transfer system that utilizes Socket Programming, Connection Management, Reliable Communication, and security protocol that utilizes SHA-1. It allows 2 individuals (1 server and 1 client) on different computers to communicate via network. This project supports Windows, Mac, and Linux. We use Java to build this program. We create 2 different projects/modules, a main.Client.java and a main.Server.java, both lie within the FileTransferApplication project. The server sets up the sockets and wait for connection. The client sets up its socket and connect to the server. This program also records the start and end time of the session. There are several commands that allows the client to communicate to the server. The server does not initiate any message. It waits for the commands from the client and sends responses. The client can request server to view all the files the server contains, to download files from the server, or to upload files from local host to store in the server. All messages transported over the network shall be secured with respect to Authentication, Confidentiality, and Integrity. Build on top of my [Chatroom](https://github.com/baonguyen96/Chatroom) project. ## Execution ### To run program via IDE 1. Open main.Server and main.Client projects on separated windows. 2. Then individually click "Run" to run each code in parallel. *NOTE*: May have to configure classpath to successfully compile and run (for Eclipse) ### To run program in the command line environment 1. Navigate to [Shell](./Shell) directory 2. Run `./build.windows.ps1` 3. Run `./start-server.ps1` 4. Run `./start-client.ps1` *NOTE*: `attack.FakeClient` and `attack.FakeServer` are for testing and demo only.
C++
UTF-8
2,468
2.546875
3
[ "Apache-2.0" ]
permissive
#include <HAL/Devices/DeviceFactory.h> #include "AutoExposureDriver.h" namespace hal { class AutoExposureFactory : public DeviceFactory<CameraDriverInterface> { public: AutoExposureFactory(const std::string& name) : DeviceFactory<CameraDriverInterface>(name) { Params() = { {"p", "-1", "Proportional gain (-1 driver default)"}, {"i", "-1", "Integral gain (-1 driver default)"}, {"d", "-1", "Derivative gain (-1 driver default)"}, {"target", "127", "Target mean image intensity"}, {"roi", "0+0+0x0", "ROI for computing mean intensity"}, {"limit", "1.0", "Exposure limit (proportional to max value)"}, {"gain", "0.0", "Constant camera gain (proportional to max value)"}, {"sync", "true", "Apply exposure to all camera channels"}, {"channel", "0", "Camera channel for computing exposure"}, {"color", "-1", "Color channel for computing exposure (-1 all colors)"} }; } std::shared_ptr<CameraDriverInterface> GetDevice(const Uri &uri) { const double p = uri.properties.Get<double>("p", -1); const double i = uri.properties.Get<double>("i", -1); const double d = uri.properties.Get<double>("d", -1); const double target = uri.properties.Get<double>("target", 127); const ImageRoi roi = uri.properties.Get<ImageRoi>("roi", ImageRoi()); const double limit = uri.properties.Get<double>("limit", 1.0); const double gain = uri.properties.Get<double>("gain", 0.0); const bool sync = uri.properties.Get<bool>("sync", true); const int channel = uri.properties.Get<int>("channel", 0); const int color = uri.properties.Get<int>("color", -1); std::shared_ptr<AutoExposureInterface> input = GetInput(uri.url); return std::make_shared<AutoExposureDriver>(input, p, i, d, target, roi, limit, gain, sync, channel, color); } protected: std::shared_ptr<AutoExposureInterface> GetInput(const std::string& url) { std::shared_ptr<AutoExposureInterface> input; std::shared_ptr<CameraDriverInterface> raw_input; raw_input = DeviceRegistry<CameraDriverInterface>::Instance().Create(url); input = std::dynamic_pointer_cast<AutoExposureInterface>(raw_input); if (!input) throw hal::DeviceException("auto-exposure not supported "); return input; } }; static AutoExposureFactory g_AutoExposureFactory("autoexp"); } // namespace hal
Shell
UTF-8
535
3.375
3
[ "MIT" ]
permissive
#!/bin/bash # Get the status from command line applet DROP_STATUS="$(dropbox-cli status)" # Define comparison strings SYNCED="Up to date" STOPPED="Dropbox isn't running!" if [ "$DROP_STATUS" == "$STOPPED" ]; then echo OFF # Long message echo OFF # Short message echo "#FF0000" # Red when off elif [ "$DROP_STATUS" == "$SYNCED" ]; then echo Synced # Long message echo Synced # Short message echo "#00ccFF" # Cyan when synced else echo Syncing # Long message echo Syncing # Short message echo "#FFFF00" # Yellow when syncing fi
PHP
UTF-8
1,564
3.25
3
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Тренируемся !!!</title> <?php $h = date('H'); # Присваеваем переменной текущее время (часы) ?> <style> body { background: url(/img/0<?php echo $h % 8; ?>.jpg); background-size: cover; color: blue; } </style> </head> <body> <?php /* echo "Многострочный коментарий!"; echo "Данные строки закоментированы"; */ # Однострочный коментарий. Можно так, а // можно коментировать и так $r = 50; # Числовая переменная $a = 'Много'; # Строковая переменная $b = 50.5; # Дроби $c = true; # Булевые const PI = 3.14; # Константы echo "Сейчас $h часов <br>"; # Выводим текущие часы echo 'Площадь круга '; echo $r * $r * PI; $str1 = '$r рублей'; $str2 = "$a рублей"; $final = $str1 . $str2; # Через точку склеиваем переменные echo $final; echo '<hr>'; # Проведем горизонтальную черту // Арифметические операции + - * / % $res1 = $b + $r; $res2 = $b - $r; $res3 = $b * $r; $res4 = $b / $r; $res5 = $b % 8; echo "$res1<br>$res2<br>$res3<br>$res4<br>$res5"; ?> </body> </html>
PHP
UTF-8
2,108
2.625
3
[]
no_license
<?php header('Content-Type: application/json'); $_POST = json_decode(file_get_contents('php://input'), true); if(isset($_POST['type'])){ if($_POST['type'] ==="Delete_General") { $table_name = $_POST['table_name']; $deleteListIndexBy = $_POST['deleteListIndexBy']; $toDeleteList = $_POST['toDeleteList']; $update = new Updates(); $update->delete_general($table_name,$deleteListIndexBy,$toDeleteList); $update = null; // //$response = json_encode('{"response":"'.$_POST['type'].'"}'); //echo $response; } }else{ $response = json_encode('{"response":"failed to update"}'); echo $response; } //echo "$username : $password"; //echo date('d-m-Y H:i:s'); //$auth = new Auth(); //echo $auth->check_auth($username,$password); class Updates{ public $servername = "localhost"; public $username = "root"; public $password = ""; public $dbname = "db_imprimante"; public $conn; function getConnection(){ // Create connection $this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname); // Check connection if ($this->conn->connect_error) { $err="Error: connection failed: " . $this->conn->connect_error; //die($err. "<br>"); $res = json_encode('{"response":"'.$err.'"}'); echo $res; } } function closeConection(){ $this->conn->close(); } function delete_general($table_name,$deleteListIndexBy,$toDeleteList){ $this->getConnection(); $result=""; foreach($toDeleteList as $item){ $sql = "delete from $table_name where $deleteListIndexBy='$item'"; $result = $this->conn->query($sql); } if($result ===true ) $result="ok"; $res = json_encode('{"response":"'.$result.'"}'); echo $res; $this->closeConection(); } } ?>
Python
UTF-8
375
2.9375
3
[]
no_license
""" MY NOTE: assingment to x makes new list the e before the 'for' is not the new list only the temp place holder for each item in em. I assume the first occurence of e is to allow operations to be done on e post assingment """ import sys import re x = [e for e in sys.stdin if re.match("[A-z]+\s<[a-z](\w|\.|\_|-)+@[a-z]+\.[a-z]{1,3}>$", e) != None] print("".join(x))
SQL
UTF-8
196
2.609375
3
[ "MIT" ]
permissive
DROP MATERIALIZED VIEW IF EXISTS object_type_cache CASCADE; CREATE MATERIALIZED VIEW object_type_cache AS SELECT hash, (git_parse_object_type(content))::objtype as type FROM objects;
Python
UTF-8
285
3.6875
4
[]
no_license
numero = int(input('Digite um número: ')) numeros_iguais = False while numero > 0 and not numeros_iguais: i1 = numero % 10 numero = numero // 10 i2 = numero % 10 if i1 == i2: numeros_iguais = True if numeros_iguais: print ('sim') else: print('não')
Rust
UTF-8
1,761
2.765625
3
[]
no_license
use crate::error::*; use crate::ir::*; use falcon::{il, RC}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Program<V: Value> { functions: BTreeMap<usize, RC<Function<V>>>, } impl<V: Value> Program<V> { pub fn new() -> Program<V> { Program { functions: BTreeMap::new(), } } pub fn from_il(program: &il::Program) -> Result<Program<Constant>> { let functions: ::std::result::Result<BTreeMap<usize, RC<Function<Constant>>>, Error> = program.functions_map().into_iter().try_fold( BTreeMap::new(), |mut functions, (index, function)| { functions.insert(index, RC::new(Function::<Constant>::from_il(function)?)); Ok(functions) }, ); Ok(Program { functions: functions?, }) } pub fn function(&self, index: usize) -> Option<&Function<V>> { self.functions.get(&index).map(|function| function.as_ref()) } pub fn functions(&self) -> Vec<&Function<V>> { self.functions .iter() .map(|(_, function)| function.as_ref()) .collect::<Vec<&Function<V>>>() } pub fn function_by_name(&self, name: &str) -> Option<&Function<V>> { self.functions .iter() .find(|(_, function)| function.name() == name) .map(|(_, function)| function.as_ref()) } pub fn replace_function(&mut self, index: usize, function: Function<V>) { self.functions.insert(index, RC::new(function)); } } impl<V: Value> Default for Program<V> { fn default() -> Self { Self::new() } }
Shell
UTF-8
3,905
4
4
[]
no_license
#!/usr/bin/dumb-init /bin/bash set -e # Note above that we run dumb-init as PID 1 in order to reap zombie processes # as well as forward signals to all processes in its session. Normally, sh # wouldn't do either of these functions so we'd leak zombies as well as do # unclean termination of all our sub-processes. # As of docker 1.13, using docker run --init achieves the same outcome. # You can set NOMAD_BIND_INTERFACE to the name of the interface you'd like to # bind to and this will look up the IP and pass the proper -bind= option along # to Nomad. NOMAD_BIND= if [ -n "$NOMAD_BIND_INTERFACE" ]; then NOMAD_BIND_ADDRESS=$(ip -o -4 addr list $NOMAD_BIND_INTERFACE | head -n1 | awk '{print $4}' | cut -d/ -f1) if [ -z "$NOMAD_BIND_ADDRESS" ]; then echo "Could not find IP for interface '$NOMAD_BIND_INTERFACE', exiting" exit 1 fi NOMAD_BIND="-bind=$NOMAD_BIND_ADDRESS" echo "==> Found address '$NOMAD_BIND_ADDRESS' for interface '$NOMAD_BIND_INTERFACE', setting bind option..." fi # You can set NOMAD_CLIENT_INTERFACE to the name of the interface you'd like to # bind client intefaces (HTTP, DNS, and RPC) to and this will look up the IP and # pass the proper -client= option along to Nomad. NOMAD_CLIENT= if [ -n "$NOMAD_CLIENT_INTERFACE" ]; then NOMAD_CLIENT_ADDRESS=$(ip -o -4 addr list $NOMAD_CLIENT_INTERFACE | head -n1 | awk '{print $4}' | cut -d/ -f1) if [ -z "$NOMAD_CLIENT_ADDRESS" ]; then echo "Could not find IP for interface '$NOMAD_CLIENT_INTERFACE', exiting" exit 1 fi NOMAD_CLIENT="-client=$NOMAD_CLIENT_ADDRESS" echo "==> Found address '$NOMAD_CLIENT_ADDRESS' for interface '$NOMAD_CLIENT_INTERFACE', setting client option..." fi consul_ip=`dig +short consul.service.consul` if [ "$WAIT_FOR_CONSUL" = true ]; then echo "Waiting for consul to be resolvable" until [ -n "$consul_ip" ]; do echo "Consul Unavailable waiting 5..." sleep 5 done echo "Consul resolved" fi DOCKER_GID=$(stat -c '%g' '/var/run/docker.sock') echo "docker group: ${DOCKER_GID}" groupadd -for -g ${DOCKER_GID} hostdocker usermod -aG hostdocker nomad # NOMAD_DATA_DIR is exposed as a volume for possible persistent storage. The # NOMAD_CONFIG_DIR isn't exposed as a volume but you can compose additional # config files in there if you use this image as a base, or use NOMAD_LOCAL_CONFIG # below. NOMAD_DATA_DIR=/nomad/data NOMAD_CONFIG_DIR=/nomad/config # You can also set the NOMAD_LOCAL_CONFIG environemnt variable to pass some # Nomad configuration JSON without having to bind any volumes. if [ -n "$NOMAD_LOCAL_CONFIG" ]; then echo "$NOMAD_LOCAL_CONFIG" > "$NOMAD_CONFIG_DIR/local.json" fi # If the user is trying to run Nomad directly with some arguments, then # pass them to Nomad. if [ "${1:0:1}" = '-' ]; then set -- nomad "$@" fi # Look for Nomad subcommands. if [ "$1" = 'agent' ]; then shift set -- nomad agent \ -data-dir="$NOMAD_DATA_DIR" \ -config="$NOMAD_CONFIG_DIR" \ $NOMAD_BIND \ $NOMAD_CLIENT \ "$@" elif [ "$1" = 'version' ]; then # This needs a special case because there's no help output. set -- nomad "$@" elif nomad --help "$1" 2>&1 | grep -q "nomad $1"; then # We can't use the return code to check for the existence of a subcommand, so # we have to use grep to look for a pattern in the help output. set -- nomad "$@" fi # If we are running Nomad, make sure it executes as the proper user. if [ "$1" = 'nomad' ]; then # If the data or config dirs are bind mounted then chown them. # Note: This checks for root ownership as that's the most common case. if [ "$(stat -c %u /nomad/data)" != "$(id -u nomad)" ]; then chown -R root:root /nomad/data fi if [ "$(stat -c %u /nomad/config)" != "$(id -u nomad)" ]; then chown -R root:root /nomad/config fi set -- su-exec root:root "$@" fi exec "$@"
Python
UTF-8
159
3.40625
3
[]
no_license
def gen(n): print("ist value") yield n n+=1 print("2nd value") yield n n+=1 print("3rd value") yield name print(next(gen(3)))
Markdown
UTF-8
1,507
3.078125
3
[ "MIT", "CC-BY-4.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
## Application settings and HTTPS ### Verify application settings For your bot to function properly in the cloud, you must ensure that its application settings are correct. If you've already [registered](~/portal-register-bot.md) your bot with the Bot Framework, update the Microsoft App Id and Microsoft App Password values in your application's configuration settings as part of the deployment process. Specify the **app ID** and **password** values that were generated for your bot during registration. > [!TIP] [!include[Application configuration settings](~/includes/snippet-tip-bot-config-settings.md)] If you have not yet registered your bot with the Bot Framework (and therefore do not yet have an **app ID** and **password**), you can deploy your bot with temporary placeholder values for these settings. Then later, after you register your bot, update your deployed application's settings with the **app ID** and **password** values that were generated for your bot during registration. ###<a id="httpsEndpoint"></a> Verify HTTPS endpoint Your deployed bot must have an **HTTPS** endpoint that can receive messages from the Bot Framework Connector Service. > [!NOTE] > When you deploy your bot to Azure, SSL will automatically be configured for your application, thereby enabling the **HTTPS** endpoint that the Bot Framework requires. > If you deploy to another cloud service, be sure to verify that your application is configured for SSL so that the bot will have an **HTTPS** endpoint.
Markdown
UTF-8
4,355
2.765625
3
[ "Apache-2.0" ]
permissive
# sovren-dotnet ![Nuget](https://img.shields.io/nuget/dt/Sovren.SDK?color=0575aa) ![GitHub](https://img.shields.io/github/license/sovren/sovren-dotnet?color=0575aa) ![Nuget](https://img.shields.io/nuget/v/Sovren.SDK?color=0575aa) ![GitHub Workflow Status](https://img.shields.io/github/workflow/status/sovren/sovren-dotnet/build) The official C# SDK for the Sovren v10 API for resume/CV and job parsing, searching, and matching. Supports .NET Framework 4.6.1+ and .NET Core 2.0+. ## Installation From within Visual Studio: 1. Open the Solution Explorer. 2. Right-click on a project within your solution. 3. Click on *Manage NuGet Packages...* 4. Click on the *Browse* tab and search for "Sovren.SDK" (ensure the *Package source* dropdown is set to `nuget.org`). 5. Click on the Sovren.SDK package, select the appropriate version in the right-tab and click *Install*. Using the [.NET Core command-line interface (CLI) tools][dotnet-core-cli-tools]: ```sh dotnet add package Sovren.SDK ``` Using the [NuGet Command Line Interface (CLI)][nuget-cli]: ```sh nuget install Sovren.SDK ``` Using the [Package Manager Console][package-manager-console]: ```powershell Install-Package Sovren.SDK ``` ## Documentation For the full API documentation, information about best practices, FAQs, etc. check out our [docs site][api-docs]. ## Examples For full code examples, see [here][examples]. ## Usage ### Creating a `SovrenClient` This is the object that you will use to perform API calls. You create it with your account credentials and the `SovrenClient` makes the raw API calls for you. These credentials can be found in the [Sovren Portal][portal]. Be sure to select the correct `DataCenter` for your account. ```c# SovrenClient client = new SovrenClient("12345678", "abcdefghijklmnopqrstuvwxyz", DataCenter.US); ``` For self-hosted customers, you can create a `DataCenter` object with your custom URL using the constructor provided on that class. ### Handling errors and the `SovrenException` Every call to any of the methods in the `SovrenClient` should be wrapped in a `try/catch` block. Any 4xx/5xx level errors will cause a `SovrenException` to be thrown. Sometimes these are a normal and expected part of the Sovren API. For example, if you have a website where users upload resumes, sometimes a user will upload a scanned image as their resume. Sovren does not process these, and will return a `422 Unprocessable Entity` response which will throw a `SovrenException`. You should handle any `SovrenException` in a way that makes sense in your application. Additionally, there are `SovrenUsableResumeException` and `SovrenUsableJobException` which are thrown when some error/issue occurs in the API, but the response still contains a usable resume/job. For example, if you are geocoding while parsing and there is a geocoding error (which happens after parsing is done), the `ParsedResume` might still be usable in your application. ### How to create a Matching UI session You may be wondering, "where are the Matching UI endpoints/methods?". We have made the difference between a normal API call (such as `Search`) and its equivalent Matching UI call extremely trivial. See the following example: ```c# SovrenClient client = new SovrenClient("12345678", "abcdefghijklmnopqrstuvwxyz", DataCenter.US); List<string> indexesToSearch = ...; FilterCriteria searchQuery = ...; SearchResponse searchResponse = await client.Search(indexesToSearch, searchQuery); ``` To generate a Matching UI session with the above Search query, you simply need to call the `UI(...)` extension method on the `SovrenClient` object, pass in any UI settings, and then make the same call as above: ```c# MatchUISettings uiSettings = ...; GenerateUIResponse uiResponse = await client.UI(uiSettings).Search(indexesToSearch, searchQuery); ``` For every relevant method in the `SovrenClient`, you can create a Matching UI session for that query by doing the same as above. [examples]: https://github.com/sovren/sovren-dotnet/tree/master/examples [portal]: https://portal.sovren.com [api-docs]: https://docs.sovren.com [dotnet-core-cli-tools]: https://docs.microsoft.com/en-us/dotnet/core/tools/ [nuget-cli]: https://docs.microsoft.com/en-us/nuget/tools/nuget-exe-cli-reference [package-manager-console]: https://docs.microsoft.com/en-us/nuget/tools/package-manager-console
Markdown
UTF-8
1,545
2.921875
3
[]
no_license
Getting-Cleaning-Data ===================== Coursera's Getting &amp; Cleaning Data ## Steps followed in generating the tidy dataset * Download the zip file in the current working directory * Unzip the file in the "UCI HAR Dataset" subfolder in the current working directory * Read the subject_train, X_train and y_train files in train subfolder within "UCI HAR Dataset" folder into separate data frames * Read the subject_test, X_test and y_test files in test subfolder within "UCI HAR Dataset" folder into separate data frames * Union these 6 data frames into 3 data frames named subjects.df, features.df and activtites.df * Read the features.txt and activity_labels.txt into separate data frames named feature.labels and activity.labels * Remove the special characters (open bracket, close bracket and hyphen) in the feature.labels data frame which represents mean or standard deviation (contains 'mean' or 'std' in it) * Name the features.df with the clensed values of feature.labels data frame * Name the subjects.df and activities.df properly * Merge activities.df and activity.labels by the key column * Combine features.df, subjects.df and activities.df data frames into a new data frame * Select only the attributes which are measure of mean or standard deviation (contains 'mean' or 'std' in it) * Convert the subject id and activity description as factors * Create the tidy data frame by calculating the mean of all the columns grouped by subject id and activity description * Write the data of this data frame into tidy.txt file
Java
UTF-8
1,836
2.515625
3
[]
no_license
package itcast.ssm.controller; import itcast.ssm.po.Items; import org.springframework.stereotype.Controller; import org.springframework.web.HttpRequestHandler; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @program: springmvc * @description: * @author: Huabuxiu * @create: 2019-02-23 18:53 **/ @Controller public class ItemsController2 implements HttpRequestHandler { @RequestMapping("/queryItems") @Override public void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { //调用service查找 数据库,查询商品列表,这里使用静态数据模拟 List<Items> itemsList = new ArrayList<Items>(); //向list中填充静态数据 Items items_1 = new Items(); items_1.setName("联想笔记本"); items_1.setPrice(6000f); items_1.setDetail("ThinkPad T430 联想笔记本电脑!"); Items items_2 = new Items(); items_2.setName("苹果手机"); items_2.setPrice(5000f); items_2.setDetail("iphone6苹果手机!"); itemsList.add(items_1); itemsList.add(items_2); httpServletRequest.setAttribute("itemsList", itemsList); httpServletResponse.setCharacterEncoding("utf-8"); httpServletResponse.setContentType("application/json;charset=utf-8"); for (Items item: itemsList) { httpServletResponse.getWriter().print(item); } // httpServletRequest.getRequestDispatcher("WEB-INF/jsp/items/itemsList.jsp"); } }
Python
UTF-8
18,420
2.671875
3
[]
no_license
import pygame from pygame import * import pygame.mixer #----CORES----------------- PRETO = (0, 0, 0) BRANCO = (255, 255, 255) CINZA = (100, 100, 100) VERMELHO = (120, 0, 0) VERDE_ESCURO = (0, 120, 0) VERDE_CLARO = (0, 255, 0) VERMELHO_CLARO = (255, 0, 0) AZUL = (0, 0, 255) COR_FUNDO = (54, 54, 54) COR_TABULEIRO = (0, 31, 0) CINZA_CLARO = (241,241,241) DOURADO = (218, 165, 32) AZUL1 = (51, 198, 254) AZUL2 = (51, 255, 243) AZUL3 = (51, 226, 249) Clock = pygame.time.Clock() pygame.display.set_caption('Dama - Vinicius') class Tabuleiro(object): def __init__(self): # ------INICIA-TELA------------------------- self.screen = pygame.display.set_mode((400, 470)) pygame.display.set_caption('Jogo de Damas') pygame.font.init() # --------------IMAGENS---------------------- p_branco_image_filename = 'p_branca.png' p_preto_image_filename = 'p_preta.png' b_branco_image_filename = 'b_branco.png' b_preto_image_filename = 'b_preto.png' b_box_image_filename = 'box1.png' b_flecha1_image_filename = 'flecha1.png' b_flecha2_image_filename = 'flecha2.png' p_branco_dama_image_filename = 'p_branca1.png' p_preto_dama_image_filename = 'p_preta1.png' # --------CHAMANDO-IMAGENS------------------- b_branco = pygame.image.load(b_branco_image_filename).convert() b_preto = pygame.image.load(b_preto_image_filename).convert() branco = pygame.image.load(p_branco_image_filename).convert_alpha() preto = pygame.image.load(p_preto_image_filename).convert_alpha() b_box = pygame.image.load(b_box_image_filename).convert() b_flecha1 = pygame.image.load(b_flecha1_image_filename).convert_alpha() b_flecha2 = pygame.image.load(b_flecha2_image_filename).convert_alpha() d_branco = pygame.image.load(p_branco_dama_image_filename).convert_alpha() d_preto = pygame.image.load(p_preto_dama_image_filename).convert_alpha() # -----------CONVERTENDO-IMAGENS------------- self.bloco_branco = pygame.transform.scale(branco, (50, 50)) self.bloco_preto = pygame.transform.scale(preto, (55, 50)) self.b_bloco_branco = pygame.transform.scale(b_branco, (50, 50)) self.b_bloco_preto = pygame.transform.scale(b_preto, (50, 50)) self.box = pygame.transform.scale(b_box, (400, 70)) self.flecha1 = pygame.transform.scale(b_flecha1, (70, 30)) self.flecha2 = pygame.transform.scale(b_flecha2, (70, 30)) self.dama_preta = pygame.transform.scale(d_preto, (55, 50)) self.dama_branca = pygame.transform.scale(d_branco, (50, 50)) # ------------CHAMADA-SOM-------------------- #-------------LIMITE-PARA-DAMA---------------- self.limite_preta = [(0, 0), (100, 0), (200, 0), (300, 0)] self.limite_branca = [(50, 350), (150, 350), (250, 350), (350, 350)] #------------VETOR-DAMA----------------------- self.pos_dama = [] self.font = pygame.font.SysFont("Comic sans MS", 20) self.screen.fill(CINZA) self.turno = False self.val_pontos_branco = [] self.jogada_branco = [] self.val_pontos_preto = [] self.jogada_preto = [] self.pecas_tab_preto = [] self.pontuacao_branco = 0 self.pontuacao_preto = 0 def gera_tabuleiro(self, pecas_tabuleiro): tamanho = 50 x, y = 0, 0 P = self.b_bloco_preto B = self.b_bloco_branco aux = False for j in range(8): if aux == True: y += tamanho x = 0 TEMP = P P = B B = TEMP for i in range(4): self.screen.blit(P, (x, y)) pecas_tabuleiro.append((x, y)) self.pecas_tab_preto.append((x,y)) x += tamanho self.screen.blit(B, (x, y)) pecas_tabuleiro.append((x, y)) x += tamanho aux = True pygame.display.flip() def imprime_pecas(self, p_preta, p_branca): for ux, uy in p_preta: self.screen.blit(self.bloco_preto,(ux-2.5, uy)) for px, py in p_branca: self.screen.blit(self.bloco_branco, (px, py)) def identifica_peca(self, pecas, x, y): for x_tab, y_tab in pecas: if x > x_tab and y > y_tab and (x_tab + 50) > x and (y_tab + 50) > y: return x_tab, y_tab return (0,0) def seleciona_peca(self, coord, cor): x, y = coord pygame.draw.circle(self.screen, cor, (x + 25, y + 25), 23) pygame.display.flip() def regras (self, pecas_branca, pecas_preta, pos_atual, pos_pulo): #-REGRA DE MOVIMENTAÇÃO------------------ x, y = pos_atual px,py = pos_pulo regra_movi_branca = [(x - 50, y + 50), (x + 50, y + 50)] regra_movi_preta = [(x + 50, y - 50), (x - 50, y - 50)] kill_branca = [(px + 50, py - 50), (px - 50, py - 50)] kill_preta = [(px - 50, py + 50), (px + 50, py + 50)] regra_kill_branca = [(x - 2*50, y + 2*50),(x + 2*50, y + 2*50)] regra_kill_preta = [(x + 2 * 50, y - 2 * 50), (x - 2 * 50, y - 2 * 50)] if pos_atual in pecas_branca: if pos_pulo not in pecas_preta: if pos_pulo in regra_movi_branca: self.val_pontos_branco.append(1) self.jogada_branco.append((pos_atual,pos_pulo)) return 1 else: for aux_pedra in pecas_preta: if pos_pulo in regra_kill_branca and aux_pedra in kill_branca and pos_pulo not in pecas_branca: self.val_pontos_branco.append(3) self.jogada_branco.append((pos_atual,pos_pulo)) return 2 elif pos_atual in pecas_preta: if pos_pulo in regra_movi_preta: self.val_pontos_preto.append(1) self.jogada_preto.append((pos_atual,pos_pulo)) return 1 else: for aux_pedra in pecas_branca: if pos_pulo in regra_kill_preta and aux_pedra in kill_preta and pos_pulo not in pecas_preta: self.val_pontos_preto.append(3) self.jogada_preto.append((pos_atual,pos_pulo)) return 2 else: return 0 def kill_pedra(self, pos,pos_pulo, peca_branca, peca_preta): x, y = pos px, py = pos_pulo if pos in peca_branca: tab.pontuacao_branco += 1 if pos_pulo == (x + 2 * 50, y + 2 * 50): kill = (px - 50, py - 50) peca_preta.remove(kill) else: kill = (px + 50, py - 50) peca_preta.remove(kill) else:#if pos in peca_preta: tab.pontuacao_preto += 1 if pos_pulo == (x + 2 * 50, y - 2 * 50): kill = (px - 50, py + 50) peca_branca.remove(kill) else: kill = (px + 50, py + 50) peca_branca.remove(kill) def dama(self, pecas_brancas , pecas_pretas, pedra_select, pedra_select_pulo): #movimenta_branca x_select, y_select = pedra_select x_jump, y_jump = pedra_select_pulo aux = pecas_brancas + pecas_pretas for n in range(8): regra_movimento = [(x_select - 50 * n, y_select + 50 * n), (x_select + 50 * n, y_select + 50 * n), (x_select + 50 * n, y_select - 50 * n), (x_select - 50 * n, y_select - 50 * n)] kill = [(x_jump + 50, y_jump - 50), (x_jump - 50, y_jump - 50), (x_jump - 50, y_jump + 50), (x_jump + 50, y_jump + 50)] regra_kill = [(x_select - 2 * 50 * n, y_select + 2 * 50 * n), (x_select + 2 * 50 * n, y_select + 2 * 50 * n), (x_select + 2 * 50 * n, y_select - 2 * 50 * n), (x_select - 2 * 50 * n, y_select - 2 * 50 * n)] for peca in pecas_brancas + pecas_pretas: if pedra_select_pulo in regra_kill and peca in kill: self.kill_dama(pedra_select, pedra_select_pulo, pecas_brancas, pecas_pretas) return 3 elif pedra_select_pulo in regra_movimento: return 1 else: print("1") return 3 def kill_dama(self, pos,pos_pulo, peca_branca, peca_preta): x, y = pos px, py = pos_pulo if pos in peca_branca: tab.pontuacao_branco += 1 for n in range(8): if pos_pulo == (x + 2 * 50*(n+1), y + 2 * 50*(n+1)): kill = (px - 50, py - 50) peca_preta.remove(kill) else: kill = (px + 50, py - 50) peca_preta.remove(kill) else: tab.pontuacao_preto += 1 for n in range(8): if pos_pulo == (x + 2 * 50*(n+1), y - 2 * 50*(n+1)): kill = (px - 50, py + 50) peca_branca.remove(kill) else: kill = (px + 50, py + 50) peca_branca.remove(kill) def imprime_dama(self, pecas_pretas, pecas_brancas): for peca in self.pos_dama: if peca in pecas_pretas: x, y = peca self.screen.blit(self.dama_preta, (x - 2.5, y)) else: x, y = peca self.screen.blit(self.dama_branca, (x - 2.5, y)) class pedras(Tabuleiro): def inicia_pecas_pc(self, pecas_tabuleiro, pc): tam = len(pecas_tabuleiro)-1 for i in range(3): for j in range(4): x, y = pecas_tabuleiro[tam] pc.append((x, y)) tam -= 2 if i == 1: tam += 1 else: tam -= 1 pygame.display.flip() def inicia_pecas_user(self, pecas_tabuleiro, usuario): i = 0 for q in range(3): for j in range(4): x, y = pecas_tabuleiro[i] usuario.append((x, y)) i += 2 if q == 1: i -= 1 else: i += 1 pygame.display.flip() while True: #----OBJETOS------ tab = Tabuleiro() pedra = pedras() #----ARRAY-DE-POSICOES--- pecas_tabuleiro = [] pecas_pretas = [] pecas_brancas = [] #----CHAMADA-DE-METODOS--- tab.gera_tabuleiro(pecas_tabuleiro) pedra.inicia_pecas_pc(pecas_tabuleiro, pecas_pretas) pedra.inicia_pecas_user(pecas_tabuleiro, pecas_brancas) tab.imprime_pecas(pecas_pretas,pecas_brancas) tab.screen.blit(tab.box, (0, 400)) #----O-METODO-IMPRIME_PEÇAS-APENAS-GERA-A-POSIÇÃO-DAS-PEDRAS pygame.display.flip() #-----VARIAVEL-DE-CONTROLE-DE-LOOP--- fim = False #-----VARIAVEL-DE-CONTROLE-PARA-SELECIONAR-ONDE-PULAR pula_pBranca = False pula_pPreta = False #-----PEGA-NOMES--------- player1 = input("digite o nome do Primeiro jogador") player2 = input("digite o nome do Segundo jogador") while not fim: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() if event.type == KEYDOWN: if event.key == K_ESCAPE: fim = True if event.key == K_v: pedra_select = (0, 0) pedra_select_pulo = (0, 0) tab.turno = not tab.turno pula_pPreta = False pula_pBranca = False tab.gera_tabuleiro(pecas_tabuleiro) tab.imprime_pecas(pecas_pretas, pecas_brancas) pygame.display.flip() if event.type == MOUSEBUTTONDOWN: x_mouse, y_mouse = pygame.mouse.get_pos() if tab.turno == False: if pula_pBranca == True: pedra_select_pulo = tab.identifica_peca(pecas_tabuleiro, x_mouse, y_mouse) else: pedra_select = tab.identifica_peca(pecas_brancas, x_mouse, y_mouse) if pedra_select != (0, 0): if pula_pBranca == False: tab.seleciona_peca(pedra_select, DOURADO) if pula_pBranca == True: pedra_select_pulo = tab.identifica_peca(pecas_tabuleiro,x_mouse,y_mouse) if pedra_select in tab.pos_dama: regra = tab.dama(pecas_brancas , pecas_pretas, pedra_select, pedra_select_pulo) #-----AQUI SERA A CHAMADA DA DAMA else: regra = tab.regras(pecas_brancas,pecas_pretas,pedra_select,pedra_select_pulo) if regra == 1: pecas_brancas.append(pedra_select_pulo) pecas_brancas.remove(pedra_select) pula_pBranca = False tab.turno = True if pedra_select in tab.pos_dama: tab.pos_dama.append(pedra_select_pulo) tab.pos_dama.remove(pedra_select) tab.gera_tabuleiro(pecas_tabuleiro) tab.imprime_pecas(pecas_pretas, pecas_brancas) tab.imprime_dama(pecas_pretas, pecas_brancas) pygame.display.flip() if regra == 2: tab.kill_pedra(pedra_select, pedra_select_pulo, pecas_brancas, pecas_pretas) pecas_brancas.append(pedra_select_pulo) pecas_brancas.remove(pedra_select) pula_pBranca = False tab.gera_tabuleiro(pecas_tabuleiro) tab.imprime_pecas(pecas_pretas, pecas_brancas) tab.imprime_dama(pecas_pretas, pecas_brancas) pygame.display.flip() pedra_select = pedra_select_pulo if regra == 3: print("andou") else: pula_pBranca = True elif tab.turno == True: if pula_pPreta == True: pedra_select_pulo = tab.identifica_peca(pecas_tabuleiro, x_mouse, y_mouse) else: pedra_select = tab.identifica_peca(pecas_pretas, x_mouse, y_mouse) if pedra_select != (0, 0): if pula_pPreta == False: tab.seleciona_peca(pedra_select, DOURADO) if pula_pPreta == True: pedra_select_pulo = tab.identifica_peca(pecas_tabuleiro,x_mouse,y_mouse) regra = tab.regras(pecas_brancas, pecas_pretas, pedra_select, pedra_select_pulo) if regra == 1: pecas_pretas.append(pedra_select_pulo) pecas_pretas.remove(pedra_select) pula_pPreta = False tab.turno = False if pedra_select in tab.pos_dama: tab.pos_dama.append(pedra_select_pulo) tab.pos_dama.remove(pedra_select) tab.gera_tabuleiro(pecas_tabuleiro) tab.imprime_pecas(pecas_pretas, pecas_brancas) tab.imprime_dama(pecas_pretas, pecas_brancas) pygame.display.flip() if regra == 2: tab.kill_pedra(pedra_select, pedra_select_pulo, pecas_brancas, pecas_pretas) pecas_pretas.append(pedra_select_pulo) pecas_pretas.remove(pedra_select) pula_pPreta = False tab.gera_tabuleiro(pecas_tabuleiro) tab.imprime_pecas(pecas_pretas, pecas_brancas) tab.imprime_dama(pecas_pretas, pecas_brancas) pygame.display.flip() pedra_select = pedra_select_pulo else: pula_pPreta = True nome1 = tab.font.render(player1, True, AZUL) nome2 = tab.font.render(player2, True, AZUL) pontos1 = tab.font.render(str(tab.pontuacao_branco), False, AZUL) pontos2 = tab.font.render(str(tab.pontuacao_preto), False, AZUL) tab.screen.blit(nome1, [15, 400]) tab.screen.blit(nome2, [270, 400]) pygame.draw.rect(tab.screen, AZUL1, (45, 435, 30, 20)) tab.screen.blit(pontos1, [50, 430]) pygame.draw.rect(tab.screen, AZUL2, (315, 435, 30, 20)) tab.screen.blit(pontos2, [320, 430]) if tab.turno == True: pygame.draw.rect(tab.screen, AZUL3, (170, 420, 70, 30)) tab.screen.blit(tab.flecha1, [170, 420]) else: pygame.draw.rect(tab.screen, AZUL3, (170, 420, 70, 30)) tab.screen.blit(tab.flecha2, [170, 420]) pygame.display.flip() if len(pecas_brancas) < 1: print(player1 + " GANHOU!!") fim = True if len(pecas_pretas) < 1: print(player2 + " GANHOU!!") fim = True for davez in pecas_brancas: if davez in tab.limite_branca: tab.pos_dama.append(davez) for davez in pecas_pretas: if davez in tab.limite_preta: tab.pos_dama.append(davez) tab.imprime_dama(pecas_pretas, pecas_brancas) Clock.tick(10)
PHP
UTF-8
2,460
2.703125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Bridit\ExpertSenderApi\Tests\Request; use Bridit\ExpertSenderApi\Enum\HttpMethod; use Bridit\ExpertSenderApi\Request\SnoozedSubscribersPostRequest; /** * SnoozedSubscribersPostRequestTest * * @author Nikita Sapogov <p.zelant@gmail.com> */ class SnoozedSubscribersPostRequestTest extends \PHPUnit\Framework\TestCase { /** * Test */ public function testCreateWithId() { $id = 567; $snoozedWeeks = 23; $listId = 27; $request = SnoozedSubscribersPostRequest::createWithId($id, $snoozedWeeks, $listId); $this->assertSame([], $request->getQueryParams()); $this->assertSame('/v2/Api/SnoozedSubscribers', $request->getUri()); $this->assertSame('<Id>567</Id><ListId>27</ListId><SnoozeWeeks>23</SnoozeWeeks>', $request->toXml()); $this->assertTrue($request->getMethod()->equals(HttpMethod::POST())); } /** * Test */ public function testCreateWithEmail() { $email = 'test@test.ru'; $snoozedWeeks = 23; $listId = 27; $request = SnoozedSubscribersPostRequest::createWithEmail($email, $snoozedWeeks, $listId); $this->assertSame([], $request->getQueryParams()); $this->assertSame('/v2/Api/SnoozedSubscribers', $request->getUri()); $this->assertSame('<Email>test@test.ru</Email><ListId>27</ListId><SnoozeWeeks>23</SnoozeWeeks>', $request->toXml()); $this->assertTrue($request->getMethod()->equals(HttpMethod::POST())); } /** * Test */ public function testXmlShouldNotContainListIdIfItValusIsNull() { $request = SnoozedSubscribersPostRequest::createWithId(567, 23); $this->assertSame('<Id>567</Id><SnoozeWeeks>23</SnoozeWeeks>', $request->toXml()); } /** * Test */ public function testConstructorShouldThrowExceptionIfSnoozeWeeksLessThanOne() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage("Expected a value greater than or equal to 1. Got: 0"); SnoozedSubscribersPostRequest::createWithId(567, 0); } /** * Test */ public function testConstructorShouldThrowExceptionIfSnoozeWeeksGreaterThan26() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage("Expected a value less than or equal to 26. Got: 27"); SnoozedSubscribersPostRequest::createWithId(567, 27); } }
Java
UTF-8
1,835
2.5
2
[]
no_license
package com.example.android.note.Room; import android.app.Application; import android.os.AsyncTask; import java.util.List; import androidx.lifecycle.LiveData; public class ItemRepository { private ItemDao itemDao; private ItemDatabase itemDatabase; private LiveData<List<Item>> allNotes; public ItemRepository(Application application) { itemDatabase=itemDatabase.getInstance(application); itemDao=itemDatabase.itemDao(); allNotes=itemDao.getItems(); } public void insert(Item item){ new insertAsyncTask().execute(item); } public LiveData<List<Item>> getAllNotes(){ return allNotes; } public void update(Item item){ new updateAsyncTask().execute(item); } public void delete(Item item){ new deleteAsyncTask().execute(item); } public void deleteAllNotes(){ new deleteAllAsyncTask().execute(); } private class insertAsyncTask extends android.os.AsyncTask<Item,Void,Void> { @Override protected Void doInBackground(Item... items) { itemDao.insert(items[0]); return null; } } private class updateAsyncTask extends android.os.AsyncTask<Item,Void,Void> { @Override protected Void doInBackground(Item... items) { itemDao.update(items[0]); return null; } } private class deleteAsyncTask extends AsyncTask<Item,Void,Void> { @Override protected Void doInBackground(Item... items) { itemDao.delete(items[0]); return null; } } private class deleteAllAsyncTask extends AsyncTask<Void,Void,Void> { @Override protected Void doInBackground(Void... voids) { itemDao.deleteAll(); return null; } } }
Java
UTF-8
342
1.585938
2
[]
no_license
package com.sys.monitor.mapper; import com.sys.monitor.entity.AppWhiteList; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * 白名单,不管接口慢成傻德行,都不管 Mapper 接口 * </p> * * @author willis * @since 2020-02-26 */ public interface AppWhiteListMapper extends BaseMapper<AppWhiteList> { }
PHP
UTF-8
809
2.578125
3
[]
no_license
<!-- This is the index page after the login --> <?php session_start(); include "../html/admin-header.html"; include "../function/connection.php"; include "../function/functions.php"; $user_data = check_login($con); $timestamp = strtotime($user_data['date']); $date = date("l jS \of F Y", $timestamp); $time = date("H:i:s", $timestamp); ?> <link rel="stylesheet" href="../css/style.css"> <title>Login App - Account Page</title> </head> <body> <?php include "../html/admin-navbar.html";?> <div class="page"> <br> <h4>Welcome back, <?php echo $user_data['user_name'];?> !</h4><br> <h5>This is your profile page!</h5> <br> <h6>You're a member since <?php echo $date . " at " . $time;?></h6> </div> <?php include "../html/footer.html";?> </body> </html>
C++
UTF-8
1,046
2.53125
3
[]
no_license
#include "PlatformControl.h" PlatformControl::PlatformControl() { // Use Requires() here to declare subsystem dependencies Requires(platform); } // Called just before this Command runs the first time void PlatformControl::Initialize() { platform->setSpeed(0.0); } // Called repeatedly when this Command is scheduled to run void PlatformControl::Execute() { // Pspeed = oi->getJoystick3()->GetY(); // platform->setSpeed(Pspeed); platform->setSpeed(oi->getJoystick3()->GetY()); //Asked to get speed from SmartDashboard, but it's Y axis, so instead printing that to SmartDashboard // Pspeed = SmartDashboard.PutNumber("Belt Speed"); } // Make this return true when this Command no longer needs to run execute() bool PlatformControl::IsFinished() { return false; } // Called once after isFinished returns true void PlatformControl::End() { platform->setSpeed(0.0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run void PlatformControl::Interrupted() { platform->setSpeed(0.0); }
Shell
UTF-8
112
3.28125
3
[]
no_license
EXIT_CODE="$(($$ % 2))" echo "My exit code is: $EXIT_CODE" if [ $EXIT_CODE -ne 0 ]; then exit $EXIT_CODE fi
Python
UTF-8
1,617
3.09375
3
[]
no_license
import numpy as np import scipy.optimize from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import pandas fig = plt.figure() ax = fig.gca(projection='3d') def fitPlaneLTSQ(XYZ): (rows, cols) = XYZ.shape print(rows, cols) G = np.ones((rows, 3)) print(XYZ) print(XYZ[0]) G[:, 0] = XYZ[0] # X G[:, 1] = XYZ[1] # Y print(G) Z = XYZ[2] (a, b, c), resid, rank, s = np.linalg.lstsq(G, Z) print(a , b , c, resid, rank, s) normal = (a, b, -1) nn = np.linalg.norm(normal) normal = normal/nn print(normal) return (c, normal) Filename = "xxx" #Import Data from CSV result = pandas.read_csv(Filename, header=None) # , names=['X', 'Y','Z'] #result =result.head(5) print(result) #standard normal distribution / Bell. #np.random.seed(seed=1) data = result #print(data) print("NEW : ") print(data) c, normal = fitPlaneLTSQ(data) print(c, normal) # plot fitted plane maxx = np.max(data[0]) maxy = np.max(data[1]) minx = np.min(data[0]) miny = np.min(data[1]) print(maxx,maxy, minx, miny) point = np.array([0.0, 0.0, c]) print(point) d = -point.dot(normal) print(d) # plot original points ax.scatter(data[0], data[1], data[2]) # compute needed points for plane plotting xx, yy = np.meshgrid([minx, maxx], [miny, maxy]) z = (-normal[0]*xx - normal[1]*yy - d)*1. / normal[2] # plot plane ax.plot_surface(xx, yy, z, alpha=0.2) ax.set_xlim(-1, 1) ax.set_ylim(-1,1) ax.set_zlim(1,2) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') plt.show()
PHP
UTF-8
1,531
2.546875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace api\controllers; use yii\db\ActiveRecord; use yii\helpers\Json; use yii\rest\ActiveController; use common\models\Feedback; use yii\web\ServerErrorHttpException; use yii\httpclient\Client; class FeedbackController extends ActiveController { const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'; public $modelClass = Feedback::class; public function actions() { return []; } public function actionCreate() { /** @var $model ActiveRecord */ $model = new $this->modelClass(); $data = Json::decode(\Yii::$app->getRequest()->getRawBody()); $client = new Client(); $response = $client->createRequest() ->setMethod('GET') ->setUrl(self::SITE_VERIFY_URL) ->setData([ 'secret' => \Yii::$app->params['recaptchaSecretKey'], 'response' => $data['recaptchaToken']]) ->send(); if (!$response->isOk) { throw new \Exception('Connection to the captcha server failed'); } if (!filter_var($response->data['success'], FILTER_VALIDATE_BOOLEAN)) { throw new \Exception('Recaptcha check failed'); } $model->load($data, ''); if ($model->save()) { $response = \Yii::$app->getResponse(); $response->setStatusCode(201); } else { throw new ServerErrorHttpException('Failed to save the message'); } return $model; } }
Markdown
UTF-8
1,964
2.875
3
[ "MIT" ]
permissive
# Deep Remove Folders and Directories in Windows Welcome to the '**DeepRemove**' tool page! The tool that removes folder or directory structures that are too deep to remove by traditional tools or shell commands in Windows. ## Little bit of history I started this tool long time back in CodePlex to solve a recurrent problem in Windows. In Windows, some tools can create deeply nested folder structures, with paths that exceed the 260 character max lenght (in the shell and UI); once the path exceeds the limit, there were no tools to help you remove those folders. Now that CodePlex is being retired (or already retired), I ported the tool to this place. And, also added a new version of the tool. ## [DeepRemove](DeepRemove/README.md) version 1 - This is a Windows, window, UI application. - The tool was written in C# with calls into Kernel32. - The executable (installer) is [DeepRemove_1_0_26_58.zip](setup/DeepRemove_1_0_26_58.zip) - For the tool usage see [DeepRemove](DeepRemove/README.md) ## [DeepRemove2](DeepRemove2/README.md) version 2 - This is a command line application. - The tool was written in C++ with calls into the standard library (STL) and "windows.h". - The executable (installer) is [DeepRemove2_1_0_3.zip](setup/DeepRemove2_1_0_3.zip) - Type 'DeepRemove2' at a console prompt to get help (assuming the tool folder is listed in your path). ## Developing and Contributing At this moment I'm not monitoring this site as I should, so your contributions (either PRs or issues) might wait for a long time. ## Legal and Licensing PowerShell is licensed under the [MIT license](LICENSE.md). ## Code of Conduct This project has adopted the [Microsoft Open Source Code of Conduct](http://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](http://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
Python
UTF-8
3,243
2.90625
3
[]
no_license
from tkinter import * from tkinter.messagebox import * # some useful variable font=('verna',30,"bold") # important function def all_clear(): textfield.delete(0,END) def click_btn_function(event): global textfield print("btn clicked") b=event.widget text=b['text'] if text=="x": textfield.insert(END,"*") return if text=="=": try: ex=textfield.get() anser=eval(ex) textfield.delete(0,END) textfield.insert(0,anser) except Exception as e: print("error...",e) showerror("Error",e) return textfield.insert(END, text) # creating a window window=Tk() window.title("My Calculator") window.geometry("584x650") textfield=StringVar() textfield.set("") # picture label window.wm_iconbitmap("1.ico") pic=PhotoImage(file="image.png") headingpic=Label(window,image=pic) headingpic.pack(side=TOP) # heading label headinglabel=Label(window,text="My calculator",font=font,underline=0) headinglabel.pack(side=TOP,pady=7) # textfield textfield=Entry(window,font=font,justify=CENTER) textfield.pack(side=TOP,pady=8,fill=X,padx=8) # button buttonframe=Frame(window) buttonframe.pack(side=TOP) # adding button temp=1 for i in range(0,3): for j in range(0,3): btn=Button(buttonframe,text=str(temp),font=font,width=5,relief=RIDGE,activebackground="orange",activeforeground="white") btn.grid(row=i,column=j,padx=3,pady=3) temp = temp + 1 btn.bind('<Button-1>',click_btn_function) zerobtn=Button(buttonframe,text="0",font=font,width=5,relief=RIDGE,activebackground="orange",activeforeground="white") zerobtn.grid(row=3,column=0,padx=3,pady=3) dotbtn=Button(buttonframe,text=".",font=font,width=5,relief=RIDGE,activebackground="orange",activeforeground="white") dotbtn.grid(row=3,column=1,padx=3,pady=3) equaltobtn=Button(buttonframe,text="=",font=font,width=5,relief=RIDGE,activebackground="orange",activeforeground="white") equaltobtn.grid(row=3,column=2,padx=3,pady=3) plusbtn=Button(buttonframe,text="+",font=font,width=5,relief=RIDGE) plusbtn.grid(row=0,column=3,padx=3,pady=3) minusbtn=Button(buttonframe,text="-",font=font,width=5,relief=RIDGE) minusbtn.grid(row=1,column=3,padx=3,pady=3) pbtn=Button(buttonframe,text="x",font=font,width=5,relief=RIDGE) pbtn.grid(row=2,column=3,padx=3,pady=3) dividebtn=Button(buttonframe,text="/",font=font,width=5,relief=RIDGE) dividebtn.grid(row=3,column=3,padx=3,pady=3) clearbtn=Button(buttonframe,text=".",font=font,width=10,relief=RIDGE,command=click_btn_function) clearbtn.grid(row=4,column=0,padx=3,pady=3,columnspan=2) plbtn=Button(buttonframe,text="AC",font=font,width=10,relief=RIDGE,command=all_clear) plbtn.grid(row=4,column=2,padx=3,pady=3,columnspan=2) # binding all button plusbtn.bind('<Button-1>',click_btn_function) minusbtn.bind('<Button-1>',click_btn_function) zerobtn.bind('<Button-1>',click_btn_function) equaltobtn.bind('<Button-1>',click_btn_function) dotbtn.bind('<Button-1>',click_btn_function) pbtn.bind('<Button-1>',click_btn_function) clearbtn.bind('<Button-1>',click_btn_function) dividebtn.bind('<Button-1>',click_btn_function) plbtn.bind('<Button-1>',click_btn_function) window.mainloop()
Markdown
UTF-8
5,391
2.71875
3
[ "MIT" ]
permissive
--- layout: default title: Output nav_order: 5 --- # Output As described in the **tool manuscript**, the main output of the workflow consists on two files, which can be found in the **call-hipathia** task directory created by [cromwell](https://github.com/broadinstitute/cromwell). ## Circuit activity matrix **path_values.tsv** This matrix contain the results of the circuit activity estimation performed by hiPathia after applying the *in-silico knockdown* strategy and contain a value for each circuit (row) and sample (column). | | ERR3481954 | ERR3481955 | ERR3481956 | ERR3481957 | |---------------|------------|------------|------------|------------| | P-hsa03320-37 | 0.0000 | 0.0000 | 0.0123 | 0.0000 | | P-hsa03320-61 | 0.0320 | 0.0286 | 0.0123 | 0.0485 | | P-hsa03320-46 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | | P-hsa03320-57 | 0.0000 | 0.0000 | 0.0123 | 0.0000 | | P-hsa03320-64 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | | P-hsa03320-47 | 0.0808 | 0.0768 | 0.0301 | 0.0693 | | P-hsa03320-65 | 0.2524 | 0.2466 | 0.2550 | 0.2727 | | P-hsa03320-55 | 0.3917 | 0.3999 | 0.4006 | 0.4027 | | P-hsa03320-56 | 0.2252 | 0.2238 | 0.2306 | 0.2976 | ## Differential signaling activity analysis This data frame contains the results of making all the possible pairwise comparisons between the circuit activity values of the sample groups specified by the **group** input. Those results are generated through the application of an iterative Wilcoxon Test. The group contrast is indicated in the "comparison" column. **differential_signaling.tsv** | pathId | UP.DOWN | statistic | p.value | FDRp.value | comparison | |----------------|---------|-----------|---------|------------|-------------------| | P-hsa03320-37 | DOWN | -1.5275 | 0.2000 | 0.7026 | 16_weeks-12_weeks | | P-hsa03320-61 | DOWN | -0.2182 | 1.0000 | 1.0000 | 16_weeks-12_weeks | | P-hsa03320-46 | DOWN | -1.9640 | 0.1000 | 0.6091 | 16_weeks-12_weeks | | P-hsa03320-57 | DOWN | -1.9640 | 0.1000 | 0.6091 | 16_weeks-12_weeks | | P-hsa03320-64 | UP | 1.0911 | 0.3537 | 0.8566 | 16_weeks-12_weeks | | P-hsa03320-47 | DOWN | -1.0911 | 0.4000 | 0.8566 | 16_weeks-12_weeks | | P-hsa03320-65 | UP | 0.2182 | 1.0000 | 1.0000 | 16_weeks-12_weeks | | P-hsa03320-55 | UP | 0.6547 | 0.7000 | 0.9215 | 16_weeks-12_weeks | | P-hsa03320-56 | DOWN | -1.0911 | 0.4000 | 0.8566 | 16_weeks-12_weeks | | … | … | … | … | … | … | | P-hsa05321-94 | DOWN | -1.3093 | 0.1967 | 0.5469 | 9_weeks-16_weeks | | P-hsa05321-95 | UP | 1.9640 | 0.1000 | 0.4000 | 9_weeks-16_weeks | | P-hsa05321-122 | UP | 1.9640 | 0.0765 | 0.4000 | 9_weeks-16_weeks | | P-hsa05321-123 | UP | 0.2182 | 1.0000 | 1.0000 | 9_weeks-16_weeks | | P-hsa05321-55 | UP | 1.9640 | 0.1000 | 0.4000 | 9_weeks-16_weeks | | P-hsa05321-74 | UP | 1.3093 | 0.1967 | 0.5469 | 9_weeks-16_weeks | | P-hsa05321-81 | UP | 1.3093 | 0.1967 | 0.5469 | 9_weeks-16_weeks | | P-hsa05321-138 | DOWN | -1.0911 | 0.3537 | 0.7966 | 9_weeks-16_weeks | | P-hsa05321-75 | UP | 1.9640 | 0.1000 | 0.4000 | 9_weeks-16_weeks | | P-hsa05321-152 | UP | 1.0911 | 0.4000 | 0.7966 | 9_weeks-16_weeks | ## Pathway viewer The above results can be visualized using the [hiPathia package](https://bioconductor.org/packages/release/bioc/html/hipathia.html), by subsetting the table to the comparison of interest and using the `create_report()` function. ![Viewer](https://github.com/babelomics/hipathia/blob/master/vignettes/pics/hipathia_report_1.png?raw=true) ## Other outputs ### Knockdown matrix **ko_matrix.tsv** This matrix contains the gene table that is used to perform the in-silico knockdown of genes that present a Loss of Function (LoF) variant and that therefore, can not propagate the signal across the circuits. | | ERR2704712 | ERR2704713 | ERR2704714 | ERR2704715 | |-----------------|------------|------------|------------|------------| | ENSG00000128342 | 1 | 1 | 1 | 1 | | ENSG00000187860 | 0.01 | 1 | 1 | 1 | | ENSG00000100003 | 1 | 1 | 1 | 1 | | ENSG00000100012 | 1 | 1 | 1 | 1 | | ENSG00000181123 | 1 | 1 | 1 | 1 | | ENSG00000133488 | 1 | 1 | 0.01 | 1 | | ENSG00000128242 | 1 | 0.01 | 1 | 1 | | ENSG00000100029 | 1 | 1 | 1 | 1 | | ENSG00000185339 | 1 | 1 | 1 | 1 | ### Inner tools outputs Apart from the outputs derived directly from the MIGNON strategy, some of the tools employed during the raw reads processing generate intermediate output reports which can be explored in its corresponding call directories. Additionally, we strongly recommend to use the [MultiQC](https://multiqc.info/) tool to summarize all those intermediate outputs in a single html report.
PHP
UTF-8
499
2.515625
3
[]
no_license
<?php use app\entity; use PHPUnit\Framework\TestCase; class ProductoTest extends TestCase { public function TestObtenerProducto(){ $producto = new producto(); $producto -> id_producto('10'); $producto -> categoria('socalos'); $producto -> presentacion('saco'); $producto -> unidad_medida('kilo'); $producto -> precio_compra('12.52'); $producto -> precio_venta('15'); $producto -> stock('2'); $this -> assertEquals($producto->getProducto(),'10,socalos,saco,kilo,12.52,15,2'); } } ?>
C++
UHC
1,011
3.140625
3
[]
no_license
/* : ã ȣ: 11403 Ǯ̹ : BFS ¥ : 160821 Ÿ : BFSε 2 ϴ ƴ϶ ϳϳ ذϱ 1 ̽ ans ȴ. ٸ ׷ ̿ ʴ´. */ #include<iostream> #include<cstdio> #include<queue> using namespace std; int n; int arr[102][102]; int ans[102][102]; int flag[102]; queue<int> q; int main(void) { scanf("%d", &n); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { int m = 0; scanf("%d", &m); arr[i][j] = m; } } for (int i = 1; i <= n; i++) { q.push(i); xhile (!q.empty()) { int a = q.front(); q.pop(); for (int j = 1; j <= n; j++) { if (arr[a][j] == 1 && ans[i][j]!=1) { q.push(j); ans[i][j] = 1; } } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { printf("%d ",ans[i][j]); } printf("\n"); } return 0; }
Python
UTF-8
1,260
3.3125
3
[]
no_license
import pdb class Solution: # @param num, a list of integer # @return an integer def findPeakElement(self, num): if not num: return if len(num) == 1: return 0 low, high = 0, len(num) pdb.set_trace() while low < high: mid = (low + high)/2 if mid > 0 and mid + 1 < len(num): if num[mid] > num[mid - 1] and num[mid] > num[mid + 1]: return mid elif num[mid] > num[mid - 1] and num[mid] < num[mid + 1]: low = mid + 1 else: high = mid - 1 elif mid == 0: if num[mid] > num[1]: return mid else: low = mid + 1 else: if num[mid] > num[mid - 1]: return mid else: high = mid - 1 return low if __name__ == "__main__": s = Solution() print s.findPeakElement([1, 2, 3]) print s.findPeakElement([1]) print s.findPeakElement([1, 2, 3, 1]) print s.findPeakElement([1, 2, 3, 4, 5, 6, 7, 5])
Python
UTF-8
161
3.34375
3
[]
no_license
def conta_a(string): cont=0 n=len(string) for i in range(0, len(string)): if string[i]=="a": contador+=1 return contador
C++
UTF-8
2,123
2.59375
3
[]
no_license
#include "TextureImporter.h" #include <crunch/inc/crnlib.h> #include <crunch/crnlib/crn_mipmapped_texture.h> #include <crunch/crnlib/crn_texture_conversion.h> #include <crunch/crnlib/crn_console.h> bool TextureImporter::importFile(const std::string &sourceFile, const std::string &outputFile) const { // Read the texture file. crnlib::texture_file_types::format sourceFormat = crnlib::texture_file_types::determine_file_format(sourceFile.c_str()); crnlib::mipmapped_texture sourceTexture; if (!(sourceTexture.read_from_file(sourceFile.c_str(), sourceFormat))) { printf("- ERROR: Failed to read source file \n"); return false; } // Texture name determines conversion settings const bool isNormalMap = sourceFile.find("_normals.") != std::string::npos; const bool sRGB = sourceFile.find("_albedo.") != std::string::npos; const crnlib::texture_type type = isNormalMap ? crnlib::texture_type::cTextureTypeNormalMap : crnlib::texture_type::cTextureTypeRegularMap; // Dont display the crunch console output. // For large numbers of files it is too verbose. crnlib::console::disable_output(); // Configure crunch texture compression crnlib::texture_conversion::convert_params settings; settings.m_texture_type = type; settings.m_pInput_texture = &sourceTexture; settings.m_dst_filename = outputFile.c_str(); settings.m_dst_file_type = crnlib::texture_file_types::cFormatDDS; settings.m_comp_params.m_quality_level = cCRNMaxQualityLevel; settings.m_comp_params.m_dxt_quality = cCRNDXTQualityFast; settings.m_comp_params.set_flag(cCRNCompFlagPerceptual, !isNormalMap); settings.m_comp_params.m_num_helper_threads = 7; settings.m_mipmap_params.m_mode = cCRNMipModeGenerateMips; settings.m_mipmap_params.m_scale_mode = cCRNSMNearestPow2; settings.m_mipmap_params.m_gamma_filtering = sRGB; // Perform the texture conversion process // This creates a .crn file at outputFile path, which can be read at runtime. crnlib::texture_conversion::convert_stats stats; if (!process(settings, stats)) { printf(" - ERROR: Texture conversion failed \n"); return false; } return true; }
C++
UTF-8
506
3
3
[]
no_license
#include <iostream> #include <vector> #include <ctime> using namespace std; vector<vector<int> > generateMatrix(int n); int main() { int n; scanf("%d", &n); clock_t runtime = clock(); vector<vector<int> > matrix = generateMatrix(n); runtime = clock() - runtime; FILE * ftime = fopen("runtime.txt", "w"); fprintf(ftime, "%d", runtime > 1000 ? -1 : runtime); fclose(ftime); for (int i = 0;i < n;++i) { for (int j = 0;j < n;++j) cout << matrix[i][j] << ' '; cout << endl; } return 0; }
C#
UTF-8
6,686
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Web; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Ninject.Activation; using Microsoft.AspNetCore.Http; using System.IO; using Tweetinvi; using System.Diagnostics; using TwitterBotAppCovid.DataHandler; using LINQtoCSV; using TwitterBotAppCovid.Core; namespace TwitterBotAppCovid { public class Program { static HttpClient client = new HttpClient(); public static void ExportToFile(string[] tokenArr) { File.WriteAllLines(Configurations.tokenPath, tokenArr); } public static List<T> Deserialize<T>(string SerializedJSONString) { var listOfCountries = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString); return listOfCountries; } static async Task<List<CountryData>> GetCountryListAsync(string path) { HttpResponseMessage response = await client.GetAsync(client.BaseAddress + path); List<CountryData> listCount = new List<CountryData>(); if (response.IsSuccessStatusCode) { var countriesJson = await response.Content.ReadAsStringAsync(); listCount = Deserialize<CountryData>(countriesJson); } return listCount; } public static string WriteTweetFormat(Country arg, Country randomCountry) { Emoji argFlag = new Emoji(new int[] { 0x1F1E6, 0x1F1F7 }); int[] hexDataFlagRandomCountry= CsvHandler.GetFlagDataFromCSV(randomCountry); Emoji countryflag = new Emoji(hexDataFlagRandomCountry); string str = $" {arg.CountryName} {argFlag} - {randomCountry.CountryName} {countryflag} " + "\n\r" + $"Casos por millon de habitantes {arg.DailyCases} / {randomCountry.DailyCases}" + "\n\r" + $"Cantidad de vacunas aplicadas {arg.VaccinationNumber} / {randomCountry.VaccinationNumber}"+ "\n\r" + $"Porcentaje vacunados 0 / 0" + "\n\r" + $""; return str; } static async Task Main() { Console.WriteLine($"<{DateTime.Now}> - Bot Started"); RunAsync().GetAwaiter().GetResult(); Console.WriteLine($"<{DateTime.Now}> - Task Bot Finished"); } static async Task RunAsync() { // Update port # in the following line. client.BaseAddress = new Uri("https://corona.lmao.ninja/v2/countries/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); try { TwitterClient userClient = new TwitterClient(Configurations.consumerKey, Configurations.consumerSecret); //await AuthenticateClientAsync(); if (!File.Exists(Configurations.tokenPath)) { // Create a client for your app TwitterClient appClient = new TwitterClient(Configurations.consumerKey, Configurations.consumerSecret); // Start the authentication process var authenticationRequest = await appClient.Auth.RequestAuthenticationUrlAsync(); // Go to the URL so that Twitter authenticates the user and gives him a PIN code. Process.Start(new ProcessStartInfo(authenticationRequest.AuthorizationURL) { UseShellExecute = true }); // Ask the user to enter the pin code given by Twitter Console.WriteLine("Please enter the code and press enter."); var pinCode = Console.ReadLine(); // With this pin code it is now possible to get the credentials back from Twitter var userCredentials = await appClient.Auth.RequestCredentialsFromVerifierCodeAsync(pinCode, authenticationRequest); string[] tokarr = new string[] { userCredentials.AccessToken, userCredentials.AccessTokenSecret }; ExportToFile(tokarr); // You can now save those credentials or use them as followed userClient = new TwitterClient(userCredentials); var user = await userClient.Users.GetAuthenticatedUserAsync(); Console.WriteLine("Congratulation you have authenticated the user: " + user); Console.Read(); } else { string[] readText = File.ReadAllLines(Configurations.tokenPath, Encoding.UTF8); var accessToken = readText[0]; var accessSecretToken = readText[1]; userClient = new TwitterClient(Configurations.consumerKey, Configurations.consumerSecret, accessToken, accessSecretToken); } //Get countries from api var listOfCountries = await GetCountryListAsync("?yesterday&sort"); Random rand = new Random(); var randomCountry = listOfCountries[rand.Next(listOfCountries.Count)]; var argentina = listOfCountries.Where(l => l.Country == "Argentina").FirstOrDefault(); //Download data from Our World in Data //Process.Start(new ProcessStartInfo("https://covid.ourworldindata.org/data/owid-covid-data.csv")); var result = CsvHandler.GetVaccineDataFromCSV(argentina, randomCountry); Country arg = new Country(argentina.Country, argentina.CasesPerOneMillion, result.Where(i => i.location == argentina.Country).Select(i => i.people_vaccinated).FirstOrDefault()); Country randomSelectedCountry = new Country(randomCountry.Country, randomCountry.CasesPerOneMillion, result.Where(i => i.location == randomCountry.Country).Select(i => i.people_vaccinated).FirstOrDefault()); var finalString = WriteTweetFormat(arg, randomSelectedCountry); var tweet = await userClient.Tweets.PublishTweetAsync(finalString); File.Delete(Configurations.csvVaccinesDataFile); } catch (Exception e) { Console.WriteLine(e.Message); } } } }
SQL
UTF-8
691
3.5625
4
[ "Apache-2.0" ]
permissive
CREATE TEMPORARY FUNCTION countColorMixDeclarations(css STRING) RETURNS NUMERIC LANGUAGE js OPTIONS (library = "gs://httparchive/lib/css-utils.js") AS r''' try { const ast = JSON.parse(css); return countDeclarations(ast.stylesheet.rules, {values: /color-mix\(.*\)/}); } catch (e) { return null; } '''; SELECT client, COUNT(DISTINCT IF(declarations > 0, page, NULL)) AS pages, COUNT(DISTINCT page) AS total, COUNT(DISTINCT IF(declarations > 0, page, NULL)) / COUNT(DISTINCT page) AS pct_pages FROM ( SELECT client, page, countColorMixDeclarations(css) AS declarations FROM `httparchive.almanac.parsed_css` WHERE date = '2022-07-01') GROUP BY client
C#
UTF-8
3,035
2.890625
3
[]
no_license
/* * 描述: * 1. * * 修改者: 邓平 */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; namespace PracticeByDeng { public class CellSendStream { //数据缓冲区 private List<byte> _byteList = null; public CellSendStream(int nSize = 128) { _byteList = new List<byte>(nSize); } public void Write(byte[] data) { _byteList.AddRange(data); } public void WriteInt8(sbyte n) { _byteList.Add((byte) n); } public void WriteInt16(Int16 n) { Write(BitConverter.GetBytes(n)); } public void WriteInt32(Int32 n) { Write(BitConverter.GetBytes(n)); } public void WriteInt64(Int64 n) { Write(BitConverter.GetBytes(n)); } public void SetNetCmd(NetCmd cmd) { WriteUInt16((UInt16) cmd); } public byte[] Array { get { return _byteList.ToArray(); } } public void Finish() { if (_byteList.Count > UInt16.MaxValue) { //Error Debug.LogError("数据大于 Uint16最大字节 数据应该分包"); } //写入消息头 UInt16 len = (UInt16)_byteList.Count; //Uint16 2个字节 len += 2; _byteList.InsertRange(0,BitConverter.GetBytes(len)); } public void Release() { } public void WriteUInt8(byte n) { _byteList.Add(n); } public void WriteUInt16(UInt16 n) { Write(BitConverter.GetBytes(n)); } public void WriteUInt32(UInt32 n) { Write(BitConverter.GetBytes(n)); } public void WriteUInt64(UInt64 n) { Write(BitConverter.GetBytes(n)); } public void WriteFloat(float n) { Write(BitConverter.GetBytes(n)); } public void WriteDouble(double n) { Write(BitConverter.GetBytes(n)); } /// <summary> /// UTF8 /// </summary> /// <param name="s"></param> public void WriteString(string s) { byte[] buff = Encoding.UTF8.GetBytes(s); WriteUInt32((UInt32)buff.Length + 1/*最后多希尔一个结束符*/); Write(buff); //字符串的结束符 WriteUInt8(0); } public void WriteBytes(byte[] data) { WriteUInt32((UInt32)data.Length); Write(data); } public void WriteInt32s(Int32[] data) { WriteUInt32((UInt32)data.Length); for (int i = 0; i < data.Length; i++) { WriteInt32(data[i]); } } } }
Markdown
UTF-8
871
3.75
4
[]
no_license
#### 编程练习 某班的成绩出来了,现在老师要把班级的成绩打印出来。 效果图: XXXX年XX月X日 星期X--班级总分为:81 格式要求: 1、显示打印的日期。 格式为类似“XXXX年XX月XX日 星期X” 的当前的时间。 2、计算出该班级的平均分(保留整数)。 同学成绩数据如下: "小明:87; 小花:81; 小红:97; 小天:76;小张:74;小小:94;小西:90;小伍:76;小迪:64;小曼:76" #### 任务 第一步:可通过javascript的日期对象来得到当前的日期。 提示:使用Date()日期对象,注意星期返回值为0-6,所以要转成文字"星期X" 第二步:一长窜的字符串不好弄,找规律后分割放到数组里更好操作哦。 第三步:分割字符串得到分数,然后求和取整。 提示:parseInt() 字符串类型转成整型。
Python
UTF-8
1,133
4.25
4
[]
no_license
""" ----------------- Palindrome Check ----------------- Write a function that takes in a non-empty string and that returns a boolean representing whether the string is a palindrome. A palindrome is defined as a string that's written the same forward and backward. Note that single-character strings are palindromes. Sample Input: "abcdcba" Sample Output: true """ # Solution 1 ---> # Time - O(n^2) | Space - O(n) --------- def isPalindrome(s): rev = '' for i in reversed(range(len(s))): rev += s[i] return rev == s # Solution 2 ---> # Time - O(n) | Space - O(n) --------- def isPalindrome(s): rev = [] for i in reversed(range(len(s))): rev .append(s[i]) return ''.join(rev) == s # Solution 3 ---> # Time - O(n) | Space - O(n) --------- def isPalindrome(s,i=0): j = len(s) - 1 - i return True if i >= j else s[i] == s[j] and isPalindrome(s,i+1) # Solution 4 ---> # Time - O(n) | Space - O(1) --------- def isPalindrome(s): l = 0 r = len(s) - 1 while l < r: if s[l] != s[r]: return False i += 1 r -= 1 return False
Java
UTF-8
578
2.078125
2
[]
no_license
/*$Id$*/ package ru.naumen.NauChat.server; import java.util.List; import com.google.common.collect.Lists; /** * Реализация @MessagingService - пока просто при каждом вызове добавляет новое сообщение MessageXXX * @author ivodopyanov * @since 22.06.2012 */ public class MessagingServiceImpl implements MessagingService { private final List<String> messages = Lists.newArrayList(); public List<String> getMessages() { messages.add("Message" + messages.size()); return messages; } }
Python
UTF-8
874
2.84375
3
[]
no_license
from flask import Flask from flask import render_template from flask import request app = Flask(__name__) @app.route("/hello", methods = ['POST', 'GET']) def index(): greeting = "Hello World" if request.method == "POST": name = request.form['name'] greet = request.form['greet'] greeting = f"{greet}, {name}" return render_template("index.html", greeting = greeting) else: return render_template("hello_form.html") if __name__ == '__main__': ##For Windows CMD, use set instead of export: #(set FLASK_ENV=development) ##For PowerShell, use $env: #($env:FLASK_ENV = "development") ##Prior to Flask 1.0, this was controlled by the FLASK_DEBUG=1 environment variable instead. ##If using the app.run() method instead of the (flask run) command, pass debug=True to enable debug mode #app.debug = True app.run()
C#
UTF-8
513
3.21875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Palindrome.Web.Extensions { public static class StringExtensions { public static bool IsPalindrome(this string str) { var allChars = str.Where(c => Char.IsLetter(c)).Select(c => Char.ToLower(c)).ToArray(); char[] allCharsReverse = allChars.Reverse().ToArray(); return new string(allChars) == new string(allCharsReverse); } } }
PHP
UTF-8
2,726
2.890625
3
[]
no_license
<?php namespace App\Console\Commands; use Artisan; use GuzzleHttp\Client; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; class CreateStorageSymlink extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'storage:symlink'; /** * The console command description. * * @var string */ protected $description = 'Create symlink for storage public directory.'; /** * @var Filesystem */ private $fs; /** * Create a new command instance. * @param Filesystem $fs */ public function __construct(Filesystem $fs) { parent::__construct(); $this->fs = $fs; } /** * Execute the console command. */ public function handle() { $this->createTestFile(); if ($this->tryDefaultSymlink() || $this->tryAlternativeSymlink()) { $this->info('Created storage symlink successfully.'); return; } //reset default symlink $this->tryDefaultSymlink(); $this->warn('Created storage symlink, but it does not seem to be working properly.'); } /** * Create a file for testing storage symlink. */ private function createTestFile() { $path = storage_path('app/public/symlink_test.txt'); if ( ! $this->fs->exists($path)) { $this->fs->put($path, 'works'); } } /** * Try alternative symlink creation. * * @return bool */ private function tryAlternativeSymlink() { $this->removeCurrentSymlink(); //symlink('../storage/app/public', './storage'); symlink('../../../storage/app/public', '../../../public/storage'); return $this->symlinkWorks(); } /** * Try default laravel storage symlink. * * @return bool */ private function tryDefaultSymlink() { $this->removeCurrentSymlink(); Artisan::call('storage:link'); return $this->symlinkWorks(); } /** * Check if current storage symlink works properly. * * @return bool */ private function symlinkWorks() { $http = new Client(['verify' => false, 'exceptions' => false]); $response = $http->get(url('storage/symlink_test.txt'))->getBody()->getContents(); return $response === 'works'; } /** * Remove current storage symlink. * * @return bool */ private function removeCurrentSymlink() { try { return unlink(public_path('storage')); } catch (\Exception $e) { return false; } } }