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
PHP
UTF-8
8,546
2.515625
3
[]
no_license
<?php class RActiDepaPFunAFXls { private $columnas=array(); private $fila; private $objParam; public $url_archivo; var $total; var $datos_entidad; var $datos_periodo; var $ult_codigo_partida; var $ult_concepto; function __construct(CTParametro $objParam){ $this->objParam = $objParam; $this->url_archivo = "../../../reportes_generados/".$this->objParam->getParametro('nombre_archivo'); //ini_set('memory_limit','512M'); set_time_limit(400); $cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp; $cacheSettings = array('memoryCacheSize' => '10MB'); PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings); $this->docexcel = new PHPExcel(); $this->docexcel->getProperties()->setCreator("PXP") ->setLastModifiedBy("PXP") ->setTitle($this->objParam->getParametro('titulo_archivo')) ->setSubject($this->objParam->getParametro('titulo_archivo')) ->setDescription('Reporte "'.$this->objParam->getParametro('titulo_archivo').'", generado por el framework PXP') ->setKeywords("office 2007 openxml php") ->setCategory("Report File"); $this->docexcel->setActiveSheetIndex(0); $this->docexcel->getActiveSheet()->setTitle($this->objParam->getParametro('titulo_archivo')); $this->equivalencias=array(0=>'A',1=>'B',2=>'C',3=>'D',4=>'E',5=>'F',6=>'G',7=>'H',8=>'I', 9=>'J',10=>'K',11=>'L',12=>'M',13=>'N',14=>'O',15=>'P',16=>'Q',17=>'R', 18=>'S',19=>'T',20=>'U',21=>'V',22=>'W',23=>'X',24=>'Y',25=>'Z', 26=>'AA',27=>'AB',28=>'AC',29=>'AD',30=>'AE',31=>'AF',32=>'AG',33=>'AH', 34=>'AI',35=>'AJ',36=>'AK',37=>'AL',38=>'AM',39=>'AN',40=>'AO',41=>'AP', 42=>'AQ',43=>'AR',44=>'AS',45=>'AT',46=>'AU',47=>'AV',48=>'AW',49=>'AX', 50=>'AY',51=>'AZ', 52=>'BA',53=>'BB',54=>'BC',55=>'BD',56=>'BE',57=>'BF',58=>'BG',59=>'BH', 60=>'BI',61=>'BJ',62=>'BK',63=>'BL',64=>'BM',65=>'BN',66=>'BO',67=>'BP', 68=>'BQ',69=>'BR',70=>'BS',71=>'BT',72=>'BU',73=>'BV',74=>'BW',75=>'BX', 76=>'BY',77=>'BZ'); } function setDatos ($param) { $this->datos = $param; } function generarReporte(){ $this->imprimeDatos(); $this->docexcel->setActiveSheetIndex(0); $this->objWriter = PHPExcel_IOFactory::createWriter($this->docexcel, 'Excel5'); $this->objWriter->save($this->url_archivo); } function imprimeDatos(){ $datos = $this->datos; $columnas = 0; $this->docexcel->setActiveSheetIndex(0); $sheet0 = $this->docexcel->getActiveSheet(); $sheet0->setTitle('Activos X Deposito'); $sheet0->getColumnDimension('B')->setWidth(15); $sheet0->getColumnDimension('C')->setWidth(25); $sheet0->getColumnDimension('D')->setWidth(60); $sheet0->getColumnDimension('E')->setWidth(20); $sheet0->getColumnDimension('F')->setWidth(20); $sheet0->getColumnDimension('G')->setWidth(50); $encargado = $datos[0]['encargado']; $almacen = $datos[0]['almacen']; $sheet0->mergeCells('B1:G1'); $sheet0->setCellValue('B1', 'ACTIVOS FIJOS POR DEPOSITO'); $sheet0->mergeCells('B2:G2'); $sheet0->setCellValue('B2', 'Reporte de Activos en Detalle'); $sheet0->mergeCells('B3:C3'); $sheet0->setCellValue('B3','RESPONSABLE: '.$encargado.''); $sheet0->mergeCells('B4:C4'); $sheet0->setCellValue('B4','ALMACEN: '.$almacen.''); $styleTitulos = array( 'font' => array( 'bold' => true, 'size' => 8, 'name' => 'Arial' ), 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array( 'rgb' => '768290' ) ), 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN ) )); $styleCabeza = array( 'font' => array( 'bold' => true, 'size' => 8, 'name' => 'Arial' ), 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array( 'rgb' => '768290' ) ), 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_NONE ) ) ); $styleCa = array( 'font' => array( 'bold' => true, 'size' => 8, 'name' => 'Arial' ), 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array( 'rgb' => '768290' ) ), 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN ) ) ); $sheet0->getStyle('B1:G4')->applyFromArray($styleCabeza); $styleTitulos['fill']['color']['rgb'] = '8DB4E2'; $styleTitulos['fill']['color']['rgb'] = 'CCBBAA'; $sheet0->getRowDimension('6')->setRowHeight(35); $sheet0->getStyle('B6:G6')->applyFromArray($styleCa); $sheet0->getStyle('C6:G6')->getAlignment()->setWrapText(true); //*************************************Cabecera***************************************** $sheet0->setCellValue('B6', 'CODIGO'); $sheet0->setCellValue('C6', 'NOMBRE'); $sheet0->setCellValue('D6', 'DESCRIPCION'); $sheet0->setCellValue('E6', 'ESTADO'."\n".'FUNCIONAL'); $sheet0->setCellValue('F6', 'FECHA DE INGRESO'."\n".'DE DEPOSITO'); $sheet0->setCellValue('G6', 'UBICACION'); //*************************************Fin Cabecera***************************************** $fila = 7; $codigo = ''; $nombre = ''; $cont_87 = 0; $cont_100 = 0; $contador = 1; $total_general_87 = 0; $total_general_100 = 0; $total_grupo_87 = 0; $total_grupo_100 = 0; //************************************************Detalle*********************************************** //$tipo = $this->objParam->getParametro('tipo_reporte'); $sheet0->getRowDimension('35')->setRowHeight(35); $sum=0; foreach($datos as $value) { $sheet0->getStyle('B'.$fila.':G'.$fila)->applyFromArray($styleTitulos); $sheet0->getStyle('B'.$fila.':G'.$fila)->getAlignment()->setWrapText(true); $sheet0->getStyle('A'.$fila)->getNumberFormat()->setFormatCode(''); $this->docexcel->setActiveSheetIndex(0)->setCellValueByColumnAndRow(1, $fila, $value['codigo']); $this->docexcel->setActiveSheetIndex(0)->setCellValueByColumnAndRow(2, $fila, $value['denominacion']); $this->docexcel->setActiveSheetIndex(0)->setCellValueByColumnAndRow(3, $fila, $value['descripcion']); $this->docexcel->setActiveSheetIndex(0)->setCellValueByColumnAndRow(4, $fila, $value['cat_desc']); $this->docexcel->setActiveSheetIndex(0)->setCellValueByColumnAndRow(5, $fila, date("d/m/Y", strtotime($value['fecha_mov']))); $this->docexcel->setActiveSheetIndex(0)->setCellValueByColumnAndRow(6, $fila, $value['ubicacion']); $fila ++; } } } ?>
Java
UTF-8
1,370
2.5625
3
[]
no_license
package com.oompow.homeboi; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.PowerManager; /** * Created by scottvanderlind on 7/16/15. */ public class OnScreenOffReceiver extends BroadcastReceiver { /** * Someone tried to press the power button. FIX IT! * @param context * @param intent */ @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) { KioskApplication app = (KioskApplication) context.getApplicationContext(); if (kioskModeEnabled(app)) { wakeUpDevice(app); } } } /** * Wake up the device!!! * @param app */ private void wakeUpDevice(KioskApplication app) { PowerManager.WakeLock wakeLock = app.getWakeLock(); if (wakeLock.isHeld()) { wakeLock.release(); } wakeLock.acquire(); wakeLock.release(); } /** * See if we are in kiosk mode. * @param app * @return */ private boolean kioskModeEnabled(KioskApplication app) { SharedPreferences prefs = app.getPreferences(); return prefs.getBoolean(KioskApplication.PREF_KIOSK_MODE, false); } }
Markdown
UTF-8
1,341
3.015625
3
[]
no_license
# GraphGitRepo Creates a map of a git repository. To achieve this there are two scripts available: * shell script `get_data_fom_git.sh` * python script `draw_graph.py` The first one prepares the necessary data with the help of `git` commands. The python script then visualizes the data previously collected with the help of `graphviz`. Requieres `graphviz` module to be installed. **Shell Script `get_data_fom_git.sh`** At first I clone the OpenSSL repository if not present: git clone https://github.com/openssl/openssl.git And I enter the cloned repository. This is the main piece of code which also explains the format of the output file: git branch -r | # a list of all branches in the repository sed '1d' | # changes 'origin/<branch name>' to '<branch name>' while read BRANCH # for each branch do echo \$$BRANCH >> $OUTPUT_FILE git tag --merged $BRANCH --sort=creatordate | # list all tags (releases) for a given branch sorted by time of creation while read TAG # for each tag do echo $TAG\;\*\; >> $OUTPUT_FILE done done Right now both the scripts are configured for OpenSSL GitHub repo, but they can be easily modified. (A cropped example for OpenSSL GitHub repo) <img src="https://i.imgur.com/ZxnnrTW.jpg" /> You can find more examples in the `examples` directory.
PHP
UTF-8
4,066
2.796875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace MAD\ExperienceBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Question */ class Question { /** * @var integer */ private $id; /** * @var string */ private $title; /** * @var string */ private $wording; /** * @var \DateTime */ private $createdAt; /** * @var \Doctrine\Common\Collections\Collection */ private $experiences; /** * @var \MAD\ExperienceBundle\Entity\Subject */ private $subject; /** * @var \Doctrine\Common\Collections\Collection */ private $groups; /** * Constructor */ public function __construct() { $this->experiences = new \Doctrine\Common\Collections\ArrayCollection(); $this->groups = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set title * * @param string $title * @return Question */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } /** * Set wording * * @param string $wording * @return Question */ public function setWording($wording) { $this->wording = $wording; return $this; } /** * Get wording * * @return string */ public function getWording() { return $this->wording; } /** * Set createdAt * * @param \DateTime $createdAt * @return Question */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; return $this; } /** * Get createdAt * * @return \DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * Add experiences * * @param \MAD\ExperienceBundle\Entity\Experience $experiences * @return Question */ public function addExperience(\MAD\ExperienceBundle\Entity\Experience $experiences) { $this->experiences[] = $experiences; return $this; } /** * Remove experiences * * @param \MAD\ExperienceBundle\Entity\Experience $experiences */ public function removeExperience(\MAD\ExperienceBundle\Entity\Experience $experiences) { $this->experiences->removeElement($experiences); } /** * Get experiences * * @return \Doctrine\Common\Collections\Collection */ public function getExperiences() { return $this->experiences; } /** * Set subject * * @param \MAD\ExperienceBundle\Entity\Subject $subject * @return Question */ public function setSubject(\MAD\ExperienceBundle\Entity\Subject $subject = null) { $this->subject = $subject; return $this; } /** * Get subject * * @return \MAD\ExperienceBundle\Entity\Subject */ public function getSubject() { return $this->subject; } /** * Add groups * * @param \MAD\UserBundle\Entity\Group $group * @return Question */ public function addGroup(\MAD\UserBundle\Entity\Group $group) { $this->groups->add($group); $group->addQuestion($this); return $this; } /** * Remove groups * * @param \MAD\UserBundle\Entity\Group $group * @return Question */ public function removeGroup(\MAD\UserBundle\Entity\Group $group) { $this->groups->removeElement($group); $group->removeQuestion($this); return $this; } /** * Get groups * * @return \Doctrine\Common\Collections\Collection */ public function getGroups() { return $this->groups; } }
TypeScript
UTF-8
4,088
2.734375
3
[]
no_license
import { IGCPubnubConfig } from '../types/IGCPubnubConfig'; import { Unwatch } from '../utils'; // pubnub doesn't work in web worker by default, // so we use slightly modified web worker compatible version import PubNub from './misc/pubnub'; export class GCPubNub { private _callbacks: Map<string, any[]> = new Map<string, any[]>(); private _pubnub: IPubNub; private _listener = { message: this.messageHandler.bind(this), }; constructor(private _config: IGCPubnubConfig) {} public init(uuid: string) { this.destroy(); this._pubnub = new PubNub({ uuid, ssl: true, ...this._config, }); this._pubnub.addListener(this._listener); const channels: string[] = Array.from(this._callbacks.keys()); if (channels.length) { this._pubnub.subscribe({ channels, }); } } public publish(message: IPubNubMessage): Promise<void> { return this._pubnub.publish(message); } public subscribe<T>( options: { channel: string; withPresence?: boolean }, callback: (value: T) => void, ): Unwatch { const channel = options.channel; let callbacks = this._callbacks.get(channel); if (callbacks) { callbacks.push(callback); } else { callbacks = [callback]; if (this._pubnub) { this._pubnub.subscribe({ channels: [channel], withPresence: options.withPresence, }); } this._callbacks.set(channel, callbacks); } return () => { const callbacks = this._callbacks.get(channel); if (!callbacks) { return; } const index = callbacks.indexOf(callback); if (index !== -1) { callbacks.splice(index, 1); } if (callbacks.length === 0) { this._callbacks.delete(channel); this._pubnub.unsubscribe({ channels: [channel], }); } }; } private messageHandler(m: IPubNubMessage) { const callbacks = this._callbacks.get(m.channel); if (callbacks) { callbacks.forEach((callback) => callback(m.message)); } } public destroy() { if (!this._pubnub) { return; } this._pubnub.unsubscribeAll(); this._pubnub.removeListener(this._listener); this._pubnub.stop(); this._pubnub = undefined; } public async time(): Promise<number> { const { timetoken } = await this._pubnub.time(); return timetoken; } public hereNow(options: { channels?: string[]; channelGroups?: string[]; includeUUIDs?: boolean; }): Promise<IHereNowResponse> { return this._pubnub.hereNow(options); } public addChannelsToGroup(channels: string[], channelGroup: string) { return this._pubnub.channelGroups.addChannels({ channels, channelGroup, }); } public async listChannels(channelGroup: string): Promise<string[]> { const { channels } = await this._pubnub.channelGroups.listChannels({ channelGroup, }); return channels; } public removeChannelsFromGroup(channels: string[], channelGroup: string) { return this._pubnub.channelGroups.removeChannels({ channels, channelGroup, }); } } interface IPubNub { channelGroups: { addChannels(options: { channels: string[]; channelGroup: string }); listChannels(options: { channelGroup: string }); removeChannels(options: { channels: string[]; channelGroup: string }); }; subscribe(options: { channels: string[]; withPresence?: boolean }): void; publish(message: IPubNubMessage); unsubscribe(options: { channels: string[] }): void; unsubscribeAll(): void; addListener(listener: IPubNubListener): void; removeListener(listener: IPubNubListener): void; stop(): void; time(); hereNow(options: { channels?: string[]; channelGroups?: string[]; includeUUIDs?: boolean; }); } interface IPubNubListener { message: (value: IPubNubMessage) => void; } interface IPubNubMessage { channel: string; message: any; } interface IHereNowResponse { totalChannels: number; totalOccupancy: number; channels: any; }
Python
UTF-8
5,659
2.890625
3
[ "MIT" ]
permissive
#!/usr/sbin/env python3 import argparse import os import sys import shutil import logging import uuid import re import threading import requests import rarfile logger = logging.getLogger('rapiddl.main') def clean_name(link): '''Cleans a file name, stripping it it's base url. Args: link (str): a link/url to clean Returns: (str): a suitable file name ''' if link[-5:] == '.html': link = link[:-5] file_name = link.split('/')[-1] logger.info(f' file name: {file_name}') return file_name def build_payload(username, password): '''Returns authentication information in the form of dict. Args: username (str): the username to authenticate with password (str): the password to authenticate with Returns: (dict): login payload ''' if not re.match(r'[^@]+@[^@]+\.[^@]+', username): raise ValueError('Username is not a valid email address.') return {'LoginForm[email]': username, 'LoginForm[password]': password} def make_staging(destination): '''Creates a staging directory based off uuid.uuid4[:8] and returns the path as a string. Args: destination (str): the original destination path. Returns: (str): staging path ''' guid = str(uuid.uuid4())[:8] staging_path = os.path.join(destination, guid) os.mkdir(staging_path) logger.info(f' staging path: {staging_path}') return staging_path def parse_args(args): '''Parses arguemnts using the argparse package. Args: args (list): arguments passed from sys.argv Returns: argparse.NameSpace ''' parser = argparse.ArgumentParser(description='Rapidgator downloader') parser.add_argument('-l', '--link', nargs='+') parser.add_argument('-d', '--destination', required=True) parser.add_argument('-f', '--file') parser.add_argument('-e', '--extract', nargs='?', default=False, const=True) parser.add_argument('-n', '--filename') parser.add_argument('-u', '--username') parser.add_argument('-p', '--password') parser.add_argument('-v', '--verbose', action='count') return parser.parse_args(args) def get(session, link, path, threads): '''Uses thread objects to concurrently download the remote file(s). Args: session (requests.Session): a valid session object link (str): a valid rapidgator link path (str): the destination path to download the file(s) threads (list): threading.Thread list ''' thread = threading.Thread(target=_get, args=(session, link, path)) threads.append(thread) thread.start() def _get(session, link, path): '''Encapsulates the process of fetching and saving the file(s) to disk. Args: session (requests.Session): a valid session object link (str): a valid rapidgator link path (str): the destination path to download the file(s) ''' file_name = clean_name(link) logger.info(f' downloading file from: {link}') with session.get(link, allow_redirects=True, stream=True) as response: with open(os.path.join(path, file_name), 'wb') as file: for chunk in response.iter_content(chunk_size=1024): if chunk: file.write(chunk) def unzip(file, path): '''Unzips files with the .rar extension Args: file: full path to the file that you want to extract path (str): full path to the zip file ''' file = os.path.join(path, file) file_name = file.split(os.path.sep)[-1] try: with rarfile.RarFile(file, crc_check=False) as rf: for rar_file in rf.infolist(): rf.extract(rar_file, path=path) logging.info(f' extracting {file_name} to {path}') except Exception as err: logger.warning(str(err)) def main(args): parser = parse_args(args) if parser.verbose == None: log_level = logging.ERROR elif parser.verbose == 1: log_level = logging.WARN elif parser.verbose == 2: log_level = logging.INFO elif parser.verbose > 2: log_level = logging.DEBUG logging.basicConfig(level=log_level) if not os.path.exists(parser.destination): raise FileNotFoundError(f'{parser.destination} does not exist.') else: staging_path = make_staging(parser.destination) threads = [] ZIP_FORMATS = ['.rar'] VIDEO_FORMATS = ['.mkv','.mp4'] LOGIN_URL = 'https://rapidgator.net/auth/login' LOGIN_PAYLOAD = build_payload(parser.username, parser.password) with requests.Session() as session: post = session.post(LOGIN_URL, data=LOGIN_PAYLOAD) for link in parser.link: get(session, link, staging_path, threads) for thread in threads: thread.join() for file in os.listdir(staging_path): full_path = os.path.join(staging_path, file) if file[-4:] in ZIP_FORMATS: if parser.extract: logger.info(f' extracting files to {parser.destination}') unzip(file=full_path, path=parser.destination) else: shutil.move(full_path, parser.destination) else: try: shutil.move(full_path, parser.destination) logger.info(f' {file} moved to {parser.destination}') except Exception as err: logger.error(str(err)) shutil.rmtree(staging_path) logger.info(f' removing staging directory: {staging_path}') if __name__ == '__main__': main(sys.argv[1:])
C++
UTF-8
7,142
2.828125
3
[]
no_license
#include "pch.h" #include "corona.h" string corona::getmeta() { return meta_file_path; } void corona::openfile(vector <string>& file_names, ifstream& in) { //for loop runs till the number of images mentioned at the start of the meta file string file_path; in >> file_path; //file names are read and stored file_names.push_back(file_path); in >> file_path; file_names.push_back(file_path); } void corona::setcount(int& count1, int& count2, ifstream& file1, ifstream& file2) { file1.open(corona_file_names[0]); if (file1.is_open()) { cout << "file 1 open" << endl; } else { cout << "failed to open file 1" << endl; } file2.open(corona_file_names[1]); if (file2.is_open()) { cout << "file 2 open" << endl; } else { cout << "failed to open file 2" << endl; } while (file1) { char a; file1 >> a; count1++; } cout << "\ncount set1" << endl; cout << count1 << endl; while (file2) { char a; file2 >> a; count2++; } cout << "\ncount set2" << endl; cout << count2 << endl; int root1 = sqrt(count1); if (root1 * root1 < count1) { col1 = root1 + 1; row1 = root1 + 1; } else { col1 = root1; row1 = root1; } int root2 = sqrt(count2); if (root2 * root2 < count2) { col2 = root2 + 1; row2 = root2 + 1; } else { col2 = root2; row2 = root2; } file1.close(); file2.close(); } void corona::open_arr(int virus_arr_1[], int virus_arr_2[], ifstream& file1, ifstream& file2, int& count1, int& count2) { file1.open(corona_file_names[0]); file2.open(corona_file_names[1]); char inp1, inp2; int i = 0; while (!file1.eof()) { file1 >> inp1; switch (inp1) { case 'a': { virus_arr_1[i] = 1; break; } case 'c': { virus_arr_1[i] = 2; break; } case 't': { virus_arr_1[i] = 3; break; } case 'g': { virus_arr_1[i] = 4; break; } default: break; } i++; } i = 0; while (!file2.eof()) { file2 >> inp2; switch (inp2) { case 'a': { virus_arr_2[i] = 1; break; } case 'c': { virus_arr_2[i] = 2; break; } case 't': { virus_arr_2[i] = 3; break; } case 'g': { virus_arr_2[i] = 4; break; } default: break; } i++; } file1.close(); file2.close(); } void corona::open_image(Mat& image_1, Mat& image_2, int virus_arr_1[], int virus_arr_2[], int count1, int count2) { image_1 = Mat::zeros(row1, col1, CV_8UC3); image_2 = Mat::zeros(row2, col2, CV_8UC3); cout << "\nrow1 = " << row1 << endl; cout << "col1 = " << col1 << endl; cout << "row2 = " << row2 << endl; cout << "col2 = " << col2 << endl; int inc = 0; while (inc < count1) { for (int i = 0; i < row1; i++) { for (int j = 0; j < col1; j++) { Vec3b color_s = image_1.at<Vec3b>(Point(i, j)); if (virus_arr_1[inc] == 1) { color_s.val[0] = 255; color_s.val[1] = 0; color_s.val[2] = 0; image_1.at<Vec3b>(Point(i, j)) = color_s; } else if (virus_arr_1[inc] == 2) { color_s.val[0] = 0; color_s.val[1] = 255; color_s.val[2] = 0; image_1.at<Vec3b>(Point(i, j)) = color_s; } else if (virus_arr_1[inc] == 3) { color_s.val[0] = 0; color_s.val[1] = 0; color_s.val[2] = 255; image_1.at<Vec3b>(Point(i, j)) = color_s; } else if (virus_arr_1[inc] == 4) { color_s.val[0] = 0; color_s.val[1] = 255; color_s.val[2] = 255; image_1.at<Vec3b>(Point(i, j)) = color_s; } else { color_s.val[0] = 0; color_s.val[1] = 0; color_s.val[2] = 0; } inc++; } } } inc = 0; while (inc < count2) { for (int i = 0; i < row2; i++) { for (int j = 0; j < col2; j++) { Vec3b color_s = image_2.at<Vec3b>(Point(i, j)); if (virus_arr_2[inc] == 1) { color_s.val[0] = 255; color_s.val[1] = 0; color_s.val[2] = 0; image_2.at<Vec3b>(Point(i, j)) = color_s; } else if (virus_arr_2[inc] == 2) { color_s.val[0] = 0; color_s.val[1] = 255; color_s.val[2] = 0; image_2.at<Vec3b>(Point(i, j)) = color_s; } else if (virus_arr_2[inc] == 3) { color_s.val[0] = 0; color_s.val[1] = 0; color_s.val[2] = 255; image_2.at<Vec3b>(Point(i, j)) = color_s; } else if (virus_arr_2[inc] == 4) { color_s.val[0] = 0; color_s.val[1] = 255; color_s.val[2] = 255; image_2.at<Vec3b>(Point(i, j)) = color_s; } else { color_s.val[0] = 0; color_s.val[1] = 0; color_s.val[2] = 0; } inc++; } } } cv::namedWindow("Image_1"); cv::namedWindow("Image_2"); cv::resizeWindow("Image_1", 600, 600); cv::resizeWindow("Image_2", 600, 600); cv::imshow("Image_1", image_1); cv::imshow("Image_2", image_2); cv::waitKey(0); } double corona::compare_img(Mat& image_1, Mat& image_2) { Mat m_flat_1 = image_1.reshape(1, 1); Mat m_flat_2 = image_2.reshape(1, 1); int count = 0; int limit_i = (m_flat_1.cols / 3) - 10; int limit_j = (m_flat_2.cols / 3) - 10; double divide = 0; cout << limit_i << endl; cout << limit_j << endl; for (int i = 0; i < limit_i; i = i + 10) { divide++; for (int j = 0; j < limit_j; j = j + 10) { bool equal = 1; for (int c = 0; c < 10; c++) { //cout <<endl<< i << " " << j; if (m_flat_1.at<Vec3b>(Point(i + c, 0)) != m_flat_2.at<Vec3b>(Point(j + c, 0))) { equal = 0; } } if (equal) { count++; cout << endl << " Count = " << count; break; } } } cout << endl << "Count = " << count; cout << endl << "Divide = " << divide; cout << endl << "Percentage = " << (count / divide) * 100 << "%"; return (count / divide) * 100; } void corona::subt(Mat& image_1, Mat& image_2) { Mat subt = image_1 - image_2; cv::imshow("Subtracted Image", subt); cv::waitKey(0); } void corona::sim(Mat& image_1, Mat& image_2) { Mat siml = Mat::zeros(row1, col1, CV_8UC3); for (int i = 0; i < row1; i++) { for (int j = 0; j < col1; j++) { Vec3b color_s = image_1.at<Vec3b>(Point(i, j)); if (image_1.at<Vec3b>(Point(i, j)) == image_2.at<Vec3b>(Point(i, j))) { color_s.val[0] = 255; color_s.val[1] = 255; color_s.val[2] = 255; siml.at<Vec3b>(Point(i, j)) = color_s; } else { color_s.val[0] = 0; color_s.val[1] = 0; color_s.val[2] = 0; siml.at<Vec3b>(Point(i, j)) = color_s; } } } cv::imshow("Similarity Image", siml); cv::waitKey(0); } void corona::per_out() { ifstream per_in; per_in.open("per_dat.txt"); if (per_in.is_open()) { cout << endl << "percentage file open" << endl; } else { cout << "failed to open" << endl; } for (int i = 0; i < 5; i++) { double val; per_in >> val; per_val.push_back(val); } for (int i = 0; i < per_val.size(); i++) { cout << endl << per_val[i]; } }
TypeScript
UTF-8
226
2.625
3
[]
no_license
import { PrimaryColumn, Column, Entity } from 'typeorm'; @Entity() export class KeyValuePair { @PrimaryColumn() key?: string; @Column({ type: 'varchar', length: 90, nullable: false, }) value: string; }
PHP
UTF-8
906
2.625
3
[ "MIT" ]
permissive
<?php namespace Database\Factories; use App\Models\Equipe; use Illuminate\Database\Eloquent\Factories\Factory; class EquipeFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Equipe::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ "nom" => $this->faker->company, "ville" => $this->faker->city, "pays" => $this->faker->randomElement( [ 'Allemagne', 'Belgique', 'Autriche', 'Bulgarie', 'Chypre', 'Croatie', 'Danemark', 'Australie', 'Japon', 'Nouvelle-Zélande', 'Rwanda', 'Singapour', 'Corée du Sud', 'Thaïlande', 'Uruguay' ] ), "joueurs_max" => rand(1, 10) ]; } }
Java
UTF-8
868
2.65625
3
[]
no_license
import java.util.Objects; public class answerkey extends exam { public static int mark; String qstno; public answerkey(String qstno, String answer, int mark) { this.qstno = qstno; this.answer = answer; this.mark = mark; } void answer(){ int mark1; } String answer; public static void main(String[] args) { } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof answerkey)) return false; answerkey answerkey = (answerkey) o; return mark == answerkey.mark && Objects.equals(qstno, answerkey.qstno) && Objects.equals(answer, answerkey.answer); } @Override public int hashCode() { return Objects.hash(mark, qstno, answer); } }
C#
UTF-8
1,126
3.390625
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FFX2SaveEditor { public static class Utils { public static double RadianToDegree(double angle) { return angle * (180.0 / Math.PI); } public static byte[] BoolsToBytes(bool[] bools) { var bytes = new byte[bools.Length / 8]; for (int b = 0; b < bytes.Length; b++) { for (int bit = 0; bit < 8; bit++) { if (bools[b + bit]) bytes[b] &= (byte)Math.Pow(2, bit); } } return bytes; } } public static class Extensions { public static void Write(this BinaryWriter bw, bool[] bools) { bw.Write(Utils.BoolsToBytes(bools)); } public static void Write(this BinaryWriter bw, int offset, short value) { bw.BaseStream.Seek(offset, SeekOrigin.Begin); bw.Write(value); } } }
Markdown
UTF-8
2,008
2.703125
3
[]
no_license
自2020年12月1日起,专线网关提供自然月内各实例的出方向用量明细详情,帮助您精准量化资源消耗,轻松核算项目成本。本文将介绍如何下载并查看专线网关用量明细。 >?目前流控功能仅支持 VPC 型的专线网关。 > ## 操作步骤 1. 登录 [专线接入控制台](https://console.cloud.tencent.com/dc/dc) ,并在右上角菜单栏选择**费用** > **费用账单**。 2. 在费用中心控制台左侧导航栏选择**费用账单**> **用量明细下载**。 3. 在“用量明细下载”页面上方选择账单月份。 >? 用量明细是按扣费时间生成的月度账单。例如在1月31日23:00~23:59使用的按小时结算的按量计费资源,实际扣费时间发生在2月1日,则按扣费周期,该笔费用统计到2月账单。 > 4. 在产品列表中勾选**专线接入**,然后单击**下载用量明细**。 ![](https://main.qcloudimg.com/raw/0347d72549ee23ee7a24df9cb3ef74c9.png) 5. 在“导出记录”页面,找到所生成的文件,并在右侧“操作”列,单击**下载**。 ![](https://main.qcloudimg.com/raw/a0f748a013b46cad702d83a839efbda8.png) 6. 在本地打开下载的用量明细表,即可查看专线网关出方向的用量明细。用量明细表各数据说明如下: - <img src="https://main.qcloudimg.com/raw/4701489f2bc9418144293df4a62c020e.png" width="2%">:专线网关的出方向用量明细每5分钟统计一次。 - <img src="https://main.qcloudimg.com/raw/a45f3c11fbb957fd2a5b656442cd3652.png" width="2%">:专线网关为后付费,且每月产生的用量明细在次月1日统计。 - <img src="https://main.qcloudimg.com/raw/37845b477446d77bbc943cd5afb3390b.png" width="2%">:专线网关出方向每5分钟的流量统计,单位为 GB。 - <img src="https://main.qcloudimg.com/raw/24c49b08be3a98330aa42da6e5c70896.png" width="2%">:每个页签表示一个专线网关。 ![](https://main.qcloudimg.com/raw/cae95efd17481fefa237b87f76956060.png)
TypeScript
UTF-8
667
3.125
3
[]
no_license
import { parseDate, parseDateTime, dayOfYear, currentDayOfYear, } from "https://deno.land/std/datetime/mod.ts"; console.log(parseDate("20-01-2019", "dd-mm-yyyy")); // output : new Date(2019, 0, 20) console.log(parseDate("2019-01-20", "yyyy-mm-dd")); // output : new Date(2019, 0, 20) console.log(parseDateTime("01-20-2019 16:34", "mm-dd-yyyy hh:mm")); // output : new Date(2019, 0, 20, 16, 34) console.log(parseDateTime("16:34 01-20-2019", "hh:mm mm-dd-yyyy")); // output : new Date(2019, 0, 20, 16, 34) console.log(dayOfYear(new Date("2020-05-05T10:24:00"))); // output: 126 console.log(currentDayOfYear()); // output: ** depends on when you run it :) **
Swift
UTF-8
7,046
2.640625
3
[]
no_license
// // SmartHomeTests.swift // SmartHomeTests // // Created by Goga Barabadze on 12.10.20. // Copyright © 2020 Goga Barabadze. All rights reserved. // import XCTest @testable import Smart_Home class ModelTests: XCTestCase { override func setUpWithError() throws { } override func tearDownWithError() throws { } // func testCurrentConsumptionEmpty() throws { // let weather = OldWeather(temperatureInCelsius: 0, windSpeedInKilometerPerHour: 0, sunrise: "", sunset: "", visibilityInKilometers: 0) // let location = OldLocation(zip: "ZIP", place: "PLACE", province: "PROVINCE", weather: weather) // let device = OldDevice(name: "DEVICE NAME", company: "COMPANY", state: .running) // let station = OldStation(name: "STATION NAME", location: location, devices: [device]) // // XCTAssert(station.currentConsumption == 0) // } // // func testCurrentProductionEmpty() { // let weather = OldWeather(temperatureInCelsius: 0, windSpeedInKilometerPerHour: 0, sunrise: "", sunset: "", visibilityInKilometers: 0) // let location = OldLocation(zip: "ZIP", place: "PLACE", province: "PROVINCE", weather: weather) // let device = OldDevice(name: "DEVICE NAME", company: "COMPANY", state: .running) // let station = OldStation(name: "STATION NAME", location: location, devices: [device]) // // XCTAssert(station.currentProduction == 0) // } // // func testCurrentConsumptionWithMultipleRunningConsumers() throws { // let weather = OldWeather(temperatureInCelsius: 0, windSpeedInKilometerPerHour: 0, sunrise: "", sunset: "", visibilityInKilometers: 0) // let location = OldLocation(zip: "ZIP", place: "PLACE", province: "PROVINCE", weather: weather) // let consumer_1 = OldConsumer(name: "CONSUMER", consumption: 7, manufacturer: "MANUFACTURER", state: .running) // let consumer_2 = OldConsumer(name: "CONSUMER", consumption: 8, manufacturer: "MANUFACTURER", state: .running) // let consumer_3 = OldConsumer(name: "CONSUMER", consumption: 9, manufacturer: "MANUFACTURER", state: .running) // let station = OldStation(name: "STATION NAME", location: location, devices: [consumer_1, consumer_2, consumer_3]) // // XCTAssert(station.currentConsumption == 24) // } // // func testCurrentProductionWithMultipleRunningProducers() throws { // let weather = OldWeather(temperatureInCelsius: 0, windSpeedInKilometerPerHour: 0, sunrise: "", sunset: "", visibilityInKilometers: 0) // let location = OldLocation(zip: "ZIP", place: "PLACE", province: "PROVINCE", weather: weather) // let producer_1 = OldProducer(name: "PRODUCER", production: 7, manufacturer: "MANUFACTURER", state: .running) // let producer_2 = OldProducer(name: "PRODUCER", production: 8, manufacturer: "MANUFACTURER", state: .running) // let producer_3 = OldProducer(name: "PRODUCER", production: 9, manufacturer: "MANUFACTURER", state: .running) // let station = OldStation(name: "STATION NAME", location: location, devices: [producer_1, producer_2, producer_3]) // // XCTAssert(station.currentProduction == 24) // } // // func testCurrentConsumptionWithMultipleMixedRunningAndNotRunningConsumers() throws { // let weather = OldWeather(temperatureInCelsius: 0, windSpeedInKilometerPerHour: 0, sunrise: "", sunset: "", visibilityInKilometers: 0) // let location = OldLocation(zip: "ZIP", place: "PLACE", province: "PROVINCE", weather: weather) // let consumer_1 = OldConsumer(name: "CONSUMER", consumption: 1, manufacturer: "MANUFACTURER", state: .running) // let consumer_2 = OldConsumer(name: "CONSUMER", consumption: 1, manufacturer: "MANUFACTURER", state: .not_running) // let consumer_3 = OldConsumer(name: "CONSUMER", consumption: 1, manufacturer: "MANUFACTURER", state: .should_be_running) // let consumer_4 = OldConsumer(name: "CONSUMER", consumption: 1, manufacturer: "MANUFACTURER", state: .should_not_be_running) // let station = OldStation(name: "STATION NAME", location: location, devices: [consumer_1, consumer_2, consumer_3, consumer_4]) // // XCTAssert(station.currentConsumption == 2) // } // // func testCurrentProductionWithMultipleMixedRunningAndNotRunningProducers() throws { // let weather = OldWeather(temperatureInCelsius: 0, windSpeedInKilometerPerHour: 0, sunrise: "", sunset: "", visibilityInKilometers: 0) // let location = OldLocation(zip: "ZIP", place: "PLACE", province: "PROVINCE", weather: weather) // let producer_1 = OldProducer(name: "PRODUCER", production: 1, manufacturer: "MANUFACTURER", state: .running) // let producer_2 = OldProducer(name: "PRODUCER", production: 1, manufacturer: "MANUFACTURER", state: .not_running) // let producer_3 = OldProducer(name: "PRODUCER", production: 1, manufacturer: "MANUFACTURER", state: .should_be_running) // let producer_4 = OldProducer(name: "PRODUCER", production: 1, manufacturer: "MANUFACTURER", state: .should_not_be_running) // let station = OldStation(name: "STATION NAME", location: location, devices: [producer_1, producer_2, producer_3, producer_4]) // // XCTAssert(station.currentProduction == 2) // } // // func testPerformanceOfConsumptionProductionCalculation() throws { // // let weather = OldWeather(temperatureInCelsius: 0, windSpeedInKilometerPerHour: 0, sunrise: "", sunset: "", visibilityInKilometers: 0) // let location = OldLocation(zip: "ZIP", place: "PLACE", province: "PROVINCE", weather: weather) // var devices = [OldDevice]() // // for i in 0...99999 { // devices.append(OldProducer(name: "PRODUCER", production: i * 1, manufacturer: "MANUFACTURER", state: .running)) // devices.append(OldProducer(name: "PRODUCER", production: i * 11, manufacturer: "MANUFACTURER", state: .not_running)) // devices.append(OldProducer(name: "PRODUCER", production: i * 111, manufacturer: "MANUFACTURER", state: .should_be_running)) // devices.append(OldProducer(name: "PRODUCER", production: i * 1111, manufacturer: "MANUFACTURER", state: .should_not_be_running)) // // devices.append(OldConsumer(name: "CONSUMER", consumption: i * 1, manufacturer: "MANUFACTURER", state: .running)) // devices.append(OldConsumer(name: "CONSUMER", consumption: i * 11, manufacturer: "MANUFACTURER", state: .not_running)) // devices.append(OldConsumer(name: "CONSUMER", consumption: i * 111, manufacturer: "MANUFACTURER", state: .should_be_running)) // devices.append(OldConsumer(name: "CONSUMER", consumption: i * 1111, manufacturer: "MANUFACTURER", state: .should_not_be_running)) // } // // let station = OldStation(name: "STATION NAME", location: location, devices: devices) // // measure { // XCTAssert(station.currentConsumption == 5559944400000) // XCTAssert(station.currentProduction == 5559944400000) // } // } }
Python
UTF-8
3,711
3.078125
3
[]
no_license
""" Host Scanning ============= """ import random from ipaddress import IPv4Address, IPv4Network from mininet.node import Controller from container.kali import Kali from scenarios import Scenario from utils import subnet class Import(Scenario): """This scenario asks the user to find out information about they are connected to by checking thier adapter and performing a scan with `nmap`.""" name = "Host Scanning" enabled = True weight = 10 kali = None # type: Kali """Kali: Kali docker container used to access the scenario.""" subnet = None # type: IPv4Network """IPv4Network: Network range from which host IPs are taken.""" prefixlen = None def create_network(self, controller=Controller): """ Adds a switch, a Kali container, and several mininet hosts to the network created in the base class. TODO: An __init__ parameter should be used to allow overriding prefixlen and host count """ Scenario.create_network(self, controller) # Add switch switch = self.net.addSwitch('s1') # Create a random subnet to add hosts to self.prefixlen = random.randint(24, 27) self.subnet = subnet.generate(self.prefixlen) hosts = list(self.subnet.hosts()) # Add kali self.kali = self.net.addDocker('kali', cls=Kali, ip="%s/%s" % (hosts.pop(), self.prefixlen)) self.net.addLink(switch, self.kali) for i in range(0, random.randint(10, 25)): # If the host list is empty, exit if not hosts: break # Get a random IP from the list of hosts ip = hosts.pop(random.randrange(len(hosts))) # Add a host host = self.net.addHost('h' + str(i), ip="%s/%s" % (ip, self.prefixlen)) # Link host to switch self.net.addLink(switch, host) def run_network(self): """ Extends base function to run the commands neccesary to complete the task if we are a developer, for testing. """ super(Import, self).run_network() if self.developer: self.kali.cmd('ip a') self.kali.cmd('nmap -sP %s/%s' % (self.kali.defaultIntf().IP(), self.subnet.prefixlen)) def generate_task(self, doc): super(Import, self).generate_task(doc) doc.add_paragraph( 'This task requires you to use ip/ifconfig and nmap ' 'to gather information about the connected network. ' 'Answer the following questions:') def generate_questions(self): self.questions += [("What subnet is assigned to the Kali machine", str(self.kali.defaultIntf().IP())), ("What is the Network Address of this network", str(self.subnet.network_address)), ("What is the Broadcast Address of this network", str(self.subnet.broadcast_address)), ("What Range of IP adresses is usable in this subnet", "%s - %s" % (self.subnet.network_address + 1, self.subnet.broadcast_address - 1)), # Sort by IP, don't include Kali ("What IP adresses are found to have hosts up", "\n"+("\n".join( host.IP() for host in sorted(self.net.hosts, key=lambda x: int(IPv4Address(x.IP()))) if host.name != 'kali')))] if __name__ == "__main__": # Run network Import(developer=True, seed="debug").run()
Java
UTF-8
1,901
2.609375
3
[]
no_license
package cz.vutbr.fit.gja.gjaddr.gui; import com.community.xanadu.components.table.BeanReaderJTable; import cz.vutbr.fit.gja.gjaddr.persistancelayer.*; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableRowSorter; /** * Panel with contacts * * @author Bc. Jan Kaláb <xkalab00@stud.fit,vutbr.cz> */ class ContactsPanel extends JPanel { static final long serialVersionUID = 0; private static final Database db = new Database(); private static final BeanReaderJTable<Contact> table = new BeanReaderJTable<Contact>(new String[] {"FullName", "Phones"}, new String[] {"Name", "Phone"}); private static final TableRowSorter<BeanReaderJTable.GenericTableModel> sorter = new TableRowSorter<BeanReaderJTable.GenericTableModel>(table.getModel()); /** * Constructor */ public ContactsPanel(ListSelectionListener listSelectionListener) { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); JLabel label = new JLabel("Contacts"); label.setAlignmentX(CENTER_ALIGNMENT); add(label); fillTable(db.getAllContacts()); table.getSelectionModel().addListSelectionListener(listSelectionListener); table.setRowSorter(sorter); JScrollPane scrollPane = new JScrollPane(table); filter(""); add(scrollPane); } /** * Fill table with data from list */ void fillTable(List<Contact> contacts) { final RowFilter filter = sorter.getRowFilter(); //Warnings! sorter.setRowFilter(null); table.clear(); table.addRow(contacts); //System.out.println(model.getDataVector()); sorter.setRowFilter(filter); } /** * Filter contacts * * @param f String to filter */ void filter(String f) { //System.out.println("Filtering: " + f); sorter.setRowFilter(RowFilter.regexFilter("(?i)" + f)); } Contact getSelectedContact() { return table.getSelectedObject(); } }
Java
UTF-8
138
1.546875
2
[ "Apache-2.0" ]
permissive
package com.hyq.hm.videosdk.impl; public interface OnAuthStateListener { void onSucess(); void onFail(); void onError(); }
Python
UTF-8
6,838
2.59375
3
[]
no_license
import os import math import pandas as pd import numpy as np from joblib import load #default_path = r'C:\Users\Cyndi\Documents\Git Repository\Stat 404 Private\Project_Final' #os.chdir(default_path) # Load model model = load('app_installations.joblib') # User input data def input_data(): INPUT = pd.DataFrame() i = 0 while True: INPUT.loc[i,'Category'] = input("Please enter category: ") INPUT.loc[i,'Rating'] = input("Please enter Rating: ") INPUT.loc[i,'Size'] = input("Please enter Size: ") INPUT.loc[i,'Type'] = input("Please enter Type: ") INPUT.loc[i,'Price'] = input("Please enter Price: ") INPUT.loc[i,'Content Rating'] = input("Please enter Content Rating: ") INPUT.loc[i,'Genres'] = input("Please enter Genres: ") INPUT.loc[i,'Last Updated'] = input("Please enter Last Updated: ") INPUT.loc[i,'Android Ver'] = input("Please enter Android Ver: ") if input("More inputs? Yes = Continue, No = See Results: ") == 'No': break i += 1 return INPUT # Data processing: def data_processing(DF): DF['Rating'] = DF['Rating'].apply(lambda x: float(x)) DF['Size'] = DF['Size'].apply(lambda x: x.replace('M', '000000').replace('.', '').replace('k', '000')) DF['size_category'] = ' ' for i in range(len(DF)): if DF.loc[i, 'Size'] == 'Varies with device': DF.loc[i, 'size_category'] = 'Varies with device' elif int(DF.loc[i, 'Size']) < 10000000: DF.loc[i, 'size_category'] = 'Size < 10MB' elif int(DF.loc[i, 'Size']) < 50000000: DF.loc[i, 'size_category'] = '10MB<=Size<50MB' else: DF.loc[i, 'size_category'] = 'Size >= 50MB' def log_transform(x): return math.log10(x+1) def float_price(x): return float(x.replace('$', '')) DF['Price'] = DF['Price'].apply(float_price) DF['log_Price'] = DF['Price'].apply(log_transform) DF['Content Rating'] = ['Mature 17+' if r == 'Adults only 18+' else 'Everyone' if r == 'Unrated' else r for r in DF['Content Rating']] DF['Last Updated'] = pd.to_datetime(DF['Last Updated']) DF['Year'] = [d.year for d in DF['Last Updated']] DF['Month'] = [d.month for d in DF['Last Updated']] DF['Android Version Group'] = ' ' for i in range(len(DF)): if DF.loc[i, 'Android Ver'] == 'Varies with device': DF.loc[i, 'Android Version Group'] = 'Varies with device' elif int(DF.loc[i, 'Android Ver'][0]) < 4: DF.loc[i, 'Android Version Group'] = 'Allow Older than Android Ver 4' elif int(DF.loc[i, 'Android Ver'][0]) < 5: DF.loc[i, 'Android Version Group'] = 'Android Version 4 and up' else: DF.loc[i, 'Android Version Group'] = 'Android Version newer than 5' DF['Genres_count'] = DF['Genres'].apply(lambda x: len(x.split(';'))) DF['First_Genres'] = DF['Genres'].str.split(';', expand=True)[0] def add_dummies(DF): DF = DF[['Category', 'Type', 'Content Rating', 'Android Version Group', 'size_category', \ 'log_Price', 'Year', 'Month', 'Genres_count', 'First_Genres', 'Rating']] DF = pd.get_dummies(DF) INDEX = ['log_Price', 'Year', 'Month', 'Genres_count', 'Category_ART_AND_DESIGN', 'Category_AUTO_AND_VEHICLES', 'Category_BEAUTY', 'Category_BOOKS_AND_REFERENCE', 'Category_BUSINESS', 'Category_COMICS', 'Category_COMMUNICATION', 'Category_DATING', 'Category_EDUCATION', 'Category_ENTERTAINMENT', 'Category_EVENTS', 'Category_FAMILY', 'Category_FINANCE', 'Category_FOOD_AND_DRINK', 'Category_GAME', 'Category_HEALTH_AND_FITNESS', 'Category_HOUSE_AND_HOME', 'Category_LIBRARIES_AND_DEMO', 'Category_LIFESTYLE', 'Category_MAPS_AND_NAVIGATION', 'Category_MEDICAL', 'Category_NEWS_AND_MAGAZINES', 'Category_PARENTING', 'Category_PERSONALIZATION', 'Category_PHOTOGRAPHY', 'Category_PRODUCTIVITY', 'Category_SHOPPING', 'Category_SOCIAL', 'Category_SPORTS', 'Category_TOOLS', 'Category_TRAVEL_AND_LOCAL', 'Category_VIDEO_PLAYERS', 'Category_WEATHER', 'Type_Free', 'Type_Paid', 'Content Rating_Everyone', 'Content Rating_Everyone 10+', 'Content Rating_Mature 17+', 'Content Rating_Teen', 'Android Version Group_Allow Older than Android Ver 4', 'Android Version Group_Android Version 4 and up', 'Android Version Group_Android Version newer than 5', 'Android Version Group_Varies with device', 'size_category_10MB<=Size<50MB', 'size_category_Size < 10MB', 'size_category_Size >= 50MB', 'size_category_Varies with device', 'First_Genres_Action', 'First_Genres_Adventure', 'First_Genres_Arcade', 'First_Genres_Art & Design', 'First_Genres_Auto & Vehicles', 'First_Genres_Beauty', 'First_Genres_Board', 'First_Genres_Books & Reference', 'First_Genres_Business', 'First_Genres_Card', 'First_Genres_Casino', 'First_Genres_Casual', 'First_Genres_Comics', 'First_Genres_Communication', 'First_Genres_Dating', 'First_Genres_Education', 'First_Genres_Educational', 'First_Genres_Entertainment', 'First_Genres_Events', 'First_Genres_Finance', 'First_Genres_Food & Drink', 'First_Genres_Health & Fitness', 'First_Genres_House & Home', 'First_Genres_Libraries & Demo', 'First_Genres_Lifestyle', 'First_Genres_Maps & Navigation', 'First_Genres_Medical', 'First_Genres_Music', 'First_Genres_Music & Audio', 'First_Genres_News & Magazines', 'First_Genres_Parenting', 'First_Genres_Personalization', 'First_Genres_Photography', 'First_Genres_Productivity', 'First_Genres_Puzzle', 'First_Genres_Racing', 'First_Genres_Role Playing', 'First_Genres_Shopping', 'First_Genres_Simulation', 'First_Genres_Social', 'First_Genres_Sports', 'First_Genres_Strategy', 'First_Genres_Tools', 'First_Genres_Travel & Local', 'First_Genres_Trivia', 'First_Genres_Video Players & Editors', 'First_Genres_Weather', 'First_Genres_Word', 'Rating'] DF = DF.reindex(columns=INDEX, fill_value=0) return DF # Final predictions def prediction(DF): prediction = np.round(10**model.predict(DF)) for i in range(len(prediction)): print(f'The predicted number of installations for the input data is: {prediction[i]}') #Sample input: #ART_AND_DESIGN 4.1 19M Free 0 Everyone Art & Design 7-Jan-18 4.0.3 and up #ART_AND_DESIGN 3.9 14M Free 0 Everyone Art & Design;Pretend Play 15-Jan-18 4.0.3 and up #ART_AND_DESIGN 4.7 8.7M Free 0 Everyone Art & Design 1-Aug-18 4.0.3 and up # Run the models def run_model(): DF = input_data() data_processing(DF) DF = add_dummies(DF) prediction(DF) run_model()
Go
UTF-8
485
3.546875
4
[]
no_license
package leetcode import "fmt" func jump(nums []int) int { // 记录可达最远距离 max := 0 // 记录步数 step := 0 // 寻找范围内最远距离的过程中最远距离可能会更新,所以用一个 end 变量来记录。 end := 0 for i := 0; i < len(nums)-1; i++ { max = getMax(max, nums[i]+i) if i == end { step++ end = max } fmt.Println(end) } fmt.Println(step) return step } func getMax(a, b int) int { if a > b { return a } return b }
Java
UTF-8
1,434
2.34375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.onesystem.domain.builder; import br.com.onesystem.domain.Item; import br.com.onesystem.domain.ItemDePedido; import br.com.onesystem.domain.Pedido; import br.com.onesystem.exception.DadoInvalidoException; import java.math.BigDecimal; /** * * @author Rafael Cordeiro */ public class ItemDePedidoBuilder { private Long id; private Item item; private BigDecimal unitario; private BigDecimal quantidade; private Pedido pedido; public ItemDePedidoBuilder comItem(Item item) { this.item = item; return this; } public ItemDePedidoBuilder comId(Long id) { this.id = id; return this; } public ItemDePedidoBuilder comUnitario(BigDecimal unitario) { this.unitario = unitario; return this; } public ItemDePedidoBuilder comQuantidade(BigDecimal quantidade) { this.quantidade = quantidade; return this; } public ItemDePedidoBuilder comPedido(Pedido pedido) { this.pedido = pedido; return this; } public ItemDePedido construir() throws DadoInvalidoException { return new ItemDePedido(id, item, unitario, quantidade, pedido); } }
Go
UTF-8
1,818
2.59375
3
[]
no_license
package mongodb import ( "context" "fmt" config "golang-project/config/db" "golang-project/config/dbiface" "golang-project/models" "log" "github.com/segmentio/ksuid" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" ) type SessionsCollection struct { Ca *mongo.Collection } func GetSessionsCollection() *SessionsCollection { collections := config.DB.Collection(config.Cfg.SessionCollection) return &SessionsCollection{Ca: collections} } func GetSessions(ctx context.Context, collection dbiface.CollectionAPI) ([]models.Session, error) { var session []models.Session cursor, err := collection.Find(ctx, bson.M{}) if err != nil { log.Printf("Incapaz de encontrar el libro %+v", err) } err = cursor.All(ctx, &session) if err != nil { log.Printf("Incapaz de leer el cursor %+v", err) } return session, nil } func (s *SessionsCollection) GetSessionById(ctx context.Context, ssid string) (*models.Session, error) { var session models.Session res := s.Ca.FindOne(ctx, bson.M{"_id": ssid}) err := res.Decode(&session) if err != nil { return nil, err } return &session, nil } func (s *SessionsCollection) AddSession(ctx context.Context, session *models.Session) error { if len(session.ID) == 0 { session.ID = ksuid.New().String() } _, err := s.Ca.InsertOne(ctx, session) if err != nil { log.Printf("Incapaz de insertar en la base de datos:%v", err) return err } return nil } func (s *SessionsCollection) ValidateSession(ctx context.Context, ssid string) bool { var session models.Session res := s.Ca.FindOne(ctx, bson.M{"ssid": ssid, "enabled": true}) fmt.Printf("\n\n\nlinea 81 session %v\n\n", session) err := res.Decode(&session) fmt.Printf("\n\n\nlinea 81 session %v\n\n", res.Decode(&session)) if err != nil { return false } return true }
PHP
UTF-8
1,324
3.53125
4
[]
no_license
<?php class PasswordGenerator { public function __construct(){ } private function generatePasswordString(){ // Generer tekststreng // ASCII tal for($i = 48; $i <= 57; $i++){ $allChars .= chr($i); } // ASCII store bogstaver for($i = 65; $i <= 90; $i++){ $allChars .= chr($i); } // ASCII små bogstaver for($i = 97; $i <= 122; $i++){ $allChars .= chr($i); } // Tilføj udvalgte specialtegn til tekststreng $allChars .= ".,!?#()[]=%&~^:;-_"; // Bland karaktererne $allChars = str_shuffle($allChars); // Trim tekststreng til random antal karakterer (dog mellem 8 og 35) $chars = substr($allChars, 0, rand(8,35)); return $chars; } public function returnNewPassword(){ // Generer et password $password = $this->generatePasswordString(); // Test om passwordet indeholder alle påkrævede karakterer if(preg_match('/[a-z][A-Z][0-9]/', $password) && preg_match('/[!]|[#-&]|[(-,]|[{-~]|[:-@]/', $password) && strlen($password) >= 8){ return $password; }else { // Hvis password mangler en type karakterer, generer nyt password return $this->returnNewPassword(); } } }
C#
UTF-8
6,532
2.5625
3
[]
no_license
using Managing_Car_Program.DB; using MaterialSkin.Controls; using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Managing_Car_Program.Ui { partial class Cust_ma_add_Form : MaterialForm { public Cust_ma_add_Form() { InitializeComponent(); // 달력 uiTextBox_start.Text = monthCalendar1.SelectionRange.Start.ToString("yyyy-MM-dd"); uiTextBox_end.Text = monthCalendar1.SelectionRange.Start.ToString("yyyy-MM-dd"); } private void button_okay_Click(object sender, EventArgs e) { if (uiTextBox_nm.Text.Trim() == "") { MessageBox.Show("이름을 입력하세요."); return; } if (uiTextBox_carnum.Text.Trim() == "") { MessageBox.Show("차량번호를 입력하세요."); return; } if (uiTextBox_ph.Text.Trim() == "") { MessageBox.Show("전화번호를 입력하세요."); return; } if (uiTextBox_start.Text.Trim() == "") { MessageBox.Show("시작일을 입력하세요."); return; } if (uiTextBox_end.Text.Trim() == "") { MessageBox.Show("종료일을 입력하세요."); return; } // 차량 번호 중복 확인 for (int i = 0; i < VipData.vips.Count; i++) { string str = uiTextBox_carnum.Text; str = string.Concat(str.Where(x => !char.IsWhiteSpace(x))); // 모든 공백 삭제 if (uiTextBox_carnum.Text == VipData.vips[i].custcarnum) { MessageBox.Show("이미 등록된 차량 번호입니다."); return; } } if (uiTextBox_nm.Text != "" && uiTextBox_carnum.Text != "" && uiTextBox_ph.Text != "" && uiTextBox_start.Text != "" && uiTextBox_end.Text != "") { VipData.vips.Add(new VipCust(uiTextBox_nm.Text, uiTextBox_carnum.Text, uiTextBox_ph.Text, uiTextBox_start.Text, uiTextBox_end.Text)); // SQL DB.DB_mysql.insert_vip_DB(uiTextBox_nm.Text, uiTextBox_carnum.Text, uiTextBox_ph.Text, uiTextBox_start.Text, uiTextBox_end.Text); /*// SQL // 칼럼에 추가하는 커리문 insertQuery string insertQuery = "INSERT INTO viplist(name, carnumber, phone, start, end) VALUES ('" + uiTextBox_name_text.Text + "', '" + uiTextBox_car_text.Text + "', '" + uiTextBox_ph_text.Text + "', '" + uiTextBox_start_text.Text + "', '" + uiTextBox_end_text.Text + "')"; // 텍스트 박스에 입력한 내용이 테이블 viplist에 추가됨 connection.Open(); MySqlCommand command = new MySqlCommand(insertQuery, connection); try { if (command.ExecuteNonQuery() == 1) // 정상적으로 들어갔다면 { //MessageBox.Show("DB에 저장되었습니다."); } else { //MessageBox.Show("DB 저장에 실패했습니다."); return; } } catch (Exception ex) { MessageBox.Show(ex.Message); MessageBox.Show(ex.StackTrace); //throw; } connection.Close();*/ MessageBox.Show("정기권을 등록했습니다."); VipData.Savetxt(); string str = $"관리자 - 이름 : {uiTextBox_nm.Text}, 차량번호 : {uiTextBox_carnum.Text}, 전화번호 : {uiTextBox_ph.Text}," + $"정기권 시작일 : {uiTextBox_start.Text}, 정기권 종료일 : {uiTextBox_end.Text}이 등록되었습니다. (DB 저장 완료)"; txtwriteLog(str); DataManager.Save(); Close(); } else { MessageBox.Show("정기권을 등록하지 못했습니다."); return; } } private void txtwriteLog(string txtcontents) { string txtlogcontents = $"[{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}]{txtcontents}"; DataManager.printLog(txtlogcontents); } private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e) { //uiTextBox_start.Text = monthCalendar1.SelectionRange.Start.ToString("yyyy-MM-dd"); //uiTextBox_end.Text = monthCalendar1.SelectionRange.Start.ToString("yyyy-MM-dd"); if (uiRadioButton_start.Checked == true) { uiTextBox_start.Text = monthCalendar1.SelectionRange.Start.ToString("yyyy-MM-dd"); } else { uiTextBox_end.Text = monthCalendar1.SelectionRange.Start.ToString("yyyy-MM-dd"); } } private void uiTextBox_nm_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { uiTextBox_carnum.Focus(); } } private void uiTextBox_carnum_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { uiTextBox_ph.Focus(); } } private void uiTextBox_ph_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { uiTextBox_start.Focus(); } } private void uiTextBox_start_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { uiTextBox_end.Focus(); } } private void uiTextBox_end_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { button_okay.Focus(); } } } }
Java
UTF-8
5,502
2.59375
3
[ "Apache-2.0" ]
permissive
package org.adligo.fabricate.common.files; import java.io.File; import java.io.FileNotFoundException; import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.StandardCopyOption; import java.util.List; import java.util.zip.ZipFile; /** * This is a way to stub out calls to the file system * for test development. All methods implemented * for this interface are expected to be thread safe. * * @author scott * */ public interface I_FabFileIO { /** * calculate the md5 check sum of a file. * @param file * @return * @throws IOException */ public String calculateMd5(String file) throws IOException; /** * @param url * @return the status code from the http gets response. * @throws IOException */ public int check(String url) throws IOException; /** * copy a file * @param from * @param to * @param opt * @throws IOException */ public void copy(String from, String to, StandardCopyOption opt) throws IOException; /** * Creates a new file;<br/> * new File(filePath).createNewFile(); * @param filePath * @return */ public File create(String filePath) throws IOException; /** * Delete the file now * @param path * @return */ public void delete(String path) throws IOException ; /** * Calls new File(path).deleteOnExit(); * @param path */ public void deleteOnExit(String path); /** * This method deletes the files and folders under this path * and the path itself. * @param path * @throws IOException */ public void deleteRecursive(String path) throws IOException; /** * This method downloads a file from the url * to the file path (may be relative or absolute). * * @param url * @param file * @throws IOException */ public void downloadFile(String url, String file) throws IOException; /** * @param filePath * @return * new File(String filePath).exists(); */ public boolean exists(String filePath); /** * * @param filePath * @return new File(String filePath).getAbsolutePath() * the system dependent path. */ public String getAbsolutePath(String filePath); /** * * @return the system dependent directory * separator (Unix and Mac '\', Windows '/') */ public String getNameSeparator(); /** * returns the parent directory of the dir or file, * includes the last File.separatorChar. * * @param file * @return */ public String getParentDir(String file); /** * * @param absolutePath a system dependent * path. * @return a path which contains / for path separators, * for Unix (Mac) paths this returns a unchanged value. * For Windows paths this will return a strange value;<br/> * Input;<br/> * C:\foo\bar\etc<br/> * Output;<br/> * C:/foo/bar/etc<br/> */ public String getSlashPath(String absolutePath); /** * Creates a File instance;<br/> * return new File(filePath); * @param filePath * @return */ public File instance(String filePath); /** * This method lists the files under the path which match the file matcher. * @param path * @param matcher * @return The list of absolute path names. * @throws IOException */ public List<String> list(String path, final I_FileMatcher matcher) throws IOException; /** * @param dirsPath * new File(String dirsPath).mkDirs(); * @return */ public boolean mkdirs(String dirsPath); /** * * @param from * @param to * @param options * @throws IOException */ public void move(String from, String to, StandardCopyOption options) throws IOException; /** * * @param file * @return A OutputStream which is a OutputStream, which was done * because mockito had issues mocking OutputStream I think. * * @throws IOException * @throws FileNotFoundException */ public OutputStream newFileOutputStream(String file) throws IOException, FileNotFoundException; /** * simply creates a new ZipFile instance. * @param file * @return * @throws IOException */ public ZipFile newZipFile(String file) throws IOException; /** * Read the content of a file * @param path * @return * @throws IOException */ public String readFile(String path) throws IOException; /** * unzips a zip file. * @param file * @param toDir * @throws IOException */ public void unzip(String file, String toDir) throws IOException; /** * @param dir * @param zip * @return false when one of the zip file entries * is not on the disk under the dir. */ public boolean verifyZipFileExtract(String dir, ZipFile zip); /** * This method writes a file out to disk from a input stream, using NIO * (ByteBuffer, ReadableByteChannel, FileChannel). It uses * a default buffer size of 16Kb. * @param in * @param fos * @throws IOException */ public void writeFile(InputStream in, OutputStream fos) throws IOException; /** * This method writes a file out to disk from a input stream, using NIO * (ByteBuffer, ReadableByteChannel, FileChannel). * @param in * @param fos * @throws IOException */ public void writeFile(InputStream in, OutputStream fos, int bufferSize) throws IOException; /** * * @param filePath * @return */ // public boolean move(String filePath); }
Markdown
UTF-8
6,045
2.515625
3
[]
no_license
--- layout: post title: Trackguru, l'application des alumni Thomas Chrétien et Olivier Brunet dédiée au son techno author: cedric labels: - alumni - startup pushed: true thumbnail: thomas-chretien-trackguru.jpg description: "Parmi les alumni du Wagon se cachent certains individus aux initiatives sonores sympathiques. C'est le cas de Thomas Chrétien et Olivier Brunet, tous deux associés autour d'un projet commun : Trackguru. Les deux garçons ont pour ambition de prendre soin des esgourdes de tous les amateurs de son techno & house avec un outil de curation communautaire plutôt bien ficelé. Présentation de l'application et retour sur leur expérience au Wagon avec Thomas." --- ![Thomas Chrétien, cofondateur de Trackguru](blog_image_path thomas-chretien-trackguru.jpg) Parmi les alumni du Wagon se cachent certains individus aux initiatives sonores sympathiques. C'est le cas de [Thomas Chrétien](https://twitter.com/tchret) et [Olivier Brunet](https://twitter.com/olbrun), tous deux associés autour d'un projet commun : [Trackguru](http://www.trackguru.co/). Les deux garçons ont pour ambition de prendre soin des esgourdes de tous les amateurs de son techno & house avec un outil de curation communautaire plutôt bien ficelé. Présentation de l'application et retour sur leur expérience au Wagon avec Thomas. ###Comment as-tu atterri au Wagon ? À l'origine j’ai fait deux ans d’études en webmarketing. Rapidement, je me suis rendu compte qu’en plus de vouloir vendre un produit, je souhaitais surtout en créer un. J'avais plein d'idée et le fait de ne pas savoir coder représentait un obstacle de taille. Naturellement je me suis éloigné de l'école et j'ai exploré le milieu startup parisien. Rapidement je suis tombé sur [The Family](http://www.thefamily.co/) avant de me rediriger sur le site du [Wagon](http://www.lewagon.org/). Sans trop savoir sur quoi je m’embarquais, j’ai postulé directement et je me suis retrouvé quelques jours après à parler avec [Romain](https://twitter.com/romainpaillard), l'un des deux fondateurs du Wagon avec qui le feeling est super bien passé. Malgré quelques-uns de mes amis qui m'ont regardé un peu bizarrement sans oublier de ponctuer nos discussions de “Mais mec, tu ne fais plus d’étude ?!”, je me suis donné cette chance et j’ai foncé. ##Peux-tu nous en dire plus sur Trackguru ? Trackguru permet aux utilisateurs de poster des sons techno / house / deep house [...] en provenance de Youtube ou Soundcloud et de voter pour les autres tracks partagées par la communauté. Quand nous avons commencé à plancher sur le sujet avec Olivier, nous savions que l'enjeu principal se situait au niveau du prototype avec une bonne gestion des tracks. Pour faire simple, les tracks sont regroupées par jour de publication et le classement se fait par un tri de la liste obtenue en fonction du nombre de votes. ![Screen de Trackguru](blog_image_path screen-trackguru.jpg) ###Des envies de lever des fonds ? D'ajouts de nouvelles features ? Notre objectif principal est avant tout de réunir et fédérer une communauté pointue et d'améliorer sans cesse leur expérience utilisateur en apportant de nouvelles fonctionnalités sur la plateforme. Actuellement dans le pipe nous avançons sur la mise en place des profils "Guru" ainsi qu'une nouvelle interface orientée *player* afin de suivre les feedbacks de nos utilisateurs. Nous travaillons beaucoup en suivant leurs recommandations et nombreux retours (via Olark). Cela nous permet de résoudre pas mal de bugs très rapidement. Pour répondre à la première question, le service est encore très jeune. Avant de nous lancer dans une levée de fonds, nous préférons d'abord travailler notre acquisition et établir un *business model* centré sur l'utilisateur. ###Un mot sur ton associé et votre process d'exécution ? Oui avec plaisir. Olivier sort de l'[ESSCA](http://www.essca.fr/) et s'occupe désormais de la partie Market du projet. Pendant un cours de Lean Startup au Wagon, un des intervenants nous a conseillé de nous lancer à deux. Je savais que nous avions déjà pas mal d'atomes crochus ne serait-ce que par nos univers musicaux respectifs. L'association s'est faite naturellement à partir de là. Travailler à deux s'avère toujours complexe, mais cela permet de se sortir la tête du guidon quand l'autre se rend compte que l'on a complètement dérivé de l’idée de base. La dimension de binôme prend tout son sens à ce moment-là, lorsque suite à cette remarque, on en revient au plan initial pour ne pas se perdre et continuer d'avancer dans la bonne direction. ###Du coup, ravi de ton expérience au Wagon ? Complètement. Je prêche cette formation partout ! Nous gardons une relation très forte avec toute l'équipe du Wagon. Les profs n'hésitent pas à garder un oeil sur notre code, voir même à nous aider. Ça a été le cas au moment où nous étions en train de travailler sur un search intégré afin de parser les résultats de YouTube et SoundCloud en fonction de la requête user. Le code était assez velu et [Seb](https://twitter.com/ssaunier), le CTO du Wagon, n'a pas hésité à développer cette feature avec nous. L'aspect qui me semble le plus important à souligner, c’est qu’en plus de t’apprendre à coder, on t’enseigne un véritable *mindset* en plus d'être introduit dans un écosystème de personnalités ultras compétentes en terme de produit, de dev et d’exécution. La formation fullstack te donne des outils pour être hyper productif, les bonnes méthodes de travail et toutes les clefs en main pour devenir dev junior. À la fin de la formation, j'avais envie de partager tout ce que j'ai appris et de continuer à progresser. Du coup, je suis désormais *teaching assistant* quelques jours par semaine au Wagon. Au plaisir de vous y croiser ! ###Infos pratiques - Site : [Trackguru](http://www.trackguru.co/) - Facebook : [www.facebook.com/trackguru](https://www.facebook.com/trackguruapp) - Twitter : [@trackguruapp](https://twitter.com/trackguruapp)
Shell
UTF-8
828
3.265625
3
[]
no_license
#!/bin/bash TARGET_HOST="$MPD_MUSIC_HOST" CONTROL_SOCKET=/tmp/player-control-socket EXITING= if [[ "$TARGET_HOST" = "" ]] ; then echo "Your environment variable for MPD_MUSIC_HOST is not set." exit 1 fi function stop-tunnel { if [ -e "$CONTROL_SOCKET" ] ; then echo ":: closing tunnels..." ssh -S $CONTROL_SOCKET -O exit $TARGET_HOST fi } function start-tunnels { if [ ! -e "$CONTROL_SOCKET" ] ; then echo ":: starting tunnels ..." ssh -M -A -S $CONTROL_SOCKET -fnNT -L6600:localhost:6600 -L28000:localhost:8000 root@$TARGET_HOST -i ~/.ssh/id.ssh fi } function player { while [ -e "$CONTROL_SOCKET" ] ; do mpg123 "http://localhost:28000/mpd.mp3" >/dev/null 2>&1 sleep 1 done } trap stop-tunnel SIGINT SIGTERM start-tunnels player & ncmpcpp stop-tunnel
Java
UTF-8
2,875
2.125
2
[ "GPL-2.0-only", "Apache-2.0", "BSD-3-Clause", "MIT", "GPL-1.0-or-later", "LicenseRef-scancode-unknown", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.globo.globoaclapi.cloudstack.response; import com.cloud.agent.api.Answer; import java.util.List; public class GloboACLRulesResponse extends Answer { protected List<ACLRule> rules; public GloboACLRulesResponse(){ super(); } public GloboACLRulesResponse(List<ACLRule> rules) { this.result = true; this.setRules(rules); } public List<ACLRule> getRules() { return rules; } public void setRules(List<ACLRule> rules) { this.rules = rules; } public static class ACLRule { private String id; private String protocol; private String destination; private Integer icmpType; private Integer icmpCode; private Integer destPortStart; private Integer destPortEnd; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public Integer getIcmpType() { return icmpType; } public void setIcmpType(Integer icmpType) { this.icmpType = icmpType; } public Integer getIcmpCode() { return icmpCode; } public void setIcmpCode(Integer icmpCode) { this.icmpCode = icmpCode; } public Integer getPortStart() { return destPortStart; } public void setPortStart(Integer destPortStart) { this.destPortStart = destPortStart; } public Integer getPortEnd() { return destPortEnd; } public void setPortEnd(Integer destPortEnd) { this.destPortEnd = destPortEnd; } } }
Java
UTF-8
2,019
1.921875
2
[ "Apache-2.0" ]
permissive
package cu.uci.solr; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.common.SolrException; import org.apache.solr.common.params.CommonParams; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class MaxParamsSearchComponentTest extends SolrTestCaseJ4 { @Rule public ExpectedException exception = ExpectedException.none(); @BeforeClass public static void beforeClass() throws Exception { initCore("solrconfig-maxparams.xml", "schema.xml"); } @Test public void testRequestWithinBoundaries() throws Exception { assertU(adoc("id", "4505", "subject", "Hoss the Hoss man Hostetter")); assertU(commit()); assertU(optimize()); assertQ("couldn't find subject hoss", req(CommonParams.Q, "*:*", CommonParams.ROWS, Integer.toString(4)), "//result[@numFound=1]", "//int[@name='id'][.='4505']"); } @Test public void testRequestWithRowsParamExceeded() throws Exception { exception.expect(SolrException.class); exception.expectMessage( "Your start or rows parameter has exceeded the allowed values"); h.query( req(CommonParams.Q, "*:*", CommonParams.ROWS, Integer.toString(400))); } @Test public void testRequestWithStartParamExceeded() throws Exception { exception.expect(SolrException.class); exception.expectMessage( "Your start or rows parameter has exceeded the allowed values"); h.query( req(CommonParams.Q, "*:*", CommonParams.START, Integer.toString(5))); } @Test public void testOverwriteParams() throws Exception { assertU(adoc("id", "4505", "subject", "Hoss the Hoss man Hostetter")); assertU(commit()); assertU(optimize()); assertQ("the parameters haven't been overwritten", req(CommonParams.Q, "*:*", CommonParams.ROWS, Integer.toString(400), CommonParams.QT, "/overwrite"), "//result[@numFound=1]", "//int[@name='id'][.='4505']"); } }
SQL
UTF-8
2,839
3.09375
3
[ "MIT" ]
permissive
ALTER view [dw].[v_st_toimitilat] as --amk select Tilastovuosi = vuosi --,Ammattikorkeakoulu = d7.amk_nimi_fi ,Yliopisto = d1.yo_nimi_fi ,Ammattikorkeakoulu = NULL ,Toimipiste = NULL ,Toimipaikka = NULL --mittarit ,harjoittelukoulujen_tilat ,muut_vuokratilat ,yliopistokiinteistoyhtion_toimitilat_aalto_yliopistokiinteistot_oy ,yliopistokiinteistoyhtion_toimitilat_helsingin_yliopistokiinteistot_oy ,yliopistokiinteistoyhtion_toimitilat_suomen_yliopistokiinteistot_oy ,toimipaikan_henkilokunnan_henkilotyovuodet = NULL ,tutkimusaseman_henkilokunnan_maksimimäärä = NULL ,tutkimusaseman_henkilokunnan_minimäärä = NULL ,tutkimusaseman_yopymisvuorokaudet = NULL --koodit ,[Koodit Yliopisto] = d1.yo_tunnus ,[Koodit Ammattikorkeakoulu] = NULL --järjestykset from [dw].[f_yo_tilat] f join dw.d_yo d1 on d1.id=f.d_yliopisto_id UNION ALL select Tilastovuosi = vuosi --,Ammattikorkeakoulu = d7.amk_nimi_fi ,Yliopisto = NULL ,Ammattikorkeakoulu = d1.amk_nimi_fi ,Toimipiste = d3.toimipisteen_nimi ,Toimipaikka = d3.toimipaikan_nimi --mittarit ,harjoittelukoulujen_tilat = NULL ,muut_vuokratilat = NULL ,yliopistokiinteistoyhtion_toimitilat_aalto_yliopistokiinteistot_oy = NULL ,yliopistokiinteistoyhtion_toimitilat_helsingin_yliopistokiinteistot_oy = NULL ,yliopistokiinteistoyhtion_toimitilat_suomen_yliopistokiinteistot_oy = NULL ,toimipaikan_henkilokunnan_henkilotyovuodet ,tutkimusaseman_henkilokunnan_maksimimäärä = NULL ,tutkimusaseman_henkilokunnan_minimäärä = NULL ,tutkimusaseman_yopymisvuorokaudet = NULL --koodit ,[Koodit Yliopisto] = NULL ,[Koodit Ammattikorkeakoulu] = d1.amk_tunnus FROM [dw].[f_amk_toimipisteet] f join dw.d_amk d1 on d1.id=f.d_amk_id --join dw.d_amk_toimipiste d2 on d2.id=f.d_toimipiste_id join dw.d_amk_toimipisteen_toimipaikka d3 on d3.id=f.d_toimipisteen_toimipaikka_id --join dw.d_amk_t UNION ALL select Tilastovuosi = f.vuosi ,Yliopisto = d1.yo_nimi_fi ,Ammattikorkeakoulu = NULL ,Toimipiste = d2.selite_fi ,Toimipaikka = d3.selite_fi --mittarit ,harjoittelukoulujen_tilat = NULL ,muut_vuokratilat = NULL ,yliopistokiinteistoyhtion_toimitilat_aalto_yliopistokiinteistot_oy = NULL ,yliopistokiinteistoyhtion_toimitilat_helsingin_yliopistokiinteistot_oy = NULL ,yliopistokiinteistoyhtion_toimitilat_suomen_yliopistokiinteistot_oy = NULL ,toimipaikan_henkilokunnan_henkilotyovuodet ,tutkimusaseman_henkilokunnan_maksimimäärä ,tutkimusaseman_henkilokunnan_minimäärä ,tutkimusaseman_yopymisvuorokaudet --koodit ,[Koodit Yliopisto] = d1.yo_tunnus ,[Koodit Ammattikorkeakoulu] = NULL FROM [dw].[f_yo_toimipisteet] f join dw.d_yo d1 on d1.id=f.d_yliopisto_id --Lisätty vuosi ehdoksi, koska yo-toimipisteet vaihtelevat vuosittain join dw.d_yo_toimipiste d2 on d2.id=f.d_toimipiste_id and d2.vuosi = f.vuosi join dw.d_yo_toimipisteen_toimipaikka d3 on d3.id=f.d_toimipaikka_id
Java
UTF-8
958
2.09375
2
[]
no_license
package com.apr7.sponge.model; import com.apr7.sponge.constants.PollutantTypeEnum; public class Pollutant { private Long id; private String name; private PollutantTypeEnum type; private Boolean show; private Integer order; private PollutantMapping mapping; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public PollutantTypeEnum getType() { return type; } public void setType(PollutantTypeEnum type) { this.type = type; } public Boolean getShow() { return show; } public void setShow(Boolean show) { this.show = show; } public Integer getOrder() { return order; } public void setOrder(Integer order) { this.order = order; } public PollutantMapping getMapping() { return mapping; } public void setMapping(PollutantMapping mapping) { this.mapping = mapping; } }
Java
UTF-8
6,076
2.359375
2
[ "MIT" ]
permissive
package com.eaglesakura.andriders.media; import com.eaglesakura.andriders.AcesEnvironment; import com.eaglesakura.andriders.central.CentralDataReceiver; import com.eaglesakura.andriders.serialize.AcesProtocol; import com.eaglesakura.andriders.serialize.GeoProtocol; import com.eaglesakura.andriders.serialize.MediaMetaProtocol; import com.eaglesakura.andriders.serialize.SensorProtocol; import com.eaglesakura.util.StringUtil; import android.content.Context; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * 画像書き込みを行う */ @Deprecated public class MediaFileManager { /** * ACEのメタファイルの内容 */ public static final String METAFILE_EXT = ".mediameta"; final Context context; Date imageDate = new Date(); /** * 書き込みを行った場合はファイルパスを保持しておく */ File mediaFilePath; /** * 1時間毎のディレクトリを生成する場合はtrue */ boolean mediaDirectory1h = false; public MediaFileManager(Context context) { this.context = context.getApplicationContext(); } public MediaFileManager(Context context, File file) { if (!file.isFile()) { throw new IllegalArgumentException("!= File"); } this.context = context.getApplicationContext(); this.mediaFilePath = file; } public Date getImageDate() { return imageDate; } public boolean isMediaDirectory1h() { return mediaDirectory1h; } public void setMediaDirectory1h(boolean mediaDirectory1h) { this.mediaDirectory1h = mediaDirectory1h; } static final SimpleDateFormat formatter = new SimpleDateFormat("HH-mm-ss"); static final SimpleDateFormat hourFormatter = new SimpleDateFormat("HH"); public String getVideoFileName() { return String.format("%s.mp4", formatter.format(imageDate)); } /** * 画像ファイル名を取得する */ public String getImageFileName() { return String.format("%s.jpg", formatter.format(imageDate)); } /** * 画像ディレクトリを取得する */ public File getImageDirectory() { File result = AcesEnvironment.getDateMediaDirectory(context, imageDate); // 一時間ごとにディレクトリを区切る場合は再度区切る if (mediaDirectory1h) { result = new File(result, hourFormatter.format(imageDate)); } return result; } public File getMediaMetaFileName() { return new File(String.format("%s%s", mediaFilePath.getAbsolutePath(), METAFILE_EXT)); } /** * メタ情報を書き出す */ public void writeMediaMeta(CentralDataReceiver receiver) throws IOException { final GeoProtocol.GeoPayload geo = receiver.getLastReceivedGeo(); final SensorProtocol.RawHeartrate heartrate = receiver.getLastReceivedHeartrate(); final SensorProtocol.RawSpeed speed = receiver.getLastReceivedSpeed(); final SensorProtocol.RawCadence cadence = receiver.getLastReceivedCadence(); final AcesProtocol.CentralStatus centralStatus = receiver.getLastReceivedCentralStatus(); if (centralStatus == null) { // セントラルを取得できて無ければ何もしない return; } MediaMetaProtocol.MediaMetaPayload.Builder metaBuilder = MediaMetaProtocol.MediaMetaPayload.newBuilder(); metaBuilder.setDate(StringUtil.toString(new Date())); if (geo != null) { metaBuilder.setGeo(receiver.getLastReceivedGeo()); } if (heartrate != null && centralStatus.getConnectedHeartrate()) { metaBuilder.setHeartrate(heartrate); } if (cadence != null && centralStatus.getConnectedCadence()) { metaBuilder.setCadence(cadence); } if (speed != null && centralStatus.getConnectedSpeed()) { metaBuilder.setSpeed(speed); } // ファイルを書き出す FileOutputStream os = new FileOutputStream(getMediaMetaFileName()); os.write(metaBuilder.build().toByteArray()); os.flush(); os.close(); } public void generateNomedia() { File nomedia = new File(AcesEnvironment.getMediaDirectory(context), ".nomedia"); // nomediaが存在する場合は何もしない if (nomedia.exists()) { return; } FileOutputStream os = null; try { os = new FileOutputStream(nomedia); os.write(0); } catch (Exception e) { } finally { if (os != null) { try { os.close(); } catch (Exception e) { } } } } /** * 画像を保存する * * @param jpegImage  Jpeg画像配列 * @return 書き込んだ画像のURI */ public File writeImage(byte[] jpegImage) throws IOException { if (jpegImage == null || jpegImage.length == 0) { return null; } mediaFilePath = new File(getImageDirectory(), getImageFileName()); mediaFilePath.getParentFile().mkdirs(); FileOutputStream os = new FileOutputStream(mediaFilePath); os.write(jpegImage); os.flush(); os.close(); return mediaFilePath; } /** * 一時ファイルから本番領域にファイルを移す */ public File swapVideo(File tempFile) { if (tempFile == null || tempFile.length() == 0) { return null; } mediaFilePath = new File(getImageDirectory(), getVideoFileName()); mediaFilePath.getParentFile().mkdirs(); tempFile.renameTo(mediaFilePath); return mediaFilePath; } /** * 画像ファイル本体を取得する */ public File getMediaFilePath() { return mediaFilePath; } }
Swift
UTF-8
1,463
2.59375
3
[ "MIT" ]
permissive
// // Copyright © 2020 Tasuku Tozawa. All rights reserved. // import Domain protocol ClipCollectionMenuBuildable { func build(for clip: Clip, source: ClipCollection.Source) -> [ClipCollection.MenuElement] } struct ClipCollectionMenuBuilder { // MARK: - Properties private let storage: UserSettingsStorageProtocol // MARK: - Lifecycle init(storage: UserSettingsStorageProtocol) { self.storage = storage } } extension ClipCollectionMenuBuilder: ClipCollectionMenuBuildable { // MARK: - ClipCollectionMenuBuildable func build(for clip: Clip, source: ClipCollection.Source) -> [ClipCollection.MenuElement] { return [ source.isAlbum ? .item(.addTag) : .subMenu(.init(kind: .add, isInline: false, children: [.item(.addTag), .item(.addToAlbum)])), clip.isHidden ? .item(.reveal) : .item(.hide(immediately: storage.readShowHiddenItems())), .item(.edit), .item(.share), .subMenu(.init(kind: .others, isInline: true, children: [ clip.items.count > 1 ? .item(.purge) : nil, source.isAlbum ? .item(.removeFromAlbum) : .item(.delete) ].compactMap { $0 })) ].compactMap { $0 } } }
Python
UTF-8
909
3.765625
4
[ "MIT" ]
permissive
from Data_Structures.linked_list.linked_list import LinkedList def zipLists(list_one,list_two): #Edge cases when one of the lists is empty if not list_one: return list_two elif not list_two: return list_one zip_list = LinkedList() current_one=list_one current_one=current_one.head current_two=list_two.head while current_one or current_two: if current_one: zip_list.append(current_one.data) current_one=current_one.next_node if current_two: zip_list.append(current_two.data) current_two=current_two.next_node return zip_list if __name__=='__main__': list_one=LinkedList() list_two=LinkedList() list_one.append(25) list_one.append(1996) list_one.append("birthday") list_two.append(5) list_two.append("my") result=zipLists(list_one,list_two) print(result)
Python
UTF-8
686
2.59375
3
[]
no_license
w = 25 h = 6 image = input() layers = [image[i:i+w*h] for i in range(0, len(image), w*h)] # min0, minLay = min((sum(1 for p in l if p == "0"), l) for l in layers) # print(sum(1 for p in minLay if p == "1") * sum(1 for p in minLay if p == "2")) finalImg = [p for p in layers[-1]] for l in reversed(layers): for i, p in enumerate(l): if p != "2": finalImg[i] = p imgimg = [finalImg[i:i+w] for i in range(0, len(finalImg), w)] # s = 0 for l in imgimg: for p in l: if p == "1": print("#", end="") # s += 1 else: print(" ", end="") print() # AZCJC # print(s, len(finalImg) - s)
Python
UTF-8
703
4.53125
5
[]
no_license
def is_anagram(first, second): if len(first) != len(second): return False first, second = sorted(first.lower()), sorted(second.lower()) if first != second: return False return True # I want you to write a function that accepts two strings and returns True if the two strings are anagrams of each other. # Your function should work like this: print(is_anagram("tea", "eat")) # True print(is_anagram("tea", "treat")) # False print(is_anagram("sinks", "skin")) # False print(is_anagram("Listen", "silent")) # True # Make sure your function works with mixed case. # Before you try to solve any bonuses, I recommend you try to find at least two ways to solve this problem.
Java
UTF-8
1,398
2.359375
2
[]
no_license
package com.example.catapp.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.catapp.Cat; import com.example.catapp.R; import com.example.catapp.adapters.FavsAdapter; import java.util.ArrayList; import java.util.List; public class FavouritesRecycler extends Fragment { private RecyclerView recyclerView; public FavouritesRecycler() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.favourites_list, container, false); recyclerView = view.findViewById(R.id.favs_rv); LinearLayoutManager layoutManager = new LinearLayoutManager(view.getContext()); recyclerView.setLayoutManager(layoutManager); final FavsAdapter adapter = new FavsAdapter(); Cat cat = new Cat("beng","Bengal", "Orange"); Cat cat2 = new Cat("beng","Bengal", "Orange"); List<Cat> sample = new ArrayList<>(); sample.add(cat); sample.add(cat2); adapter.setData(sample); recyclerView.setAdapter(adapter); return view; } }
Java
UTF-8
2,648
2.3125
2
[]
no_license
package studyFire.schedule.domain; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; import static org.assertj.core.api.Assertions.*; @SpringBootTest @Transactional public class domainTest { @Autowired EntityManager em; @Test public void 멤버() throws Exception { //given Member member = Member.createMember("aa@aaa.com","aaa", "세준" , 10); Team team = Team.createTeam("팀1"); //when //멤버가 팀에 들어가기 em.persist(member); em.persist(team); Member findMember = em.find(Member.class, 1L); //then assertThat("세준").isEqualTo(findMember.getName()); } @Test public void 채팅() throws Exception { //given Member member = Member.createMember("aa@aaa.com", "aaa", "세준", 10); Team team = Team.createTeam("팀1"); ChatMessage message = ChatMessage.createMessage("안녕", team.getChat(), member); //when em.persist(member); em.persist(team); em.persist(message); Chat findChat = em.find(Chat.class, team.getChat().getId()); ChatMessage chatMessage = em.find(ChatMessage.class, message.getId()); //then assertThat("안녕").isEqualTo(chatMessage.getMessage()); assertThat(team.getChat()).isSameAs(findChat); } @Test @Rollback(value = false) public void 스케줄() throws Exception { //given Member member = Member.createMember("aa@aaa.com", "aaa", "세준", 10); Team team = Team.createTeam("팀1"); ScheduleContent content = ScheduleContent.createContent("제목", "여기에 글 쓰기"); //when em.persist(member); em.persist(team); em.persist(content); //then // Schedule findSchedule = em.find(Schedule.class, .getId()); // // //멤버가 가지고 있는 스케줄과 만든 스케줄의 id 같은지 확인 // assertThat(member.getSchedules().get(0).getId()).isEqualTo(schedule.getId()); // //글쓴게 스케줄에 들어갔는지 확인 // assertThat(content.getSchedule().getId()).isEqualTo(schedule.getId()); //글쓴게 똑같은지 확인 assertThat(content.getContent_body()).isEqualTo("여기에 글 쓰기"); } }
JavaScript
UTF-8
2,127
3.203125
3
[]
no_license
var ANGLE = -3; var X_NUMBER = 100; var Y_NUMBER = 10; var body = document.getElementsByTagName('body')[0]; function move() { ANGLE = (event.pageX - window.innerWidth/2)/100; var top; var divList = body.getElementsByTagName('div'); for (var i=0; i<X_NUMBER; i++) { top = 0; for (var j=0; j<Y_NUMBER; j++) { var div = divList[i*Y_NUMBER+j]; div.style.top = top + 'px'; div.style.left = -2000 + i*101 + ANGLE*top + 'px'; div.style.transform = "matrix(1, 0, "+ANGLE+", 1, 0, 0)"; top += parseInt(div.style.height.split('px')[0]) + 1; } } } function draw() { while (body.firstChild) { body.removeChild(body.firstChild); } var r, g, b, h, top; r = Math.round(Math.random()*255); g = Math.round(Math.random()*255); b = Math.round(Math.random()*255); for (var i=0; i<X_NUMBER; i++) { top = 0; for (var j=0; j<Y_NUMBER; j++) { r += Math.round((Math.random()-0.5)*20); if (r<0) {r=0} else if (r>255) {r=255} g += Math.round((Math.random()-0.5)*20); if (g<0) {g=0} else if (g>255) {g=255} b += Math.round((Math.random()-0.5)*20); if (b<0) {b=0} else if (b>255) {b=255} var div = document.createElement('div'); h = 100 + Math.round(Math.random()*200); div.style.height = h; div.style.backgroundColor = "rgb("+r+","+g+","+b+")"; div.style.top = top + 'px'; div.style.left = -2000 + i*101 + ANGLE*top + 'px'; div.style.transform = "matrix(1, 0, "+ANGLE+", 1, 0, 0)"; body.appendChild(div); top += h + 1; } } } function setup() { draw(); document.body.onmousemove = move; document.addEventListener('touchmove', function(e) { e.preventDefault(); move(); }, false); document.body.onclick = draw; document.addEventListener('click', function(e) { e.preventDefault(); draw(); }, false); } setup();
Java
UTF-8
3,818
2.734375
3
[]
no_license
/* * TunerMIDlet.java * */ package net.sharedmemory.tuner; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; /** * An instrument tuner MIDlet. It detects the pitch of the note played * and displays whether it is sharp, flat or in tune. * * @author David Keen */ public class TunerMIDlet extends MIDlet implements CommandListener { // Constants static final int RATE = 8000; // Encapsulate? // The length of the FFT is 2 raised to this power. private int power = 12; // Threads private Thread recorder; private Thread processor; private Buffer buffer; boolean okToRun; // Flag to control threads. // UI private Display display; private TunerCanvas tunerCanvas; private PreferencesForm preferencesForm; private Command exitCommand; private Command preferencesCommand; public TunerMIDlet() { power = 12; display = Display.getDisplay(this); tunerCanvas = new TunerCanvas(); preferencesForm = new PreferencesForm(this); exitCommand = new Command("Exit", Command.EXIT, 0); tunerCanvas.addCommand(exitCommand); preferencesCommand = new Command("Preferences", Command.SCREEN, 1); tunerCanvas.addCommand(preferencesCommand); tunerCanvas.setCommandListener(this); } public void startApp() { // Allocate all the memory we will need for objects at the start. buffer = new Buffer(getSampleLength()); recorder = new Thread(new Recorder(buffer, this)); processor = new Thread(new Processor(buffer, this, tunerCanvas)); display.setCurrent(tunerCanvas); okToRun = true; recorder.start(); processor.start(); } public void pauseApp() { stopThreads(); releaseResources(); } public void destroyApp(boolean unconditional) { stopThreads(); releaseResources(); } public void commandAction(Command command, Displayable displayable) { int commandType = command.getCommandType(); if (commandType == Command.CANCEL) { // Returning to main screen. startApp(); } else if (commandType == Command.OK) { if (displayable == preferencesForm) { ((PreferencesForm)displayable).savePreferences(); startApp(); } } else if (commandType == Command.EXIT) { destroyApp(true); notifyDestroyed(); } else if (commandType == Command.SCREEN) { if (command == preferencesCommand) { pauseApp(); display.setCurrent(preferencesForm); } } } /** * Stops the Recorder and Processor threads. */ private void stopThreads() { // Signal threads to stop. okToRun = false; // Wake up any sleeping threads so they can stop. recorder.interrupt(); processor.interrupt(); } /** * Releases references to objects we have created * so they can be garbage collected. */ private void releaseResources() { buffer = null; recorder = null; processor = null; } public int getPower() { return power; } public void setPower(int power) { this.power = power; } public int getSampleLength() { return 1 << power; } /** * Shows any error alerts. * * @param message the String to display. * @param next the next Displayable to be shown after the alert. */ public void showError(String message, Displayable next) { Alert alert = new Alert("Message", message, null, AlertType.ERROR); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert, next); } }
JavaScript
UTF-8
272
2.96875
3
[]
no_license
Game.extend = function extend(src, dest) { // Create a copy of the source. const result = {}; for (const key in src) { result[key] = src[key]; } // Copy over all keys from dest for (const key in dest) { result[key] = dest[key]; } return result; };
Java
UTF-8
14,071
2.21875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.facilities.services; import edu.facilities.dao.FacilitiesInfoDao; import edu.facilities.dao.ReserveRecordDao; import edu.facilities.dao.UserDao; import edu.facilities.dao.VacationDao; import edu.facilities.model.FacilitiesInfo; import edu.facilities.model.ReserveRecord; import edu.facilities.model.User; import edu.facilities.model.Vacation; import edu.facilities.utils.Format; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 预约管理控制类 * * @author user */ public class ReserveServices { private ReserveRecordDao mReserveRecordDao = new ReserveRecordDao(); private FacilitiesInfoDao mFacilitiesInfoDao = new FacilitiesInfoDao(); private UserDao mUserDao = new UserDao(); private VacationDao mVacationDao = new VacationDao(); private int mUserTypeId = 0; private int mUserId = 0; /** * 预约管理控制方法 * * @param request * @param response * @return */ public void reserveRecordDispatcher(HttpServletRequest request, HttpServletResponse response) { String type = Format.null2Blank(request.getParameter("_type")); int facilitiesTypeId = Format.str2Int(request.getParameter("facilitiesTypeId")); FacilitiesInfo facilitiesInfo = null; if (facilitiesTypeId > 0) { try { int facilitiesInfoId = Format.str2Int(request.getParameter("facilitiesInfoId")); facilitiesInfo = mFacilitiesInfoDao.findById(facilitiesInfoId); request.setAttribute("facilitiesInfo", facilitiesInfo); request.setAttribute("facilitiesInfoList", mFacilitiesInfoDao.findByTypeID(String.valueOf(facilitiesTypeId))); request.setAttribute("facilitiesInfoId", facilitiesInfoId); if (type.equals("add")) { addDispatcher(request, response, facilitiesInfo); }else if(type.equals("cancle")) { cancleDispatcher(request, response); }else if(type.equals("absence")) { absenceDispatcher(request, response); }else if(type.equals("noabsence")) { noAbsenceDispatcher(request, response); } if (facilitiesInfoId > 0) { List<ReserveRecord> list = mReserveRecordDao.findByFacilityID(facilitiesInfoId); request.setAttribute("reserveRecordList", list); } } catch (Exception e) { } } mUserTypeId = Format.str2Int(request.getSession().getAttribute("userTypeId")); mUserId = Format.str2Int(request.getSession().getAttribute("userId")); request.setAttribute("facilitiesTypeId", facilitiesTypeId); request.setAttribute("fid", 3); request.setAttribute("currentdate", Format.formatDate(new Date())); } /** * 未缺席设置 * @param request * @param response * @throws Exception */ public void noAbsenceDispatcher(HttpServletRequest request, HttpServletResponse response) throws Exception{ int reserverecordid = Format.str2Int(request.getParameter("_reserverecordid")); try { ReserveRecord rr = mReserveRecordDao.findById(reserverecordid); rr.setIsAbsence(0);//0为不缺席 mReserveRecordDao.saveOrUpdate(rr); // TODO 更新用户缺席次数和时间 User user = mUserDao.findById(rr.getUserID()); int absenceNum = user.getAbsenceNum(); if(absenceNum <= 0) { absenceNum = 0; }else { absenceNum --; } user.setAbsenceNum(absenceNum); user.setAbsenceDate(mReserveRecordDao.findLastAbsenceByUserId(rr.getUserID()).getEndDate()); mUserDao.saveOrUpdate(user); } catch (Exception e) { } } /** * 缺席设置 * @param request * @param response * @throws Exception */ public void absenceDispatcher(HttpServletRequest request, HttpServletResponse response) throws Exception{ int reserverecordid = Format.str2Int(request.getParameter("_reserverecordid")); try { ReserveRecord rr = mReserveRecordDao.findById(reserverecordid); rr.setIsAbsence(1);//1为缺席 mReserveRecordDao.saveOrUpdate(rr); // TODO 更新用户缺席次数和时间 User user = mUserDao.findById(rr.getUserID()); int absenceNum = user.getAbsenceNum() + 1; if(absenceNum >= 3) { user.setIsValid(1); } user.setAbsenceNum(absenceNum); user.setAbsenceDate(rr.getEndDate()); mUserDao.saveOrUpdate(user); } catch (Exception e) { } } /** * 取消预约方法 * @param request * @param response * @throws Exception */ public void cancleDispatcher(HttpServletRequest request, HttpServletResponse response) throws Exception{ int reserverecordid = Format.str2Int(request.getParameter("_reserverecordid")); ReserveRecord rr = mReserveRecordDao.findById(reserverecordid); if (null != rr) { if (mUserTypeId == 4) {//学生 Calendar calendar = Calendar.getInstance(); Date nDate = new Date(); calendar.setTime(nDate); calendar.add(Calendar.DAY_OF_MONTH, 1); if(Format.compareDateWithDate(calendar.getTime(), Format.formatDate(rr.getStartDate())) == 1) { request.setAttribute("errorMsg", "无法取消,您需要提前24小时取消预约!"); return; } } int flag = mReserveRecordDao.del(rr); if(flag > 0) { request.setAttribute("errorMsg", "取消预约成功!"); }else { request.setAttribute("errorMsg", "取消预约失败!"); } } } /** * 增加预约方法 * @param request * @param response * @return * @throws Exception */ public void addDispatcher(HttpServletRequest request, HttpServletResponse response, FacilitiesInfo facilitiesInfo) throws Exception{ String startdate = Format.null2Blank(request.getParameter("startdate")); String enddate = Format.null2Blank(request.getParameter("enddate")); String[] hour = request.getParameterValues("_hour"); startdate = startdate + " " + hour[0] + ":00";//补全以适应derby数据库的timstamp函数 enddate = enddate + " " + hour[1] + ":00";//补全以适应derby数据库的timstamp函数 String validStr = isValidVacation(startdate, enddate); if(validStr.equals("true") && null != facilitiesInfo) { ReserveRecord rr = new ReserveRecord(); rr.setCreateDate(Format.formatDate(new Date())); rr.setEndDate(enddate); rr.setFacilityID(facilitiesInfo.getId()); rr.setFacilityName(facilitiesInfo.getName()); rr.setIsAbsence(0); rr.setStartDate(startdate); rr.setUserID(Format.str2Int(request.getSession().getAttribute("userId"))); rr.setUserName(Format.null2Blank(request.getSession().getAttribute("userName"))); try { mReserveRecordDao.saveOrUpdate(rr); } catch (Exception e) { } }else { request.setAttribute("errorMsg", validStr); } } /** * 是否为有效日期 * @param request * @param response * @param userTypeId * @return */ public String isValidVacation(String fromstartdate, String fromenddate) { try { if(Format.compareDateWithDate(Format.formatDate(fromstartdate), new Date()) != 1) { return "开始日期要大于当前日期,请重新选择"; } if(Format.compareDateWithDate(Format.formatDate(fromenddate), Format.formatDate(fromstartdate)) != 1) { return "结束日期要大于开始日期,请重新选择"; } Date nDate = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(nDate); if (mUserTypeId == 2 || mUserTypeId == 3) {//操作员或者老师 calendar.add(Calendar.YEAR, 1); if (Format.compareDateWithDate(calendar.getTime(), Format.formatDate(fromstartdate)) == -1) { return "您只能预约一年以内的设备!"; } }else if(mUserTypeId == 4) {//学生 calendar.add(Calendar.DAY_OF_MONTH, 62); if (Format.compareDateWithDate(calendar.getTime(), Format.formatDate(fromstartdate)) == -1) { return "您只能预约两个月以内的设备!"; } // 查下学生的预约设备数 不能超过五个 long num = mReserveRecordDao.findReserveRecordByUserIdAndNoExpiry(mUserId, Format.formatDate(new Date())); if (num >= 5) { return "您最多只能预约五个设备奥!"; } } List<Vacation> list = mVacationDao.findAll(); for(Vacation vacation: list) { boolean flag = false; String startdate = vacation.getStartDate(); String enddate = vacation.getEndDate(); //第一种时间段都在某假期开始前 if((Format.compareDate(fromstartdate, startdate) == -1) && (Format.compareDate(fromenddate, startdate) == -1)) { flag = true; } //第二种时间段都在某假期之后 if((Format.compareDate(fromstartdate, enddate) == 1) && (Format.compareDate(fromenddate, enddate) == 1)) { flag = true; } if(!flag) { return "您选择的日期包含【" + vacation.getName() + "(" + vacation.getStartDate() + " ~ " + vacation.getEndDate() + ")】 请重新选择"; } } List<ReserveRecord> reserveRecords = mReserveRecordDao.findRserveRecordByNowDate(Format.formatDate(new Date())); for (ReserveRecord reserveRecord : reserveRecords) { boolean flag = false; String startdate = reserveRecord.getStartDate(); String enddate = reserveRecord.getEndDate(); //第一种时间段都在某假期开始前 if((Format.compareDateWithReserve(fromstartdate, startdate) == -1) && (Format.compareDateWithReserve(fromenddate, startdate) == -1)) { flag = true; } //第二种时间段都在某假期之后 if(((Format.compareDateWithReserve(fromstartdate, enddate) == 1) || (Format.compareDateWithReserve(fromstartdate, enddate) == 0)) && (Format.compareDateWithReserve(fromenddate, enddate) == 1)) { flag = true; } if(!flag) { return "【" + reserveRecord.getUserName() + "】 在【" + reserveRecord.getStartDate() + " ~ " + reserveRecord.getEndDate() + "】已预约"; } } } catch (Exception e) { } return "true"; } /** * 设备使用统计 控制方法 * @param request * @param response * @return */ public void reportDispatcher(HttpServletRequest request, HttpServletResponse response) { String monthDate = Format.null2Blank(request.getParameter("_month")); if(monthDate.length() > 0) { try { String nowDate = Format.formatStringToMonth(new Date()); if(Format.compareDateWithDate(Format.formatStringToMonth(monthDate), Format.formatStringToMonth(nowDate)) == -1) { String[] date = getMaxAndMinDate(Format.formatStringToMonth(monthDate), true); List<ReserveRecord> list = mReserveRecordDao.findReserveRecordByDatesAndFacilityId(date[1] + " 00:00:00", date[0] + " 21:30:00", 0);//最晚21:30 request.setAttribute("reserverecordList", list); } } catch (Exception e) { } } request.setAttribute("maxdate", getMaxAndMinDate(new Date(), false)[0]); request.setAttribute("monthDate", monthDate); request.setAttribute("fid", 6); } /** * 得到某日期的最大和最小日期 * @param date * @param isSelect * @return */ private String[] getMaxAndMinDate(Date date, boolean isSelect) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); if(!isSelect) { if (calendar.getTime().getTime() != Format.formatString(Format.formatString(new Date())).getTime()) { calendar.add(Calendar.MONTH, -1); } } String maxDate = Format.formatString(calendar.getTime()); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); String minDate = Format.formatString(calendar.getTime()); return new String[]{maxDate, minDate}; } // public static void main(String[] args) { // Calendar calendar = Calendar.getInstance(); // calendar.setTime(new Date()); // System.out.println(Format.formatStringToMonth(calendar.getTime())); // calendar.add(Calendar.MONTH, -1); // System.out.print(Format.formatStringToMonth(calendar.getTime())); // } }
Java
UTF-8
8,769
3.578125
4
[]
no_license
package com.alejandroaraya.ds.chicagoanalysis; import com.alejandroaraya.ds.chicagoanalysis.models.Worker; public class Facts { private Worker[] workers; public Facts(Worker[] workers) { this.workers = workers; // this.getHigherPaidWorker(); this.getHigherPaidHalfTimePosition(); // this.getAverageSalaryForPartTimeWorkers(); this.getDeparmentWithHigherSalary(); this.getJobttitleAnnualSalaryAverage(); this.getFiveHigherPaidWorkers(); this.getDepartmentWithLessSalary(); } // // public void getHigherPaidWorker() { // Worker higherPaid = workers[0]; // for (int index = 0; index < this.workers.length; ++index) { // if (this.workers[index].getAnnualSalary() > higherPaid.getAnnualSalary()) { // higherPaid = this.workers[index]; // } // } // System.out.println("The worker who gain higher salary is "); // System.out.println(higherPaid.toString()); // } // // public void getHigherPaidHalfTimePosition() { // Worker higherPaid = null; // for (int index = 0; index < this.workers.length; ++index) { // if (this.workers[index].isPartTime() && (higherPaid == null || this.workers[index].getAnnualSalary() > higherPaid.getAnnualSalary())) { // higherPaid = this.workers[index]; // } // } // System.out.println(" El empleado que trabaja medio tiempo con el salario más alto es:"); // System.out.println(higherPaid.toString()); // } // // public void getAverageSalaryForPartTimeWorkers() { // int amountOfPartTimeWorkers = 0; // double totalPartTimeSalaries = 0.0; // for (Worker worker : workers) { // if (worker.isPartTime()) { // amountOfPartTimeWorkers++; // totalPartTimeSalaries += worker.getAnnualSalary(); // } // } // System.out.println("El promedio salarial de los empleados de medio tiempo en la ciudad de Chicago es: " + totalPartTimeSalaries / amountOfPartTimeWorkers); // } //1. ¿Cuál es el departamento más caro por año? public void getDeparmentWithHigherSalary() { Worker higherPaidDepartment = workers[0]; for (int index = 0; index < this.workers.length; ++index) { if (this.workers[index].getAnnualSalary() > higherPaidDepartment.getAnnualSalary()) { higherPaidDepartment = this.workers[index]; } } System.out.println('\n' + "The department with higher salary per year is "); System.out.println(higherPaidDepartment.toString()); } //2.¿ Cuáles son los 5 trabajadores que ganan más dinero por año? public void getFiveHigherPaidWorkers(){ Worker higherPaid1 = workers[0]; Worker higherPaid2 = workers[0]; Worker higherPaid3 = workers[0]; Worker higherPaid4 = workers[0]; Worker higherPaid5 = workers[0]; for(int index = 0; index < this.workers.length; ++index){ if(this.workers[index].getAnnualSalary() > higherPaid1.getAnnualSalary()){ higherPaid1 = this.workers[index]; }else if(this.workers[index].getAnnualSalary() > higherPaid2.getAnnualSalary()){ higherPaid2 = this.workers[index]; }else if(this.workers[index].getAnnualSalary() > higherPaid3.getAnnualSalary()){ higherPaid3 = this.workers[index]; }else if(this.workers[index].getAnnualSalary() > higherPaid4.getAnnualSalary()){ higherPaid4 = this.workers[index]; }else if(this.workers[index].getAnnualSalary() > higherPaid5.getAnnualSalary()){ higherPaid5 = this.workers[index]; } } System.out.println('\n' + "The employees with higher salary are n:"); System.out.println(higherPaid1.toString()); System.out.println(higherPaid2.toString()); System.out.println(higherPaid3.toString()); System.out.println(higherPaid4.toString()); System.out.println(higherPaid5.toString()); } //3. ¿Cuál puesto gana más dinero al año en promedio? public void getJobttitleAnnualSalaryAverage(){ int amountOfWorkers = 0; double totalAnnualSalaries = 0.0; for(Worker worker : workers){ amountOfWorkers++; totalAnnualSalaries += worker.getAnnualSalary(); } Worker higherPaidJobTitle = workers[0]; for (int index= 0; index < this.workers.length; index++){ if(this.workers[index].getAnnualSalary() > higherPaidJobTitle.getAnnualSalary()){ higherPaidJobTitle = this.workers[index]; } } System.out.println('\n' + "The average annual salary for the city of Chicago is: "); System.out.println(+totalAnnualSalaries/amountOfWorkers); System.out.println("The jobtitle with the higher salary per year is "); System.out.println(higherPaidJobTitle.toString()); } //4. ¿Cuál puesto con jornada de medio tiempo gana más dinero al año? public void getHigherPaidHalfTimePosition() { Worker higherPaid = null; for (int index = 0; index < this.workers.length; ++index) { if (this.workers[index].isPartTime() && (higherPaid == null || this.workers[index].getAnnualSalary() > higherPaid.getAnnualSalary())) { higherPaid = this.workers[index]; } } System.out.println('\n' + " The employee who works part time and earns more salary is:"); System.out.println(higherPaid.toString()); } //5. ¿Cuáles son los 5 departamentos con menor gasto por año? public void getDepartmentWithLessSalary() { Worker lessPaidDepartment = workers[0]; int index1 = 0; for (int index = 0; index < this.workers.length; ++index) { if (this.workers[index].getAnnualSalary() < lessPaidDepartment.getAnnualSalary()) { lessPaidDepartment = this.workers[index]; index1 = index; } } Worker lessPaidDeparment2 = workers[0]; int index2 = 0; for (int index = 0; index < this.workers.length; ++index) { if (this.workers[index].getAnnualSalary() < lessPaidDeparment2.getAnnualSalary() && index !=index1) { lessPaidDeparment2 = this.workers[index]; index2 = index; } } Worker lessPaidDeparment3 = workers[0]; int index3 = 0; for (int index = 0; index < this.workers.length; ++index) { if (this.workers[index].getAnnualSalary() < lessPaidDeparment3.getAnnualSalary() && this.workers[index].getAnnualSalary() != lessPaidDeparment2.getAnnualSalary() && index !=index1 && index != index2 ) { lessPaidDeparment3 = this.workers[index]; index3 = index; } } Worker lessPaidDeparment4 = workers[0]; int index4 = 0; for (int index = 0; index < this.workers.length; ++index) { if (this.workers[index].getAnnualSalary() < lessPaidDeparment4.getAnnualSalary() && this.workers[index].getAnnualSalary() != lessPaidDeparment2.getAnnualSalary() && this.workers[index].getAnnualSalary() != lessPaidDeparment3.getAnnualSalary() && index !=index1 && index != index2 && index !=index3) { lessPaidDeparment4 = this.workers[index]; index4= index; } } Worker lessPaidDeparment5 = workers[0]; int index5 = 0; for (int index = 0; index < this.workers.length; ++index) { if (this.workers[index].getAnnualSalary() < lessPaidDeparment5.getAnnualSalary() && this.workers[index].getAnnualSalary() != lessPaidDeparment2.getAnnualSalary() && this.workers[index].getAnnualSalary() != lessPaidDeparment3.getAnnualSalary() && this.workers[index].getAnnualSalary() != lessPaidDeparment4.getAnnualSalary() && index !=index1 && index != index2 && index !=index3 && index !=index4) { lessPaidDeparment5 = this.workers[index]; index5= index; } } System.out.println('\n' + "The department with less salary per year is "); System.out.println(lessPaidDepartment.toString()); System.out.println(lessPaidDeparment2.toString()); System.out.println(lessPaidDeparment3.toString()); System.out.println(lessPaidDeparment4.toString()); System.out.println(lessPaidDeparment5.toString()); } }
TypeScript
UTF-8
322
2.796875
3
[]
no_license
import { BasicTreeNode } from './basic-node'; export type NRangeNode = RangeNode | null; export class RangeNode extends BasicTreeNode { public min: number; public max: number; constructor(key: number, min: number = -Infinity, max: number = Infinity) { super(key); this.min = min; this.max = max; } }
Java
UTF-8
3,736
2.46875
2
[]
no_license
package com.zcq; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInterceptor; import com.zcq.dao.StudentDao; import com.zcq.domain.MyStudent; import com.zcq.domain.Student; import com.zcq.utils.MybatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; public class TestMybatis { @Test public void selectMultiParam(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); List<Student> students = dao.selectMultiParam("张三", 20); for (Student student : students) { System.out.println("学生信息为:"+student); } sqlSession.close(); } @Test public void selectStudentCount(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); int count = dao.selectStudentCount(); System.out.println(count); } @Test public void selectMyStudent(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); List<MyStudent> myStudents = dao.selectMyStudent(20); for (MyStudent myStudent : myStudents) { System.out.println(myStudent); } sqlSession.close(); } @Test public void selectOneStudent(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); Map<Object, Object> map = dao.selectOneStudent(1002); System.out.println(map); } @Test public void insertStudent(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); int num = dao.insertStudent(new Student(1005, "李华", "lihua@qq.com", 21)); System.out.println(num); sqlSession.commit(); sqlSession.close(); } @Test public void selectLikeStudent(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); String name = "%李%"; List<Student> students = dao.selectLikeStudent(name); for (Student student : students) { System.out.println(student); } sqlSession.close(); } @Test public void selectStudentWhere(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); List<Student> students = dao.selectStudentWhere("李华", 20); for (Student student : students) { System.out.println(student); } sqlSession.close(); } @Test public void selectStudentForeach(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); List<Integer> list = new ArrayList(); list.add(1001); list.add(1002); list.add(1003); List<Student> students = dao.selectStudentForeach(list); for (Student student : students) { System.out.println(student); } sqlSession.close(); } @Test public void selectAllStudents(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); PageHelper.startPage(2, 3); List<Student> students = dao.selectAllStudents(); for (Student student : students) { System.out.println(student); } sqlSession.close(); } }
C++
UTF-8
406
2.96875
3
[]
no_license
#include "../Socket.hpp" #include <string.h> using namespace std; int main(){ char chunk[100]; try{ Socket::TCP server; server.listen_on_port(10000); Socket::TCP client = server.accept_client(); cout << "receiving ... " << endl; client.receive<char>(chunk, 100); cout << chunk << endl; cout << "done. " << endl; } catch(Socket::SocketException &e){ cout << e << endl; } }
Python
UTF-8
947
2.734375
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[70]: import pandas as pd import seaborn as sns import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB from sklearn import svm import pickle # In[2]: df = pd.read_csv('covid19.csv') # In[8]: y = df['Outcome'] x = df[['P_age','P_gender','Fever','Running_Nose','Travel_History','Coughing','Difficulty breathing']] # In[39]: X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.85, random_state=42) # In[40]: tr = LogisticRegression().fit(X_train,y_train) # In[41]: tr.score(X_test,y_test) # In[42]: nav = MultinomialNB().fit(X_train,y_train) # In[47]: nav.score(X_test,y_test) # In[66]: nav.predict_proba([[30,1,1,1,1,1,1]]) # In[67]: # In[69]: pickle.dump(nav, open('model.pkl','wb')) model = pickle.load(open('model.pkl','rb'))
C#
UTF-8
1,998
3.421875
3
[ "MIT" ]
permissive
using System; using System.Linq; using System.Reflection; namespace BassUtils { /// <summary> /// Copies properties from one object to another. /// </summary> public static class PropertyCopier { /// <summary> /// Copies all possible property values from <paramref name="source"/> to <paramref name="destination"/>. /// Properties are matched by name, and the property on the destination must have a setter and /// a type that is compatible with the source. /// </summary> /// <param name="source">Object to copy properties from.</param> /// <param name="destination">Object to copy properties to.</param> public static void CopyProperties(object source, object destination) { source.ThrowIfNull("source"); destination.ThrowIfNull("destination"); // Getting the Types of the objects Type typeDest = destination.GetType(); Type typeSrc = source.GetType(); // Collect all the valid properties to map var properties = from srcProp in typeSrc.GetProperties() let targetProperty = typeDest.GetProperty(srcProp.Name) where srcProp.CanRead && targetProperty != null && targetProperty.CanWrite && (targetProperty.GetSetMethod().Attributes & MethodAttributes.Static) == 0 && targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType) select new { sourceProperty = srcProp, targetProperty = targetProperty }; // Set the properties in the destination. foreach (var property in properties) property.targetProperty.SetValue(destination, property.sourceProperty.GetValue(source, null), null); } } }
C#
UTF-8
4,023
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Text.RegularExpressions; using System.Threading; using System.ComponentModel; using System.Diagnostics; namespace dotNet5781_03B_4307_0791 { /// <summary> /// Interaction logic for driveWindow.xaml /// </summary> public partial class drivewindow : Window { BackgroundWorker driving;//thread for driving BackgroundWorker timeCounter;//thread for time Counter(time to end of the prossec) Bus toDrive;//bus to make the drive int speed; int distance; Button senderBtn; public drivewindow(object sender, Bus b1)//ctor { InitializeComponent(); senderBtn = sender as Button; toDrive = b1; speed = new Random(DateTime.Now.Millisecond).Next(20, 50);//Speed ​​lottery driving = new BackgroundWorker(); timeCounter = new BackgroundWorker(); driving.DoWork += Driving_DoWork; driving.RunWorkerCompleted += Driving_RunWorkerCompleted; timeCounter.DoWork += TimeCounter_DoWork; timeCounter.ProgressChanged += TimeCounter_ProgressChanged; timeCounter.RunWorkerCompleted += TimeCounter_RunWorkerCompleted; } private void TimeCounter_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)//When the timer finishes running { toDrive.TimerText = "";//show 00:00:00 } private void TimeCounter_ProgressChanged(object sender, ProgressChangedEventArgs e)//During the process { toDrive.TimerText = (DateTime.Now.AddSeconds(6 * (distance / speed)) - DateTime.Now.AddSeconds(e.ProgressPercentage)).ToString().Substring(0, 8);//Update the timer } private void TimeCounter_DoWork(object sender, DoWorkEventArgs e)//work of timer { int i = 0; while (!toDrive.IsReady) { TimeCounter_ProgressChanged(this, new ProgressChangedEventArgs(i, new object()));//Update every second i++; Thread.Sleep(1000); } } private void Driving_DoWork(object sender, DoWorkEventArgs e)//to drivind-work of drivimg prosses { string distance2 = (string)e.Argument; distance = int.Parse(distance2); toDrive.State = STATUS.INDRIVE;//update the status toDrive.Drive(distance);//make drive timeCounter.RunWorkerAsync(distance);//begin timer thread Thread.Sleep(6000 * (distance / speed));//sleep until drive will finish } private void Driving_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)//That the drive was over { if (!toDrive.DangerTest()) toDrive.State = STATUS.READY;//update the status if (e.Error != null)//If the trip was unsuccessful (as a result of the bus danger) MessageBox.Show(e.Error.Message); senderBtn.IsEnabled = true; } private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)//Enables typing of digits only { Regex regex = new Regex("[^0-9]+"); e.Handled = regex.IsMatch(e.Text); } private void tbdistance_KeyDown(object sender, KeyEventArgs e)//when the usur Press on a key { if (e.Key == Key.Enter)//if he Press enter { string distance = tbdistance.Text; driving.RunWorkerAsync(distance);//begin the drive thread this.Close();//close the window } } } }
Python
UTF-8
774
4.28125
4
[]
no_license
"8. Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado pelo usuário, assim como a quantidade de dias pelos quais o carro foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60,00 por dia e R$ 0,15 por km rodado." from typing import Tuple km_carro = float (input("Informe a quantidade de quilometros percorridos com o veículo:")) dias_carro = float (input("Informe por quantos dias o carro está alugado:")) valor_aluguel = float = 60 * dias_carro valor_km = 0.15 * km_carro totalzao = valor_aluguel + valor_km print ("Total a pagar: R$", totalzao ) print ("Sendo: R$", valor_aluguel, "o valor do tempo em que o veículo ficou alugado e R$:", valor_km, "o custo da quilometragem rodada com o veículo.")
PHP
UTF-8
2,083
2.734375
3
[ "MIT" ]
permissive
<?php /* * Copyright (c) 2017 Salah Alkhwlani <yemenifree@yandex.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Yemenifree\Validation; class TranslateLoader { protected $path; protected $defaultPath; protected $supportLang = ['ar']; /** * TranslateLoader constructor. */ public function __construct() { $this->defaultPath = __DIR__ . '/lang'; $this->path = __DIR__ . '/lang'; } /** * load lang. * * @param $locale * * @return array */ public function load($locale): array { // if file not exists if (!\file_exists($this->getFilePath($locale))) { // if local support build in get translate from package. if ($this->isSupportLocal($locale)) { return include $this->getFilePath($locale, true); } return []; } return include $this->getFilePath($locale); } /** * @param $locale * @param bool $default * * @return string */ protected function getFilePath($locale, $default = false): string { return $this->getPath($default) . '/' . $locale . '.php'; } /** * get path lang. * * @param bool $default * * @return string */ public function getPath($default = false): string { return $default ? $this->getDefaultPath() : $this->path; } /** * @param string $path * * @return TranslateLoader */ public function setPath($path): self { $this->path = $path; return $this; } /** * @return string */ public function getDefaultPath(): string { return $this->defaultPath; } /** * Check if local support build in with package. * * @param $locale * * @return bool */ private function isSupportLocal($locale): bool { return \in_array($locale, $this->supportLang, true); } }
Swift
UTF-8
371
2.6875
3
[]
no_license
// // NSLayoutConstraint+setContraint.swift // Common // // Created by Breno Aquino on 18/12/21. // import UIKit public extension NSLayoutConstraint { func set(id: String? = nil, priority: UILayoutPriority? = nil, isActive: Bool = true) { identifier = id if let priority = priority { self.priority = priority } self.isActive = isActive } }
PHP
UTF-8
3,145
3.09375
3
[ "MIT" ]
permissive
<?php class Log { private $id; private $ip; private $userAgent; private $api; private $status; private $user; private $timestamp; /* Constructor */ private function __construct($id, $ip, $userAgent, $api, $status, $user, $timestamp) { $this->id = $id; $this->ip = $ip; $this->userAgent = $userAgent; $this->api = $api; $this->status = $status; $this->user = $user; $this->timestamp = $timestamp; } /* Getter */ public function getId() { return $this->id; } public function getIp() { return $this->ip; } public function getUserAgent() { return $this->userAgent; } public function getApi() { return $this->api; } public function getStatus() { return $this->status; } public function getUser() { return $this->user; } public function getTimestamp() { return $this->timestamp; } public function getInfos() { return array("id" => $this->getId(), "ip" => $this->getIp(), "userAgent" => $this->getUserAgent(), "api" => $this->getApi(), "status" => $this->getStatus(), "user" => $this->getUser()->getInfos(), "timestamp" => $this->getTimestamp()); } public static function create($api, $status, $user) { if ($GLOBALS['config']['logging'] == false || is_null($user)) { return null; } else { if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['REMOTE_ADDR']; } else { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } $data = array("ip" => $ip, "userAgent" => $_SERVER['HTTP_USER_AGENT'], "api" => $api, "status" => $status, "user" => $user->getId(), "ts" => (new DateTime())->format('Y-m-d H:i:s')); $id = $GLOBALS['db']->update("INSERT INTO log(`ip`, `userAgent`, `api`, `status`, `user`, `timestamp`) VALUES(:ip, :userAgent, :api, :status, :user, :ts)", $data); return self::getById($id); } } public static function existById($id) { return is_array($GLOBALS['db']->query("SELECT `id` FROM log WHERE id = :id", array("id" => $id))); } public static function getById($id) { if (self::existById($id)) { $arr = $GLOBALS['db']->query("SELECT * FROM log WHERE id = :id", array("id" => $id)); return new Log($arr['id'], $arr['ip'], $arr['userAgent'], $arr['api'], $arr['status'], User::getById($arr['user']), $arr['timestamp']); } } public static function getAll() { $arr = $GLOBALS['db']->queryAll("SELECT id FROM `log`", array()); $data = array(); foreach ($arr as $row) { $data[] = self::getById($row['id'])->getInfos(); } return $data; } }
C
UTF-8
3,149
3.484375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "../1.PublicDefine/publicDefine.c" #define LIST_INIT_SIZE 100 //线性表最大初始空间 #define LISTINCREMENT 10 //线性表分配空间增量 typedef struct { ElemType *elem;//指针等于说是数组 int length; int listSize; } SqList; //初始化函数 Status initSqList(SqList *list) { list->elem = (ElemType *) malloc(LIST_INIT_SIZE * sizeof(ElemType)); if (!list->elem) exit(OVERFLOW); list->length = 0; list->listSize = LIST_INIT_SIZE; return OK; } //增量添加 Status increaseSqListLength(SqList *list) { ElemType *ptr = (ElemType *) realloc(list->elem, LISTINCREMENT * sizeof(ElemType)); if (NULL == ptr) return OVERFLOW; list->elem = ptr; list->listSize += LISTINCREMENT; return OK; } //销毁函数 Status destroyList(SqList *list) { if (!list) return ERROR; free(list); return OK; } //清空线性表 Status clearList(SqList *list) { if (!list) return ERROR; list->length = 0; return OK; } //判断是否空顺序线性表 Status listEmpty(SqList *list) { if (!list) return ERROR; if (list->length == 0) return TRUE; else return FALSE; } //返回长度 int listLength(SqList *list) { if (!list) return ERROR; return list->length; } //返回第i个位置元素,从0开始 ElemType getELem(SqList *list, int i) { if (!list) return ERROR; if (i < 0 || i >= list->length) return ERROR; return list->elem[i]; } //返回元素在顺序表中的位置 返回i+1 int locateElem(SqList *list, ElemType e) { int i; if (!list || listEmpty(list)) return ERROR; for (i = 0; i < list->length; i++) { if (list->elem[i] == e) return i + 1; } if (i = list->length) return INFEASIBLE; } //返回前置元素 ElemType priorElem(SqList *list, ElemType e, ElemType *pre_e) { if (locateElem(list, e)) { *pre_e = getELem(list, locateElem(list, e)); return OK; } return INFEASIBLE; } //在position位置插入元素e position位置的元素变成e Status sqListInsert(SqList *list, ElemType e, int position) { if (++list->length > list->listSize){ //增加空间 } if (-2 != increaseSqListLength(list)) { for (int i = list->length; i > position; i--) { list->elem[i] = list->elem[i - 1]; } list->elem[position] = e; return OK; } return ERROR; } //有序插完继续有序 不需要假设是按照升序的 //2分查找优化怎么实现? Status sqListIn(SqList *list, ElemType e) { int i; for(i=0;i<list->length;i++){ if(i=list->length-1){ break; } if(e>=list->elem[i] && e<=list->elem[i+1]){ break; } if(e<=list->elem[i] && e>=list->elem[i+1]){ break; } } Status status=sqListInsert(list,e,++i); if(status){ return OK; } }//2分查找优化怎么实现? Status sqListBinaryIn(SqList *list, ElemType e) { int i; Status status=sqListInsert(list,e,++i); if(status){ return OK; } }
Markdown
UTF-8
1,879
3.03125
3
[]
no_license
负责人:王硕 ## Scroller 跨平台相同操作体验的滚动组件。 > **[info] 新增** > 使用v-model可以绑定判断是否在顶部的Boolean值 > ### 基本用法 ``` html <scroller style="flex-grow: 1" ref="scroller" @pullRefresh="refresh" canPullRefresh> <div>content</div> </scroller> ``` ```js import Scroller from '@/components/Scroller' export default { components: { Scroller }, methods: { scrollTop () { this.$refs.scroller.scrollTop() }, refresh (over) { // 加载内容 over()//加载完毕后调用,放在合适的位置 } } } ``` > **[danger] 注意** > > Scroller一定要设置大小且滚动内容不能脱离文档流,否则将无法正常运行。 ### BottomBarItem Attributes |参数|说明|类型|可选值|默认值| |:-----|:-----|:-----|:-----|:-----| |can-pull-refresh|开启下拉刷新|`Boolean`|`true`、`false`|`false`| |refreshing-text|正在刷新提示文字|`String`|-|`加载中...`| |pullRefresh-text|下拉刷新提示文字|`String`|-|`下拉刷新`| |activeRefresh-text|激活刷新提示文字|`String`|-|`释放刷新`| |refresh-icon|刷新图标|`String`|`@/components/Icon/svg/`中的`SVG`文件名|`loading`| ### Events |事件名称|说明|回调参数| |:-----|:-----|:-----| |beforeScrollStart|在用户触摸屏幕但还没有开始滚动时触发|-| |scrollStart|开始滚动时触发|-| |scrollEnd|停止滚动时触发|-| |pullRefresh|下拉刷新时触发|`over`:通知`Scroller`刷新完毕| ### Slots |name|说明| |:-----|:-----| |-|滚动内容| ### Functions |方法名|说明|参数| |:-----|:-----|:-----| |scrollTop|滚动到顶部|-| |scrollTo|滚动到任意的位置|x:横坐标,y:纵坐标| |scrollBy|从当前位置进行滚动|x:横坐标,y:纵坐标| |refresh|刷新滚动区域大小,当滚动内容改动后需要调用|-|
Markdown
UTF-8
1,184
3.34375
3
[ "Apache-2.0" ]
permissive
# GPIO 通用输入输出 GPIO 口用于读写开关量信号, 即可以用于控制类似 LED 灯之类的简单设备, 也可以用于读取按钮或类似设备的开关状态 通过 `require('device/gpio')` 调用。 ## gpio gpio(pin) ## gpio:close gpio:close(callback) 所其他所有方法之后调用, 用来关闭打开或导出的 GPIO 文件 (不会影响 GPIO 口的状态) ## gpio:open gpio:open(callback) 必须在其他方法前调用 - callback {function} 打开完成后被调用 ## gpio:direction gpio:direction(direction, callback) 设置或读取当前 GPIO 的输入输出方向 - direction {'in'|'out'|nil} GPIO 输入输出方向, 只接受 'in' 或者 'out', 如果为 nil 则表示不修改 direction - callback {function} callback(direction) 返回最后读取的 GPIO 输入输出方向 ## gpio:read gpio:read(callback) 读取 GPIO 当前电平状态, 返回 0 或者 1 - callback {function} callback(value) 返回最后读取的 GPIO 的输入输出电平 ## gpio:write gpio:write(value, callback) 设置 GPIO 输出电平 - value {number} 只接受 0 或 1. - callback {function} 设置完成后被调用
JavaScript
UTF-8
368
3.0625
3
[]
no_license
//url的关键字提取函数 function urlTool(urlStr) { //1. 把url以?分割 var arr = urlStr.split("?").pop().split("&"); console.log(arr); //["proName=1", "page=1"] var query = []; arr.forEach(function(v) { var param = v.split("="); // query[param[0]] = param[1]; query.push(param[1]); }); return query; }
Markdown
UTF-8
4,569
2.515625
3
[]
no_license
.NET WHOIS Lookup and Parser ============================ [![GitHub Stars](https://img.shields.io/github/stars/flipbit/whois.svg)](https://github.com/flipbit/whois/stargazers) [![GitHub Issues](https://img.shields.io/github/issues/flipbit/whois.svg)](https://github.com/flipbit/whois/issues) [![NuGet Version](https://img.shields.io/nuget/v/whois.svg)](https://www.nuget.org/packages/Whois/) [![NuGet Downloads](https://img.shields.io/nuget/dt/whois.svg)](https://www.nuget.org/packages/Whois/) Query and parse WHOIS domain registration information with this library for .NET Standard 2.0 and .NET Framework 4.5.2. ```csharp // Create a WhoisLookup instance var whois = new WhoisLookup(); // Query github.com var response = whois.Lookup("github.com"); // Output the response Console.WriteLine(response.Content); // Domain Name: github.com // Registry Domain ID: 1264983250_DOMAIN_COM-VRSN // Registrar WHOIS Server: whois.markmonitor.com // Registrar URL: http://www.markmonitor.com // ... ``` ### Parsing WHOIS data is parsed into objects using extensible [Tokenizer](https://github.com/flipbit/tokenizer) templates. ```csharp // Query github.com var response = whois.Lookup("github.com"); // Convert the response to JSON var json = JsonConvert.SerializeObject(response, Formatting.Indented); // Output the json Console.WriteLine(json); // { // "ContentLength": 3730, // "Status": 1, // "DomainName": { // "IsPunyCode": false, // "IsTld": false, // "Tld": "com", // "Value": "github.com" // }, // "RegistryDomainId": "1264983250_DOMAIN_COM-VRSN", // "DomainStatus": [ // "clientUpdateProhibited", // "clientTransferProhibited", // "clientDeleteProhibited" // ], // "Registered": "2007-10-09T18:20:50Z", // "Updated": "2020-09-08T09:18:27Z", // "Expiration": "2022-10-09T07:00:00Z", // ... ``` ### Async/Await The library is fully `async/await` compatible. ```csharp // Create a WhoisLookup instance var whois = new WhoisLookup(); // Query github.com var response = await whois.LookupAsync("github.com"); // Output the json Console.WriteLine(response.Content); ``` ### Configuration The library can be configured globally or per instance: ```csharp // Global configuration WhoisOptions.Defaults.Encoding = Encoding.UTF8; // Per-instance configuration var lookup = new WhoisLookup(); lookup.Options.TimeoutSeconds = 30; ``` ## Extending ### Parsing More Data If a registrar's WHOIS data isn't being parsed correctly, you can simply add a new template: ```csharp var lookup = new WhoisLookup(); // Clear the embedded templates (not recommended) lookup.Parser.ClearTemplates(); // Add a custom WHOIS response parsing template lookup.Parser.AddTemplate("Domain: { DomainName$ }", "Simple Pattern"); ``` See the [existing patterns](https://github.com/flipbit/whois/blob/master/Whois/Resources/generic/tld/Found02.txt) and [Tokenizer](https://github.com/flipbit/tokenizer) documentation for information about creating patterns. You can also add validation and transformation functions to your patterns. ### Networking The library communicates via an `ITcpReader` interface. The [default implementation](https://github.com/flipbit/whois/blob/master/Whois/Net/TcpReader.cs) will talk directly to a WHOIS server over port 43. You can change this behaviour by creating a new `ITcpReader` implementation and registering it the `TcpReaderFactory`: ```csharp // Create a custom ITcpReader implementation class MyCustomTcpReader : ITcpReader { private readonly ITcpReader reader; public MyCustomTcpReader() { reader = new TcpReader(); } public Task<string> Read(string url, int port, string command, Encoding encoding, int timeoutSeconds) { Console.WriteLine($"Reading from URL: {url}"); return reader.Read(url, port, command, encoding, timeoutSeconds); } public void Dispose() { reader.Dispose(); } } // Create a WhoisLookup instance var lookup = new WhoisLookup(); // Assign the custom TcpReader lookup.TcpReader = new MyCustomTcpReader(); // Lookups will now use the custom TcpReader var response = lookup.Lookup("github.com"); ``` ### Installation You can install the library via the NuGet GUI or by entering the following command into the Package Manager Console: Install-Package Whois The source code is available on Github and can be downloaded and compiled. ### Further Reading Further details about how the library works can be found on [this blog post](http://flipbit.co.uk/2009/06/querying-whois-server-data-with-c.html).
TypeScript
UTF-8
3,192
2.890625
3
[ "Apache-2.0" ]
permissive
import { expectTypeOf } from "expect-type"; import { createNodeRedisClient, WrappedNodeRedisClient, createHandyClient, IHandyRedis } from "../src"; import { RedisClient } from "redis"; import { Push as Push_ts40 } from "../src/push"; import { Push as Push_ts34 } from "../src/push.ts34"; test("create client with existing client", () => { expectTypeOf(createNodeRedisClient).toBeCallableWith({} as RedisClient); expectTypeOf(createNodeRedisClient).returns.toEqualTypeOf<WrappedNodeRedisClient>(); }); test("deprecated imports are aliases of current ones", () => { expectTypeOf(createHandyClient).toEqualTypeOf(createNodeRedisClient); expectTypeOf<IHandyRedis>().toEqualTypeOf<WrappedNodeRedisClient>(); }); test("client has promisified redis methods", () => { const client = {} as WrappedNodeRedisClient; expectTypeOf(client.get).returns.resolves.toEqualTypeOf<string | null>(); expectTypeOf(client.set).returns.resolves.toEqualTypeOf<string | null>(); expectTypeOf(client.setex).returns.resolves.toEqualTypeOf<"OK">(); expectTypeOf(client.geohash).parameters.toEqualTypeOf<[string, ...string[]]>(); expectTypeOf(client.geohash).returns.resolves.items.toBeString(); expectTypeOf(client.zrevrange).toBeCallableWith("key", 1, 2); expectTypeOf(client.zrevrange).returns.resolves.items.toBeString(); expectTypeOf(client.quit).returns.resolves.toBeString(); expectTypeOf(client.end).returns.toEqualTypeOf<void>(); expectTypeOf(client.spop).returns.resolves.toEqualTypeOf<null | string | string[]>(); expectTypeOf(client.scan).returns.resolves.toEqualTypeOf<[string, string[]]>(); expectTypeOf(client.sscan).returns.resolves.toEqualTypeOf<[string, string[]]>(); expectTypeOf(client.zscan).returns.resolves.toEqualTypeOf<[string, string[]]>(); // @ts-expect-error expectTypeOf(client.xgroup).toBeCallableWith([["CREATE", ["foo", "bar"]], "SOMETHINGWRONG"]); }); test("Push", () => { // typescript 4+ can add to the end of tuples expectTypeOf<Push_ts40<[], 1>>().toEqualTypeOf<[1]>(); expectTypeOf<Push_ts40<[1, 2], 3>>().toEqualTypeOf<[1, 2, 3]>(); // old typescript versions just get a union-ed array expectTypeOf<Push_ts34<[], 1>>().toEqualTypeOf<1[]>(); expectTypeOf<Push_ts34<[1, 2], 3>>().toEqualTypeOf<Array<1 | 2 | 3>>(); }); const _xgroupTests = async (client: WrappedNodeRedisClient) => { await client.xgroup( [["CREATE", ["one", "two"]], "ID", "MKSTREAM"], ["DESTROY", ["three", "four"]], ["CREATECONSUMER", ["five", "six", "seven"]], ["DELCONSUMER", ["eight", "nine", "ten"]] ); await client.xgroup( // @ts-expect-error [["CREATE", ["one", "two"]], "ID", "typo_this_should_be_MKSTREAM"], ["DESTROY", ["three", "four"]], ["CREATECONSUMER", ["five", "six", "seven"]], ["DELCONSUMER", ["eight", "nine", "ten"]] ); await client.xgroup( [["CREATE", ["one", "two"]], "ID"], [["SETID", ["one", "two"]], "$"], ["DESTROY", ["three", "four"]], ["CREATECONSUMER", ["five", "six", "seven"]], ["DELCONSUMER", ["eight", "nine", "ten"]] ); };
Python
UTF-8
678
2.984375
3
[]
no_license
class Leetcode70: def climbStairs(self, n: int) -> int: def stairs(i): if i <= 2: return i return stairs(i - 1) + stairs(i - 2) return stairs(n) def climbStairs2(self, n: int) -> int: if n <= 2: return n dp = [0 for _ in range(n)] dp[0], dp[1] = 1, 2 for i in range(2, n): dp[i] = dp[i - 1] + dp[i - 2] return dp[n - 1] def climbStairs3(self, n: int) -> int: if n <= 2: return n prev, curr = 1, 2 for i in range(2, n): total = prev + curr prev, curr = curr, total return curr
Markdown
UTF-8
2,417
3.859375
4
[]
no_license
## Implementation of listeners and event handlers ### Python Python does not have listeners or event handlers by default. It is up to the programmer to implement for themselves (using, for example, Observer patterns), or to import a library that will add the functionality. ### C# C# has one of the richest event systems of any object oriented language. C# uses a system of events, listeners, delegates, and publish-subscribe patters to handle events and notifications. If you know anything about object oriented languages, events, listeners, and publish-subscribe are self-explanatory. Delegates, however, are a special feature of C#. Delegates provide a functionality similar to function pointers from C. They are an improved version, however, as they allow you to execute a list of multiple functions referenced by a single delegate with one line of code. Delegates are ideally suited for use as events — notifications from one component to "listeners" about changes in that component, so they are often used in conjunction with the wider event system. A code snippet can provide the best explanation of the interactions of this complicated system. In the below snippet, a Metronome class creates events at a rate of one every 3 seconds, and a Listener class hears the metronome ticks by 'Subscribing' to the delegate and prints "HEARD IT" to the console every time it receives an event. ``` using System; namespace example { public class Metronome { public event TickHandler Tick; public EventArgs e = null; public delegate void TickHandler(Metronome m, EventArgs e); public void Start() { while (true) { System.Threading.Thread.Sleep(3000); if (Tick != null) { Tick(this, e); } } } } public class Listener { public void Subscribe(Metronome m) { m.Tick += new Metronome.TickHandler(HeardIt); } private void HeardIt(Metronome m, EventArgs e) { System.Console.WriteLine("HEARD IT"); } } class Test { static void Main() { Metronome m = new Metronome(); Listener l = new Listener(); l.Subscribe(m); m.Start(); } } } ```
PHP
UTF-8
759
2.625
3
[]
no_license
<?php /** * Created by PhpStorm. * * PHP version 5.6, 7 * * @package Zeravcic\PhpUnit_De\Tests\chapter09 * @author Nikola Zeravcic <niks986@gmail.com> * @license <http://opensource.org/licenses/gpl-license.php GPL * @link http://nikolazeravcic.iz.rs Personal site */ namespace Zeravcic\PhpUnit_De\Tests\chapter09; use PHPUnit\Framework\TestCase; /** * Class TraitClassTest * * @package Zeravcic\PhpUnit_De\Tests\chapter09 */ class TraitClassTest extends TestCase { public function testConcreteMethod() { $mock = $this->getMockForTrait(AbstractTrait::class); $mock->expects($this->any()) ->method('abstractMethod') ->will($this->returnValue(true)); $this->assertTrue($mock->concreteMethod()); } }
Python
UTF-8
2,263
4.5
4
[]
no_license
""" Given an array of integers, return `True` or `False` if array has two numbers that add up to a specific target. Assumption: - Each input has only one solution so the algorithm will return on the first result APPROACHES: There are three solution provided to this problem as different methods of the given class. All the approaches there have been described as well. """ class TwoSumProblem: def __init__(self, array, target): self.array = array self.target = target def two_sum_brute_force(self): """ This function use the brute force approach to get to the solution -> Time Complexity: O(n^2) -> Space Complexity: O(1) """ for i in range(len(self.array) - 1): for j in range(i + 1, len(self.array)): if self.array[i] + self.array[j] == self.target: return True return False def two_sum_hash_table(self): """ This function uses has table to keep track of entries and get to the result -> Time Complexity: O(n) -> Space Complexity: O(n) """ hash_table = dict() for i in range(len(self.array)): if self.array[i] in hash_table: return True else: hash_table[self.target - self.array[i]] = self.array[i] def two_sum_both_ways_track(self): """ Here, we have two indices that we keep track of, one at the front and one at the back. We move either the left or right indices based on whether the sum of the elements at these indices is either greater than or less than the target element. -> Time Complexity: O(n) -> Space Complexity: O(1) Assumption: - This approach assumes that the array passed is sorted """ i = 0 j = len(self.array) - 1 while i < j: if self.array[i] + self.array[j] == self.target: return True elif self.array[i] + self.array[j] < self.target: i += 1 else: j -= 1 return False
Python
UTF-8
291
3.09375
3
[]
no_license
s=input() c=1 g="" for i in range(0,len(s)): if i<len(s)-1: if s[i]==s[i+1]: c+=1 elif s[i]!=s[i+1]: g=g+s[i]+str(c) c=1 else: if s[i]==s[i-1]: g=g+s[i]+str(c) else: g=g+s[i]+str(1) print(g)
C++
UTF-8
1,015
3.03125
3
[]
no_license
#ifndef __NETSERVER_COUNTDOWNLATCH_H__ #define __NETSERVER_COUNTDOWNLATCH_H__ #include"noncopyable.h" #include<mutex> #include<condition_variable> /** * 倒计时(CountDownLatch)同步手段, 主要用途 * * 一. 主线程发起多个子线程,等这些子线程各自都完成一定的任务之后,主线程才继续执行。 * 通常用于主线程等待多个子线程完成初始化。 * * 二. 主线程发起多个子线程,子线程都等待主线程,主线程完成其他一些任务之后通知所有子线程开始执行。 * 通常用于多个子线程等待主线程发起“起跑”命令。 */ namespace net { class CountDownLatch : public noncopyable { public: explicit CountDownLatch(int count); void wait(); void countDown(); int getCount() const; private: mutable std::mutex mutex_; std::condition_variable cv_; int count_; }; } #endif
Python
UTF-8
4,939
3.546875
4
[]
no_license
class DoublyLinkedList: class _Node: def __init__(self,_value): self._value = _value self._previous_node = None self._next_node = None def __init__(self): self._head = None self._queue = None self._size = 0 def __str__(self): _array = [] _present_node = self._head while _present_node != None: _array.append(_present_node._value) _present_node = _present_node._next_node return str(_array)+" Size: "+ str(self._size) def prepend(self,_value): _new_node = self._Node(_value) if self._head == None and self._queue == None: self._head = _new_node self._queue = _new_node else: self._head._previous_node = _new_node _new_node._next_node = self._head self._head = _new_node self._size += 1 def append(self,_value): _new_node = self._Node(_value) if self._head == None and self._queue == None: self._head = _new_node self._queue = _new_node else: self._queue._next_node = _new_node _new_node._previous_node = self._queue self._queue = _new_node self._size += 1 def shift(self): if self._size == 0: self._head = None self._queue = None elif self._head != None: _removed_node = self._head self._head = _removed_node._next_node _removed_node._next_node = None self._size -= 1 return _removed_node._value def pop(self): if self._size == 0: self._head = None self._queue = None else: _removed_node = self._queue self._queue = _removed_node._previous_node self._queue._next_node = None _removed_node._next_node = None self._size -= 1 return _removed_node._value def get(self, _index): if _index == self._size - 1: return self._queue elif _index == 0: return self._head elif _index > 0 and _index < self._size - 1: _auxiliary_index = int(self._size/2) if _index <= _auxiliary_index: _present_node = self._head _accountant = 0 while _accountant != _index: _present_node = _present_node._next_node _accountant += 1 return _present_node else: _present_node = self._queue _accountant = self._size - 1 while _accountant != _index: _present_node = _present_node._previous_node _accountant -= 1 return _present_node else: return None def update(self,_index, _value): _target_node = self.get(_index) if _target_node != None: _target_node._value = _value else: return None def insert(self,_index, _value): if _index == self._size - 1: return self.append(_value) elif _index >= 0 and _index < self._size - 1: _new_node = self._Node(_value) _previous_nodes = self.get(_index) _next_nodes = _previous_nodes._next_node _previous_nodes._next_node = _new_node _new_node._previous_node = _previous_nodes _new_node._next_node = _next_nodes _next_nodes._previous_node = _new_node self._size += 1 else: return None def remove(self,_index): if _index == self._size - 1: return self.pop() elif _index == 0: return self.shift() elif _index > 0 and _index < self._size - 1: _removed_node = self.get(_index) _previous_nodes = _removed_node._previous_node _next_nodes = _removed_node._next_node _previous_nodes._next_node = _next_nodes _next_nodes._previous_node = _previous_nodes _removed_node._previous_node = None _removed_node._next_node = None self._size -= 1 return _removed_node else: return None def reverse(self): _reverted_nodes = None _present_node = self._head self._queue = _present_node while _present_node!= None: _reverted_nodes = _present_node._previous_node _present_node._previous_node = _present_node._next_node _present_node._next_node = _reverted_nodes _present_node = _present_node._previous_node self._head = _reverted_nodes._previous_node obj_node = DoublyLinkedList() obj_node.append(1) obj_node.append(2) obj_node.append(3) obj_node.append(4) print(obj_node) obj_node.reverse() print(obj_node)
PHP
UTF-8
2,985
2.6875
3
[]
no_license
<?php if (strpos($_SERVER["HTTP_ACCEPT"], "application/rss+xml") !== FALSE) header("Content-Type: application/rss+xml"); else header("Content-Type: application/xml"); $user = $_GET["user"]; $notesContent = file_get_contents("https://api.openstreetmap.org/api/0.6/notes/search?display_name=".urlencode($user)."&closed=7"); $notes = new SimpleXMLElement($notesContent); use Bhaktaraz\RSSGenerator\Item; use Bhaktaraz\RSSGenerator\Feed; use Bhaktaraz\RSSGenerator\Channel; require 'vendor/autoload.php'; $feed = new Feed(); $channel = new Channel(); $now = new DateTime(); $channel ->title("OSM notes of ".$user) ->description("This channel contains all open and recently closed notes of the user ".$user) ->url('http://webmapping.cyou') ->language('en-US') ->copyright('OpenStreetMap® is open data, licensed under the Open Data Commons Open Database License (ODbL) by the OpenStreetMap Foundation (OSMF).') ->pubDate($now->getTimeStamp()) ->lastBuildDate($now->getTimeStamp()) ->updateFrequency(1) ->updatePeriod('hourly') ->ttl(1) ->appendTo($feed); foreach ($notes as $n) { $creator = (!is_array($n->comments->comment) ? $n->comments->comment->user : $n->comments->comment[0]->user); if ($creator == "") $creator = "<Anonymous>"; $desc = (!is_array($n->comments->comment) ? $n->comments->comment->text : $n->comments->comment[0]->text); $desc = str_replace(" ", " ", str_replace("\n", " ", $desc)) $html = ""; $last_date = ""; foreach($n->comments->comment as $c) { $last_date = $c->date; if (!isset($c->user)) $user_link = "&lt;Anonymous&gt;"; else $user_link = "<a href=\"{$c->user_url}\">{$c->user}</a>"; if ($c->action == "opened") { $html .= "<p>On {$c->date} $user_link opened the note" . (trim($c->text) != "" ? ", writing:</p>\n" . $c->html . "\n" : "."); } if ($c->action == "closed") { $html .= "<p>On {$c->date} $user_link closed the note" . (trim($c->text) != "" ? ", writing:</p>\n" . $c->html . "\n" : "."); } if ($c->action == "reopened") { $html .= "<p>On {$c->date} $user_link reopened the note."; } if ($c->action == "commented") { $html .= "<p>On {$c->date} $user_link writes:</p>\n" . $c->html . "\n"; } } $item = new Item(); $item ->title(($n->status == "closed" ? "[CLOSED] " : "")."Note " . $n->id . " (".$n->date_created.")") ->creator($creator) ->description(str_replace("&","&amp;",$desc)) ->content($html) ->url("https://osm.org/note/{$n->id}") ->guid(createGUID($n)) ->pubDate(strtotime($last_date)) ->appendTo($channel); } echo $feed->render(); function createGUID($n) { $token = sprintf("%09x", $n->id); $token .= $n->date; $hash = strtoupper(md5($token)); $guid = ''; $guid .= substr($hash, 0, 8) . '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12); return $guid; } ?>
Java
UTF-8
2,049
2.59375
3
[]
no_license
package com.pepario.run.Levels; public class Level { private String leaderboardKey; private String tmxLevelName; private String musicNameWithPath; private int nextLevelId; private float playerMaxRunningSpeed; private float deltaTimeRunningSpeedUpdateWeight; private float playerMovementSpeed; public Level() {} public String getLeaderboardKey() { return leaderboardKey; } public String getTmxLevelName() { return tmxLevelName; } public String getMusicNameWithPath() { return musicNameWithPath; } public int getNextLevelId() { return nextLevelId; } public float getPlayerMaxRunningSpeed() { return playerMaxRunningSpeed; } public float getDeltaTimeRunningSpeedUpdateWeight() { return deltaTimeRunningSpeedUpdateWeight; } public float getPlayerMovementSpeed() { return playerMovementSpeed; } public Level setLeaderboardKey(String leaderboardKey) { this.leaderboardKey = leaderboardKey; return this; } public Level setTmxLevelName(String tmxLevelName) { this.tmxLevelName = tmxLevelName; return this; } public Level setMusicNameWithPath(String musicNameWithPath) { this.musicNameWithPath = musicNameWithPath; return this; } public Level setNextLevelId(int nextLevelId) { this.nextLevelId = nextLevelId; return this; } public Level setPlayerMaxRunningSpeed(float playerMaxRunningSpeed) { this.playerMaxRunningSpeed = playerMaxRunningSpeed; return this; } public Level setDeltaTimeRunningSpeedUpdateWeight(float deltaTimeRunningSpeedUpdateWeight) { this.deltaTimeRunningSpeedUpdateWeight = deltaTimeRunningSpeedUpdateWeight; return this; } public Level setPlayerMovementSpeed(float playerMovementSpeed) { this.playerMovementSpeed = playerMovementSpeed; return this; } }
JavaScript
UTF-8
3,131
4.125
4
[]
no_license
/* we need the button and that container div */ const get_meal_btn = document.getElementById( "get_meal" ); /* we're making a GET request to that endpoint, it sends back a JSON response, which we can parse in order to retrieve the data we want.*/ const meal_container = document.getElementById("meal"); get_meal_btn.addEventListener("click", () => { fetch("https://www.themealdb.com/api/json/v1/1/random.php") .then((res) => res.json()) .then((res) => { createMeal(res.meals[0]); }) .catch((e) => { console.warn(e); }); }); /* We're using the fetch API to do the request. We just have to pass in the url of the API we want to make a GET request to, and we're going to get back a promise. Once this is resolved we have a response (res). This res isn't yet in the state we want it to be, so we're going to call the .json() method on it. Then finally we have the beautiful object. Yay! ? The API returns the meals array but only with one item in it. So we're going to pass that item (at index 0) into our createMeal function, which we'll define next.*/ const createMeal = (meal) => { const ingredients = []; // Get all ingredients from the object. Up to 20 for (let i = 1; i <= 20; i++) { if (meal[`strIngredient${i}`]) { ingredients.push( `${meal[`strIngredient${i}`]} - ${meal[`strMeasure${i}`]}` ); } else { // Stop if there are no more ingredients break; } } const newInnerHTML = ` <div class="row"> <div class="columns five"> <img src="${meal.strMealThumb}" alt="Meal Image"> <h2>${meal.strMeal}</h2> ${ meal.strCategory ? `<p><strong>Category:</strong> ${meal.strCategory}<p/>` : "" } ${meal.strArea ? `<p><strong>Area:</strong> ${meal.strArea}</p>` : ""} ${ meal.strTags ? `<p><strong>Tags:</strong> ${meal.strTags .split(",") .join(", ")}</p>` : "" } <h4>Ingredients:</h4> <ul> ${ingredients.map((ingredient) => `<li>${ingredient}</li>`).join("")} </ul> </div> <div class="columns seven"> <h3>Instructions</h3> <p>${meal.strInstructions}<p/> </div> </div> ${ meal.strYoutube ? ` <div class="row"> <h3>Video Recipe</h3> <div class="videoWrapper"> <iframe width="420" height="315" src="https://www.youtube.com/embed/${meal.strYoutube.slice(-11)}"> </iframe> </div> </div>` : "" } `; meal_container.innerHTML = newInnerHTML; }; /* Note that some of the properties might not be available. So for that we're using the ternary operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) to check if we have the data to display the corresponding tag. If we don't have it then we're returning an empty string and nothing will be displayed on the page. The category and the area are examples of these type of properties. */
Shell
UTF-8
719
3.484375
3
[ "Apache-2.0" ]
permissive
#!/bin/bash config=/mattermost/config/config.json echo -ne "Configure database connection..." if [ ! -f $config ] then cp /config.template.json $config sed -Ei "s/MYSQL_USER/$MYSQL_USER/" $config sed -Ei "s/MYSQL_PASSWORD/$MYSQL_PASSWORD/" $config sed -Ei "s/MYSQL_DATABASE/$MYSQL_DATABASE/" $config sed -Ei "s/MYSQL_HOST/$MYSQL_HOST/" $config echo OK else echo SKIP fi echo "show Config File" cat /mattermost/config/config.json #echo "Wait until database is ready..." #until nc -z db $DB_PORT_5432_TCP_PORT #do # sleep 1 #done # Wait to avoid "panic: Failed to open sql connection pq: the database system is starting up" sleep 1 echo "Starting platform" cd /mattermost/bin ./platform
Shell
UTF-8
1,203
3.828125
4
[]
no_license
#!/bin/bash #check for sudo if [[ $EUID -ne 0 ]]; then echo "This script must be run as root" exit 1 fi if [ $# -eq 0 ] then echo "You should specify java file as argument" exit 1 elif [ $# -gt 1 ] then echo "Specify only the java installation tar file" exit 1 else echo "Installation starts now" fi if [ ${1: -3} != ".gz" ] then echo "Yous should give a tar file" exit 1 fi jvm_path='/usr/lib/jvm/' java_file=$1 mkdir -p $jvm_path #get the folder which will be extracted file_n=$(tar tf $1 | awk -F/ '{if (NF=1) print }' | awk 'NR==1; END{}') tar xvf $java_file -C $jvm_path #echo "aa" #echo "${file_n}" sudo update-alternatives --install "/usr/bin/java" "java" "${jvm_path}${file_n}/bin/java" 1 sudo update-alternatives --install "/usr/bin/javac" "javac" "${jvm_path}${file_n}/bin/javac" 1 sudo update-alternatives --install "/usr/bin/javaws" "javaws" "${jvm_path}${file_n}/bin/javaws" 1 sudo chmod a+x /usr/bin/java sudo chmod a+x /usr/bin/javac sudo chmod a+x /usr/bin/javaws sudo chown -R root:root ${jvm_path}${file_n} sudo update-alternatives --config java sudo update-alternatives --config javac sudo update-alternatives --config javaws #mkdir -p /usr/lib/jvm
C
UTF-8
1,356
3.15625
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #define NO_PACKETS 10 int rand1(int a){ int rn = (random() % 10) % a; return rn = 0 ? 1 : rn; } int main(){ int packets[NO_PACKETS],i,clk,bsize,oprate,rem=0,op,prize,ptime; for(i=0;i<NO_PACKETS;i++){ packets[i] = rand1(6) * 10; printf("%d\n",packets[i]); } printf("\nEnter the output rate"); scanf("%d",&oprate); printf("\nEnter the bucket size:"); scanf("%d",&bsize); for(i=0;i<NO_PACKETS;i++){ if((packets[i] + rem) > bsize){ if(packets[i] > bsize) printf("\n\nIncoming packet size (%d, bytes) is greater than bucket capacity (%d,bytes) PACKET REJECTED",packets[i],bsize); else printf("\n\nBucket capacity exceeded"); } else{ rem += packets[i]; printf("\n\nIncoming packet size %d",packets[i]); printf("\nBytes remaining to transmit : %d",rem); ptime = 10; printf("\nTime left for transmission : %d ",ptime); for(clk = 10;clk <= ptime ; clk += 10){ sleep(1); if(rem){ if(rem < oprate){ op = rem; rem = 0; } else{ op = oprate; rem = rem - oprate; } printf("\nPacket of size %d transmitted",op); printf("\n...Bytes remaining to transmit : %d",rem); } else{ printf("\nTime left for transmission : %d",ptime-clk); printf("\nNo packets to transmit"); } } } } }
TypeScript
UTF-8
6,372
2.859375
3
[ "MIT" ]
permissive
import { IconCollection } from "../IconCollection"; import { Icon, IconAttributes } from "../Icon"; const iconTest = (name: string): IconAttributes => ({ name, texture: `assets/${name}` }); describe("IconCollection", () => { describe("constructor", () => { const iconCollection = new IconCollection([ new Icon(iconTest("A")), new Icon(iconTest("B")), new Icon(iconTest("C")) ]); test("success", () => { expect(iconCollection.extract("A")).toBeDefined(); expect(iconCollection.extract("B")).toBeDefined(); expect(iconCollection.extract("C")).toBeDefined(); }); test("instance.toXml()", () => { expect(iconCollection.toXml()).toMatchInlineSnapshot(` "<icons> <icon name=\\"A\\" texture=\\"assets/A\\"/> <icon name=\\"B\\" texture=\\"assets/B\\"/> <icon name=\\"C\\" texture=\\"assets/C\\"/> </icons>" `); }); test("instance.toJson()", () => { expect(iconCollection.toJson()).toMatchInlineSnapshot( `"{\\"icon\\":[{\\"Attributes\\":{\\"name\\":\\"A\\",\\"texture\\":\\"assets/A\\"}},{\\"Attributes\\":{\\"name\\":\\"B\\",\\"texture\\":\\"assets/B\\"}},{\\"Attributes\\":{\\"name\\":\\"C\\",\\"texture\\":\\"assets/C\\"}}]}"` ); }); }); describe("instance.add()", () => { test("instance.toXml()", () => { const iconCollection = new IconCollection(); iconCollection.add(new Icon(iconTest("A"))); iconCollection.add(new Icon(iconTest("B"))); expect(iconCollection.toXml()).toMatchInlineSnapshot(` "<icons> <icon name=\\"A\\" texture=\\"assets/A\\"/> <icon name=\\"B\\" texture=\\"assets/B\\"/> </icons>" `); }); test("instance.toJson()", () => { const iconCollection = new IconCollection(); iconCollection.add(new Icon(iconTest("A"))); iconCollection.add(new Icon(iconTest("B"))); expect(iconCollection.toJson()).toMatchInlineSnapshot( `"{\\"icon\\":[{\\"Attributes\\":{\\"name\\":\\"A\\",\\"texture\\":\\"assets/A\\"}},{\\"Attributes\\":{\\"name\\":\\"B\\",\\"texture\\":\\"assets/B\\"}}]}"` ); }); }); describe("instance.remove()", () => { test("instance.toXml()", () => { const iconCollection = new IconCollection(); iconCollection.add(new Icon(iconTest("A"))); iconCollection.add(new Icon(iconTest("B"))); iconCollection.remove("A"); expect(iconCollection.toXml()).toMatchInlineSnapshot(` "<icons> <icon name=\\"B\\" texture=\\"assets/B\\"/> </icons>" `); }); test("instance.toJson()", () => { const iconCollection = new IconCollection(); iconCollection.add(new Icon(iconTest("A"))); iconCollection.add(new Icon(iconTest("B"))); iconCollection.remove("A"); expect(iconCollection.toJson()).toMatchInlineSnapshot( `"{\\"icon\\":[{\\"Attributes\\":{\\"name\\":\\"B\\",\\"texture\\":\\"assets/B\\"}}]}"` ); }); }); describe("instance.replace()", () => { test("instance.toXml()", () => { const iconCollection = new IconCollection(); iconCollection.add(new Icon(iconTest("A"))); const replacement = new Icon(iconTest("A")); replacement.texture = "REPLACED!"; iconCollection.replace(replacement); expect(iconCollection.toXml()).toMatchInlineSnapshot(` "<icons> <icon name=\\"A\\" texture=\\"REPLACED!\\"/> </icons>" `); }); test("instance.toJson()", () => { const iconCollection = new IconCollection(); iconCollection.add(new Icon(iconTest("A"))); const replacement = new Icon(iconTest("A")); replacement.texture = "REPLACED!"; iconCollection.replace(replacement); expect(iconCollection.toJson()).toMatchInlineSnapshot( `"{\\"icon\\":[{\\"Attributes\\":{\\"name\\":\\"A\\",\\"texture\\":\\"REPLACED!\\"}}]}"` ); }); }); describe("instance.import()", () => { const testXml = () => { return ` <icons> <icon name="missile_dumbfire_mk1" texture="assets/fx/gui/textures/PlayerHud/hud_ms_dumbfire_mk1.tga" height="32" width="64"></icon> <icon name="missile_dumbfire_mk2" texture="assets/fx/gui/textures/PlayerHud/hud_ms_dumbfire_mk2.tga" height="32" width="64"></icon> <icon name="missile_dumbfire_mk3" texture="assets/fx/gui/textures/PlayerHud/hud_ms_dumbfire_mk3.tga" height="32" width="64"></icon> <icon name="missile_guided_mk1" texture="assets/fx/gui/textures/PlayerHud/hud_ms_guided_mk1.tga" height="32" width="64"></icon> <icon name="missile_guided_mk2" texture="assets/fx/gui/textures/PlayerHud/hud_ms_guided_mk2.tga" height="32" width="64"></icon> <icon name="missile_guided_mk3" texture="assets/fx/gui/textures/PlayerHud/hud_ms_guided_mk3.tga" height="32" width="64"></icon> <icon name="missile_torpedo_mk1" texture="assets/fx/gui/textures/PlayerHud/hud_ms_torpedo_mk1.tga" height="32" width="64"></icon> <icon name="missile_torpedo_mk2" texture="assets/fx/gui/textures/PlayerHud/hud_ms_torpedo_mk2.tga" height="32" width="64"></icon> <icon name="missile_torpedo_mk3" texture="assets/fx/gui/textures/PlayerHud/hud_ms_torpedo_mk3.tga" height="32" width="64"></icon> <icon name="weapon_beam_mk1" texture="assets/fx/gui/textures/PlayerHud/hud_wp_beam_mk1.tga" height="32" width="64"></icon> <icon name="weapon_beam_mk2" texture="assets/fx/gui/textures/PlayerHud/hud_wp_beam_mk2.tga" height="32" width="64"></icon> <icon name="weapon_beam_mk3" texture="assets/fx/gui/textures/PlayerHud/hud_wp_beam_mk3.tga" height="32" width="64"></icon> </icons> `; }; test("toXML()", async () => { const testCollection = new IconCollection(); await testCollection.import(testXml()); expect(testCollection.toXml()).toMatchSnapshot(); }); test("with add", async () => { const testCollection = new IconCollection(); await testCollection.import(testXml()); testCollection.add(new Icon(iconTest("A"))); expect(testCollection.toXml()).toMatchSnapshot(); }); test("with remove", async () => { const testCollection = new IconCollection(); await testCollection.import(testXml()); testCollection.remove("weapon_beam_mk1"); testCollection.remove("weapon_beam_mk2"); testCollection.remove("weapon_beam_mk3"); expect(testCollection.toXml()).toMatchSnapshot(); }); }); });
Java
UTF-8
890
2.296875
2
[]
no_license
package com.mobilevanity.backend; import com.mobilevanity.backend.common.Result; import com.mobilevanity.backend.common.Utility; import com.mobilevanity.backend.data.Brand; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by Administrator on 2016-08-10. */ public class BrandListServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<Brand> brands = DataManager.getInstance().listBrand(); if (brands != null) { Utility.responseSuccessMessage(resp, brands); return; } Utility.responseErrorMessage(resp, Result.ERROR_UNKNOWN); } }
PHP
UTF-8
23,338
3.015625
3
[]
no_license
<?php namespace sergeynezbritskiy\ZendPdfTable\Table; use sergeynezbritskiy\ZendPdfTable\AbstractElement; use sergeynezbritskiy\ZendPdfTable\Table; use Zend_Exception; use Zend_Pdf_Image; use Zend_Pdf_Page; use Zend_Pdf_Style; /** * Class Cell * * @package sergeynezbritskiy\ZendPdfTable\Table */ class Cell extends AbstractElement { protected $width; private $_height; private $_recommendedWidth; private $_recommendedHeight; private $_text; private $_vAlign; private $_textLineSpacing = 0; private $_image; /** * Set Text Line Height * * @param int $value */ public function setTextLineSpacing($value) { $this->_textLineSpacing = $value; } /** * Checks if Cell contains a Image Element * * @return bool */ public function hasImage() { if ($this->_image) { return true; } else { return false; } } /** * Checks if Cell contains a Text Element * * @return bool */ public function hasText() { if ($this->_text) { return true; } else { return false; } } /** * @return int */ public function getRecommendedWidth() { return $this->_recommendedWidth; } /** * @return int */ public function getRecommendedHeight() { return $this->_recommendedHeight; } /** * Set Vertical Alignment * * @param int $align */ public function setVAlignment($align) { $this->_vAlign = $align; } /** * @return int */ public function getVAlignment() { return $this->_vAlign; } /** * Remove Cell Border * * @param int $position */ public function removeBorder($position) { unset($this->borderStyles[$position]); } /** * Set Cell Width * * @param int $value */ public function setWidth($value) { $this->width = $value; } /** * Get Cell Width * * @return int */ public function getWidth() { return $this->width; } /** * Set Cell Height * * @param int $value */ public function setHeight($value) { $this->_height = $value; } /** * Get Cell Height * * @return int */ public function getHeight() { return $this->_height; } /** * Add text to cell * * @param string $text * @param int $textAlign Horizontal Alignment * @param int $vAlign Vertical Alignment */ public function setText($text, $textAlign = null, $vAlign = null) { $this->_text['text'] = $text; if ($textAlign) { $this->setTextAlign($textAlign); } if ($vAlign) $this->_vAlign = $vAlign; } /** * Get Cell Text Element * * @return array(text,width,lines) */ public function getText() { return $this->_text; } /** * Replace Text String in Text-Element * * @param mixed $search * @param mixed $replace * @return int number of replaced strings */ public function replaceText($search, $replace) { $num_replaced = 0; $text = str_replace($search, $replace, $this->_text['text'], $num_replaced); $this->_text['text'] = $text; return $num_replaced; } /** * Add image to cell * * @param string $filename full path * @param int $textAlign Horizontal Alignment * @param int $vAlign Vertical Alignment * @throws \Zend_Exception */ public function setImage($filename, $textAlign = null, $vAlign = null) { $this->_image['filename'] = $filename; $this->setTextAlign($textAlign); $this->_vAlign = $vAlign; } /** * Pre-render cell to get recommended width and height * * @param \Zend_Pdf_Page $page * @param int $posX * @param int $posY * @param bool $inContentArea * @throws \Zend_Exception * @throws \Zend_Pdf_Exception */ public function preRender(\Zend_Pdf_Page $page, $posX, /** @noinspection PhpUnusedParameterInspection */ $posY, $inContentArea = true) { if (!$this->width) { //no width given, get max width of page if ($inContentArea) { $width = $page->getWidth() - $posX - $this->getMargin(Table::LEFT) - $this->getMargin(Table::RIGHT); } else { $width = $page->getWidth() - $posX; } } else { $width = $this->width; } //calc max cell width $maxWidth = $width - ($this->paddings[Table::LEFT] + $this->paddings[Table::RIGHT]) - (+$this->_getBorderLineWidth(Table::LEFT) + $this->_getBorderLineWidth(Table::RIGHT)); if ($this->_text) { //set font $page->setFont($this->fontStyle, $this->fontSize); //get height,width,lines $text_props = $this->getTextProperties($page, $this->_text['text'], $maxWidth); //reset style $page->setStyle($this->getDefaultStyle()); //set width if (!$this->width) { //add padding $this->_recommendedWidth = $text_props['text_width'] + ($this->paddings[Table::LEFT] + $this->paddings[Table::RIGHT]) + $this->_getBorderLineWidth(Table::LEFT) + $this->_getBorderLineWidth(Table::RIGHT); } else { $this->_recommendedWidth = $text_props['max_width']; } if (!$this->_height) { //set height, add padding if ($this->_textLineSpacing) { $height = $this->_textLineSpacing * count($text_props['lines']) + $text_props['height']; } else { $height = $text_props['height']; } $this->_recommendedHeight = $height + ($this->paddings[Table::TOP] + $this->paddings[Table::BOTTOM]); } //store text props; $this->_text['width'] = $text_props['text_width']; $this->_text['max_width'] = $text_props['max_width']; $this->_text['height'] = $text_props['height']; $this->_text['lines'] = $text_props['lines']; } elseif ($this->_image) { $image = Zend_Pdf_Image::imageWithPath($this->_image['filename']); //assuming the image is not a "skyscraper" $width = $image->getPixelWidth(); $height = $image->getPixelHeight(); $widthLimit = $this->getContentWidth() ?: $width; $heightLimit = $this->getContentHeight() ?: $height; //preserving aspect ratio (proportions) $ratio = $width / $height; if ($ratio > 1 && $width > $widthLimit) { $width = $widthLimit; $height = $width / $ratio; } elseif ($ratio < 1 && $height > $heightLimit) { $height = $heightLimit; $width = $height * $ratio; } elseif ($ratio == 1 && $height > $heightLimit) { $height = $heightLimit; $width = $widthLimit; } if (!$this->width) $this->_recommendedWidth = $width + ($this->paddings[Table::LEFT] + $this->paddings[Table::RIGHT]) + $this->_getBorderLineWidth(Table::LEFT) + $this->_getBorderLineWidth(Table::RIGHT); if (!$this->_height) $this->_recommendedHeight = $height + ($this->paddings[Table::TOP] + $this->paddings[Table::BOTTOM]); $this->_image['image'] = $image; $this->_image['width'] = $width; $this->_image['height'] = $height; } else { throw new Zend_Exception("not defined", "preRender()"); } } /** * Get text properties (width, height, [#lines using $max Width]), and warps lines * * @param Zend_Pdf_Page $page * @param string $text * @param int $maxWidth * @return array */ public function getTextProperties($page, $text, $maxWidth = null) { $lines = $this->_textLines($text, $maxWidth); return array( 'text_width' => $lines['text_width'], 'max_width' => $lines['max_width'], 'height' => ($this->getFontHeight($page) * count($lines['lines'])), 'lines' => $lines['lines'] ); } /** * Get Font Height * * @param \Zend_Pdf_Page $page * @return int */ public function getFontHeight($page) { $line_height = $page->getFont()->getLineHeight(); $line_gap = $page->getFont()->getLineGap(); $em = $page->getFont()->getUnitsPerEm(); $size = $page->getFontSize(); return ($line_height - $line_gap) / $em * $size; } /** * Returns the with of the text * * @param string $text * @return int $width */ private function _getTextWidth($text) { $glyphs = array(); $em = $this->fontStyle->getUnitsPerEm(); //get glyph for each character foreach (range(0, strlen($text) - 1) as $i) { $glyphs [] = @ord($text [$i]); } $width = array_sum($this->fontStyle->widthsForGlyphs($glyphs)) / $em * $this->fontSize; return $width; } /** * Wrap text according to max width * * @param string $text * @param int $maxWidth * @return array lines */ private function _wrapText($text, $maxWidth) { $x_inc = 0; $curr_line = ''; $words = explode(' ', trim($text)); $space_width = $this->_getTextWidth(' '); foreach ($words as $word) { //no new line found $width = $this->_getTextWidth($word); if (isset ($maxWidth) && ($x_inc + $width) <= $maxWidth) { //add word to current line $curr_line .= ' ' . $word; $x_inc += $width + $space_width; } else { //store current line if (strlen(trim($curr_line, "\n")) > 0) $lines [] = trim($curr_line); //new line $x_inc = 0; //reset position //add word $curr_line = $word; $x_inc += $width + $space_width; } } $lines = []; //last line if (strlen(trim($curr_line, "\n")) > 0) { $lines [] = trim($curr_line); } return $lines; } /** * @param string $text * @param int $maxWidth (optional, if not set (auto width) the max width is set by reference) * @return array line(text); */ private function _textLines($text, $maxWidth = null) { $trimmed_lines = array(); $lines = explode("\n", $text); $max_line_width = 0; foreach ($lines as $line) { if (strlen($line) <= 0) continue; $line_width = $this->_getTextWidth($line); if ($maxWidth > 0 && $line_width > $maxWidth) { $new_lines = $this->_wrapText($line, $maxWidth); $trimmed_lines += $new_lines; foreach ($new_lines as $nline) { $line_width = $this->_getTextWidth($nline); if ($line_width > $max_line_width) $max_line_width = $line_width; } } else { $trimmed_lines[] = $line; } if ($line_width > $max_line_width) $max_line_width = $line_width; } //set actual width of line if (is_null($maxWidth)) $maxWidth = $max_line_width; $textWidth = $max_line_width; return array('lines' => $trimmed_lines, 'text_width' => $textWidth, 'max_width' => $maxWidth); } /** * Render Cell * * @param \Zend_Pdf_Page $page * @param int $posX * @param int $posY */ public function render(\Zend_Pdf_Page $page, $posX, $posY) { $this->_renderBackground($page, $posX, $posY); $this->_renderText($page, $posX, $posY); $this->_renderImage($page, $posX, $posY); $this->_renderBorder($page, $posX, $posY); } /** * @param \Zend_Pdf_Page $page * @param int $posX * @param int $posY */ private function _renderText(\Zend_Pdf_Page $page, $posX, $posY) { if (!$this->_text) return; $page->setFont($this->fontStyle, $this->fontSize); if ($this->fillColor) $page->setFillColor($this->fillColor); if (count($this->_text['lines']) > 1) { $line_height = $this->getFontHeight($page) + $this->_textLineSpacing; /* //write multi-line text switch ($this->_vAlign){ case sergeynezbritskiy\ZendPdfTable\My_Pdf::BOTTOM: $y_inc=$posY-$this->_textLineSpacing; $rev_lines=array_reverse($this->_text['lines']); foreach ($rev_lines as $line){ $page->drawText($line,$this->_getTextPosX($posX), $this->_getTextPosY($page,$y_inc)); $y_inc-=$line_height; } break; default: $y_inc=$posY-$this->_textLineSpacing; foreach ($this->_text['lines'] as $line){ $page->drawText($line,$this->_getTextPosX($posX), $this->_getTextPosY($page,$y_inc)); $y_inc+=$line_height; } break; } */ //@@TODO VERTICAL POSITIONING OF MULTI-LINED TEXT $y_inc = $posY - $this->_textLineSpacing; //@@TODO HACK $this->_vAlign = Table::TOP; //@@TODO ONLY TOP ALIGNMENT IS VALID AT THIS MOMENT foreach ($this->_text['lines'] as $line) { $this->drawText($page, $line, $this->_getTextPosX($posX), $this->_getTextPosY($page, $y_inc)); $y_inc += $line_height; } } else { //write single line of text $this->drawText($page, $this->_text['text'], $this->_getTextPosX($posX), $this->_getTextPosY($page, $posY)); } //reset style $page->setStyle($this->getDefaultStyle()); } /** * Draw Text * * @param \Zend_Pdf_Page $page * @param string $text * @param int $x1 * @param int $y1 * @param string $charEncoding * @return \Zend_Pdf_Canvas_Interface * @throws \Zend_Pdf_Exception * @internal param bool $inContentArea */ public function drawText(\Zend_Pdf_Page $page, $text, $x1, $y1, $charEncoding = "") { //move origin $y1 = $page->getHeight() - $y1 - $this->getMargin(Table::TOP); $x1 = $x1 + $this->getMargin(Table::LEFT); return $page->drawText($text, $x1, $y1, $charEncoding); } private function _renderImage(\Zend_Pdf_Page $page, $posX, $posY) { if (!$this->_image) return; $this->drawImage($page, $this->_image['image'], $this->_getImagePosX($posX), $this->_getImagePosY($posY), $this->_image['width'], $this->_image['height']); } public function drawImage(\Zend_Pdf_Page $page, \Zend_Pdf_Resource_Image $image, $x1, $y1, $width, $height) { $y1 = $page->getHeight() - $y1 - $height - $this->getMargin(Table::TOP); $x1 = $x1 + $this->getMargin(Table::LEFT); $y2 = $y1 + $height; $x2 = $x1 + $width; $page->drawImage($image, $x1, $y1, $x2, $y2); } private function _renderBorder(\Zend_Pdf_Page $page, $posX, $posY) { if (!$this->borderStyles) return; foreach ($this->borderStyles as $key => $style) { $page->setStyle($style); switch ($key) { case Table::TOP: $this->drawLine($page, $posX, $posY - $this->_getBorderLineWidth(Table::TOP) / 2, $posX + $this->width, $posY - $this->_getBorderLineWidth(Table::TOP) / 2 ); break; case Table::BOTTOM: $this->drawLine($page, $posX, $posY + $this->_height + $this->_getBorderLineWidth(Table::BOTTOM) / 2, $posX + $this->width, $posY + $this->_height + $this->_getBorderLineWidth(Table::BOTTOM) / 2 ); break; case Table::RIGHT: $this->drawLine($page, $posX + $this->width - $this->_getBorderLineWidth(self::RIGHT) / 2, $posY, $posX + $this->width - $this->_getBorderLineWidth(self::RIGHT) / 2, $posY + $this->_height ); break; case Table::LEFT: $this->drawLine($page, $posX + $this->_getBorderLineWidth(self::LEFT) / 2, $posY, $posX + $this->_getBorderLineWidth(self::LEFT) / 2, $posY + $this->_height ); break; } //reset page style $page->setStyle($this->getDefaultStyle()); } } /** * Draw Line * * @param \Zend_Pdf_Page $page * @param int $x1 * @param int $y1 * @param int $x2 * @param int $y2 * @return \Zend_Pdf_Canvas_Interface */ public function drawLine(\Zend_Pdf_Page $page, $x1, $y1, $x2, $y2) { $y1 = $page->getHeight() - $y1 - $this->getMargin(Table::TOP); $y2 = $page->getHeight() - $y2 - $this->getMargin(Table::TOP); $x1 = $x1 + $this->getMargin(Table::LEFT); $x2 = $x2 + $this->getMargin(Table::LEFT); return $page->drawLine($x1, $y1, $x2, $y2); } /** * @param \Zend_Pdf_Page $page * @param int $posX * @param int $posY */ private function _renderBackground(\Zend_Pdf_Page $page, $posX, $posY) { if ($this->getBackgroundColor()) { $page->setFillColor($this->getBackgroundColor()); $this->drawRectangle($page, $posX, $posY, $posX + $this->width, $posY + $this->_height, Zend_Pdf_Page::SHAPE_DRAW_FILL); //reset style $page->setStyle($this->getDefaultStyle()); } } /** * Draw Rectangle * * @param \Zend_Pdf_Page $page * @param int $x1 * @param int $y1 * @param int $x2 * @param int $y2 * @param string $fillType * @return \Zend_Pdf_Canvas_Interface */ public function drawRectangle(\Zend_Pdf_Page $page, $x1, $y1, $x2, $y2, $fillType = null) { //move origin $y1 = $page->getHeight() - $y1 - $this->getMargin(Table::TOP); $y2 = $page->getHeight() - $y2 - $this->getMargin(Table::TOP); $x1 = $x1 + $this->getMargin(Table::LEFT); $x2 = $x2 + $this->getMargin(Table::LEFT); return $page->drawRectangle($x1, $y1, $x2, $y2, $fillType); } /** * Positions text horizontally (x-axis) adding alignment * Default alignment: LEFT * * @param int $posX * @return int */ private function _getTextPosX($posX) { switch ($this->getTextAlign()) { case Table::RIGHT: $x = $posX + $this->getWidth() + $this->getMargin(self::LEFT) - $this->_text['width'] - $this->paddings[Table::RIGHT] - $this->_getBorderLineWidth(Table::RIGHT); break; case Table::CENTER: $x = $posX + $this->getWidth() / 2 - $this->_text['width'] / 2; break; default: //LEFT $x = $posX + $this->paddings[Table::LEFT] + $this->_getBorderLineWidth(Table::LEFT) / 2; break; } return $x; } /** * Positions text vertically (y-axis) adding vertical alignment * Default alignment: TOP * * @param \Zend_Pdf_Page $page * @param int $posY * @return int */ private function _getTextPosY(\Zend_Pdf_Page $page, $posY) { $line_height = $this->getFontHeight($page) + $this->_textLineSpacing; switch ($this->_vAlign) { case Table::BOTTOM: $y = $posY + $this->_height - $this->paddings[Table::BOTTOM]; break; case Table::MIDDLE: $y = $posY + $this->_height / 2 + $line_height / 2; break; default: //TOP $y = $posY + $line_height + $this->paddings[Table::TOP]; break; } return $y; } /** * @param int $posX * @return float */ private function _getImagePosX($posX) { switch ($this->getTextAlign()) { case Table::RIGHT: $x = $posX + $this->width - $this->_image['width'] - $this->paddings[Table::RIGHT]; break; case Table::CENTER: $x = $posX + $this->width / 2 - $this->_image['width'] / 2; break; default: //LEFT $x = $posX + $this->paddings[Table::LEFT]; break; } return $x; } /** * @param int $posY * @return float */ private function _getImagePosY($posY) { switch ($this->_vAlign) { case Table::BOTTOM: $y = $posY + $this->_height - $this->_image['height'] - $this->paddings[Table::BOTTOM]; break; case Table::MIDDLE: $y = $posY + ($this->_height - $this->_image['height']) / 2; break; default: //TOP $y = $posY + $this->paddings[Table::TOP]; break; } return $y; } /** * @param int $position * @return int */ private function _getBorderLineWidth($position) { if (isset($this->borderStyles[$position])) { $style = $this->borderStyles[$position]; $width = $style->getLineWidth(); } else { $width = 0; } return $width; } /** * @return \Zend_Pdf_Style * @throws \Zend_Pdf_Exception */ private function getDefaultStyle() { $style = new Zend_Pdf_Style(); $style->setLineColor(new \Zend_Pdf_Color_Html("#000000")); $style->setFillColor(new \Zend_Pdf_Color_Html("#000000")); $style->setLineWidth(0.5); $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_COURIER); $style->setFont($font, 10); /** @noinspection PhpParamsInspection */ $style->setLineDashingPattern(Zend_Pdf_Page::LINE_DASHING_SOLID); return $style; } /** * @param array $options */ public function setStyles(array $options) { parent::setStyles($options); if (isset($options['width'])) { $this->setWidth($options['width']); } } }
C#
UTF-8
2,544
3.6875
4
[]
no_license
namespace DefiningClasses { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class School { private List<Trainer> trainers; public List<Trainer> Trainers { get { return this.trainers; } } public School() { this.trainers = new List<Trainer>(); } public bool IsTrainerExist(string trainerName) { string name = trainers .Select(n => n.Name) .Where(n => n == trainerName) .FirstOrDefault(); return name != null; } public void AddTrainer(Trainer trainer) { this.trainers.Add(trainer); } public Trainer GetTrainer(string name) { return trainers .FirstOrDefault(n => n.Name == name); } public List<Trainer> GetTrainersIsContentElement(string element) { List<Trainer> contentElement = new List<Trainer>(); foreach (var trainer in trainers) { foreach (var pokemon in trainer.Pokemons) { if (pokemon.Element == element) { contentElement.Add(trainer); break; } } } return contentElement; } public List<Trainer> GetTrainersIsNotContentElement(string element) { List<Trainer> notContentElement = new List<Trainer>(); foreach (var trainer in trainers) { bool isNotContent = true; foreach (var pokemon in trainer.Pokemons) { if (pokemon.Element == element) { isNotContent = false; break; } } if (isNotContent) { notContentElement.Add(trainer); } } return notContentElement; } public void Print() { trainers = trainers .OrderByDescending(b => b.Badges) .ToList(); foreach (var trainer in trainers) { Console.Write($"{trainer.Name} {trainer.Badges} {trainer.Pokemons.Count}"); Console.WriteLine(); } } } }
Rust
UTF-8
2,587
2.9375
3
[ "MIT" ]
permissive
extern crate indextree; #[cfg(feature = "par_iter")] extern crate rayon; use indextree::Arena; #[cfg(feature = "par_iter")] use rayon::prelude::*; #[test] fn arenatree_success_create() { let mut new_counter = 0; let arena = &mut Arena::new(); macro_rules! new { () => {{ new_counter += 1; arena.new_node(new_counter) }}; }; let a = new!(); // 1 a.append(new!(), arena); // 2 a.append(new!(), arena); // 3 a.prepend(new!(), arena); // 4 let b = new!(); // 5 b.append(a, arena); a.insert_before(new!(), arena); // 6 a.insert_before(new!(), arena); // 7 a.insert_after(new!(), arena); // 8 a.insert_after(new!(), arena); // 9 let c = new!(); // 10 b.append(c, arena); arena[c].previous_sibling().unwrap().detach(arena); assert_eq!( b.descendants(arena).map(|node| arena[node].data).collect::<Vec<_>>(), [5, 6, 7, 1, 4, 2, 3, 9, 10] ); } #[test] #[should_panic] fn arenatree_failure_prepend() { let arena = &mut Arena::new(); let a = arena.new_node(1); let b = arena.new_node(2); a.prepend(b, arena); } #[test] fn arenatree_success_detach() { let arena = &mut Arena::new(); let a = arena.new_node(1); let b = arena.new_node(1); a.append(b, arena); assert_eq!(b.ancestors(arena).into_iter().count(), 2); b.detach(arena); assert_eq!(b.ancestors(arena).into_iter().count(), 1); } #[test] fn arenatree_get() { let arena = &mut Arena::new(); let id = arena.new_node(1); assert_eq!(arena.get(id).unwrap().data, 1); } #[test] fn arenatree_get_mut() { let arena = &mut Arena::new(); let id = arena.new_node(1); assert_eq!(arena.get_mut(id).unwrap().data, 1); } #[test] fn arenatree_iter() { let arena = &mut Arena::new(); let a = arena.new_node(1); let b = arena.new_node(2); let c = arena.new_node(3); let d = arena.new_node(4); a.append(b, arena); b.append(c, arena); a.append(d, arena); let node_refs = arena.iter().collect::<Vec<_>>(); assert_eq!(node_refs, vec![&arena[a], &arena[b], &arena[c], &arena[d]]); } #[cfg(feature = "par_iter")] #[test] fn arenatree_par_iter() { let arena = &mut Arena::new(); let a = arena.new_node(1); let b = arena.new_node(2); let c = arena.new_node(3); let d = arena.new_node(4); a.append(b, arena); b.append(c, arena); a.append(d, arena); let node_refs = arena.par_iter().collect::<Vec<_>>(); assert_eq!(node_refs, vec![&arena[a], &arena[b], &arena[c], &arena[d]]); }
Java
UTF-8
523
3.234375
3
[]
no_license
package task10_3; import java.util.ArrayList; import java.util.Date; public class Statistics { public ParkedCar[] parkedCars; public ParkedCar[] getCars(Date start, Date end) { ArrayList<ParkedCar> list = new ArrayList<ParkedCar>(); for(ParkedCar c : parkedCars) { if(c.in.compareTo(start) >= 0 && c.out.compareTo(end) <= 0) { list.add(c); } } ParkedCar[] res = new ParkedCar[list.size()]; list.toArray(res); return res; } public Statistics(ParkedCar[] cars) { parkedCars = cars; } }
Markdown
UTF-8
1,541
3.4375
3
[]
no_license
## DatePicker Using NgbModule you need to convert initial value ```javascript /** * fixInitialDateValue * @param datePipe datePipe service, must be declare before use * in components module, then initilized in components constructor * @param dateValue * @returns formatted date */ export function fixInitialDateValue(datePipe: DatePipe, dateValue: Date) { let value = {}; try { const birthYear = Number(datePipe.transform(dateValue, 'yyyy')); const birthMonth = Number(datePipe.transform(dateValue, 'MM')); const birthDay = Number(datePipe.transform(dateValue, 'dd')); value = { year: birthYear, month: birthMonth, day: birthDay }; } catch (e) { console.error(e); value = null; } return value; } ``` ## UpperCase Directive ```javascript import { Directive, EventEmitter, HostListener, Output } from '@angular/core'; /** usage: <input type="text" class="form-control" placeholder="ID" formControlName="id" [(ngModel)]="form.value.id" uppercase/> */ @Directive({ selector: '[ngModel][uppercase]' }) export class UppercaseDirective { @Output() ngModelChange: EventEmitter<any> = new EventEmitter(); value: any; @HostListener('input', ['$event']) onInputChange($event) { this.value = $event.target.value.toUpperCase(); this.ngModelChange.emit(this.value); } } ```
Markdown
UTF-8
962
2.8125
3
[]
no_license
# 网络应用开发课程实践项目 ## 想法 + 后端使用MySQL + JDBC + Web框架实用SpringBoot框架 + 前断html + css +thymeleaf + js ## 相关技术 + MySQL + JDBC之前接触过,不介绍了 + SpringBoot是一个纯Java的Web框架 + 前端主要介绍一下thymeleaf,这是一个从html模板生成动态页面的技术,也是SpringBoot官方推荐的动态页面技术,大该就是在html中写一些变量,然后在Web框架中设置这些变量,然后返回这个设置好的页面。可以参见article.html和articles.html中的动态显示文章的部分。 ## 进度 #### 目前实现了: + 数据库的设计 + 基本的文章内容显示 + 发送验证码到邮箱 #### 需要实现: + 登录注册的完善 + 评论区功能(评论,点赞等等) ## 参考 + [thymeleaf教程](https://www.baeldung.com/tag/thymeleaf/) + [SpringBoot官方文档翻译](http://blog.geekidentity.com/spring/spring_boot_translation/)
Markdown
UTF-8
3,634
2.65625
3
[]
no_license
--- categories: !!python/unicode 'WebNotes' channel_desc: 请不要被「小道消息」这个名字误导.在这里,我只想努力为读者呈现一幅中国互联网的清明上河图. channel_ercode: !!python/unicode 'img/WebNotes.ercode.png' channel_id: !!python/unicode 'WebNotes' channel_name: 小道消息 channel_photo: !!python/unicode 'img/WebNotes.photo.png' createtime: 2016-03-31 07:37:45+00:00 description: 信任很重要,一旦打破,重建太难。 keywords: !!python/str '小道消息,WebNotes' language: chinese layout: 1_0_post tags: !!python/unicode 'internet' title: 很尴尬,在反省,要道歉 --- <div class="rich_media_content" id="js_content"> <p> 在 41 天前,我在朋友圈转了一篇文章,加上了一句评论「这次我相信某某」,某某 (L) 是一个招聘服务的名字。 </p> <p> <br/> </p> <p> 当时的情况是这样的,另一家招聘服务(B) 发檄文暗示说 L 把他们黑了,把他们的 App 下架了。朋友圈里看了半天,从直觉和常识分析都认为这事情不可能,即使竞争在激烈,一家公司怎么可能去黑到竞争对手 App Store 管理员账号,然后让 App 自动下架呢? </p> <p> <br/> </p> <p> 然而,今天,事情就真的反转了。L 公司发布声明承认此事确有其事,是自己公司程序员干的。且不说 L 公司道歉信的态度以及具体细节(未必是全部,当然,这事情还可能反转),对我而言,这是个教训。 </p> <p> <br/> </p> <p> 这件事情值得我反省,大多数时候,作为旁观者,不会知道真相到底是怎样的,做出的判断往往会误导别人。我会在朋友圈道歉。 </p> <p> <br/> </p> <p> 我确实会先相信值得信得过的人(或许天真吧),但信得过的人或团队乃至公司,他们也不一定知道事情的真相,也可能被误导,最终导致我传递出去的信息就走偏了,甚至完全错误。这种事情以前就有过,多方信息来源比对之后,把信息发布出去还是错的。 </p> <p> <br/> </p> <p> 顺便说一下,我跟这两家当事公司没有利益往来。过去他们找过我很多次合作,我都拒绝了。我个人不太喜欢这种激烈竞争下的站队合作。你或许过去在我这里看到过一点商业推广内容,但那个内容已经是经过筛选的,多数是小团队,而且,不会损害其他公司或是团队利益。但即使这样,以后还应该更慎重。 </p> <p> <br/> </p> <p> 我无意去指责别人,只是想到哪里写到哪里说明一下而已。 </p> <p> <br/> </p> <p> 信任很重要,一旦打破,重建太难。尽管过去几天有好几次类似的事情,我还会先选择 <strong> 相信 </strong> 别人,但我会去做 <strong> 验证 </strong> 。 </p> <p> <br/> </p> <hr style="font-family: Lato, Helvetica, Arial, freesans, clean, sans-serif; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-top-style: solid; border-top-color: rgb(234, 234, 234); height: 1px; margin-top: 1em; margin-bottom: 1em; color: rgb(51, 51, 51); white-space: normal;"/> <p style="font-family: Lato, Helvetica, Arial, freesans, clean, sans-serif; border: 0px; margin-top: 1em; margin-bottom: 1.5em; outline: 0px; line-height: 1.5em; color: rgb(51, 51, 51); white-space: normal;"> 题图:这句话是里根的名言 </p> <p> <br/> </p> </div>
Java
UTF-8
13,185
1.632813
2
[ "Apache-2.0", "GPL-1.0-or-later" ]
permissive
// This file is part of CPAchecker, // a tool for configurable software verification: // https://cpachecker.sosy-lab.org // // SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.cpachecker.cpa.composite; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.FluentIterable.from; import static org.sosy_lab.common.collect.Collections3.transformedImmutableListCopy; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Collection; import java.util.List; import java.util.function.Supplier; import org.sosy_lab.common.collect.Collections3; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.configuration.Option; import org.sosy_lab.common.configuration.Options; import org.sosy_lab.cpachecker.cfa.CFA; import org.sosy_lab.cpachecker.cfa.blocks.BlockPartitioning; import org.sosy_lab.cpachecker.cfa.model.CFAEdge; import org.sosy_lab.cpachecker.cfa.model.CFANode; import org.sosy_lab.cpachecker.core.defaults.AbstractCPAFactory; import org.sosy_lab.cpachecker.core.defaults.MergeSepOperator; import org.sosy_lab.cpachecker.core.defaults.SimplePrecisionAdjustment; import org.sosy_lab.cpachecker.core.interfaces.AbstractDomain; import org.sosy_lab.cpachecker.core.interfaces.AbstractState; import org.sosy_lab.cpachecker.core.interfaces.CPAFactory; import org.sosy_lab.cpachecker.core.interfaces.ConfigurableProgramAnalysis; import org.sosy_lab.cpachecker.core.interfaces.ConfigurableProgramAnalysisWithBAM; import org.sosy_lab.cpachecker.core.interfaces.MergeOperator; import org.sosy_lab.cpachecker.core.interfaces.Precision; import org.sosy_lab.cpachecker.core.interfaces.PrecisionAdjustment; import org.sosy_lab.cpachecker.core.interfaces.Reducer; import org.sosy_lab.cpachecker.core.interfaces.StateSpacePartition; import org.sosy_lab.cpachecker.core.interfaces.Statistics; import org.sosy_lab.cpachecker.core.interfaces.StatisticsProvider; import org.sosy_lab.cpachecker.core.interfaces.StopOperator; import org.sosy_lab.cpachecker.core.interfaces.WrapperCPA; import org.sosy_lab.cpachecker.core.interfaces.pcc.ProofChecker; import org.sosy_lab.cpachecker.cpa.predicate.PredicateCPA; import org.sosy_lab.cpachecker.exceptions.CPAException; import org.sosy_lab.cpachecker.exceptions.CPATransferException; @Options(prefix = "cpa.composite") public final class CompositeCPA implements StatisticsProvider, WrapperCPA, ConfigurableProgramAnalysisWithBAM, ProofChecker { @Option( secure = true, toUppercase = true, values = {"PLAIN", "AGREE"}, description = "which composite merge operator to use (plain or agree)\n" + "Both delegate to the component cpas, but agree only allows " + "merging if all cpas agree on this. This is probably what you want.") private String merge = "AGREE"; @Option( secure = true, description = "inform Composite CPA if it is run in a CPA enabled analysis because then it must " + "behave differently during merge.") private boolean inCPAEnabledAnalysis = false; @Option( secure = true, description = "By enabling this option the CompositeTransferRelation will compute abstract successors" + " for as many edges as possible in one call. For any chain of edges in the CFA" + " which does not have more than one outgoing or leaving edge the components of the" + " CompositeCPA are called for each of the edges in this chain. Strengthening is" + " still computed after every edge. The main difference is that while this option is" + " enabled not every ARGState may have a single edge connecting to the child/parent" + " ARGState but it may instead be a list.") private boolean aggregateBasicBlocks = false; private static class CompositeCPAFactory extends AbstractCPAFactory { private CFA cfa = null; private ImmutableList<ConfigurableProgramAnalysis> cpas = null; @Override public ConfigurableProgramAnalysis createInstance() throws InvalidConfigurationException { Preconditions.checkState(cpas != null, "CompositeCPA needs wrapped CPAs!"); Preconditions.checkState(cfa != null, "CompositeCPA needs CFA information!"); return new CompositeCPA(getConfiguration(), cfa, cpas); } @Override public CPAFactory setChild(ConfigurableProgramAnalysis pChild) throws UnsupportedOperationException { throw new UnsupportedOperationException("Use CompositeCPA to wrap several CPAs!"); } @CanIgnoreReturnValue @Override public CPAFactory setChildren(List<ConfigurableProgramAnalysis> pChildren) { Preconditions.checkNotNull(pChildren); Preconditions.checkArgument(!pChildren.isEmpty()); Preconditions.checkState(cpas == null); cpas = ImmutableList.copyOf(pChildren); return this; } @Override public <T> CPAFactory set(T pObject, Class<T> pClass) throws UnsupportedOperationException { if (pClass.equals(CFA.class)) { cfa = (CFA) pObject; } return super.set(pObject, pClass); } } public static CPAFactory factory() { return new CompositeCPAFactory(); } private final ImmutableList<ConfigurableProgramAnalysis> cpas; private final CFA cfa; private final Supplier<MergeOperator> mergeSupplier; private CompositeCPA( Configuration config, CFA pCfa, ImmutableList<ConfigurableProgramAnalysis> cpas) throws InvalidConfigurationException { config.inject(this); cfa = pCfa; this.cpas = cpas; mergeSupplier = buildMergeOperatorSupplier(); } @Override public AbstractDomain getAbstractDomain() { return new CompositeDomain( transformedImmutableListCopy(cpas, ConfigurableProgramAnalysis::getAbstractDomain)); } @Override public CompositeTransferRelation getTransferRelation() { return new CompositeTransferRelation( transformedImmutableListCopy(cpas, ConfigurableProgramAnalysis::getTransferRelation), cfa, aggregateBasicBlocks); } @Override public MergeOperator getMergeOperator() { return mergeSupplier.get(); } /** * Build a function that lazily instantiates a merge operator with fresh wrapped merge operators * from the CPAs. */ private Supplier<MergeOperator> buildMergeOperatorSupplier() throws InvalidConfigurationException { if (cpas.stream() .map(ConfigurableProgramAnalysis::getMergeOperator) .allMatch(mergeOp -> mergeOp == MergeSepOperator.getInstance())) { return MergeSepOperator::getInstance; } switch (merge) { case "AGREE": if (inCPAEnabledAnalysis) { PredicateCPA predicateCPA = Collections3.filterByClass(cpas.stream(), PredicateCPA.class) .findFirst() .orElseThrow( () -> new InvalidConfigurationException( "Option 'cpa.composite.inCPAEnabledAnalysis' needs PredicateCPA")); return () -> new CompositeMergeAgreeCPAEnabledAnalysisOperator( getMergeOperators(), getStopOperators(), predicateCPA.getPredicateManager()); } else { return () -> new CompositeMergeAgreeOperator(getMergeOperators(), getStopOperators()); } case "PLAIN": if (inCPAEnabledAnalysis) { throw new InvalidConfigurationException( "Merge PLAIN is currently not supported for CompositeCPA in predicated analysis"); } else { return () -> new CompositeMergePlainOperator(getMergeOperators()); } default: throw new AssertionError(); } } private ImmutableList<MergeOperator> getMergeOperators() { return transformedImmutableListCopy(cpas, ConfigurableProgramAnalysis::getMergeOperator); } private ImmutableList<StopOperator> getStopOperators() { return transformedImmutableListCopy(cpas, ConfigurableProgramAnalysis::getStopOperator); } @Override public CompositeStopOperator getStopOperator() { return new CompositeStopOperator(getStopOperators()); } @Override public PrecisionAdjustment getPrecisionAdjustment() { ImmutableList<PrecisionAdjustment> precisionAdjustments = transformedImmutableListCopy(cpas, ConfigurableProgramAnalysis::getPrecisionAdjustment); if (precisionAdjustments.stream().allMatch(prec -> prec instanceof SimplePrecisionAdjustment)) { @SuppressWarnings("unchecked") // cast is safe because we just checked this ImmutableList<SimplePrecisionAdjustment> simplePrecisionAdjustments = (ImmutableList<SimplePrecisionAdjustment>) (ImmutableList<? extends PrecisionAdjustment>) precisionAdjustments; return new CompositeSimplePrecisionAdjustment(simplePrecisionAdjustments); } else { return new CompositePrecisionAdjustment(precisionAdjustments); } } @Override public Reducer getReducer() throws InvalidConfigurationException { ImmutableList.Builder<Reducer> wrappedReducers = ImmutableList.builder(); for (ConfigurableProgramAnalysis cpa : cpas) { checkState( cpa instanceof ConfigurableProgramAnalysisWithBAM, "wrapped CPA does not support BAM: %s", cpa.getClass().getCanonicalName()); wrappedReducers.add(((ConfigurableProgramAnalysisWithBAM) cpa).getReducer()); } return new CompositeReducer(wrappedReducers.build()); } @Override public AbstractState getInitialState(CFANode pNode, StateSpacePartition pPartition) throws InterruptedException { Preconditions.checkNotNull(pNode); ImmutableList.Builder<AbstractState> initialStates = ImmutableList.builder(); for (ConfigurableProgramAnalysis sp : cpas) { initialStates.add(sp.getInitialState(pNode, pPartition)); } return new CompositeState(initialStates.build()); } @Override public Precision getInitialPrecision(CFANode pNode, StateSpacePartition partition) throws InterruptedException { Preconditions.checkNotNull(pNode); ImmutableList.Builder<Precision> initialPrecisions = ImmutableList.builder(); for (ConfigurableProgramAnalysis sp : cpas) { initialPrecisions.add(sp.getInitialPrecision(pNode, partition)); } return new CompositePrecision(initialPrecisions.build()); } @Override public void collectStatistics(Collection<Statistics> pStatsCollection) { from(cpas) .filter(StatisticsProvider.class) .forEach(cpa -> cpa.collectStatistics(pStatsCollection)); } @Override public <T extends ConfigurableProgramAnalysis> T retrieveWrappedCpa(Class<T> pType) { if (pType.isAssignableFrom(getClass())) { return pType.cast(this); } for (ConfigurableProgramAnalysis cpa : cpas) { if (pType.isAssignableFrom(cpa.getClass())) { return pType.cast(cpa); } else if (cpa instanceof WrapperCPA) { T result = ((WrapperCPA) cpa).retrieveWrappedCpa(pType); if (result != null) { return result; } } } return null; } @Override public ImmutableList<ConfigurableProgramAnalysis> getWrappedCPAs() { return cpas; } @Override public boolean areAbstractSuccessors( AbstractState pElement, CFAEdge pCfaEdge, Collection<? extends AbstractState> pSuccessors) throws CPATransferException, InterruptedException { return getTransferRelation().areAbstractSuccessors(pElement, pCfaEdge, pSuccessors, cpas); } @Override public boolean isCoveredBy(AbstractState pElement, AbstractState pOtherElement) throws CPAException, InterruptedException { return getStopOperator().isCoveredBy(pElement, pOtherElement, cpas); } @Override public void setPartitioning(BlockPartitioning partitioning) { cpas.forEach( cpa -> { checkState( cpa instanceof ConfigurableProgramAnalysisWithBAM, "wrapped CPA does not support BAM: %s", cpa.getClass().getCanonicalName()); ((ConfigurableProgramAnalysisWithBAM) cpa).setPartitioning(partitioning); }); } @Override public boolean isCoveredByRecursiveState(AbstractState pState1, AbstractState pState2) throws CPAException, InterruptedException { CompositeState state1 = (CompositeState) pState1; CompositeState state2 = (CompositeState) pState2; List<AbstractState> states1 = state1.getWrappedStates(); List<AbstractState> states2 = state2.getWrappedStates(); if (states1.size() != cpas.size()) { return false; } for (int idx = 0; idx < states1.size(); idx++) { if (!((ConfigurableProgramAnalysisWithBAM) cpas.get(idx)) .isCoveredByRecursiveState(states1.get(idx), states2.get(idx))) { return false; } } return true; } }
Python
UTF-8
505
2.8125
3
[]
no_license
class Solution: def minSetSize(self, arr: List[int]) -> int: L = len(arr) / 2 m = {} for a in arr: if a not in m: m[a] = 0 m[a] += 1 n = list(map(lambda i: (-i[1], i[0]), m.items())) heapq.heapify(n) rm = 0 ans = 0 while n and rm < L: count, _ = heapq.heappop(n) rm -= count ans += 1 return ans
PHP
UTF-8
1,025
2.625
3
[]
no_license
<?php class CambioContraMdl { private $bd; function __construct() { require_once( "BaseDeDatos.php" ); $this -> bd = BaseDeDatos::obtenerInstancia(); } function esAlumno( $pass, $nuevo_pass ) { $consulta = "UPDATE alumno SET password = \"$nuevo_pass\" WHERE password = \"$pass\""; $result = $this -> bd -> insertar( $consulta ); if( $result ) if( $this -> bd -> affectedRows() > 0 ) return true; return false; } function esProfesor( $pass, $nuevo_pass ) { $consulta = "UPDATE profesor SET password = \"$nuevo_pass\" WHERE password = \"$pass\""; $result = $this -> bd -> insertar( $consulta ); if( $result ) if( $this -> bd -> affectedRows() ) return true; return false; } function esAdministrador( $pass, $nuevo_pass ) { $consulta = "UPDATE administrador SET password = \"$nuevo_pass\" WHERE password = \"$pass\""; $result = $this -> bd -> insertar( $consulta ); if( $result ) if( $this -> bd -> affectedRows() ) return true; return false; } }
C#
UTF-8
496
2.59375
3
[]
no_license
using System; using BankDemo.ServiceIntefaces; namespace BankDemo.Services { public class ConsoleLogService : ILogService { public void Info(string message) { Console.WriteLine("INFO: {0}", message); } public void Warning(string message) { Console.WriteLine("WARNING: {0}", message); } public void Error(string message) { Console.WriteLine("ERROR: {0}", message); } } }
C++
UTF-8
4,474
2.625
3
[ "BSD-2-Clause" ]
permissive
/* @@@@@@@@ @@ @@@@@@ @@@@@@@@ @@ /@@///// /@@ @@////@@ @@////// /@@ /@@ /@@ @@@@@ @@ // /@@ /@@ /@@@@@@@ /@@ @@///@@/@@ /@@@@@@@@@/@@ /@@//// /@@/@@@@@@@/@@ ////////@@/@@ /@@ /@@/@@//// //@@ @@ /@@/@@ /@@ @@@//@@@@@@ //@@@@@@ @@@@@@@@ /@@ // /// ////// ////// //////// // Copyright (c) 2016, Los Alamos National Security, LLC All rights reserved. */ #pragma once /*! @file */ #include <cassert> #include <climits> #include <cstdint> #include <iostream> #include <flecsi/utils/target.h> namespace flecsi { namespace utils { using local_id_t = std::uint64_t; template<std::size_t PBITS, std::size_t EBITS, std::size_t FBITS, std::size_t GBITS> class id_ { public: static_assert(PBITS + EBITS + FBITS + GBITS + 4 == 128, "invalid id bit configuration"); static_assert(sizeof(std::size_t) * CHAR_BIT >= 64, "need std::size_t >= 64 bit"); // Constructors and make()... id_() = default; id_(id_ &&) = default; id_(const id_ &) = default; explicit id_(const std::size_t local_id) : dimension_(0), domain_(0), partition_(0), entity_(local_id), flags_(0), global_(0) {} template<std::size_t D, std::size_t M> static id_ make(const std::size_t local_id, const std::size_t partition_id = 0, const std::size_t global = 0, const std::size_t flags = 0) { id_ global_id; global_id.dimension_ = D; global_id.domain_ = M; global_id.partition_ = partition_id; global_id.entity_ = local_id; global_id.flags_ = flags; global_id.global_ = global; return global_id; } // Assignment... id_ & operator=(id_ &&) = default; id_ & operator=(const id_ & id) = default; // Setters... void set_partition(const std::size_t partition) { partition_ = partition; } void set_flags(const std::size_t flags) { assert(flags < (1 << FBITS) && "flag bits exceeded"); flags_ = flags; } void set_global(const std::size_t global) { global_ = global; } void set_local(const std::size_t local) { entity_ = local; } // Getters... FLECSI_INLINE_TARGET std::size_t dimension() const { return dimension_; } FLECSI_INLINE_TARGET std::size_t domain() const { return domain_; } FLECSI_INLINE_TARGET std::size_t partition() const { return partition_; } FLECSI_INLINE_TARGET std::size_t entity() const { return entity_; } std::size_t flags() const { return flags_; } std::size_t global() const { return global_; } // index_space_index(): same as entity getter FLECSI_INLINE_TARGET std::size_t index_space_index() const { return entity_; } // Construct "local ID"... // [entity][partition][domain][dimension] // // As id_ is used in FleCSI, local_id() takes this id_, which is: // dd mm pppppppppppppppppppp eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee // ffff gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg // and produces: // eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee pppppppppppppppppppp mm dd // as the return value. In short, it tosses flags and global, and reverses // the order of dimension, domain, partition, and entity. FLECSI_INLINE_TARGET local_id_t local_id() const { local_id_t r = dimension_; r |= local_id_t(domain_) << 2; r |= local_id_t(partition_) << 4; r |= local_id_t(entity_) << (4 + PBITS); return r; } // Comparison (<, ==, !=)... FLECSI_INLINE_TARGET bool operator<(const id_ & id) const { return local_id() < id.local_id(); } FLECSI_INLINE_TARGET bool operator==(const id_ & id) const { return local_id() == id.local_id(); } FLECSI_INLINE_TARGET bool operator!=(const id_ & id) const { return !(*this == id); } private: // As used elsewhere in FleCSI, this class amounts to: // [dimension:2][domain:2][partition:20][entity:40][flags:4][global:60] // Or: // dd mm pppppppppppppppppppp eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee // ffff gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg // where "m" is domain. std::size_t dimension_ : 2; std::size_t domain_ : 2; std::size_t partition_ : PBITS; std::size_t entity_ : EBITS; std::size_t flags_ : FBITS; std::size_t global_ : GBITS; }; // id_ } // namespace utils } // namespace flecsi
Java
UTF-8
1,980
2.921875
3
[ "Apache-2.0" ]
permissive
package com.seven.util; import com.seven.core.GlobalException; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; /** * @author 最爱吃小鱼 */ public class Assert { /** * 判断对象是否为空 * @param bean * @param message */ public static void isNull(String message, Object bean) { if (bean == null) { throw new GlobalException(message); } } /** * 判断参数是否不为空值 * @param message * @param params */ public static void isBlank(String message, Object... params) { if (ArrayUtils.isEmpty(params)) return; for (Object param : params) { if (param == null || StringUtils.isBlank(param.toString())) { throw new GlobalException(message); } } } /** * 判断参数是否在指定的范围内 * @param message * @param value * @param scopeValues */ public static void inScope(String message, int value, int... scopeValues) { if (ArrayUtils.isEmpty(scopeValues)) return; for (int t : scopeValues) { if (t == value) { return; } } throw new GlobalException(message); } /** * 判断参数是否在指定的范围内 * @param message * @param value * @param scopeValues */ public static void inScopeIgnoreCase(String message, String value, String... scopeValues) { if (ArrayUtils.isEmpty(scopeValues) || value == null) return; for (String scopeValue : scopeValues) { if (value.equalsIgnoreCase(scopeValue)) { return; } } throw new GlobalException(message); } /** * 检测参数是否正常传递 * * @param bean */ public static void noParams (Object bean) { isNull("没有传递任何参数", bean); } }
JavaScript
UTF-8
3,182
2.546875
3
[ "MIT" ]
permissive
import { all, compose, contains, equals, filter, find, flatten, keys, not, partial, pick, propEq, reduce, values, zip } from "ramda" import { Chess } from "chess.js" import { sample } from "~/share/util" import { PAWN } from "~/share/chess" import { UNIVERSE, LOGIN, GAME, PLAY, START, REVISION, MOVE, DROP, INVALID, RESIGN } from "~/share/constants/actions" import { MOVE as MOVE_TYPE, DROP as DROP_TYPE, RESIGN as RESIGN_TYPE } from "~/share/constants/revision_types" // TODO: strategize const MOVE_WAIT_BASE = 4000 const MOVE_WAIT_DELTA = 2000 export default class Player { constructor(send) { this.send = send this.chess = null this.color = null this.currentPosition = null } [GAME]() { } [UNIVERSE]() { } [LOGIN](user) { this.user = user this.play() } [PLAY]() { wait(this.send.bind(this, { action: PLAY })) } [START]({ game }) { this.serializedGame = game this.chess = new Chess() this.color = find(propEq("uuid", this.user.uuid), game.players).color if (this.color === this.chess.turn()) { wait(this.sendMove.bind(this)) } } [REVISION]({ uuid, revision }) { if (this.serializedGame.uuid !== uuid) { return } const position = revision.position this.currentPosition = position this.chess.load(position.fen) if (this.color === this.chess.turn()) { wait(this.move.bind(this)) } if (this.chess.game_over()) { wait(this.play.bind(this)) } } [INVALID](data) { this.send({ action: RESIGN }) wait(this.play.bind(this)) } move() { const reserve = this.currentPosition.reserves[this.color] if (all(partial(equals, [0]), values(reserve))) { this.sendMove() return } const type = sample([MOVE, DROP]) if (type === MOVE) { this.sendMove() } else if (type === DROP) { this.sendDrop() } } sendDrop() { const reserve = this.currentPosition.reserves[this.color] const reservePieces = filter(compose(not, partial(equals, [0])), keys(reserve)) const piece = sample(reservePieces) let openSquares = reduce((memo, [squareName, squareValue]) => { if (squareValue === null) { memo.push(squareName) } return memo }, [], zip(this.chess.SQUARES, flatten(this.chess.board()))) if (piece === PAWN) { openSquares = filter(square => { return square.match(/[a-h][2-7]/) }, openSquares) } const square = sample(openSquares) this.send({ action: DROP, piece, square }) } sendMove() { const moves = this.chess.moves({ verbose: true }) const move = moves[Math.floor(Math.random() * moves.length)] if (move.piece === this.chess.PAWN && move.to.match(/1|8/)) { move.promotion = [ this.chess.KNIGHT, this.chess.BISHOP, this.chess.ROOK, this.chess.QUEEN ][Math.floor(Math.random() * 4)] } this.send({ action: MOVE, ...pick(["from", "to", "promotion"], move) }) } } function wait(fn) { setTimeout(fn, MOVE_WAIT_BASE + (Math.random() * MOVE_WAIT_DELTA)) }
Java
UTF-8
267
1.648438
2
[]
no_license
package typehier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppCtx4Type { @Bean public ConsolePrinter printer() { return new ConsolePrinter(); } }
Markdown
UTF-8
3,243
3.390625
3
[]
no_license
# AJAX : TP de l'après midi ! Dans cet exercice, nous allons nous connecter à une source de données externe en AJAX afin de récupérer des auteurs et leurs articles ! # Structure HTML : Votre page devra contenir : 1) Un header qui contiendra un h1 avec le titre "_Bienvenue sur le blog WF3 !_" 2) Une balise main qui va contenir deux sous-éléments 1) Un ul dont l'identifiant sera __users__ 2) Une div dont l'identifiant sera __articles__ et qui contiendra dès le début un __h2__ qui dira "_Cliquez sur un auteur pour voir ses articles_" # Design de la page : Rien de bien particulier en termes de couleurs, juste de la disposition : 1) Le ul dont l'identifiant est __users__ devra être en inline-block et en vertical-align: top et devra avoir une largeur de 30% 2) La div dont l'identifiant est __articles__ devra être en inline-block et devra avoir une largeur de 55% 3) Les li qui sont à l'intérieur du ul qui a l'identifiant __users__ doivent avoir la propriété ```cursor: pointer``` # Typographies Google Fonts: 1) Les titres doivent être en typographie "Montserrat" 2) Le reste des éléments doivent avoir la typographie "Lato" # Fonctionnalités Javascript 1) Une fois que la page est chargée (```$(document).ready(function(){...})```) il vous faut appeler l'adresse ```https://jsonplaceholder.typicode.com/users``` qui va vous renvoyer du JSON (donc utilisez ```$.getJSON```) 2) Lorsque l'appel à l'URL est terminé, vous recevez un tableau d'utilisateurs. Vous devez donc 1) boucler sur chaque utilisateur du tableau 2) pour chaque utilisateur, créez un ```<li>``` qui contiendra la propriété ```name``` de l'user __ATTENTION :__ Il est important que le ```<li>``` que vous créez pour chaque user possède un attribut ```data-id=""``` dont la valeur devra être la propriété ```id``` de l'user ! 3) Vous devez créer un gestionnaire d'événement un peu particulier. Il exprime le fait que lorsque l'on cliquera sur un li à l'intérieur du ul#auteurs, il va se passer quelque chose : 1) Vous devez récupérer l'identifiant de l'auteur dans l'attribut ```data-id=""``` qui est dans le li sur lequel on vient de cliquer (pour faire cela vous devez utiliser ```$(this).data('id')```) ;-) 2) Vous devez faire le ménage dans la div qui a l'identifiant __articles__ 3) Une fois que vous connaissez l'identifiant vous pouvez appeler une autre URL en AJAX : ```https://jsonplaceholder.typicode.com/users/ID-DE-L-AUTEUR/posts``` en remplaçant bien ID-DE-L-AUTEUR par l'identifiant récupéré dans le li ! 4) Vous récupérez du JSON, donc utilisez $.getJSON. Une fois que le serveur vous répond, vous récupérez en fait un tableau d'articles. 1) pour chaque article récupéré, créez une balise __article__ 2) à l'intérieur de la balise article, placez un __h3__ qui contiendra la propriété __.title__ de l'objet 3) à l'intérieur de la balise article, placez aussi un __p__ qui contiendra la propriété __.body__ de l'objet 4) à l'intérieur de la balise article, placez enfin un __hr__ 4) ajoutez l'article à votre div qui a l'identifiant __articles__ # Et voilà, vous avez un blog en AJAX !
C++
UTF-8
2,123
3.671875
4
[]
no_license
#include <iostream.h> class Element { public: int key; int other; int link; Element(){other = 0; link = 0;}; }; int ListMerge(Element *list, const int start1, const int start2) // The sorted linked lists whose first elements are indexed by @start@1 and @start@2, // respectively, are merged to obtain the sorted linked list. The index of the first element of the // sorted list is returned. Integer links are used. { int iResult = 0; for (int i1 = start1, i2 = start2; i1 && i2; ) if (list[i1].key <= list[i2].key) { list[iResult].link = i1; iResult = i1; i1 = list[i1].link; } else { list[iResult].link = i2; iResult = i2; i2 = list[i2].link; } // move remainder if (i1 == 0) list[iResult].link = i2; else list[iResult].link = i1; return list[0].link; } int rMergeSort(Element *list, const int left, const int right) // List @list~=~(list[left],~... ,~list[right])@ is to be sorted on the field @key@. // @link@ is a link field in each record that is initially 0. // @rMergeSort@ returns the index of the first element in the sorted chain. // @list[0]@ is a record for intermediate results used only in @ListMerge@. { if (left >= right) return left; int mid = (left + right)/2; return ListMerge( list, rMergeSort(list, left, mid), rMergeSort(list, mid+1, right)); } void main() { /* Element *b = new Element[11]; Element e; e.key = 2;b[1] = e; e.key = 4;b[5] = e; e.key = 5;b[7] = e; e.key = 7;b[8] = e; e.key = 10;b[2] = e; e.key = 12;b[6] = e; e.key = 14;b[3] = e; e.key = 15;b[4] = e; e.key = 17;b[9] = e; e.key = 25;b[10] = e; e.key = 1000; b[11] = e; QuickSort(b, 1, 10); for (int i = 0; i <= 10; i++) cout << b[i].key << " , "; */ Element *b = new Element[11]; Element e; e.key = 26;b[1] = e; e.key = 5;b[2] = e; e.key = 77;b[3] = e; e.key = 1;b[4] = e; e.key = 61;b[5] = e; e.key = 11;b[6] = e; e.key = 59;b[7] = e; e.key = 15;b[8] = e; e.key = 48;b[9] = e; e.key = 19;b[10] = e; e.key = 1000; b[11] = e; int start = rMergeSort(b, 1, 10); for (; start; start = b[start].link) cout << b[start].key << " , "; cout << endl; }
Java
UTF-8
795
2.796875
3
[]
no_license
package ru.lember.leetcode.string; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class BasicCalculatorTest { @Test void calculateTest() { BasicCalculator service = new BasicCalculator(); //Assertions.assertEquals(82, service.calculate("82")); Assertions.assertEquals(82, service.calculateEasy("82")); //Assertions.assertEquals(7, service.calculate("3 + 2 * 2")); Assertions.assertEquals(7, service.calculateEasy("3 + 2 * 2")); //Assertions.assertEquals(1, service.calculate("3/2")); Assertions.assertEquals(1, service.calculateEasy("3/2")); //Assertions.assertEquals(5, service.calculate("3 + 5 /2")); Assertions.assertEquals(5, service.calculateEasy("3 + 5 /2")); } }
Ruby
UTF-8
5,188
2.515625
3
[]
no_license
require 'gtk3' Dir[File.dirname(__FILE__) + '/*.rb'].each {|file| require file } Dir[File.dirname(__FILE__) + '/../api/*.rb'].each {|file| require file } class SousGrille < Gtk::Table # contenant elle même une grille attr_reader :colorCandidat def new(grille) initialize(grille) end def initialize (grille) super(1,1,true) @grille = grille @grilleCandidat = Gtk::Table.new(26, 26, true) @candidat = true; @colorCandidat = "#900090" begin background = Gtk::EventBox.new().add(Gtk::Image.new( :pixbuf => GdkPixbuf::Pixbuf.new(:file => "../../vues/grille.png", :width => 432, :heigth => 432))) rescue background = Gtk::EventBox.new().add(Gtk::Image.new( :pixbuf => GdkPixbuf::Pixbuf.new(:file => "./vues/grille.png", :width => 432, :heigth => 432))) end attach(@grilleCandidat, 0, 1, 0, 1) attach(@grille , 0, 1, 0, 1) attach(background, 0, 1, 0, 1) for i in 0..26 for y in 0..26 @grilleCandidat.attach(Gtk::Label.new(), y, y+1, i, i+1) end end #loadAllCandidats() end def setTest(bool) @candidat = bool end def refreshAllCandidats() # if(!@candidat) # return # end for x in 0..8 for y in 0..8 refreshCandidatsCase(x,y) end end end def refreshCandidatsCase(x, y) # if (!@candidat) # return # end position = Position.new(x,y) if (@grille.getPartie().getPlateau().getCaseJoueur(position) != nil) pos = (x*81 + y*3) + 1 for i in 0..2 for u in 0..2 @grilleCandidat.children()[729-(pos+u+i*27)].set_text("") end end return end candidat = @grille.getPartie().getPlateau().getCase(position).getCandidat().getListeCandidat() #print "\n\tCandidat : ", x, "-", y, candidat pos = (x*81 + y*3) + 1 for i in 0..2 for u in 0..2 @grilleCandidat.children()[729-(pos+u+i*27)].set_markup("<span size=\"small\" foreground=\"#{@colorCandidat}\">#{candidat[(u+i*3)+1]}</span>") end end end def loadAllCandidats() # print "OKAllCandidat" # if(!@candidat) return end # print "Version Joueur : \n", @grille.getPartie().getPlateau() # print "Version Originale : \n", @grille.getPartie().getPlateau().printOri for x in 0..8 for y in 0..8 loadCandidatsCase(x,y) end end end def loadCandidatsCase(x, y) # print "OKloadCandidatCase" if (!@candidat) return end position = Position.new(x,y) if (@grille.getPartie().getPlateau().getCaseJoueur(position) != nil) pos = (x*81 + y*3) + 1 for i in 0..2 for u in 0..2 @grilleCandidat.children()[729-(pos+u+i*27)].set_text("") end end return end # puts(@grille.getPartie().getPlateau().getCase(position).getCandidat().getListeCandidat()) @grille.getPartie().getPlateau().getCase(position).setCandidat(@grille.getPartie().getPlateau().candidatPossible(position)) candidat = @grille.getPartie().getPlateau().getCase(position).getCandidat().getListeCandidat() #print("\n Candidat en #{x+1},#{y+1}: ", candidat) pos = (x*81 + y*3) + 1 for i in 0..2 for u in 0..2 @grilleCandidat.children()[729-(pos+u+i*27)].set_markup("<span size=\"small\" foreground=\"#{@colorCandidat}\">#{candidat[(u+i*3)+1]}</span>") end end end def resetAllCandidats() for x in 0..8 for y in 0..8 resetCandidatCase(x,y) end end end def resetCandidatCase(x,y) pos = (x*81 + y*3) + 1 for i in 0..2 for u in 0..2 @grilleCandidat.children()[729-(pos+u+i*27)].set_text("") end end end def setCandidatSurFocus(candidat) if (!candidat) return end posFocus = @grille.getCoordFocus() if (posFocus == nil || @grille.getPartie().getPlateau().getCaseJoueur(posFocus) != nil) return end #print "Undo ajouté lors du setCandidat" @grille.getPartie.getUndoRedo.addMemento pos = (posFocus.getX()*81 + posFocus.getY()*3) + 1 for i in 0..2 for u in 0..2 if (candidat.to_i == u+i*3+1) if (@grilleCandidat.children()[729-(pos+u+i*27)].text.to_i == candidat) @grilleCandidat.children()[729-(pos+u+i*27)].set_text("") @grille.getPartie().getPlateau().getCase(posFocus).getCandidat.remove(candidat) #print(@grille.getPartie().getPlateau().getCase(posFocus).getCandidat.getListeCandidat()) # @grille.getPartie.getUndoRedo.addMemento rafraichirGrille return else @grilleCandidat.children()[729-(pos+u+i*27)].set_markup("<span size=\"small\" foreground=\"#{@colorCandidat}\">#{candidat}</span>") @grille.getPartie().getPlateau().getCase(posFocus).getCandidat.add(candidat) #print(@grille.getPartie().getPlateau().getCase(posFocus).getCandidat.getListeCandidat()) # @grille.getPartie.getUndoRedo.addMemento rafraichirGrille return end end end end end def setCandidatState(bool) @candidat = bool if (@candidat) loadAllCandidats() else resetAllCandidats() end end def setColorCandidat(colorCandidat) @colorCandidat = colorCandidat refreshAllCandidats end def rafraichirGrille @grille.rafraichirGrille refreshAllCandidats end def remplirGrille @grille.remplirGrille refreshAllCandidats end end
JavaScript
UTF-8
7,298
3.5
4
[]
no_license
(function(){ //generate random number from m to n not include n function generateRandomNumber(m, n){ return Math.floor(Math.random() * (n - m)) + m } //generate random boolean function generateRandomBoolean(){ return Math.random() < 0.5 } //1. 生成20道10以内的加减法 //2. 倒计时5分钟 function generateArithmeticQuestion(upper){ let question = {} //产生两个随机数 let number1 = generateRandomNumber(0, upper) let number2 = generateRandomNumber(0, upper) //答案 //true 代表 + false 代表 - if(generateRandomBoolean()){ question = { number1: number1, number2: number2, sign: '+', answer: number1 + number2 } }else{ if(number1 >= number2){ question = { number1: number1, number2: number2, sign: '-', answer: number1 - number2 } }else{ question = { number1: number2, number2: number1, sign: '-', answer: number2 - number1 } } } return question } // for(let i = 0; i < TOTAL_COUNT_QUESTIONS; i++){ // question = generateArithmeticQuestion() // questions.push(question) // } function generateQuestions(questionsNum, upper) { const questions = [] for(let i = 0; i < questionsNum; i++){ question = generateArithmeticQuestion(upper) questions.push(question) } return questions } function checkQuestions(questions, answers){ questions = questions.map((question, index) => ({...question, userAnswer: parseInt(answers[index])})) return questions // let rightCount = 0 // questions.forEach((question,index) => { // if(question.answer === parseInt(answers[index])){ // rightCount ++ // } // }) // return rightCount } function getRightCount(questions){ return questions.reduce((prev, curr) => prev + (curr.answer === curr.userAnswer ? 1 : 0), 0) } // 产生单行的数学题 { // q1:{ // index:1, // number1: 10, // number2: 4, // sign: '-', // answer: 6}} function generateRowDOM(questionsPair){ const {q1, q2} = questionsPair const domString = `<div class="row no-gutters"> <div class="offset-2 col-4"> <div class="question"> <label class="label" for="question${q1.index}">${q1.index}. </label> <div class="expression"> <span class="num1">${q1.number1}</span> <span class="sign">${q1.sign}</span> <span class="num2">${q1.number2}</span> <span class="equal">=</span> </div> <input class="form-control answer" id="question${q1.index}"> <span class="check d-none"><img src="./assets/img/check.svg" alt="" width="32" height="32" title="Bootstrap"></span> <span class="check d-none"><img src="./assets/img/x.svg" alt="" width="32" height="32" title="Bootstrap"></span> </div> </div> <div class="offset-1 col-5"> <div class="question"> <label class="label" for="question${q2.index}">${q2.index}. </label> <div class="expression"> <span class="num1">${q2.number1}</span> <span class="sign">${q2.sign}</span> <span class="num2">${q2.number2}</span> <span class="equal">=</span> </div> <input class="form-control answer" id="${q2.index}"> <span class="check d-none"><img src="./assets/img/check.svg" alt="" width="32" height="32" title="Bootstrap"></span> <span class="check d-none"><img src="./assets/img/x.svg" alt="" width="32" height="32" title="Bootstrap"></span> </div> </div> </div>` return domString } function arrayToPair(questions){ return questions.reduce( (prev,curr,index) => { if(index % 2 == 1){ let last = prev.pop() return prev.concat({...last, q2: {...curr,index: index + 1}}) }else{ return prev.concat({q1: {...curr,index: index + 1}}) } },[]) } function generateQuestionsDOM(questions){ const pairQuestions = arrayToPair(questions) return pairQuestions.map(pairQuestion => generateRowDOM(pairQuestion) ).join('') } let AMOUNT_SETTING = 20 let TIME_SETTING = 0 let RANGE_SETTING = 10 //读取设置的初始化的值 function init(){ TIME_SETTING = +localStorage.getItem('timeSet') AMOUNT_SETTING = +localStorage.getItem('amountSet') RANGE_SETTING = +localStorage.getItem('rangeSet') } init() // const TOTAL_COUNT_QUESTIONS = 20 // const TIME_SETTING = 0 // const AMOUNT_SETTING = 10 let questions = generateQuestions(AMOUNT_SETTING,RANGE_SETTING) // console.log(questions) // console.log(arrayToPair(questions)) // console.log(generateQuestionsDOM(questions)) document.querySelector('.questions').innerHTML = generateQuestionsDOM(questions) //检查题目是否正确 let submitEl = document.getElementById('submit') submitEl.onclick = function () { let answers = [] const inputEl = document.querySelectorAll('.questions input') inputEl.forEach(input => answers.push(input.value)) questions = checkQuestions(questions, answers) const rightAnswers = getRightCount(questions) document.querySelector('.score').innerText = rightAnswers * 5 answers = questions.map(question => question.answer === question.userAnswer).reduce((prev, curr) => prev.concat(curr, !curr),[]) const checkers = document.querySelectorAll('.check') checkers.forEach((checker,index) => { if(answers[index]){ checker.classList.replace('d-none','d-block') }else{ checker.classList.replace('d-block','d-none') } }) } //刷新页面 let resetEl = document.getElementById('reset') resetEl.onclick = function() { window.location.reload(); } //刷新时间 setInterval(() => { document.querySelector('.time').innerText = +document.querySelector('.time').innerText + 1 }, 1000) })()
Java
UTF-8
11,488
2.109375
2
[ "CC-PDDC", "BSD-3-Clause", "CC0-1.0", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
/* * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. * * 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 io.helidon.service.configuration.api; import java.util.Collection; // for javadoc only import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; /** * A {@linkplain ServiceLoader service provider} that represents some * kind of <em>system</em> in which the current program is running. * * <p>The meaning of <em>system</em> is deliberately loose. A system * might be a laptop, a platform-as-a-service such as the <a * href="https://cloud.oracle.com/en_US/acc">Oracle Application * Container Cloud Service</a> or <a * href="https://www.heroku.com/">Heroku</a>, a generic Linux-like * ecosystem running as part of a <a * href="https://kubernetes.io/">Kubernetes</a> cluster, and so on.</p> * * <p>{@link System} instances {@linkplain #getenv() provide access to * their environment} as well as to {@link #getProperties() their * properties}.</p> * * <p>In an arbitrary collection of {@link System} instances, zero or * one of them may be {@linkplain #isAuthoritative() marked as being * authoritative}. An {@linkplain #isAuthoritative() authoritative * <code>System</code>} holds sway, and its {@linkplain * #getProperties() properties} and {@linkplain #getenv() environment * values} are to be preferred over all others.</p> * * @author <a href="mailto:laird.nelson@oracle.com">Laird Nelson</a> * * @see #getSystems() * * @see #getenv() * * @see #getProperties() * * @see #isAuthoritative() */ public abstract class System { /* * Instance fields. */ /** * The name of this {@link System}. * * <p>This field will never be {@code null}.</p> * * @see #System(String, boolean) * * @see #getName() */ private final String name; /** * Whether this {@link System} is authoritative. * * <p>A {@link System} that is authoritative is one whose * {@linkplain #getenv() environment} and {@linkplain * #getProperties() properties} are to be preferred over all * others that may be present.</p> * * @see #System(String, boolean) * * @see #isAuthoritative() */ private final boolean authoritative; /* * Constructors. */ /** * Creates a new {@link System}. * * @param name the name of the {@link System}; must not be {@code * null} * * @param authoritative whether the {@link System} will be * {@linkplain #isAuthoritative() authoritative} * * @exception NullPointerException if {@code name} is {@code null} * * @see #getName() * * @see #isAuthoritative() */ protected System(final String name, final boolean authoritative) { super(); this.name = Objects.requireNonNull(name); this.authoritative = authoritative; } /* * Instance methods. */ /** * Returns the name of this {@link System}. * * <p>This method never returns {@code null}.</p> * * <p>Multiple invocations of this method will return identical * {@link String} instances.</p> * * @return the name of this {@link System}; never {@code null} * * @see #System(String, boolean) */ public final String getName() { return this.name; } /** * Returns {@code true} if this {@link System} is <em>enabled</em>. * * <p>If a {@link System} is enabled, then its {@linkplain #getenv() * environment values} and {@linkplain #getProperties() properties} * may be used. If a {@link System} is not enabled, then usage of * its {@linkplain #getenv() environment values} and {@linkplain * #getProperties() properties} may result in undefined * behavior.</p> * * @return {@code true} if this {@link System} is enabled; {@code * false} otherwise * * @see #System(String, boolean) */ public abstract boolean isEnabled(); /** * Returns {@code true} if this {@link System} is * <em>authoritative</em>. * * <p>If a {@link System} is authoritative, then its {@linkplain * #getenv() environment values} and {@linkplain #getProperties() * properties} are to be preferred over any others that might be * present.</p> * * <p>In the presence of an authoritative {@link System}, usage of a * non-authoritative {@link System} may lead to undefined * behavior.</p> * * @return {@code true} if this {@link System} is authoritative; * {@code false} otherwise * * @see #System(String, boolean) */ public boolean isAuthoritative() { return this.authoritative; } /** * Returns the <em>environment</em> of this {@link System} as a * non-{@code null}, unchanging and {@linkplain * Collections#unmodifiableMap(Map) unmodifiable <code>Map</code>}. * * <p>This method never returns {@code null}.</p> * * <p>Overrides of this method must not return {@code null}.</p> * * <p>Overrides of this method must ensure that the {@link Map} * returned may be used without requiring the user to perform * synchronization.</p> * * <p>Multiple invocations of this method or any overridden variants * of it are not guaranteed to return equal or identical {@link Map} * instances.</p> * * <p>The default implementation of this method returns the result * of invoking {@link java.lang.System#getenv()}.</p> * * @return the <em>environment</em> of this {@link System} as a * non-{@code null}, unchanging and {@linkplain * Collections#unmodifiableMap(Map) unmodifiable <code>Map</code>}; * never {@code null} * * @see #getProperties() * * @see java.lang.System#getenv() */ public Map<String, String> getenv() { return java.lang.System.getenv(); } /** * Returns the properties of this {@link System} as a non-{@code * null}, unchanging and unmodifiable {@link Properties} object. * * <p>This method never returns {@code null}.</p> * * <p>Overrides of this method must not return {@code null}.</p> * * <p>Callers must not mutate the {@link Properties} object that is * returned. Attempts to do so may result in an {@link * UnsupportedOperationException}.</p> * * <p>Multiple invocations of this method or any overridden variants * of it are not guaranteed to return equal or identical {@link * Properties} instances.</p> * * <p>The default implementation of this method returns the result * of invoking {@link java.lang.System#getProperties()}.</p> * * @return the properties of this {@link System} as a non-{@code * null}, unchanging and unmodifiable {@link Properties} object; * never {@code null} * * @see #getenv() * * @see java.lang.System#getProperties() */ public Properties getProperties() { return java.lang.System.getProperties(); } /** * Returns a hashcode for this {@link System} that varies with only * its {@linkplain #getName() name}, {@linkplain #isEnabled() * enablement} and {@linkplain #isAuthoritative() authority}. * * @return a hashcode for this {@link System} * * @see #equals(Object) */ @Override public int hashCode() { int hashCode = 17; Object value = this.getName(); int c = value == null ? 0 : value.hashCode(); hashCode = 37 * hashCode + c; c = this.isEnabled() ? 1 : 0; hashCode = 37 * hashCode + c; c = this.isAuthoritative() ? 1 : 0; hashCode = 37 * hashCode + c; return hashCode; } /** * Returns {@code true} if this {@link System} is equal to the * supplied {@link Object}. * * <p>This {@link System} is deemed to be equal to an {@link Object} * passed to this method if the supplied {@link Object} is an * instance of {@link System} and {@linkplain #getName() has a name} * equal to the {@linkplain #getName() name} of this {@link System} * and {@linkplain #isEnabled() has an enabled status} equal to * {@linkplain #isEnabled() that of this <code>System</code>} and * {@linkplain #isAuthoritative() has an authoritative status} equal * to {@linkplain #isAuthoritative() that of this * <code>System</code>}.</p> * * @param other the {@link Object} to test; may be {@code null} in * which case {@code false} will be returned * * @return {@code true} if this {@link System} is equal to the * supplied {@link Object}; {@code false} otherwise * * @see #hashCode() */ @Override public boolean equals(final Object other) { if (other == this) { return true; } else if (other instanceof System) { final System her = (System) other; final Object name = this.getName(); if (name == null) { if (her.getName() != null) { return false; } } else if (!name.equals(her.getName())) { return false; } return this.isEnabled() && her.isEnabled() && this.isAuthoritative() && her.isAuthoritative(); } else { return false; } } /* * Static methods. */ /** * Returns a non-{@code null}, unchanging and {@linkplain * Collections#unmodifiableSet(Set) unmodifiable <code>Set</code>} * of {@link System} instances as found by the {@linkplain * ServiceLoader Java service provider mechanism}. * * <p>This method never returns {@code null} but may return an * {@linkplain Collection#isEmpty() empty <code>Set</code>}.</p> * * <p>If one of the {@link System} instances so discovered * {@linkplain #isAuthoritative() is authoritative}, then it will be * the only member of the returned {@link Set}.</p> * * <p>Multiple invocations of this method are not guaranteed to * return equal or identical {@link Set} instances.</p> * * @return a non-{@code null} {@linkplain * Collections#unmodifiableSet(Set) unmodifiable <code>Set</code>} * of {@link System} instances as found by the {@linkplain * ServiceLoader Java service provider mechanism}; never {@code * null} * * @see #isAuthoritative() * * @see ServiceLoader#load(Class) */ public static final Set<System> getSystems() { final Iterable<System> systemsIterable = ServiceLoader.load(System.class); assert systemsIterable != null; Set<System> returnValue = null; for (final System system : systemsIterable) { assert system != null; if (system.isEnabled()) { if (system.isAuthoritative()) { returnValue = Collections.singleton(system); break; } else if (returnValue == null) { returnValue = new HashSet<>(); returnValue.add(system); } else { returnValue.add(system); break; } } } if (returnValue == null) { returnValue = Collections.emptySet(); } else { assert !returnValue.isEmpty(); returnValue = Collections.unmodifiableSet(returnValue); } return returnValue; } }
JavaScript
UTF-8
2,691
3.296875
3
[ "MIT" ]
permissive
/* Draw tree */ var canvas = document.getElementById('myTree'); var ctx = canvas.getContext('2d'); var eduPoints; var fitPoints; var healthPoints; /* Education leaves */ var eduLeaves = new Image(); eduLeaves.src = '../img/eduleaves.png' /* Fitness Leaves */ var fitLeaves = new Image(); fitLeaves.src = '../img/fitnessleaves.png'; /* Health leaves */ var healthLeaves = new Image(); healthLeaves.src = '../img/leaves.svg'; firebase.auth().onAuthStateChanged(function (user) { var eduRef = firebase.database().ref('users/' + user.uid + '/eduPoints'); var fitRef = firebase.database().ref('users/' + user.uid + '/fitPoints'); var healthRef = firebase.database().ref('users/' + user.uid + '/healthPoints'); /* Loads education leaves */ eduRef.once('value').then(function(snap) { eduPoints = parseInt(snap.val()); getPoints(eduPoints, 'education'); if (eduPoints == 1) { ctx.drawImage(eduLeaves, 90, 295); } else if (eduPoints == 2) { ctx.drawImage(eduLeaves, 90, 295); ctx.drawImage(eduLeaves, 134, 369); } else if (eduPoints >= 3) { ctx.drawImage(eduLeaves, 90, 295); ctx.drawImage(eduLeaves, 134, 369); ctx.drawImage(eduLeaves, 175, 295); } }); /* loads fitness leaves */ fitRef.once('value', function(snap) { fitPoints = parseInt(snap.val()); getPoints(fitPoints, 'fitness'); if (fitPoints == 1) { ctx.drawImage(fitLeaves, 450, 180); } else if (fitPoints == 2) { ctx.drawImage(fitLeaves, 450, 180); ctx.drawImage(fitLeaves, 365, 182); } else if (fitPoints >= 3) { ctx.drawImage(fitLeaves, 450, 180); ctx.drawImage(fitLeaves, 365, 182); ctx.drawImage(fitLeaves, 408, 255); } }); /* loads health leaves */ healthRef.once('value', function(snap) { healthPoints = parseInt(snap.val()); getPoints(healthPoints, 'health'); if (healthPoints == 1) { ctx.drawImage(healthLeaves, 265, 50); } else if (healthPoints == 2) { ctx.drawImage(healthLeaves, 265, 50); ctx.drawImage(healthLeaves, 222, 112); } else if (healthPoints >= 3) { ctx.drawImage(healthLeaves, 265, 35); ctx.drawImage(healthLeaves, 222, 105); ctx.drawImage(healthLeaves, 309, 105); } }); }) /* Tree base */ var baseTree = new Image(); baseTree.onload = function() { ctx.drawImage(baseTree, 0, 0); }; baseTree.src = '../img/main-tree.svg'; function getPoints(points, type) { var eduDiv = document.getElementById("eduPoints"); var fitDiv = document.getElementById("fitPoints"); var hDiv = document.getElementById("healthPoints"); if (type == 'education') { eduDiv.innerHTML = points; } else if (type == 'fitness') { fitDiv.innerHTML = points; } else if (type == 'health') { hDiv.innerHTML = points; } }
Shell
UTF-8
4,505
4.1875
4
[ "MIT" ]
permissive
#!/bin/bash set -eu set -o pipefail help() { cat <<EOF ${1:-} NAME xmloscopy - wtf is my docbook broken? SYNOPSIS xmloscopy <--docbook5> <root-document.xml> <combined-document.xml> DESCRIPTION Tries to tell you why your docbook is broken. LIMITATIONS - Must run it it the parent directory of all your XML files - You should probably delete your <combined-document.xml> argument prior to running xmloscopy - This one guy said this tool might make debuggging docbook more frustrating. I'd like to see me try! - Only supports Docbook5 now - Isn't magic AUTHORS Graham Christensen <graham@grahamc.com> REPORTING BUGS https://github.com/grahamc/xmloscopy LICENSE MIT VERSION hard to say EOF exit 1 } if [ $# -ne 3 ]; then help fi if [ "$1" != "--docbook5" ]; then help "error: You MUST pass --docbook5 as the first argument" fi readonly ROOT=$2 if [ ! -f "$ROOT" ]; then help "error: root document $ROOT does not exist" fi readonly COMBINED=$3 all_files() { find . -name '*.xml' | grep -v "$COMBINED" } files_without_xinclude() { all_files | xargs grep -L "xi:include" } contextualize() { (while read -r x; do filename=$(echo "$x" | cut -d ':' -f1) line=$(echo "$x" | cut -d ':' -f2) # character=$(echo "$x" | cut -d ':' -f3) error=$(echo "$x" | cut -d ':' -f4-) errorstart=$(echo "$error" | cut -d ';' -f1) errorend=$(echo "$error" | cut -d ';' -f2-) if [ "$errorstart" == "$errorend" ]; then errorend="" fi echo "Line $line:" pattern='^[[:space:]]*'"${line}[[:space:]]" cat -n "$filename" | grep -E -B3 "$pattern" | sed '$ d' echo -en "\e[1m" cat -n "$filename" | grep -E "$pattern" echo -en "\e[0m" cat -n "$filename" | grep -E -A3 "$pattern" | tail -n +2 echo -e "\e[1m$errorstart\e[0m;$errorend" \ | fold -sw 40 \ | sed -e "s/^/ /" if echo "$errorstart" | grep -q 'error: IDREF ".*" without matching ID'; then id=$(echo "$errorstart" \ | sed 's/error: IDREF "//' \ | sed 's/" without matching ID//') echo "" echo "Maybe you intended one of the following IDs which do exist:" suggest_id "$id" | sed 's/^/ - /' fi printf "\n\n\n" done) < "$1" } suggest_id() { find . -name '*.xml' -print0 \ | xargs -0 grep -r xml:id \ | sed -e 's/^.*xml:id=["'"'"']//' \ | sed -e 's/['"'"'"].*$//' \ | sort | uniq \ | fzf -f "$1" } scratch=$(mktemp -d -t tmp.XXXXXXXXXX) function finish { rm -rf "$scratch" } trap finish EXIT anyfailed=0 cat <<EOF Feasability check on files without xincludes... A document is feasibly valid if it could be transformed into a valid document by inserting any number of attributes and child elements anywhere in the tree. This is equivalent to pretending every element is optional. This option may be useful while a document is still under construction. This option also disables checking that references are valid. EOF for f in $(files_without_xinclude); do if jing -f "$RNG" "$f" > "$scratch/errors" 2>&1; then echo "$f: OK" else echo "$f: Not feasibly valid:" contextualize "$scratch/errors" anyfailed=1 fi done if [ $anyfailed -eq 1 ]; then cat <<EOF The component XML files aren't feasibly valid. Trying to continue, just in case the invalid files aren't referenced. EOF fi printf "\n\n\n\n----\n\n\n\n" anyfailed=0 cat <<EOF Checking files without xincludes, ignoring reference errors... Ensures document fragments are valid, but without validating links are valid. EOF for f in $(files_without_xinclude); do if jing -i "$RNG" "$f" > "$scratch/errors" 2>&1; then echo "$f: OK" else echo "$f: Not valid:" contextualize "$scratch/errors" anyfailed=1 fi done if [ $anyfailed -eq 1 ]; then cat <<EOF The component XML files aren't valid as subcomponents. Trying the whole document just in case. EOF fi printf "\n\n\n\n----\n\n\n\n" echo "Doing a combined check..." xmllint --nonet --xinclude --noxincludenode "$ROOT" --output "$COMBINED" if jing "$RNG" "$COMBINED" > "$scratch/errors" 2>&1; then echo "$COMBINED: OK" else echo "$COMBINED: Not valid:" contextualize "$scratch/errors" exit 1 fi
C#
UTF-8
1,219
2.765625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using Wilcommerce.Catalog.Events.CustomAttribute; using Xunit; namespace Wilcommerce.Catalog.Test.Events.CustomAttribute { public class CustomAttributeUpdatedEventTest { [Fact] public void CustomAttributeUpdatedEvent_Ctor_Should_Set_Arguments_Correctly() { Guid attributeId = Guid.NewGuid(); string name = "name"; string type = "string"; string description = "description"; string unitOfMeasure = "unit"; IEnumerable<object> values = new[] { "v1", "v2" }; var @event = new CustomAttributeUpdatedEvent(attributeId, name, type, description, unitOfMeasure, values); Assert.Equal(attributeId, @event.AttributeId); Assert.Equal(name, @event.Name); Assert.Equal(type, @event.Type); Assert.Equal(description, @event.Description); Assert.Equal(unitOfMeasure, @event.UnitOfMeasure); Assert.Equal(values, @event.Values); Assert.Equal(attributeId, @event.AggregateId); Assert.Equal(typeof(Catalog.Models.CustomAttribute), @event.AggregateType); } } }
Java
ISO-8859-1
243
2.953125
3
[]
no_license
package es.Studium; public class Ejercicio2 { public static boolean esParOImpar(int n) { if(n%2 == 0) { System.out.println("El nmero es par."); return true; } else { System.out.println("El nmero es impar."); return false; } } }
C#
UTF-8
1,456
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Infomation.Core.Extensions { public static class EducationExtensions { public static string DisplayName(this Education edu) { string displayName = string.Empty; switch (edu) { case Education.None: displayName = "不限 "; break; case Education.A: displayName = "技校 "; break; case Education.B: displayName = "高中"; break; case Education.C: displayName = "中专"; break; case Education.D: displayName = "大专"; break; case Education.E: displayName = "本科"; break; case Education.F: displayName = "硕士"; break; case Education.G: displayName = "博士"; break; //case Education.H: // displayName = "技校"; // break; default: break; } return displayName; } } }
PHP
UTF-8
1,109
3.234375
3
[]
no_license
<?php namespace App; use GraphicsLib\CanvasInterface; use ModernGraphicsLib\ModernGraphicsRenderer; use ModernGraphicsLib\Point; class ModernGraphicsRendererAdapter extends ModernGraphicsRenderer implements CanvasInterface { /** @var ModernGraphicsRenderer */ private $renderer; /** @var Point */ private $currentPoint; public function __construct(ModernGraphicsRenderer $renderer) { $this->renderer = $renderer; $this->currentPoint = new Point(0, 0); } public function beginDraw(): void { $this->renderer->beginDraw(); } public function drawLine(Point $start, Point $end): void { $this->renderer->drawLine($start, $end); } public function endDraw(): void { $this->renderer->endDraw(); } public function moveTo(int $x, int $y): void { $this->currentPoint->setX($x); $this->currentPoint->setY($y); } public function lineTo(int $x, int $y): void { $this->renderer->drawLine($this->currentPoint, new Point($x, $y)); $this->moveTo($x, $y); } }