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
C++
UTF-8
1,253
3.359375
3
[]
no_license
#include <iostream> #include <stdio.h> using namespace std; struct Repartidor { int dni; char nom[25]; int zona; }; int main() { Repartidor rep; int cant[6]={0}; //Inicializaron el vector int i=0; FILE*arch = fopen("Repartidores.dat","wb"); if(arch==NULL) cout<<"ERROR"<<endl; else { cout<<"Ingrese dni del repartidor (Ingrese 0 para finalizar el programa):"<<endl; cin>>rep.dni; while(rep.dni!=0) { cout<<"Ingrese el nombre del repartidor:"<<endl; cin>>rep.nom; cout<<"Ingrese la zona en la que trabaja (1-6): "<<endl; cin>>rep.zona; while((rep.zona<1)||(rep.zona>6)) { cout<<rep.zona<<" no es una zona valida."<<endl<<"Ingrese una zona entre 1 y 6:"<<endl; cin>>rep.zona; } cant[rep.zona-1]++; fwrite(&rep,sizeof(Repartidor),1,arch); cout<<"Ingrese dni del repartidor (Ingrese 0 para finalizar el programa):"<<endl; cin>>rep.dni; } fclose(arch); } for(i=0;i<6;i++) { if(cant[i]!=0) cout<<"Hay "<<cant[i]<<" repartidores en la zona "<<i+1<<"."<<endl; else cout<<"No hay ningun repartidor en la zona "<<i+1<<"."<<endl; } return 0; }
C++
UTF-8
2,242
3.09375
3
[ "MIT" ]
permissive
// Вывод тока и напряжения в монитор последовательного порта: // #include <Battery_Shield.h> // Подключаем библиотеку Battery_Shield. Battery_Shield pwrBank; // Объявляем объект pwrBank для работы с функциями и методами библиотеки Battery_Shield. // void setup(){ // Serial.begin(9600); // Инициируем передачу данных в монитор последовательного порта на скорости 9600. pwrBank.begin(0.0128f); // Инициируем работу с Battery Shield, указывая номинал сопротивления (0.128 Ом) установленного в цепи аккумулятора. } // Номинал сопротивления Вашего источника автономного питания указан на вкладыше к Battery Shield, это значение используется для расчёта Ibat. // void loop(){ // Serial.println("-------------------------"); // Serial.println((String) "Vbat=" + pwrBank.voltmeter(BATTERY) + "В."); // Выводим напряжение аккумулятора в В. Serial.println((String) "Ibat=" + pwrBank.amperemeter(BATTERY) + "А."); // Выводим силу тока аккумулятора в А. Serial.println((String) "Vout=" + pwrBank.voltmeter(OUTPUT) + "В."); // Выводим напряжение на выходе в В. Serial.println((String) "Iout=" + pwrBank.amperemeter(OUTPUT) + "А."); // Выводим силу тока на выходе в А. delay(1000); // Приостанавливаем выполнение скетча на 1 секунду. }
Markdown
UTF-8
447
2.75
3
[]
no_license
# App Flow ## Stack ### Backend: * Firebase Auth * Firebase Realtime Database Functions: * Create Child: Firebase Functions - createUser (node.js) ## Sign up/Sign in ### Flow * Sign in default - if fails, automatically registers new user and signs in ### Sign up/Register Onboarding: * User Details -> saved to database * Child Details -> saved to database * Enter first chore -> saved to database * Child List ### Sign in * Child List
Markdown
UTF-8
2,513
2.859375
3
[]
no_license
# select 模拟select下拉框 效果图如下所示 ![select](example/select.jpg) **[DEMO请案例点击这里查看.](http://www.lovewebgames.com/jsmodule/select.html "select demo")** ---------- # 调用示例 ``` <select name="select" id="select"> <option value="-1">请选择</option> <option value="1">男</option> <option value="0" selected="true">女</option> <option value="10" disabled="true">"'人妖</option> </select> <select id="select2"></select> <input type="text" id="select3" style="height:30px;" value="2"> <a id="select4" data-value="1"></a> <script type="text/javascript" src="../src/jquery-1.11.2.js"></script> <script type="text/javascript" src="../src/select.js"></script> <script> var select = new Select(); select.init({ target: '#select' }); $('#select2').Select({ width:100, model: [{ text: "请选择", value: "1" }] }); var model=[{ text: "浙江浙江浙江浙江浙江", value: "1" },{ text: "杭州", value: "2" },{ text: "宁波", value: "3" },{ text: "湖北", value: "4" },{ text: "上海", value: "5" },{ text: "万达", value: "6" },{ text: "物美", value: "7", disabled:true },{ text: "中国", value: "8" },{ text: "外国", value: "9" }]; $('#select3').change(function(){ console.log('选中个:'+$(this).val())//或者selected }).Select({ width:100, maxHeight:300, maxWidth:'auto', model: model }); var sel=$('#select4').Select({ width:100, height:24 })[0]; setTimeout(function(){ sel.setData(model);//动态更改数据源 },2000); </script> ``` # API ## 属性 ### target:`[DOM|String|$]` 要改变成select的节点,可以原来就是select,也可以是其他元素,如果是其他元素时,优先取value取为选中项,否则取data-value值; ### model:`Array` 数据源数组[value:'1',text:'文本',disabled:false],如果无的时候,会去option,disabled可以控制是否可选,option上同 ### multi:`bool` 是否多选,暂缺 ### disabled:`bool` 是否可用,默认可用false, 如果没有这个值会去取target的disabled或target.hasClass('disabled')来判断是否可用 ## 方法 ### setData:`function(data)` 更改数据源data为数组[value:'1',text:'文本',disabled:false] ### selected:`function(val,txt)` 选中后的回调 ## 事件 ### change:`[value]` 选中项改变时触发 ### blur: 隐藏时触发 ### set:function(e,val) $(target).trigger('set','1')设置选中项
Java
UTF-8
219
1.65625
2
[]
no_license
package com.uca.capas.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.uca.capas.domain.Showtime; public interface ShowtimeRepository extends JpaRepository<Showtime, Integer> { }
Swift
UTF-8
3,723
3.1875
3
[]
no_license
// // AShape.swift // ShapesGenerator // // Created by Tah Tatsumoto on 1/10/16. // Copyright © 2016 Mad Hat Productions. All rights reserved. // import Foundation public class AShape : NSObject, IShape { private let type : ShapeType; private var internalPoints : [Point]!; private var externalPoints : [Point]!; private var moveSpeed : Int; private var rotationSpeed : Int; private let diameter : Int; public convenience init(type: ShapeType) { let moveSpeed = Int(arc4random_uniform(10) + 1); let rotationSpeed = Int(arc4random_uniform(10)); self.init(type: type, moveSpeed: moveSpeed, rotationSpeed: rotationSpeed); } public convenience init(type: ShapeType, moveSpeed: Int, rotationSpeed: Int) { let pt = Point(); self.init(type: type, moveSpeed: moveSpeed, rotationSpeed: rotationSpeed, initialPoint: pt); } public convenience init(type: ShapeType, moveSpeed: Int, rotationSpeed: Int, initialPoint: Point) { let d = Int(arc4random_uniform(50) + 10); self.init(type: type, moveSpeed: moveSpeed, rotationSpeed: rotationSpeed, initialPoint: Point(), diameter: d); } public init(type: ShapeType, moveSpeed: Int, rotationSpeed: Int, initialPoint: Point, diameter: Int) { self.moveSpeed = moveSpeed; self.rotationSpeed = rotationSpeed; self.type = type; self.diameter = diameter; super.init(); self.externalPoints = createExternalPoints(initialPoint); self.internalPoints = createInternalPoints(); } private func createExternalPoints(initialPoint: Point) -> [Point] { var points : [Point] = [Point](); for _ in 1..<type.OuterPointCount { // Must update points.append(Point()); } return points; } private func createInternalPoints() -> [Point] { var points : [Point] = [Point](); for _ in 0..<type.InnerPointCount { // Must update; points.append(Point()); } return points; } public var InnerPointsArray : [Point] { get { return self.internalPoints; } } public var OuterPointsArray : [Point] { get { return self.externalPoints; } } public func speedUp() -> IShape { self.moveSpeed *= 2; return self; } public func slowDown() -> IShape { self.moveSpeed /= 2; return self; } public func spinFaster() -> IShape { self.rotationSpeed *= 2; return self; } public func spinSlower() -> IShape { self.rotationSpeed /= 2; return self; } /** The rotation of the shape - Return: < 0 if the shape is rotating counter clockwise > 0 if the shape is rotating clockwise 0 if the shape is not rotating */ public var Rotation : Int { get { return self.rotationSpeed; } } /** Reverses the rotation of the Shape */ public func reverse() -> IShape { self.rotationSpeed *= -1; return self; } public func move() -> IShape { return self; } public var Type : ShapeType { get { return self.type; } } public var Name : String { get { return self.type.name; } } override public func isEqual(object: AnyObject?) -> Bool { if object is AShape { return self.type.name == (object as! ShapeType).name; } else { return false; } } }
Python
UTF-8
1,938
2.53125
3
[]
no_license
import sys import struct import numpy as np from scipy import signal from datetime import datetime import matplotlib.pyplot as plt # Useage if len(sys.argv) != 2: print("Usage: {} <samples.bin>".format(sys.argv[0])) sys.exit(1) # Data Files sample_file = open(sys.argv[1], 'rb') wfm_file = open('./wfm.bin', 'rb') # Compute Number of Samples Present sample_file.read() num_samples = int((sample_file.tell()-24)/4) sample_file.seek(0) # Read Data Capture Metadata meta = struct.unpack('QQQ', sample_file.read(24)) tx_start = meta[2] + 1360*1800 offset = tx_start - meta[1] # Extract I and Q Channels smp_I = np.zeros(num_samples, dtype=float) smp_Q = np.zeros(num_samples, dtype=float) for n in range(0, num_samples): smp_I[n] = struct.unpack('h', sample_file.read(2))[0] smp_Q[n] = struct.unpack('h', sample_file.read(2))[0] # Complex Sample Array samples = (smp_I + 1j*smp_Q) # Read in Waveform wfm_file.read() wfm_samples = int(wfm_file.tell()/4) wfm_file.seek(0) wfm_I = np.zeros(wfm_samples, dtype=float) wfm_Q = np.zeros(wfm_samples, dtype=float) for n in range(0, wfm_samples): wfm_I[n] = struct.unpack('h', wfm_file.read(2))[0] wfm_Q[n] = struct.unpack('h', wfm_file.read(2))[0] # Complex Waveform Array waveform = (wfm_I + 1j*wfm_Q) # Compute Cross Correlation c = np.absolute(signal.correlate(np.asarray(np.real(samples)), np.asarray(np.real(waveform)), 'same')) c2 = np.absolute(signal.correlate(np.asarray(np.imag(samples)), np.asarray(np.imag(waveform)), 'same')) # Search for Peak delay_i = -1 delay_q = -1 while delay_i < 0: peak_idx_i = np.argmax(c) measured_offset_i = peak_idx_i - (wfm_samples/2) delay_i = measured_offset_i - offset c[peak_idx_i] = 0 while delay_q < 0: peak_idx_q = np.argmax(c2) measured_offset_q = peak_idx_q - (wfm_samples/2) delay_q = measured_offset_q - offset c2[peak_idx_q] = 0 print(delay_i, ' ',delay_q)
JavaScript
UTF-8
1,134
3.921875
4
[ "ISC" ]
permissive
/* Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] */ const threeSum = (nums) => { nums.sort((a,b) => {return a - b}); let resArr = []; for (let i = 0; i < nums.length - 2; i++){ if (nums[i] > 0) { return resArr; } if (nums[i] === nums[i-1]){ continue; } let j = i+1, k = nums.length - 1; while (j < k){ if (nums[i] + nums[j] + nums[k] == 0){ resArr.push([nums[i], nums[j], nums[k]]); j++; while(nums[j] === nums[j - 1]){ j++; } } if (nums[i] + nums[j] + nums[k] > 0){ k--; } else if (nums[i] + nums[j] + nums[k] < 0){ j++; } } } return resArr; }
TypeScript
UTF-8
385
2.546875
3
[]
no_license
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filtro' }) export class FiltroPipe implements PipeTransform { transform(elements: any[], args: string, attr: string): any[] { if (args == '') return elements; args = args.toLowerCase(); return elements.filter( item => { return item[attr].toLowerCase().includes(args); }); } }
C
UTF-8
2,649
2.734375
3
[]
no_license
#ifndef LINK_LIST_H_ #define LINK_LIST_H_ #include <stdint.h> typedef struct st_LIST_NODE { struct st_LIST_NODE * next; struct st_LIST_NODE * prior; void * pdata; } LIST_NODE, * PLIST_NODE; typedef struct st_DLINK_LIST { PLIST_NODE head; PLIST_NODE tail; uint32_t count; } DLINK, * PDLINK; typedef int (*DLINKWORKFUN)(void * pdata, void * param); typedef int (*DLINKCMPFUN)(void * pd1, void * pd2, void * param); void dlink_init (PDLINK pList); void dlink_simple_destroy (PDLINK pList); void dlink_destroy (PDLINK pList, DLINKWORKFUN destroy_fun, void * param); /** *从链表头或者尾部插入新节点,节点数据pData由用户保存空间,不应在 *未删除节点的情况下释放pData的空间。 */ void dlink_add_head(PDLINK pList, void * pData); void dlink_add_tail(PDLINK pList, void * pData); /** * 链接后,pFromList将被清空 */ void dlink_cat_head(PDLINK pToList, PDLINK pFromList); void dlink_cat_tail(PDLINK pToList, PDLINK pFromList); void dlink_del_node(PDLINK pList, PLIST_NODE pToDelete, DLINKWORKFUN destroy_fun, void * param); #define dlink_del_tail(pList, destroy_fun, param) dlink_del_node(pList, (pList)->tail, destroy_fun, param) #define dlink_del_head(pList, destroy_fun, param) dlink_del_node(pList, (pList)->head, destroy_fun, param) void dlink_simple_del_node(PDLINK pList, PLIST_NODE pToDelete); #define dlink_simple_del_tail(pList) dlink_simple_del_node(pList, (pList)->tail) #define dlink_simple_del_head(pList) dlink_simple_del_node(pList, (pList)->head) /** * visit_fun返回0值,表示继续,非0值则中断并返回该值 */ int dlink_traverse(PDLINK pList, DLINKWORKFUN visit_fun, void * param); int dlink_traverse_back(PDLINK pList, DLINKWORKFUN visit_fun, void * param); void dlink_sort(PDLINK pList, DLINKCMPFUN cmp_fun, void * param); void dlink_del_dup(PDLINK pList, DLINKCMPFUN cmp_fun, void * cmp_param, DLINKWORKFUN destroy_fun, void * des_param); void dlink_simple_del_dup(PDLINK pList, DLINKCMPFUN cmp_fun, void * param); PLIST_NODE dlink_find(PDLINK pList, DLINKWORKFUN find_fun, void * param); PLIST_NODE dlink_get_head(PDLINK pList); PLIST_NODE dlink_get_tail(PDLINK pList); PLIST_NODE dlink_get_next(PLIST_NODE pCurrent); PLIST_NODE dlink_get_prior(PLIST_NODE pCurrent); uint32_t dlink_get_count(PDLINK pList); void dlink_move_node(PDLINK pList, PLIST_NODE pToMove, PLIST_NODE pPosition, int nFront); #define dlink_move_to_head(pList, pToMove) dlink_move_node((pList), (pToMove), dlink_get_head((pList)), 1) #define dlink_move_to_tail(pList, pToMove) dlink_move_node((pList), (pToMove), dlink_get_tail((pList)), 0) #endif /* STRUCTURES_H_ */
Markdown
UTF-8
864
3
3
[]
no_license
# holiday-maker-with-multiple-language Laravel application for maintaing and for android API # About this <ul> <li>Add any package</li> <li>Under this package admin can add any month</li> <li>Under month admin can add any date , single data or range of date with single or multiple language attribute</li> <li>It has API , where u can take ur data using package or package with start and ending date</li> <li>3 types of user roles , admin , user , and block</li> </ul> # installation <ol> <li>Clone this project</li> <li>open CMD write these following commands</li> <ol> <li> >> composer install</li> <li>setup .env file and run >> php artisan key:generate </li> <li> >> php artisan migrate</li> <li> >> php artisan db:seed</li> </ol> <li>go to login and name='admin' and password='secret'</li> <li>enjoy</li> </ol>
Java
UTF-8
2,555
2.9375
3
[]
no_license
package bitcamp.java89.ems.server; import java.io.File; import java.net.ServerSocket; import java.util.ArrayList; //import bitcamp.java89.ems.server.controller.StudentController; import java.util.HashMap; public class EduAppServer2bak { //클라이언트 요청을 처리할 Command 구현체들을 보관한다(Command 구현체 보관소). //HashMap<명령문자열,요청처리객체> commandMap HashMap<String,Command> commandMap = new HashMap<>(); public EduAppServer2bak() { /*bin 폴더를 뒤져서 AbstracrCommand의 서브 클래스를 찾아낸다.*/ ArrayList<Class> classList = new ArrayList<>(); ReflectionUtil.getCommandClasses(new File("./bin"), classList); //classList 바구니를 넘겨주면 바구니에 담아넣는다. for (Class c : classList) { //System.out.println(c.getName()); //정말 들어가는가해서 확인해봤더니 정말 제대로 들어갔음 try { // 클라이언트 요청을 처리할 Command 객체 등록 AbstractCommand command = (AbstractCommand)c.newInstance(); //타입캐스팅 commandMap.put(command.getCommandString(), command); //command.getCommandString() = 각 Controller 마다 명찰을 달아서 어떤 일을 수행하는지 알려준다. //이걸 가져와서 넣어주면 각 명찰마다 일을 수행하면 된다. } catch (Exception e) {} } // commandMap.put("contact/list", new ContactListController()); // commandMap.put("contact/view", new ContactViewController()); // commandMap.put("contact/add", new ContactAddController()); // commandMap.put("contact/delete", new ContactDeleteController()); // commandMap.put("contact/update", new ContactUpdateController()); // // commandMap.put("classroom/list", new ClassroomListController()); // commandMap.put("classroom/view", new ClassroomViewController()); // commandMap.put("classroom/add", new ClassroomAddController()); // commandMap.put("classroom/delete", new ClassroomDeleteController()); // commandMap.put("classroom/update", new ClassroomUpdateController()); } private void service() throws Exception { ServerSocket ss = new ServerSocket(8888); System.out.println("..서버 실행 중.."); while (true) { new RequestThread(ss.accept(), commandMap).start(); } } public static void main(String[] args) throws Exception { EduAppServer2bak eduServer = new EduAppServer2bak(); eduServer.service(); } }
Ruby
UTF-8
197
3.296875
3
[]
no_license
def guess_number guess number = 25 puts "Guess was too high" unless guess <= number puts "Guess was too low" unless guess >= number puts "You got it" if guess == number end guess_number 25
Markdown
UTF-8
4,681
2.953125
3
[]
no_license
# WASM Analysis This document provides notes on the WASM for a simple function named 'add' that returns the sum of two arguments, all values are of type float. Tools used to generate .wasm and .wat are from the [WABT] project. The repository (https://github.com/cullenr/wasm-analysis) for this document contains compiled Linux binaries for convenience. The WASM specification can be found here https://webassembly.github.io/spec/core/bikeshed/index.html ## WAT This is the source code (WAT) used to generate the WASM: ``` (module (func $add (param f32) (param f32) (result f32) get_local 0 get_local 1 f32.add) (export "add" (func 0))) ``` ## WASM wat2wasm output: ``` 00000000: 0061 736d 0100 0000 0107 0160 027d 7d01 .asm.......`.}}. 00000010: 7d03 0201 0007 0701 0361 6464 0000 0a09 }........add.... 00000020: 0107 0020 0020 0192 0b ... . ... ``` ## WAT from WASM Note the type section which is not present in the original WAT. The `wast2wasm` output below also contains comments indicating the indices that link the _type_ and _func_ elements; `(;` and `;)` delimit block comments. ``` (module (type (;0;) (func (param f32 f32) (result f32))) (func (;0;) (type 0) (param f32 f32) (result f32) local.get 0 local.get 1 f32.add) (export "add" (func 0))) ``` ## [Module] Breakdown The WASM file starts of with a module definition. According to the spec a module is formatted like so `magic, version, sections`. ### [Preamble][Module] `0061 736d` : magic number `0100 0000` : WASM version ### [Sections](https://webassembly.github.io/spec/core/binary/modules.html#sections) The sections portion of the module starts with a type-section ([typesec]) and is followed by a function-section ([funcsec]), export-section ([exportsec]) and finally a code-section ([codesec]). `0107 0160 027d 7d01 7d` : [typesec] data | description -----|------------ `01` | section id for type-section `07` | length of section in bytes (note the 7 bytes below) `01` | the length of the functype vector that the type-section expects `60` | functype opcode (two vectors follow for params and results respectively) `02` | the length of the valtype vector of params `7d` | the opcode for 32 bit float (1st param) `7d` | the opcode for 32 bit float (2nd param) `01` | the length of the valtype vector of results `7d` | the opcode for 32 bit float (return value) `03 0201 00` [funcsec] data | description -----|------------ `03` | section id for function-section `02` | length of this section in bytes `01` | length of the functype vector that the function-section expects `00` | the index of the code body in the code-section below. `07 0701 0361 6464 0000` [exportsec] data | description -----|------------ `07` | section id for export-section `07` | length of this section in bytes `01` | length of the export vector that the export-section expects `03` | length of the byte arr for this exports _name_ "add" `61` | byte 'a' `64` | byte 'd' `64` | byte 'd' `00` | declare this export is a function `00` | the id of the function to export, in this case 00 `0a09 0107 0020 0020 0192 0b` [codesec] data | description -----|------------ `0a` | section id for code-section `10` | length of this section in bytes `01` | length of the [code] vector that the code-section expects `07` | length of the [func] in bytes `00` | length of the locals array - 0 so no locals are present. `20` | start of the expression section - 0x20 is the local.get instruction `00` | id for local.get for the first param `20` | second call to local.get to get param 2 `01` | id for local.get for the second param `92` | the opcode for f32.add `0b` | end of the expression denoted by the end opcode 0x0b [WABT]: https://github.com/WebAssembly/wabt [Module]:https://webassembly.github.io/spec/core/binary/modules.html#binary-module [typesec]:https://webassembly.github.io/spec/core/binary/modules.html#type-section [funcsec]:https://webassembly.github.io/spec/core/binary/modules.html#function-section [exportsec]:https://webassembly.github.io/spec/core/binary/modules.html#export-section [codesec]:https://webassembly.github.io/spec/core/binary/modules.html#code-section [index]:https://webassembly.github.io/spec/core/binary/modules.html#indices [functype]:https://webassembly.github.io/spec/core/binary/types.html#binary-functype [code]:https://webassembly.github.io/spec/core/binary/modules.html#code-section [func]:https://webassembly.github.io/spec/core/binary/modules.html#code-section **TODO:** add a new function to the module so we can see how this affects the original and also make the new function contain a local - a ++ function maybe.
JavaScript
UTF-8
764
2.625
3
[]
no_license
import React, { Component } from 'react' class Child extends Component{ componentWillReceiveProps(nextProps){ console.log('componentWillReceiveProps',nextProps) } render(){ return( <div>child--{this.props.myid}</div> ) } } export default class App extends Component { state={ text:4567 } render() { console.log('render') return ( <div> <Child myid={this.state.text}></Child> { this.state.text } <button onClick={()=>{ this.setState({ text:4321 }) }}>click</button> </div> ) } }
C#
UTF-8
1,167
3.046875
3
[]
no_license
using System; using System.Collections.Generic; namespace LoxStatEdit { public class LoxStatProblem { public readonly LoxStatObject Source; public readonly object Problem; public LoxStatProblem(LoxStatObject source, object problem) { Source = source; Problem = problem; } public static IList<LoxStatProblem> GetProblems( IEnumerable<LoxStatObject> loxStatObjects) { IList<LoxStatProblem> list = new List<LoxStatProblem>(); foreach(var loxStatObject in loxStatObjects) loxStatObject.AddProblems(list); return list; } public static IList<LoxStatProblem> GetProblems( params LoxStatObject[] loxStatObjects) { return GetProblems((IEnumerable<LoxStatObject>)loxStatObjects); } public override string ToString() { try { return string.Format("{0}: {1}", Source, Problem); } catch(Exception ex) { return ex.ToString(); } } } }
Python
UTF-8
646
2.765625
3
[ "MIT" ]
permissive
f = open("DataDict.txt") lines = f.readlines() #Format into data data = [i.strip().split() for i in lines] #From original... ancient code # _A_ # # (O.o) # |__/*\ # | / \ # # AnCiEnT WiZ0rd! print(data[0]) data[1] = [data[1][0]] + [" ".join(data[1][1:])] for i in range(2,len(data)): data[i] = [data[i][0]] + [" ".join(data[i][1:-6])] + data[i][-6:] #data = [[i[:10].strip()] + [i[10:115].strip()] + i[115:].strip().split() for i in data] #3,4,5, and 6 are numeric entrees data = data[0:2] + [i[:3] + map(float,i[3:7]) + i[7:] for i in data[2:]] f = open("DataDict.js", "w") f.write("var DataDict = ") f.write(str(data)) f.close()
PHP
UTF-8
240
3.09375
3
[]
no_license
<?php class GraphicStyle { private $styleInfo; function __construct($styleInfo = array()) { $this->styleInfo = $styleInfo; } public function add($styleInfo) { $this->styleInfo = array_merge($this->styleInfo, $styleInfo); } }
Python
UTF-8
3,346
3.625
4
[]
no_license
#Ecrire un algorithme, puis un programme, qui attend une suite de 4 chiffres de maniere #a representer un nombre entier. L utilisateur devra pouvoir effectuer des saisies successives et #l algorithme acceptera tout caractere saisi mais : #- il n affichera en echo a l ecran que les chiffres, #- il ne tiendra pas compte des caracteres differents d un chiffre, #- il ne tiendra pas compte des nombres, #- il attendra davoir recu effectivement 4 chiffres (et non seulement 4 caracteres #quelconques) pour passer a la suite. #On demande ensuite d afficher le nombre de 4 chiffres ainsi que le double de ce nombre. #Remarque : L acces aux code ASCII des caracteres courants seffectue a l aide des fonctions #chr() et ord() : chr(n) renvoie le caractere dont le code Ascii est n, et ord(c) renvoie le code #Ascii du caractere c (par exemple, si le caractere est le chiffre 2, on ecrira ord( 2)). #Expliquez-moi ce que le prof attend que vous fassiez dans cet exo ??? #Ecrivez une fonction qui demande a l'ulisateur de saisir un caractere et l'affiche apres #saisissez un caractere : #a #vous avez saisi : a def afficheCaractere(): return #afficheCaractere() #Ecrivez une fonction qui demande *a chaque fois* a l'utlisateur de saisir un caractere puis affiche ce dernier #saisissez un caractere : #a #vous avez saisi : a #saisissez un caractere : #1 #vous avez saisi : 1 #saisissez un caractere : #. #vous avez saisi : . # .... def afficheCaractereS(): return #afficheCaractereS() #Ecrivez un programme qui demande de a l'utilisateur de saisir des caracteres # et au bout de 4 caracteres saisi le programme sort def affiche4CaractereS(): return #affiche4CaractereS() #Ecrivez un programme qui demande de a l'utilisateur de saisir "que" des chiffre (ou nombre) # et au bout de 4 chiffres saisi le programme sort #saisissez un chiffre : #1 #vous avez saisi : 1 #saisissez un chiffre : #2 #vous avez saisi : 2 #saisissez un chiffre : #a #saisissez un chiffre : #b #... def affiche4Chiffres(): return #affiche4Chiffres() #autre methode avec code ascii #d'abord d'est quoi le code ascii ??? #petit exo ecrivez une fonction qui prend un caractere et affiche son code ascii # indication : ord(c) def afficheCodeAscii(c): return #afficheCodeAscii('1') #petit exo ecrivez mnt une fonction qui prend un code Ascii et affiche le caractere corespondant # indication : chr(codeAscii) def afficheCaractereDeCodeAscii(codeAscii): return #afficheCaractereDeCodeAscii(60) #ecrivez mnt la fonction avec en utilisant le code Ascii def affiche4Chiffres2(): return #affiche4Chiffres2() #Ecrivez mnt la meme fonction d'avant mais en assurant que l'utilisateur # a bien saisi un chiffre pas un nombre def affiche4Chiffres3(): return #affiche4Chiffres3() #Ecrivez la meme fonction d'avant, mais cette la fonction doit afficher le nombre en entier a la fin de la saisi # exemple : # 1 # 2 # 5 # 0 # vous avez saisi 1250 #Petit rappel des tableaux def afficheNombre(): return #afficheNombre() #Autre methode pour afficher le nombre à la fin def afficheNombre1(): return #afficheNombre1() #******Fonction finale**** #cette fonction affiche un nombre saisi par l'utlisateur ce nombre est a 4 chiffre # affiche le nombre saisi et son double def afficheNombre2(): return afficheNombre2()
Python
UTF-8
753
2.578125
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -* import os import glob import zipfile # 100 gs文件解压路径 filepathzip sourcegszip = "Z:\\GS" # 指定的解压位置 filepathzipdir = "D:\\GS\\" os.chdir(sourcegszip) path = os.listdir() pathlist = [] pathdiclist = {} for i in path: if os.path.isfile(i): if "zip" in i: pathdiclist.update({int(os.path.getctime(i)): i}) pathlist.append(int(os.path.getctime(i))) else: pass # print("gs 文件不存在") newfile = filepathzipdir + (pathdiclist[max(pathlist)]) sourcegszipfile = sourcegszip + "\\" + pathdiclist[max(pathlist)] # 解压文件到目标文件 f = zipfile.ZipFile(sourcegszipfile) f.extractall(filepathzipdir) f.close() print(newfile)
Python
UTF-8
662
3.390625
3
[]
no_license
import numpy as np # transfer function def stepFunction(soma): if (soma >= 1): return 1 return 0 def sigmoidFunction(soma): return 1 / (1 + np.exp(-soma)) def tahnFunction(soma): return (np.exp(soma) - np.exp(-soma)) / (np.exp(soma) + np.exp(-soma)) def reluFunction(soma): if soma >= 0: return soma return 0 def linearFunction(soma): return soma def softmaxFunction(x): ex = np.exp(x) return ex / ex.sum() teste = stepFunction(2.1) teste1 = sigmoidFunction(2.1) teste2 = tahnFunction(2.1) teste3 = reluFunction(2.1) teste4 = linearFunction(2.1) valores = [7.0, 2.0, 1.3] print(softmaxFunction(valores))
Python
UTF-8
1,272
3.140625
3
[]
no_license
import getpass from function.dict import readText from function.make_tree import makeTree from function.convert_binary import convertBinary import sys # most names are self explanatory # the convertBinary means function to convert the Tree into encoded form def Createfile(Dictionary,cw): # create the file in encoded form and save it in binary folder tempFilename = input("Enter Filename : ") tempPassword = getpass.getpass("Enter password : ") if(tempFilename not in Dictionary.keys()): listOfFrequency,location = readText(tempFilename,cw) Tree = makeTree(listOfFrequency) # print(sys.getsizeof(Tree)) filename = convertBinary(Tree,location,cw) tempLocation = location tempBinary = filename Dictionary.update({tempFilename:[tempPassword,tempLocation,tempBinary]}) else: print("Name already exist : ") print("Want to over write? : ") n = input("Yes/No : ") if(n == 'Yes' or n == 'yes' or n == 'YES'): listOfFrequency,location = readText(tempFilename,cw) Tree = makeTree(listOfFrequency) print(sys.getsizeof(Tree)) filename = convertBinary(Tree,location,cw) tempLocation = location tempBinary = filename Dictionary[tempFilename] = [tempPassword,tempLocation,tempBinary] else: sys.exit() return Dictionary
Python
UTF-8
648
3.8125
4
[]
no_license
#coding=utf-8 from itertools import imap,ifilter,groupby rlt = imap(pow, [1, 2, 3], [1, 2, 3]) for num in rlt: print(num) test2 = ifilter(lambda x: x > 5, [2, 3, 5, 6, 7]) #将lambda函数依次作用于每个元素,如果函数返回True,则收集原来的元素。6, 7。 for test1 in test2: print test1 def height_class(h): if h > 180: return "tall" elif h < 160: return "short" else: return "middle" friends = [191, 158, 159, 165, 170, 177, 181, 182, 190] friends = sorted(friends, key = height_class) for m, n in groupby(friends, key = height_class): print(m) print(list(n))
C#
UTF-8
2,212
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using PrjCrudEF.Models; namespace PrjCrudEF.Controllers { public class CategoryController : Controller { NorthwindEntities db = new NorthwindEntities(); // GET: Category public ActionResult Index() { return View(); } //1 fetching data from categories table public ActionResult GetCategoryDetails() { List<Category> cate = db.Categories.ToList(); return View(cate); } //with scaffolding //2 fetching data from categories table public ActionResult GetCategoryDetailsScaffold() { List<Category> cate = db.Categories.ToList(); return View(cate); } //Adding new category deatils [HttpGet] public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Category category) { db.Categories.Add(category); db.SaveChanges(); return RedirectToAction("GetCategoryDetailsScaffold"); } //deleting-no need view for delete public ActionResult Delete(int id) { Category category= db.Categories.Find(id); db.Categories.Remove(category); db.SaveChanges(); return RedirectToAction("GetCategoryDetailsScaffold"); } //display details #region Display public ActionResult Details(int id) { Category category = db.Categories.Find(id); return View(category); } #endregion //edit public ActionResult Edit(int id) { Category category = db.Categories.Find(id); return View(category); } [HttpPost] public ActionResult Edit(Category c) { Category category = db.Categories.Find(c.CategoryID); category.CategoryName = c.CategoryName; category.Description = c.Description; category.Picture = c.Picture; db.SaveChanges(); return RedirectToAction("GetCategoryDetailsScaffold"); } public ActionResult GetCategorybyname() { //query syntax //display the category in ascending order List<string> c = (from cat in db.Categories orderby cat.CategoryName select cat.CategoryName).ToList(); //method sybtac //dynamic c1=db.Categories.OrderBy(ca=> ca.CategoryName.ToList(); return View(c); } } }
Java
UTF-8
3,695
3.5
4
[]
no_license
package DFS; /** * Created by yyt on 2018/1/20. */ public class SudokuSolver { public SudokuSolver() { } public void solveSudoku(char[][] board) { int N = board.length; // 行 boolean[][] used1 = new boolean[N][N]; // 列 boolean[][] used2 = new boolean[N][N]; // 小方格是哪个 boolean[][] used3 = new boolean[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // 首先确定是在第几个小方格。 int k = (i / 3) * 3 + j / 3; if (board[i][j] != '.') { int nums = board[i][j] - '1'; used1[i][nums] = true; used2[j][nums] = true; used3[k][nums] = true; } } } boolean res = DFS( board, 0, 0, used1, used2, used3 ); } private boolean DFS(char[][] board, int x, int y, boolean[][] used1, boolean[][] used2, boolean[][] used3) { int N = board.length; int grid = x / 3 * 3 + y / 3; if (board[x][y] == '.') { for (int k = 0; k < N; k++) { board[x][y] = (char) ('1' + k); if (isValidBoard( board, used1, used2, used3, x, y, k )) { // 要验证下个点的时候,要将x y 的点验证一下 if (x == 8 && y == 8) // 这是最后一个点,如果成功了,说明这个就是解了 return true; else if (x == 8) { // 如果成功了, if (DFS( board, 0, y + 1, used1, used2, used3 )) return true; } else { if (DFS( board, x + 1, y, used1, used2, used3 )) return true; } used1[x][k] = false; used2[y][k] = false; used3[grid][k] = false; } } board[x][y] = '.'; } else { if (x == 8 && y == 8) // 这是最后一个点,如果成功了,说明这个就是解了 return true; else if (x == 8) { // 如果成功了, if (DFS( board, 0, y + 1, used1, used2, used3 )) return true; } else { if (DFS( board, x + 1, y, used1, used2, used3 )) return true; } } return false; } private boolean isValidBoard(char[][] board, boolean[][] used1, boolean[][] used2, boolean[][] used3, int x, int y, int val) { int grid = x / 3 * 3 + y / 3; if (used1[x][val] || used2[y][val] || used3[grid][val]) return false; used1[x][val] = true; used2[y][val] = true; used3[grid][val] = true; return true; } public static void main(String[] args) { SudokuSolver s = new SudokuSolver(); char[][] board = {{'.', '.', '9', '7', '4', '8', '.', '.', '.'}, {'7', '.', '.', '.', '.', '.', '.', '.', '.'}, {'.', '2', '.', '1', '.', '9', '.', '.', '.'}, {'.', '.', '7', '.', '.', '.', '2', '4', '.'}, {'.', '6', '4', '.', '1', '.', '5', '9', '.'}, {'.', '9', '8', '.', '.', '.', '3', '.', '.'}, {'.', '.', '.', '8', '.', '3', '.', '2', '.'}, {'.', '.', '.', '.', '.', '.', '.', '.', '6'}, {'.', '.', '.', '2', '7', '5', '9', '.', '.'}}; s.solveSudoku( board ); } }
Java
UTF-8
1,693
1.9375
2
[]
no_license
package controller; import org.apache.log4j.Logger; import org.dmg.pmml.mining.MiningModel; import org.jpmml.evaluator.ModelEvaluator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.xml.sax.SAXException; import service.FraudulentTransferLearning; import javax.annotation.PostConstruct; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.Map; @Controller public class FraudulentTransferController { private static Logger logger = Logger.getLogger(FraudulentTransferController.class); @Autowired FraudulentTransferLearning fraudulentTransferLearning; ModelEvaluator<MiningModel> modelEvaluator; @PostConstruct public void init() { try { modelEvaluator = fraudulentTransferLearning.initPmml(); } catch (IOException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } @RequestMapping(value = "/compute", method = RequestMethod.POST) public ResponseEntity<Map> test(@RequestBody Integer idTransferDetails) { Map result = fraudulentTransferLearning.evaluate(modelEvaluator, idTransferDetails.intValue()); logger.info(result); return new ResponseEntity(result,HttpStatus.OK); } }
C++
UTF-8
3,920
3.125
3
[]
no_license
#include <iostream> #include <fstream> #include <filesystem> const char* msg = "usage:\n -c <dir> ... compile directory\n -d <PAK file> ... decompile PAK file\n -l <PAK file> ... list contents of a PAK file\n"; void readBlock(std::ifstream& pakFile, int index, std::string& sfname, size_t* fOffset, size_t* fSize) { pakFile.seekg(index * (sizeof(char) * 255 + sizeof(size_t) * 2) + sizeof(char) * 2 + sizeof(size_t)); // skip magic numbers, header size and blocks before index char fname[255]; pakFile.read(fname, sizeof(char) * 255); pakFile.read((char*)fOffset, sizeof(size_t)); pakFile.read((char*)fSize, sizeof(size_t)); sfname = fname; } void writeNextBlock(std::ofstream& pakFile, std::string& sfname, size_t fOffset, size_t fSize) { char fname[255]; memcpy(fname, sfname.c_str(), sfname.length()); fname[sfname.length()] = 0; // 0-terminate the string to eliminate any funny business pakFile.write(fname, 255); pakFile.write((char*)&fOffset, sizeof(size_t)); pakFile.write((char*)&fSize, sizeof(size_t)); } void compile(std::string dir) { try { std::ofstream pakFile("out.PAK", std::ios::binary); // add magic numbers // https://en.wikipedia.org/wiki/Magic_number_(programming) pakFile.write("AB", sizeof(char) * 2); // write content index header size size_t hSize = std::distance(std::filesystem::directory_iterator(dir), std::filesystem::directory_iterator{}); hSize *= 255 + sizeof(size_t) * 2; pakFile.write((char*)&hSize, sizeof(size_t)); // create content index header size_t offset = hSize + sizeof(size_t) + sizeof(char) * 2; for (const auto& file : std::filesystem::directory_iterator(dir)) { std::string path = file.path().string(); std::string sfname = path.substr(path.find_last_of("/\\") + 1); writeNextBlock(pakFile, sfname, offset, file.file_size()); offset += file.file_size(); } // paste data for (const auto& file : std::filesystem::directory_iterator(dir)) { std::ifstream dataFile(file.path(), std::ios::binary); char* data = (char*)malloc(file.file_size()); dataFile.read(data, file.file_size()); pakFile.write(data, file.file_size()); free(data); } pakFile.close(); } catch (std::filesystem::filesystem_error e) { std::cout << "directory \"" << dir << "\" not found\n"; exit(-1); } } void decompile(std::string pakPath) { std::filesystem::remove_all("out"); std::filesystem::create_directory("out"); std::ifstream pakFile(pakPath, std::ios::binary); // check for validity char magic[3]; pakFile.read(magic, 2); magic[2] = 0; std::string smagic = magic; if (smagic != "AB") { std::cout << "PAK file not valid\n"; exit(-1); } size_t hSize; pakFile.read((char*)&hSize, sizeof(size_t)); for (int i = 0; i < hSize / (255 + sizeof(size_t) * 2); i++) { std::string sfname; size_t fOffset, fSize; readBlock(pakFile, i, sfname, &fOffset, &fSize); std::ofstream outFile("out/" + sfname, std::ios::binary); pakFile.seekg(fOffset); char* data = (char*)malloc(fSize); pakFile.read(data, fSize); outFile.write(data, fSize); free(data); outFile.close(); } } void list(std::string pakPath) { std::ifstream pakFile(pakPath, std::ios::binary); // check for validity char magic[3]; pakFile.read(magic, 2); magic[2] = 0; std::string smagic = magic; if (smagic != "AB") { std::cout << "PAK file not valid\n"; exit(-1); } size_t hSize; pakFile.read((char*)&hSize, sizeof(size_t)); for (int i = 0; i < hSize / (255 + sizeof(size_t) * 2); i++) { std::string sfname; size_t fOffset, fSize; readBlock(pakFile, i, sfname, &fOffset, &fSize); std::cout << sfname << "\n"; } pakFile.close(); } int main(int argc, char* argv[]) { if (argc != 3) { std::cout << msg; return -1; } switch (argv[1][1]) { case 'c': compile(argv[2]); break; case 'd': decompile(argv[2]); break; case 'l': list(argv[2]); break; } return 0; }
Markdown
UTF-8
7,073
2.6875
3
[]
no_license
# CTO说:怎么成为并做好CTO - 喜欢打酱油的老鸟 - CSDN博客 2018年11月12日 08:04:23[喜欢打酱油的老鸟](https://me.csdn.net/weixin_42137700)阅读数:145标签:[CTO ](https://so.csdn.net/so/search/s.do?q=CTO&t=blog)个人分类:[管理 ](https://blog.csdn.net/weixin_42137700/article/category/8322955) CTO 可能是大多数开发者心中的梦想,但这些问题: 到底什么样的人适合做 CTO ? CTO 要做哪些事情? CTO 持有公司多少股权合适? 恐怕多数开发者都搞不清楚……包括我自己,也是五迷三道! 直到我看了下面这本书: ![640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1](https://ss.csdn.net/p?http://mmbiz.qpic.cn/mmbiz_jpg/OPlIzFpHNaXCfpkHDWAYzYdro4B1oAGAJ7o8KwCCsGxqYDYTpnb4wYbgSnHEOQIjZFzaaZhIcOpGEG6zErbpNA/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1) 这本《CTO说》,汇聚了 30 余位 CTO 导师(360副总裁、知乎CTO、京东商城总架构师等等)的经验,可以让我们习得 CTO 成长的道与术。 全书共分六篇: CTO的大格局 创业平台CTO的面面观 CTO的管理之道 CTO的第一把刷子——技术架构 CTO与CXO的相处之道 向CEO的华丽转身 大家可以根据自己的喜好,随意翻开某位大咖的文章,看看他讲的东西是否对自己的胃口。 接下来我简单介绍下我翻过此书几篇文章后印象深刻的几点: CTO 的能力模型 CTO 要做的事情 如何评价一个 CTO CTO 的股权课 程序员走向 CTO 的常见路径 ▼ CTO 的能力模型 很难说一个 CTO 必须具备什么能力,因为公司对 CTO 的要求,和公司所处的阶段有关。比如一家初创公司刚刚成立,只有两三杆枪,可能 CTO 最重要的能力是开发能力和工程实践能力。而如果一个已经有了数百人的研发团队的公司,对 CTO 的要求可能就完全不同了。 一个优秀的 CTO ,要具备下列能力: 目标规划与管理 技术架构能力 业务理解力 产品能力 团队管理 项目管理 协作沟通 决断力 执行力 人才吸引力 创新能力 注意,真实的 CTO 可能只具备上述能力清单中的某几项能力,这和公司的背景以及所处阶段有关。不过大部分企业都会要求 CTO 可以管理团队,所以,如果一个人缺乏与人沟通的欲望和团队管理的能力,很难胜任 CTO 的工作。 ▼ CTO 要做的事情 简单讲 CTO 要做的事情分为三大类: 团队建设与管理。让团队有好的发展,让队伍能力越来越强,让每个人都能获得成长。 搞定技术,保证公司的技术竞争力,满足公司对技术的期望。这是 CTO 的本质,老板把你招进来,就是要解决技术问题。你的工作的核心,就是公司的技术问题。首先要解决公司当前的技术需求,然后要具备技术前瞻性,要从技术发展的角度,保证所采用的的技术可以不断变迁,适应公司发展。 实现业务目标,支撑或引领业务发展。技术服务于业务,业务目标是 CTO 的最终目标,搞定技术的目的,是为了支撑或引领业务发展。所以 CTO 一定要懂业务,你关注的点要和公司的经营目标有交集。 根据公司所处阶段的不同, 每一类事情的边界也不同。 比如公司刚刚开始,只有 CTO 和 CEO 两个人,CTO 的主要事情,是先解决有没有的问题,是通过技术来验证创业想法。你可以自己撸代码,使用开源产品,也可以使用外包。这个时候团队管理、技术竞争力,都不重要。 比如公司经过两三年的功能开发,产品功能和用户都有明显增长,这时候,可能就要根据功能拆分团队,保证每个重要的功能都能正常迭代。 CTO 在这个时候,不但要做好团队管理、项目管理、协作沟通等等事情,还要能够理解业务,带领技术团队支撑业务目标的实现。 ▼ 如何评价一个CTO CTO 的首要目标,应该是公司的业务(商业)目标,所以,要评价一个 CTO ,就要从技术对业务的贡献出发。 如果一个 CTO 能够带领技术团队,保障公司当前业务稳定运行,就算及格。 进一步,如果 CTO 能够带领技术团队,打造出支持业务创新的架构和平台,可算胜任。 再进一步,如果一个 CTO 能够做到技术创新,进而引领业务升级,那就可以算是优秀啦。 ▼ CTO 的股权课 这部分内容来自星瀚资本创始合伙人杨歌。 首先是一个常见的问题:CTO 应该拿多少股份? 如果这个 CTO 是单纯的服务于技术,通常 10%~20% 是一个合理区间,如果他同时服务于技术和运营,所占股份甚至可以高达 50% 。 但这是理论,现实是,很多不懂技术的 CEO 或投资人觉得技术不会对市场产生太大的影响,在早期愿意给 CTO 释放的股份在 10% 左右。 除此之外,如果某个 CTO 拿到了绝对化的、差异化的专利或优势,那可能会拿到 20% ~ 25% 的股份。 再来看看股权和期权的差别。 公司给某个人分配股权,指的是给你公司的股份,你能享有相应权益。简单讲,你拿到一部分股权,就可以按市价折换成钱(有的会有锁定期,过了锁定期才能出售)。 期权,需要满足一定条件才能转化为股权,比如在公司工作满三年、达成某个业绩目标等。 如果你拿到的是期权,还要注意行权价格。如果你进入公司,给你的行权价格就是当时估值,那说明公司没什么诚意。行权价格应该远低于公司当前的估值!我在某家公司时曾被承诺过一定份额的期权,行权价格在估值的 1/3 左右。(不过我连期权都没拿到就离开了……) 这部分还谈到股权代持的坑和员工持股计划(ESOP)。ESOP 又有直接授予、期权、股权成熟三种形式。股权成熟往往也有坑。 ▼ 程序员走向 CTO 的常见路径 《CTO 说》一书中路面的 CTO 们,有相当一部分,都是从大公司的某个业务线出来,与人合伙创业或加入初创公司,成为了 CTO 。 比如豌豆公主的 CTO 陈超,是在 360 工作了十年之后,加入豌豆公主的。 这种是一种常见的路径,前提是你能够在大公司做出成绩,被人认可。 还有一种路径,是你跟着一家公司从无到有,一路打怪升级,最终成为 CTO 。 不管哪种路径,都需要你能够在当下的组织或团队中成为头部,这样才能从一个头部走向另一个头部。 怎样成为头部呢? 建议好好阅读下《CTO说》中出场的那些 CTO 们的演讲实录,并仔细研究他们的履历,对照着挖掘,肯定会有启发。 --------------------- 作者:程序视界 来源:CSDN 原文:[https://blog.csdn.net/IMbRl71u7pt5X29rlEu7/article/details/79767065](https://blog.csdn.net/IMbRl71u7pt5X29rlEu7/article/details/79767065) 版权声明:本文为博主原创文章,转载请附上博文链接!
Python
UTF-8
676
3.71875
4
[ "MIT" ]
permissive
__author__ = 'Devesh Bajpai' ''' https://codeforces.com/problemset/problem/703/A Solution: Nothing fancy. Just run the loop over the games and count the rounds won by Mishka and Chris. Return the result accordingly. ''' def solve(games): mishka = chris = 0 for game in games: if game[0] > game[1]: mishka += 1 elif game[0] < game[1]: chris += 1 return "Friendship is magic!^^" if mishka == chris else "Mishka" if mishka > chris else "Chris" if __name__ == "__main__": n = int(raw_input()) games = list() for _ in xrange(0, n): games.append(map(int, raw_input().split(" "))) print solve(games)
Markdown
UTF-8
5,323
2.984375
3
[]
no_license
# Xml Node Converts XML to and from JS node tree. ### Source XML ```xml <root><image src="image.jpg"/><content>Text <image src="image2.jpg"/> <![CDATA[&#xad;]]></content></root> ``` ### As a JS Node ```javascript var Parser = require("xml-node").XmlParser; Parser.toNode(srcxml, function(err, node){ var content = node.getChild("root").getChild("content"); // Get text from node, returns: "Text &#xad;" console.log(content.toString()); // Get an attribute of a node, returns: "image2.jpg" console.log(content.getChild("image").getAttribute("src")); }); ``` ### Raw Object ```json { "value": [ { "name": "root", "value": [ { "name": "image", "attributes": { "src": "image.jpg" } }, { "name": "content", "value": [ { "text": "Text " } { "name": "image", "attributes": { "src": "image2.jpg" }}, { "cdata": "&#xad;" } ]}, ]} ]} ``` ## Parser Converts among XmlNode / XmlNode object / XML. ```js var Parser = require("xml-node").XmlParser; ``` ### Parser.toNode(input, [options], callback]) Converts an XML or a raw object into a node. ### Parser.toXml(input, [options], callback) Converts a raw object or node into an XML string ### Parser.toObject(input, [options], callback) Converts an XML or a node into a raw object ## Node ### Creating a node ```js var name = "foo", attr: { bar: "baz" }, parent = new XmlNode(); // Empty node; // argument "attributes" and "parent" are optional var node = new XmlNode(name, attr, parent); var nodeFromObject = new XmlNode({ name: name, attributes: attr }); parent.getChild("foo").addChild(nodeFromObject); console.log(parent.toXml()) //<foo bar="baz"><foo bar="baz"/></foo> ``` ### addInstruction(name, body) ### addComment(comment, [index]) ### addCData(cdata, [index]) ### addText(text, [index]) * `text`: string ### addChild(child, [index]) Adds a child to the current node. The child must not be the node itself. * `child`: a raw object, an instance of `XmlNode`, or the name of the new node. ### getChild(query) * `query`: either `string`, `number`, or `object` * `string`: Name of the child node. Remove the first child with same node name * `number`: Index of the child node. Remove the child at the indicated index * `object`: Remove the child with the same property: `node.removeChild({name: "foo", attributes: { bar: "baz" }})` removes the child of `node` which has the name `foo` and attribute `bar` equaling to `baz` ### removeChild(query) Removes the first child node found using query * `query`: same as `getChild()` ### insert(node, [before]) Inserts the node as the next sibling of the current node. * `node`: either raw object or an instance of `XmlNode` * `before`: `boolean` * insert as the previous sibling the current node instead of the next. ### delete() Removes the current node from the node tree. ### isEmpty() Tell if the current node is an empty node. ### isRoot() Tell if the current node is the root node. ### isLeaf() Tell if the current node is a leaf node, i.e. no descendants. ### getIndex() Gets the index of the current node among the children of the parent node. ### getAttributes() Get all attributes of the current node. ### getAttribute(name) Gets an attribute of the current node. * `name`: `string` ### setAttribute(name, attribute) Sets an attribute to the current node. * `name`: `string` * `attribute`: `string` ### removeAttribute(name) Removes an attribute from the current node. * `name`: `string` ### getChildren(query) Gets the children of the current node. * `query`: `function`, `number` or `object` ### getAncestors(query) * Gets all ancestors matching the query, all ancestors if there's no query. * `query`: `string`, `function`, or `object` ### getDescendants(query) Gets all the descendants of the current node according to the query * `query`: `string`, `function`, or `object` ### getPrevious() Gets the previous sibling of the current node. ### getNext() Gets the next sibling of the current node. ### getParent() Gets the parent of the current node. ### getRoot() Gets the root node of the node tree ### getPath() Gets the path of the current node from the root node - `.`: Indicates the root node - `-`: Indicates an empty node - child nodes are in the form of `{index}:{name}[i]` or `{index}:#{type}`, - `index` is the index of the node among its siblings. - `name` is the name of the node - `i` is the index of the node with the same name among its siblings. - `#{type}` is type of the node, either `#text`, `#cdata`, or `#comment`. - E.g. `5:node[2]` means the 5th node is a `node` node, and the 3rd `node` node. ## getName() Gets the name of the current node. ### toString() Returns a string of all text content of the current node and its descendants. ### toObject() Converts the node to a raw object. ### toXml(options) Converts the whole node tree to an XML string. * `options`: `object`, Xml Build / End Options. More info at https://github.com/oozcitak/xmlbuilder-js * `escapeText`: Escape the text values when transforming. ### toXmlFragment(options) Converts the node tree with the current node as the root to an XML fragment string. * `options`: `object`, Xml Build / End Options. More info at https://github.com/oozcitak/xmlbuilder-js * `escapeText`: Escape the text values when transforming.
Shell
UTF-8
1,800
3.109375
3
[]
no_license
#!/bin/bash echo '>> installing dos2unix' sudo apt install -y dos2unix echo '>> dos2unix installed.' dos2unix ~/CLionProjects/OperatingSystemWHW/HW2/arch/x86/entry/syscalls/syscall_64.tbl dos2unix ~/CLionProjects/OperatingSystemWHW/HW2/include/linux/init_task.h dos2unix ~/CLionProjects/OperatingSystemWHW/HW2/include/linux/sched.h dos2unix ~/CLionProjects/OperatingSystemWHW/HW2/include/linux/syscalls.h dos2unix ~/CLionProjects/OperatingSystemWHW/HW2/kernel/Makefile dos2unix ~/CLionProjects/OperatingSystemWHW/HW2/kernel/hw2.c echo '>> finished unixing all source files' cd ~/linux-4.15.18-custom/ pwd echo '' echo '>> copying source files from clion folder to custom kernel folder:' cp ~/CLionProjects/OperatingSystemWHW/HW2/arch/x86/entry/syscalls/syscall_64.tbl ~/linux-4.15.18-custom/arch/x86/entry/syscalls/syscall_64.tbl cp ~/CLionProjects/OperatingSystemWHW/HW2/include/linux/init_task.h ~/linux-4.15.18-custom/include/linux/init_task.h cp ~/CLionProjects/OperatingSystemWHW/HW2/include/linux/sched.h ~/linux-4.15.18-custom/include/linux/sched.h cp ~/CLionProjects/OperatingSystemWHW/HW2/include/linux/syscalls.h ~/linux-4.15.18-custom/include/linux/syscalls.h cp ~/CLionProjects/OperatingSystemWHW/HW2/kernel/Makefile ~/linux-4.15.18-custom/kernel/Makefile cp ~/CLionProjects/OperatingSystemWHW/HW2/kernel/hw2.c ~/linux-4.15.18-custom/kernel/hw2.c echo '>> done.' echo '' echo '>> remaking the kernel source code:' echo '' echo '>> cleaning:' make clean echo '>> done.' echo '' echo '>> compiling kernel:' make -j $(nproc) echo '>> done.' echo '' echo '>> installing modules:' sudo make modules_install echo '>> done.' echo '' echo '>> installing new kernel:' sudo make install echo '>> done.' echo '' echo '>> remaking: done. now just execute: sudo reboot and pray.' echo ''
C++
GB18030
7,896
2.734375
3
[]
no_license
#include "StdAfx.h" #include "CurlInterface.h" #include "stdafx.h" #include <iostream> #include <sstream> //json using namespace std; HWND CCurlInterface::parentHwnd = NULL; wstring CCurlInterface::AsciiToUnicode(const string& str) { // Ԥ-пֽڵij int unicodeLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0); // ָ򻺳ָڴ wchar_t *pUnicode = (wchar_t*)malloc(sizeof(wchar_t)*unicodeLen); // ʼ򻺳תֽ MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pUnicode, unicodeLen); wstring ret_str = pUnicode; free(pUnicode); return ret_str; } string CCurlInterface::UnicodeToUtf8(const wstring& wstr) { // Ԥ-жֽڵij int ansiiLen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr); // ָ򻺳ָڴ char *pAssii = (char*)malloc(sizeof(char)*ansiiLen); // ʼ򻺳תֽ WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, pAssii, ansiiLen, nullptr, nullptr); string ret_str = pAssii; free(pAssii); return ret_str; } string CCurlInterface::AsciiToUtf8(const string& str) { return UnicodeToUtf8(AsciiToUnicode(str)); } //ص size_t CCurlInterface::write_data(void *ptr, size_t size, size_t nmemb, void *stream) { string data((const char*) ptr, (size_t) size * nmemb); *((stringstream*) stream) << data << endl; return size * nmemb; } int CCurlInterface::postData( const string& strUrl, string &strResponse, const string* strHeader, const string* data) { m_Option = CURLOPT_POST; return httpRequest( strUrl, strResponse, strHeader, data); } CCurlInterface::CCurlInterface() { m_Option = CURLOPT_POST; } int CCurlInterface::httpRequest( const string& strUrl, string &strResponse, const string* strHeader, const string* data) { CURL *curl = curl_easy_init(); CURLcode res; std::stringstream out;//HTTPͷ struct curl_slist* headers = NULL; if(curl) { string jsonout; if (data) { jsonout = AsciiToUtf8(*data); } //http͵ΪJSON //HTTPͷ headers = curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8"); if(strHeader){ headers = curl_slist_append(headers, (*strHeader).c_str()); } //url curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); if(m_Option==CURLOPT_POST){ curl_easy_setopt(curl, m_Option, 1); } // ҪPOSTJSON curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); // if want to use https curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false); // set peer and host verify false curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonout.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, jsonout.size());//ϴjson,ÿԺ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &CCurlInterface::write_data);//ûص curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);//д res = curl_easy_perform(curl);//ִ curl_slist_free_all(headers); /* free the list again */ strResponse = out.str();//ֵ auto Pos = strResponse.find('{'); auto LastPos = strResponse.rfind('}'); if (Pos!=-1&&LastPos!=-1) { strResponse = strResponse.substr(Pos, LastPos-Pos+1); } /* always cleanup */ curl_easy_cleanup(curl); } return 0; } static size_t write_file(void *ptr, size_t size, size_t nmemb, void *stream) { size_t written = fwrite(ptr, size, nmemb, (FILE *)stream); return written; } int CCurlInterface::ProgressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow) { if ( dltotal > -0.1 && dltotal < 0.1 ) return 0; int nPos = (int) ( (dlnow/dltotal)*100 ); //֪ͨؽ ::PostMessage(parentHwnd, WM_DOWNLOAD, nPos, 0); return 0; } int CCurlInterface::fileDownload(const string& fileName, HWND hwnd) { CCurlInterface::parentHwnd = hwnd; auto filePath = common::GetFilePath(fileName); common::CreateDir(common::stringToCString(filePath)); CURL* curl = curl_easy_init(); FILE *pagefile = fopen(filePath.c_str(),"wb"); do { CURLcode res = curl_easy_setopt(curl, CURLOPT_URL, (ServerUrl+"/dnf/upgrade/download").c_str()); if (res != CURLE_OK) { break; } struct curl_slist* headers = NULL; headers = curl_slist_append(headers, (string("filename:")+fileName).c_str()); res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); if (res != CURLE_OK) { break; } curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); // if want to use https curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false); // set peer and host verify false // ض res = curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5); if (res != CURLE_OK) { break; } // 301302תlocation res = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); if (res != CURLE_OK) { break; } res = curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0); if (res != CURLE_OK) { break; } //ýȻص res = curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, ProgressCallback); if (res != CURLE_OK) { break; } //ʼִ res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_file); if (res != CURLE_OK) { break; } curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_HEADER, 0);//ȥheader curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10); // set transport and time out time curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30); if (pagefile) { /* write the page body to this file handle */ res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, pagefile); if (res != CURLE_OK) { break; } /* get it! */ res = curl_easy_perform(curl); //鿴ǷгϢ const char* pError = curl_easy_strerror(res); if(res != CURLE_OK){ LOG_DEBUG<<pError; } /* close the header file */ fclose(pagefile); } } while (false); //curlǰijʼƥ if(pagefile){ fclose(pagefile); } curl_easy_cleanup(curl); return 0; } int CCurlInterface::getData( const string& strUrl, string &strResponse, const string* strHeader, const string* data) { CURL *curl = curl_easy_init(); // res code CURLcode res; if (curl) { // set params std::stringstream out;//HTTPͷ struct curl_slist* headers = NULL; if(strHeader){ headers = curl_slist_append(headers, (*strHeader).c_str()); } //url curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str()); // url curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); // if want to use https curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false); // set peer and host verify false curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &CCurlInterface::write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_HEADER, 1); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3); // set transport and time out time curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3); // start req res = curl_easy_perform(curl); strResponse = out.str();//ֵ auto Pos = strResponse.find('{'); auto LastPos = strResponse.rfind('}'); if (Pos!=-1&&LastPos!=-1) { strResponse = strResponse.substr(Pos, LastPos-Pos+1); } curl_easy_cleanup(curl); } return res; }
C#
UTF-8
1,417
3.71875
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LeetCodeTests.Tests { class A0045Jump { //给定一个非负整数数组,你最初位于数组的第一个位置。 //数组中的每个元素代表你在该位置可以跳跃的最大长度。 //你的目标是使用最少的跳跃次数到达数组的最后一个位置。 //示例: //输入: [2,3,1,1,4] //输出: 2 //解释: 跳到最后一个位置的最小跳跃数是 2。 // 从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。 //说明: //假设你总是可以到达数组的最后一个位置。 public int Jump(int[] nums) { int far = 0; int last = 0; int step = 0; for (int i = 0; i < nums.Length; i++) { if (i > last) { step++; last = far; } if (i + nums[i] > far) far = i + nums[i]; } return step; } public void Test() { int[] input = { 2, 3, 1, 1, 4 }; int result = Jump(input); Console.WriteLine(result); Console.ReadLine(); } } }
Markdown
UTF-8
1,023
2.625
3
[]
no_license
--- title: "Blockchain, A New Socio-Technical Environment (OpenAccess Book)" date: 2020-06-01T18:43:53+01:00 --- Book published!!! Blockchain is widely considered a new key technology. This study examines how blockchain became mainstream and provides the much-needed social contextualisation of blockchain. It explores the origins of blockchain in the early history of information technology and computer networks. The study also reveals the impact blockchain has on industrial and public spaces. Finally, it discusses the social implications and challenges of blockchain against the background of a new socio-technical environment. You can read the book on [https://socio-technical.github.io/blockchain-book/](https://socio-technical.github.io/blockchain-book/) This study was comissioned by TA-Swiss and was originaly published in [Blockchain: Capabilities, Economic Viability, and the Socio-Technical Environment](https://vdf.ch/blockchain-capabilities-economic-viability-and-the-socio-technical-environment.html).
PHP
UTF-8
248
2.515625
3
[]
no_license
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Pdf { function load($param = []) { $param['tempDir'] = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'mpdf'; return new \Mpdf\Mpdf($param); } }
JavaScript
UTF-8
2,649
2.8125
3
[]
no_license
import React, {Component} from 'react' import * as BooksAPI from './BooksAPI' import {Link} from 'react-router-dom' import ListBooks from './ListBooks'; class SearchBook extends Component { state = { query: '', books: [], invalidQuery: false, } /**FilteredBooks holds the final list of books that are to be shown in the search results */ filteredBooks = []; booksInShelfAndQuery = [] /** * Filter books that are already present in one of the 3 shelves from the books array. * Add those books with appropriate shelf name and set the state */ filterResults = (books) =>{ this.booksInShelfAndQuery = []; let bookPresent = false; BooksAPI.getAll().then((booksInShelf)=> { this.filteredBooks = books.filter((book)=>{ bookPresent = false; booksInShelf.map(bookShelf => { if(bookShelf.id === book.id){ bookPresent = true; this.booksInShelfAndQuery.push(bookShelf); } }) if(bookPresent) return false return true }) this.filteredBooks = this.booksInShelfAndQuery.concat(this.filteredBooks); this.setState({ books: this.filteredBooks, invalidQuery: false }) }); } updateQuery = (query) => { this.setState ({ query: query }); BooksAPI.search(query).then((books) => { if(!books){ this.setState({ query: '', books: [] }) } //Happens when few pieces of data are missing(Eg: missing thumbnail images for books) else if(books.error){ this.setState({ invalidQuery: true }) } else { this.filterResults(books); } }) } changeShelf = (book,newShelf) => { BooksAPI.update(book,newShelf).then(()=>{ this.updateQuery(this.state.query) }); } render () { return ( <div className="search-books"> <div className="search-books-bar"> <Link className="close-search" to="/">Close</Link> <div className="search-books-input-wrapper"> <input type="text" placeholder="Search by title or author" value={this.state.query} onChange={(event) => this.updateQuery(event.target.value)} /> </div> </div> {!this.state.invalidQuery && ( <div className="search-books-results"> <ol className="books-grid"> <ListBooks books={this.state.books} changeShelf={this.changeShelf} /> </ol> </div> )} {this.state.invalidQuery && ( <div className="search-books-results"> <div className="no-results-found"> <p className="error-line"> No results found <span>:(</span> </p> <p>We couldn't find any book matching your search</p> </div> </div> )} </div> )} } export default SearchBook
Python
UTF-8
2,082
2.8125
3
[]
no_license
''' Code made for getting the livestream data and getting it to work with Matlab. Currently works by just printing out the data!! ''' ## imports import time import socket import threading import signal import sys ## variables timeout = 1.0 running = True GLASSES_IP = "fe80::76fe:48ff:fe19:fbaf" # IPv6 address scope global PORT = 49152 # Keep-alive message content used to request live data and live video streams KA_DATA_STR = "{\"type\": \"live.data.unicast\", \"key\": \"some_GUID\", \"op\": \"start\"}" KA_DATA_MSG = KA_DATA_STR.encode() #need to encode it to work with python 3.6 #KA_VIDEO_STR = "{\"type\": \"live.video.unicast\", \"key\": \"some_other_GUID\", \"op\": \"start\"}" #KA_VIDEO_MSG = KA_VIDEO_STR.encode() ## Functions # Create UDP socket def mksock(peer): iptype = socket.AF_INET if ':' in peer[0]: iptype = socket.AF_INET6 return socket.socket(iptype, socket.SOCK_DGRAM) # Callback function def send_keepalive_msg(socket, msg, peer): while running: #print("Sending " + msg + " to target " + peer[0] + " socket no: " + str(socket.fileno()) + "\n") socket.sendto(msg, peer) time.sleep(timeout) def signal_handler(signal, frame): stop_sending_msg() sys.exit(0) def stop_sending_msg(): global running running = False # Need to put in a way to double check that it is pulling data for the required time (hopefully not as it doesnt seem like its lossfull or laggy? if __name__ == "__main__": signal.signal(signal.SIGINT, signal_handler) peer = (GLASSES_IP, PORT) # Create socket which will send a keep alive message for the live data stream data_socket = mksock(peer) data_socket.bind(('',PORT)) # Need this bind to get python to work with Windows td = threading.Timer(0, send_keepalive_msg, [data_socket, KA_DATA_MSG, peer]) td.start() # Create socket which will send a keep alive message for the live video stream #video_socket = mksock(peer) #tv = threading.Timer(0, send_keepalive_msg, [video_socket, KA_VIDEO_MSG, peer]) #tv.start() running = False
Markdown
UTF-8
805
3.03125
3
[]
no_license
# Polar [Demo](https://stefk.github.io/polar/) ![Screenshot](https://raw.githubusercontent.com/stefk/polar/master/public/screenshot.png) This app allows you to draw the graph of a function of a single real variable in both cartesian and [polar coordinates](https://en.wikipedia.org/wiki/Polar_coordinate_system). It's mostly built for recreational purposes, though rendering polar and cartesian graphs side-by-side offers some insight into the behaviour of a function and lets you explore directly the mapping between typical polar figures such as roses or spirals and their regular cartesian counterparts. If you're interested in a webgl-based version of this app, focusing on [parametric](https://en.wikipedia.org/wiki/Parametric_equation) graphs, see [this](https://github.com/stefk/parametric).
Java
UTF-8
23,431
2.875
3
[ "Zlib" ]
permissive
import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Scanner; public class Estatisque { public static void main(String[] args) throws IOException { Scanner tc = new Scanner(System.in); int quantDados, testeModa = 0; double media = 0.0, modaQtd = 1, modaNum = 0; double mediana, mediana1, mediana2; double amplitude = 0, dp = 0, variancia = 0; //data Calendar data = Calendar.getInstance(); //horario SimpleDateFormat formato = new SimpleDateFormat("HH:mm:ss"); Date hora = Calendar.getInstance().getTime(); int op = 0, op2 = 0; int a, b, c, d, l, f, g, h; do{ a = 0; b = 0; c = 0; d = 0; l = 0; f = 0; g = 0; h = 0; System.out.println("Digite o titulo: "); String titulo = tc.nextLine(); System.out.println(""); System.out.println("Deseja fazer o calculo sobre quantos dados? "); // limite 50 quantDados = tc.nextInt(); while(quantDados > 50 || quantDados <= 1){ System.out.println("\n" + "O limite de dados permitidos é 50, digite um valor abaixo ou igual a 50!"); // limite 50 quantDados = tc.nextInt(); } double dados[] = new double[quantDados]; mediana1 = dados[(dados.length/2)-1]; mediana2 = dados[dados.length/2]; mediana = mediana1 + mediana2; int vetorModa1[] = {}; double vetorNum1[] = {}; double vetorModa2[] = {}; double vetorNum2[] = {}; System.out.println(""); for (int cont = 0; cont < dados.length; cont++) { System.out.println("Valor do dado "+ (cont + 1) +": "); dados[cont] = tc.nextDouble(); System.out.println(""); } do{ System.out.println("\nDeseja fazer o que com esses dados? \n" + "1- Media \n" + "2- Moda \n" + "3- Mediana \n" + "4- Frequencia Absoluta \n" + "5- Frequencia Relativa \n" + "6- Amplitude \n" + "7- Desvio Padrão \n" + "8- Variancia \n" + "0- Sair"); op = tc.nextInt(); System.out.println(""); switch(op){ case 1:{ a++; double numeros = 0; for(int cont = 0; cont < dados.length; cont++){ numeros += dados[cont]; media = numeros/dados.length; } System.out.println("A media é: "+ media); break; } case 2:{ b++; //ordenação do vetor double aux; for (int cont1 = 0; cont1 < dados.length; cont1++) { for (int cont2 = 0; cont2 < dados.length; cont2++) { if (dados[cont1] < dados[cont2]) { aux = dados[cont1]; dados[cont1] = dados[cont2]; dados[cont2] = aux; } } } // descobrindo a moda int vetorModa[] = new int[dados.length]; double vetorNum[] = new double[dados.length]; double numTeste; int contTeste; int numRepetido; for (int cont1 = 0; cont1 < dados.length; cont1++) { numRepetido = 0; contTeste = 0; numTeste = dados[cont1]; for(int cont3 = 0; cont3<dados.length; cont3++) { if(numRepetido != 1){ if(numTeste == vetorNum[cont3]){ numRepetido = 1; } } else cont3 = dados.length -1; } if(numRepetido != 1) { for (int cont2 = 0; cont2 < dados.length; cont2++) { if(numTeste == dados[cont2]) { contTeste += 1; } } vetorModa[cont1] = contTeste; vetorNum[cont1] = numTeste; } } for(int cont4 = 0; cont4<vetorModa.length; cont4++){ if(vetorModa[cont4] > modaQtd) { modaQtd = vetorModa[cont4]; modaNum = vetorNum[cont4]; testeModa = 1; } } if(testeModa == 1) // result moda { System.out.println("Moda: "+ modaNum); System.out.println("Quatidade de repetições: "+ modaQtd ); } else { System.out.println("Dados amodais"); } break; } case 3:{ c++; double aux; for (int cont1 = 0; cont1 < dados.length; cont1++) { for (int cont2 = 0; cont2 < dados.length; cont2++) { if (dados[cont1] < dados[cont2]) { aux = dados[cont1]; dados[cont1] = dados[cont2]; dados[cont2] = aux; } } } if(dados.length % 2 == 0){ mediana = (dados[(dados.length/2)]) + (dados[(dados.length/2)]-1); System.out.println("Mediana: "+mediana/2); } else if (dados.length % 2 == 1){ mediana = dados[(dados.length/2)]; System.out.println("Mediana: "+mediana); } break; } case 4:{ d++; //ordenação do vetor double aux; for (int cont1 = 0; cont1 < dados.length; cont1++) { for (int cont2 = 0; cont2 < dados.length; cont2++) { if (dados[cont1] < dados[cont2]) { aux = dados[cont1]; dados[cont1] = dados[cont2]; dados[cont2] = aux; } } } // descobrindo a moda vetorModa1 = new int[dados.length]; vetorNum1 = new double[dados.length]; double numTeste; int contTeste; int numRepetido; for (int cont1 = 0; cont1 < dados.length; cont1++) { numRepetido = 0; contTeste = 0; numTeste = dados[cont1]; for(int cont3 = 0; cont3<dados.length; cont3++) { if(numRepetido != 1){ if(numTeste == vetorNum1[cont3]){ numRepetido = 1; } } else cont3 = dados.length -1; } if(numRepetido != 1) { for (int cont2 = 0; cont2 < dados.length; cont2++) { if(numTeste == dados[cont2]) { contTeste += 1; } } vetorModa1[cont1] = contTeste; vetorNum1[cont1] = numTeste; System.out.println("Dado: " + vetorNum1[cont1]); System.out.println("Frequencia Absoluta: " + vetorModa1[cont1]); } } break; } case 5:{ l++; //ordenação do vetor double aux; for (int cont1 = 0; cont1 < dados.length; cont1++) { for (int cont2 = 0; cont2 < dados.length; cont2++) { if (dados[cont1] < dados[cont2]) { aux = dados[cont1]; dados[cont1] = dados[cont2]; dados[cont2] = aux; } } } // descobrindo a moda vetorModa2 = new double[dados.length]; vetorNum2 = new double[dados.length]; double numTeste; int contTeste; int numRepetido; for (int cont1 = 0; cont1 < dados.length; cont1++) { numRepetido = 0; contTeste = 0; numTeste = dados[cont1]; for(int cont3 = 0; cont3<dados.length; cont3++) { if(numRepetido != 1){ if(numTeste == vetorNum2[cont3]){ numRepetido = 1; } } else cont3 = dados.length -1; } if(numRepetido != 1) { for (int cont2 = 0; cont2 < dados.length; cont2++) { if(numTeste == dados[cont2]) { contTeste += 1; } } vetorModa2[cont1] = contTeste; vetorNum2[cont1] = numTeste; System.out.println("Dado: " + vetorNum2[cont1]); System.out.println("Frequencia Relativa: " + (vetorModa2[cont1]*100)/dados.length+"%"); } } break; } case 6:{ f++; double aux; for (int cont1 = 0; cont1 < dados.length; cont1++) { for (int cont2 = 0; cont2 < dados.length; cont2++) { if (dados[cont1] < dados[cont2]) { aux = dados[cont1]; dados[cont1] = dados[cont2]; dados[cont2] = aux; } } } double menor = dados[0]; double maior = dados[(dados.length)-1]; amplitude = maior - menor; System.out.println("Amplitude: "+ amplitude); break; } case 7:{ g++; double numeros = 0; for(int cont=0; cont<dados.length; cont++){ numeros += dados[cont]; } double media2 = numeros/dados.length; double x = 0.0; for(int cont=0; cont<dados.length; cont++){ x += Math.pow((dados[cont] - media2), 2); } dp = Math.sqrt((x)/dados.length); System.out.println("Desvio padrão: "+ dp); break; } case 8:{ h++; double numeros = 0; for(int cont=0; cont < dados.length; cont++){ numeros += dados[cont]; } double media2 = numeros / dados.length; variancia = 0.0; for(int cont=0; cont<dados.length; cont++){ variancia += Math.pow((dados[cont] - media2), 2); } variancia = variancia/dados.length; System.out.println("Variancia: "+ variancia); break; } } }while(op != 0); System.out.println("Deseja salvar? \n" + "1- Sim \n" + "2- Não"); int salvar = tc.nextInt(); tc.nextLine(); if(salvar == 1){ FileWriter fw = new FileWriter("C:\\relatorio.txt", true); PrintWriter pw = new PrintWriter(fw); pw.printf("----------------------------------- \n"); pw.printf(formato.format(hora) +" - "+ data.get(Calendar.DAY_OF_MONTH)+"/"+(data.get(Calendar.MONTH)+1)+"/"+data.get(Calendar.YEAR)+ "\n"); pw.printf("----------------------------------- \n"); pw.printf(titulo +"\n\n"); pw.printf("Dados = {"); for(int i = 0; i < dados.length; i++){ pw.printf(dados[i] +", "); } pw.printf("}\n\n"); // media if(a > 0){ pw.printf(String.valueOf("A média (Me) é calculada somando-se todos os valores de um conjunto de dados e dividindo-se pelo número de elementos deste conjunto.\n")); pw.printf(String.valueOf("A formula da média é Me = Soma de termos / nº de termos \n")); pw.printf(String.valueOf("Logo a media dos dados apresentados é: "+ media +"\n\n")); } // moda if(b > 0){ pw.printf("A Moda (Mo) representa o valor mais frequente de um conjunto de dados, sendo assim, para defini-la basta observar a frequência com que os valores aparecem. \n"); if(testeModa == 1) { pw.printf("Logo a moda dos dados apresentados é: "+ modaNum + "\n"); pw.printf("Quatidade de repetições: "+ modaQtd +"\n\n"); } else { pw.printf("A moda dos dados apresentados é: Dados amodais \n\n"); } } // mediana if(c > 0){ if(dados.length % 2 == 0){ pw.printf("A Mediana (Md) representa o valor central de um conjunto de dados. Para encontrar o valor da mediana é necessário colocar os valores em ordem crescente ou decrescente.\n"); pw.printf("Logo a mediana dos dados apresentados é: "+ mediana/2 +"\n\n"); } else if (dados.length % 2 == 1){ pw.printf("A Mediana (Md) representa o valor central de um conjunto de dados. Para encontrar o valor da mediana é necessário colocar os valores em ordem crescente ou decrescente.\n"); pw.printf("Logo a mediana dos dados apresentados é: "+ mediana +"\n\n"); } } // FA if(d > 0){ pw.printf("A frequência absoluta corresponde à quantidade de ocorrências de um mesmo resultado \n"); for(int cont1 = 0; cont1 < dados.length; cont1++){ pw.printf("O dado apresentado foi: "+ String.valueOf(vetorNum1[cont1]) +"\n"); pw.printf("A frequencia absoluta desse dado apresentado é: "+ String.valueOf(vetorModa1[cont1]) +"\n\n"); } } // FR if(l > 0){ pw.printf("Em estatística denomina-se frequência relativa o resultado obtido da divisão entre a frequência absoluta - o valor que é observado na população - e a quantidade de elementos da amostra. Geralmente é apresentada na forma de porcentagem. \n"); for(int cont1 = 0; cont1 < dados.length; cont1++){ if(vetorNum2[cont1] != 0){ pw.printf("O dado apresentado foi: "+ String.valueOf(vetorNum2[cont1]) +"\n"); pw.printf("A frequencia relativa desse dado apresentado é: " + String.valueOf((vetorModa2[cont1]*100)/dados.length)+"%%\n\n");; } } } // ampli if(f > 0){ pw.printf(String.valueOf("Em um conjunto de informações numéricas, a primeira medida de tendência central é chamada amplitude e é obtida a partir da diferença entre a maior informação da lista e a menor\n")); pw.printf(String.valueOf("Amplitude: "+ amplitude +"\n\n")); } // desvio p if(g > 0){ pw.printf(String.valueOf("O desvio padrão é uma medida que indica a dispersão dos dados dentro de uma amostra com relação à média (se o dado está desviado muito acima da media ou muito abaixo). \n")); pw.printf(String.valueOf("O desvio padrão dos dados apresentados é: "+ dp +"\n\n")); } // variancia if(h > 0){ pw.printf(String.valueOf("variância é uma medida de dispersão que mostra o quão distante cada valor desse conjunto está do valor central (quanto o dado esta acima da media ou abaixo). \n")); pw.printf(String.valueOf("A variancia dos dados apresentado é: "+ variancia +"\n\n")); } try { Runtime.getRuntime().exec("explorer C:\\relatorio.txt"); } catch (Exception e) { } pw.printf("\n\n\n"); pw.close(); } System.out.println("\nDeseja fazer o calculo sobre outros dados? \n" + "0- Nao \n" + "1- Sim "); op2 = tc.nextInt(); System.out.println(""); tc.nextLine(); }while(op2 != 0); } }
C++
UTF-8
801
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int cont = 0, a = 0, total = 0; void solution(string &s, int idx, int acom) { if(idx == s.size()) { cont++; if(acom == total) { a++; } return; } if(s[idx] != '?') { if(s[idx] == '+') solution(s, idx+1, acom+1); else solution(s, idx+1, acom-1); } else { solution(s, idx+1, acom+1); solution(s, idx+1, acom-1); } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); string s1, s2; cin >> s1 >> s2; for(char i: s1) { if(i == '+') total++; else total--; } solution(s2, 0, 0); cout << fixed << setprecision(11) << (long double) a/cont << '\n'; return 0; }
Go
UTF-8
1,888
3.09375
3
[ "BSD-3-Clause" ]
permissive
package mods import ( "encoding/json" "errors" "strings" ) type Redirects []*Redirection func (rs Redirects) Copy() Redirects { c := make(Redirects, len(rs)) for i := 0; i < len(rs); i++ { c[i] = rs[i].Copy() } return c } // Redirection is the representation of a go-get redirect that should be // observed by a requesting entity (e.g. the Go compiler). type Redirection struct { Kind string `json:"kind"` // i.e. cmds or pkgs Namespace string `json:"namespace"` // e.g. foo/bar/baz VCS string `json:"vcs"` // i.e. git, https, hg Destination string `json:"destination"` // e.g. github.com/foo/bar } var ( ErrMissingKind = errors.New("kind field must not be empty") ErrMissingNamespace = errors.New("namespace field must not be empty") ErrMissingVCS = errors.New("vcs field must not be empty") ErrMissingDestination = errors.New("destination field must not be empty") ErrMissingProtocol = errors.New("protocol in destination is required") ) func Valid(r *Redirection) error { if r.Kind == "" { return ErrMissingKind } if r.Namespace == "" { return ErrMissingNamespace } if r.VCS == "" { return ErrMissingVCS } if r.Destination == "" { return ErrMissingDestination } if !strings.Contains(r.Destination, "://") { return ErrMissingProtocol } return nil } func (r *Redirection) String() string { return r.Destination } func Key(kind, module string) []byte { return []byte(strings.Join([]string{ kind, module, }, ",")) } func (r *Redirection) Key() []byte { return Key(r.Kind, r.Namespace) } func (r *Redirection) Bytes() []byte { bs, err := json.Marshal(r) if err != nil { panic(err) } return bs } func (r *Redirection) Copy() *Redirection { return &Redirection{ Kind: r.Kind, Namespace: r.Namespace, VCS: r.VCS, Destination: r.Destination, } }
C#
UTF-8
2,234
3.3125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProblemC { class program { public static bool Judge(long number) { string s = number.ToString(); bool flag = true; for (int i = 0; i < s.Length; i++) if (s[i] != s[s.Length - i - 1]) { flag = false; break; } return flag; } public static void Main() { List<long> numbers = new List<long>(); List<string> numroot = new List<string>(); long range = 10000000; for (long i = 1; i < range; i++) { long t = i; if (Judge(t)) { long sum = t * t; if (Judge(sum)) { numbers.Add(sum); double root = Math.Sqrt((double)sum); long aa = (long)root; numroot.Add(aa + "*" + aa + "=" + sum); } } } funcs.WriteLongs(@"numbers.txt", numbers); funcs.WriteLines(@"roots.txt", numroot); //List<string> lines = funcs.getInputDocs2("input.txt"); List<string> lines = funcs.getInputDocs2("C-large-1.in"); int sample = int.Parse(lines[0]); int count = 1; List<string> outlines = new List<string>(); for (int i = 0; i < sample; i++) { string[] words = lines[count].Split(' '); count++; long A = long.Parse(words[0]); long B = long.Parse(words[1]); int curnum = 0; for (int j = 0; j < numbers.Count; j++) if ((numbers[j] >= A) && (numbers[j] <= B)) curnum++; string outline = "Case #" + (i + 1).ToString() + ": " + curnum; outlines.Add(outline); } funcs.WriteLines(@"output_mid.txt", outlines); } } }
Java
UTF-8
436
1.734375
2
[]
no_license
package com.eurodyn.qlack.fuse.lexicon.repository; import com.eurodyn.qlack.common.repository.QlackBaseRepository; import com.eurodyn.qlack.fuse.lexicon.model.Language; import java.util.List; import org.springframework.stereotype.Repository; @Repository public interface LanguageRepository extends QlackBaseRepository<Language, String> { Language findByLocale(String locale); List<Language> findByActiveTrueOrderByNameAsc(); }
PHP
UTF-8
1,041
2.609375
3
[ "Apache-2.0" ]
permissive
<?php namespace app\admin\model; use think\Model; class Cart extends Model { //获取所有的数据 public static function GetAll() { $result = Cart::order('id', 'desc')->paginate(15); return $result; } //接口数据 public static function GetAllApi() { $result = Cart::all(); return $result; } /** * 查找用户的单个数据 */ public static function GetOne($id) { $result = Cart::find($id); return $result; } //执行添加 public static function AddData($data) { $Cart = New Cart; $result = $Cart->save($data); return $result; } //执行修改 public static function UpdateData($id,$data) { $Cart = New Cart; $result = $Cart->save($data,['id'=>$id]); return $result; } //执行删除 public static function DeleteData($id) { $result = Cart::destroy($id); return $result; } }
C
UTF-8
534
3.25
3
[]
no_license
#include <stdio.h> #include <math.h> int main(){ double x1,x2,x3,y1,y2,y3; double l1,l2,l3; double p; scanf("%lf %lf %lf %lf %lf %lf\n",&x1,&y1,&x2,&y2,&x3,&y3); l1 = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); l2 = sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3)); l3 = sqrt((x3-x2)*(x3-x2)+(y3-y2)*(y3-y2)); if((l1+l2) >l3 && (l2+l3)>l1 && (l1+l3)>l2){ p=(l1+l2+l3)/2; printf("L = %.2f, A = %.2f",l1+l2+l3,sqrt(p*(p-l1)*(p-l2)*(p-l3))); }else{ printf("Impossible"); } return 0; }
C#
UTF-8
5,917
3.515625
4
[ "MIT" ]
permissive
using System; using System.Collections; /// <summary> /// Contains the program entry point for the Delegates Sample. /// </summary> class DelegatesSample { static void Main( string[] args ) { try { // Create a container to hold employees Employees employees = new Employees(4); // Create and drain our simulated message queue EmployeeQueueMonitor monitor = new EmployeeQueueMonitor( employees ); monitor.start(); monitor.stop(); // Display the employee list on screen Console.WriteLine( "List of employees added via delegate:" ); foreach ( Employee employee in employees ) { string name = employee.FirstName + " " + employee.MiddleName + " " + employee.LastName; string ssn = employee.SSN; Console.WriteLine( "Name: {0}, SSN: {1}", name, ssn ); } } catch ( Exception exception ) { // Display any errors on screen Console.WriteLine( exception.Message ); } } } /// <summary> /// Simulates our message queue. /// </summary> class EmployeeQueueMonitor { // Delegate signature public delegate void AddEventCallback( string FirstName, string LastName, string MiddleName, string SSN ); // Instance of the delegate private AddEventCallback m_addEventCallback; private Employees m_employees; private int m_lengthQueue; private string[, ] m_msgQueue = { {"Timothy", "Arthur", "Tucker", "555-55-5555"}, {"Sally", "Bess", "Jones", "666-66-6666" }, {"Jeff", "Michael", "Simms", "777-77-7777"}, {"Janice", "Anne", "Best", "888-88-8888" } }; public EmployeeQueueMonitor( Employees employees ) { m_employees = employees; m_lengthQueue = 4; // Create an instace of the delegate and register the // addEmployee method of this class as a callback. m_addEventCallback = new AddEventCallback( this.addEmployee ); } // Drain the queue. public void start() { if ( m_employees == null ) return; for ( int i = 0; i < m_lengthQueue; i++ ) { string FirstName = m_msgQueue[i,0]; string MiddleName = m_msgQueue[i,1]; string LastName = m_msgQueue[i,2]; string SSN = m_msgQueue[i,3]; // Invoke the callback registered with the delegate Console.WriteLine( "Invoking delegate" ); m_addEventCallback( FirstName, LastName, MiddleName, SSN ); } } public void stop() { // In a real communications program you would shut down // gracefully. } // Called by the delegate when a an message to add an employee // is read from the message queue. public void addEmployee( string FirstName, string MiddleName, string LastName, string SSN ) { Console.WriteLine( "In delegate, adding employee\r\n" ); int index = m_employees.Length; m_employees[index] = new Employee ( FirstName, MiddleName, LastName, SSN ); } } /// <summary> /// Container class for employees. This class implements /// IEnumerable allowing use of foreach sytax /// </summary> class Employees : IEnumerable { private ArrayList m_Employees; private int m_MaxEmployees; public Employees( int MaxEmployees ) { m_MaxEmployees = MaxEmployees; m_Employees = new ArrayList( MaxEmployees ); } // Here is the implementation of the indexer by array index public Employee this[int index] { get { // Check for out of bounds condition if ( index < 0 || index > m_Employees.Count - 1 ) return null; // Return employee based on index passed in return (Employee) m_Employees[index]; } set { // Check for out of bounds condition if ( index < 0 || index > m_MaxEmployees-1 ) return; // Add new employee m_Employees.Insert( index, value ); } } // Here is the implementation of the indexer by SSN public Employee this[string SSN] { get { Employee empReturned = null; foreach ( Employee employee in m_Employees ) { // Return employee based on index passed in if ( employee.SSN == SSN ) { empReturned = employee; break; } } return empReturned; } } // Return the total number of employees. public int Length { get { return m_Employees.Count; } } // IEnumerable implementation, delegates IEnumerator to // the ArrayList public IEnumerator GetEnumerator() { return m_Employees.GetEnumerator(); } } /// <summary> /// Represents a single employee /// </summary> class Employee { private string m_firstName; private string m_middleName; private string m_lastName; private string m_SSN; // Constructor public Employee( string FirstName, string LastName, string MiddleName, string SSN ) { m_firstName = FirstName; m_middleName = MiddleName; m_lastName = LastName; m_SSN = SSN; } // FirstName property public string FirstName { get { return m_firstName; } set { m_firstName = value; } } // MiddleName property public string MiddleName { get { return m_middleName; } set { m_middleName = value; } } // LastName property public string LastName { get { return m_lastName; } set { m_lastName = value; } } // SSN property public string SSN { get { return m_SSN; } set { m_SSN = value; } } }
Swift
UTF-8
1,416
2.625
3
[]
no_license
// // BitcoreTarget.swift // TangemKit // // Created by Alexander Osokin on 03.02.2020. // Copyright © 2020 Smart Cash AG. All rights reserved. // import Foundation import Moya enum BitcoreTarget: TargetType { case balance(address:String) case unspents(address:String) case send(txHex: String) var baseURL: URL { return URL(string: "https://ducapi.rocknblock.io/api/DUC/mainnet")! } var path: String { switch self { case .balance(let address): return "/address/\(address)/balance" case .unspents(let address): return "/address/\(address)/" case .send: return "tx/send" } } var method: Moya.Method { switch self { case .balance, .unspents: return .get case .send: return .post } } var sampleData: Data { return Data() } var task: Task { switch self { case .balance: return .requestPlain case .unspents: return .requestParameters(parameters: ["unspent": "true"], encoding: URLEncoding.default) case .send(let txHex): return .requestParameters(parameters: ["rawTx": [txHex]], encoding: JSONEncoding.default) } } public var headers: [String: String]? { return ["Content-Type": "application/json"] } }
Java
UTF-8
6,141
1.84375
2
[]
no_license
package org.measure.impl; import java.net.ConnectException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import com.modeliosoft.modelio.javadesigner.annotations.objid; import org.apache.thrift.transport.TTransport; import org.hawk.service.api.Hawk; import org.hawk.service.api.HawkInstance; import org.hawk.service.api.HawkQueryOptions; import org.hawk.service.api.QueryResult; import org.hawk.service.api.utils.APIUtils.ThriftProtocol; import org.hawk.service.api.utils.APIUtils; import org.measure.smm.measure.api.IMeasurement; import org.measure.smm.measure.defaultimpl.measures.DirectMeasure; @objid ("25ef30b0-403f-4ca9-8200-08e74a044c80") public class DirectMeasureImpl extends DirectMeasure { @objid ("3928000b-10ab-4da2-a259-d2c745859ff4") public static final String SCOPE_SERVERURL = "serverUrl"; @objid ("c34bbeba-863b-425d-8203-bf29d13e50ca") public static final String SCOPE_INSTANCENAME = "instanceName"; @objid ("a285f76b-5e00-4efa-8616-c253951b2fc1") public static final String SCOPE_REPOSITORY = "repository"; @objid ("16c6c842-024c-4708-9683-c031d258f1c0") private Hawk.Client client; @objid ("9272ea6f-dcf1-4db5-9d5f-f64e9bda2886") private ThriftProtocol clientProtocol; @objid ("0bc0f6dc-3bfe-4f9c-abb5-65040372553c") private String currentInstance; @objid ("73c60f13-28b2-443f-aa16-b3b29159bbe3") private String defaultNamespaces; @objid ("30833c6d-164d-4767-9998-1dbc11ad67c9") private String serverUrl; @objid ("844f9a02-d06e-412b-ad8e-e0e3b65a55d4") private String instanceName; @objid ("9c5730d6-157d-4182-a637-dfd1ff5466cb") private String query; /** * (optional) The repository for the query (or * for all repositories). */ @objid ("37835612-bb6a-4fa3-99b0-ce95a4f50efb") private String repository; @objid ("93975517-5a83-441b-a82d-00970a9bc04a") @Override public List<IMeasurement> getMeasurement() throws Exception { List<IMeasurement> result = new ArrayList<IMeasurement>(); try { // retrieve Properties initProperties(); // check query is valid if (query == null || query.isEmpty()) { // throw exception throw new Exception("No Query is specified"); } // connect to server if not connected connect(serverUrl, "", ""); // select instance if not selected selectInstance(instanceName); try { // Execute query QueryResult qResult = executeQuery(); IntegerMeasurement res = new IntegerMeasurement(); res.setValue(qResult.getVInteger()); result.add(res); } catch (Exception e) { e.printStackTrace(); } // disconnect disconnect(); } catch (Throwable e) { throw new Exception("Error during Measure Execution : " + e.getMessage(), e); } return result; } @objid ("146096c0-ffe0-4d26-9cd4-c38f883f562f") protected void initProperties() { this.serverUrl = getProperty(SCOPE_SERVERURL); this.instanceName = getProperty(SCOPE_INSTANCENAME); this.repository = getProperty(SCOPE_REPOSITORY); this.query ="return Note.all.select(n|'@Replicable'.isSubstringOf(n.Content)).size();"; } @objid ("1e9dfbe1-aeb8-4098-be30-364bf63fbf2f") protected void connect(String url, String username, String password) throws Exception { clientProtocol = ThriftProtocol.guessFromURL(url); if (client != null) { final TTransport transport = client.getInputProtocol().getTransport(); transport.close(); } client = APIUtils.connectTo(Hawk.Client.class, url, clientProtocol, "", ""); } @objid ("26691d6d-163c-4ae6-ad90-8fbbee4d52ae") protected void disconnect() throws Exception { if (client != null) { final TTransport transport = client.getInputProtocol().getTransport(); transport.close(); client = null; currentInstance = null; } } @objid ("2bcc6817-cce1-4735-8bd8-5eaa02134988") protected void selectInstance(String name) throws Exception { checkConnected(); findInstance(name); currentInstance = name; } @objid ("ef1a06ce-df2f-4724-b4e0-1ab5593cd248") protected QueryResult executeQuery() throws Exception { checkInstanceSelected(); HawkQueryOptions opts = new HawkQueryOptions(); opts.setDefaultNamespaces(this.defaultNamespaces); opts.setFilePatterns(new ArrayList<String>()); opts.setRepositoryPattern(repository); opts.setIncludeAttributes(true); opts.setIncludeReferences(true); opts.setIncludeNodeIDs(false); opts.setIncludeContained(true); opts.setIncludeDerived(true); return client.query(currentInstance, query, "org.hawk.epsilon.emc.EOLQueryEngine", opts); } @objid ("910f380a-90a0-4b0c-85a8-403829d5deb4") private void checkConnected() throws ConnectException { if (client == null) { throw new ConnectException("Please connect to a Thrift endpoint first!"); } } @objid ("446b80a9-fd32-4c97-b7e2-924132db66b0") protected void checkInstanceSelected() throws ConnectException { checkConnected(); if (currentInstance == null) { throw new IllegalArgumentException("No Hawk instance has been selected"); } } @objid ("11a7ea94-7285-457f-b284-de4815a59e73") protected HawkInstance findInstance(final String name) throws Exception { for (HawkInstance i : client.listInstances()) { if (i.name.equals(name)) { return i; } } throw new NoSuchElementException(String.format("No instance exists with the name '%s'", name)); } }
Java
ISO-8859-1
986
3.828125
4
[]
no_license
import java.util.Scanner; /** * */ /** * @author usuario * */ public class StringsH1ej5 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // Leer una frase por teclado (mximo 80 car) y construir otras dos cadenas de forma que una contenga los caracteres en posicin par y la otra los caracteres // en posicin impar. String frase, par="", impar=""; Scanner teclado = new Scanner(System.in); do { System.out.println("introduce una frase:"); frase=teclado.nextLine(); } while ((frase.length() > 80) || (frase.length() == 0)); for (int i = 0; i < frase.length(); i++) { if ((i+1)%2==0) { par = par.concat(frase.substring(i, i+1)); } else { impar = impar.concat(frase.substring(i, i+1)); } } System.out.println("Los que se encuentran en una posicion par son " + par); System.out.println("Los que se encuentran en una posicion impar son " + impar); } }
JavaScript
UTF-8
1,404
2.609375
3
[]
no_license
import React from 'react'; import CreateTaskInput from './CreateTaskInput.jsx'; import { fetchTasksList, createNewTask, deleteTask, updateTask, } from './tasksGateway.js'; import Task from './Task.jsx'; class TasksList extends React.Component { state = { tasks: [], }; componentDidMount() { this.getTasksList(); } getTasksList = () => { fetchTasksList().then(tasks => this.setState({ tasks })); }; onDelete = id => { deleteTask(id).then(() => this.getTasksList()); }; createTask = text => { createNewTask({ text, done: false, }).then(() => this.getTasksList()); }; onCheckboxChange = id => { const task = this.state.tasks.find(task => task.id === id); const { done, text } = task; updateTask(id, { done: !done, text, }).then(() => this.getTasksList()); }; render() { const sortedTaskList = this.state.tasks .slice() .sort((a, b) => a.done - b.done); return ( <main className='todo-list'> <CreateTaskInput addTask={this.createTask} /> <ul className='list'> {sortedTaskList.map(task => ( <Task onCheckboxChange={this.onCheckboxChange} onDelete={this.onDelete} key={task.id} {...task} /> ))} </ul> </main> ); } } export default TasksList;
Markdown
UTF-8
15,105
3
3
[]
no_license
--- tags: - Docker - Compose - Advanced --- # Working with Docker >Docker, inc. is the name of the company Docker is a set of products that use OS-level virtualization to deploy software in packages called containers. The products provide a way for creating, customizing, and orchestrating containers on a network. One thing to chant in your mind as you read: A container is a standardized unit of software. There are two types of containers: Windows and Linux containers. Both are still actively developed and evolving rapidly. For more orchestration and management company examples see: https://landscape.cncf.io/ ### Background 2013 open source project called `dot cloud` became a hit. Docker is an open platform for developing, shipping, and running applications. It provides the ability to to package and run an application in an isolated environment. It enables you to separate your applications from your infrastructure so you can deliver software quickly. ## Docker Engine A client-server application with three major components. * A server, called `Docker daemon` or `dockerd`. * A REST API which programs can use to talk to the daemon to instruct it what to do * A command-line interface client (the `docker` command). ![Docker Engine](/resources/docker-daemon-visualization.png) ### Docker Objects Overview * `Images`: A template with instructions for creating a container. The binaries, libraries, and source code that make up the application. * `Containers`: A runnable instance of an image. * `Services`: Allow you to scale containers across multiple Docker daemons which all work together. A service allows you to define the desired state, such as the number of replicas of the service that must be available at any given time. ## Rundown This rundown assumes you have written a dockerfile that builds an image successfully. ### A quick note on Docker commands In the beginning days of docker containers could be managed with commands that look like this: ``` > docker <command> > docker run > docker stop > docker rm > ... ``` Now since there are so many new docker commands, it is preferred to use the management-style commands for readability. The old way is still supported. ``` > docker <entity> <command> > docker container logs > docker container exec > docker network ls > docker image rm > ... ``` ### What's in an Image The image contains the app binaries and dependencies as well as metadata about how to run the image. **It's not booting up a full OS.** That is one of the defining differences between a running image and a virutal machine. It is really just starting an application. There is no kernal and there are no kernal drivers. The kernal is actually provided by the host OS. The image can be as small as a single file or as large as multiple gigabytes. Images are designed using the union filesystem concept of "making layers about the changes". All images in the beginning start from a blank layer known as `SCRATCH`. Every set of changes that happens after that on the filesystem in the image is another layer. The output of the below command shows the layers contained within the image from the bottom-up. ``` docker image history nginx ``` To create an image, you can use `docker build ...` which is equivalent to ``` docker image build . -f Dockerfile ``` ### Working with Containers From the perspective of a running container, the underlying image it was started from is read-only. Any changes to a container are written to the writable container layer and will persist across stopping and starting. Once the container is destroyed, the data is destroyed. How do you get into the container once its started? SSH servers are not necessary. **Option 1** is to create an entirely new container with `docker run` and specify the `--tty` and `--interactive` options and specify an alternate command. The specified command will overwrite the `CMD` specified in the dockerfile. ``` docker container run -it --name test nginx bash ``` *Note: once you type `exit` the container stops because `CMD` was overwritten with `bash`* **Option 2** is to call `docker start` on a stopped container and specify the `--attach` and `--interactive` options. ``` docker container start nginx -ai ``` **Option 3** is used when you want to create a shell inside a container that is already running a program. ``` docker container exec -it nginx bash ``` ### Persistent Data Containers are meant to be temporary and disposable. What about the unique data your app produces? Ideally the applicaiton shouldn't produce data alongside the application binaries. **Separation of concerns**. You can use Volumes or Bind Mounts to keep the unique data elsewhere and redeploy changes to the container while keeping the data intact. * `Volumes` are a configuration option for a container that creates a special location outside of the container union filesystem to store unique data. Preserves the data across removals and allows attachment to any container you want. * `Bind Mounts` are a mapping of a host directory or file into a container. To tell a container it should use a **volume** you have three options. **Option 1** is to add a `VOLUME` command to the dockerfile, which tells docker when we start a container from this image to actually create a new volume location and assign it to this directory in the container. Any files you put in that location will outlive the container until the volume is deleted. ``` VOLUME /var/lib/mysql ``` *This creates a new unnamed volume every time a container is started.* **Option 2** is to specify a named volume in the `run` command. It allows you to specify a new volume, use an existing volume, ``` docker container run -d --name mysql -e MYSWL_ALLOW_EMPTY_PASSWORD=true -v mysql-db:/var/lib/mysql mysql ``` **Option 3** is to create a volume with the `docker volume create` command and attach it to the container later. This is really only used when you want to create a volume with a specific driver. To tell a container it should use a **bind mount** you must do it like this depending on the host: **Mac/Linux**: ``` docker container run ... -v /Users/reese/stuff:/path/container ``` **Windows** ``` docker container run ... -v //c/Users/reese/stuff:/path/container docker container run ... --mount type=bind,source=C:\temp,target=/builds ``` Basically just two locations pointing to the same file(s). Skips the union filesystem and host files overwrite any in the container. In the docker run command, you can use the keywords `$(pwd)` on linux or `${pwd}` on Windows on the left side of the `--volume` option ### Transferring containers and images If you need to migrate a container to a new machine you have a couple of options. The best option to use would depend on your end goal. In most situations, you have a container already running on machine A and would like to (1) move the container's data and associated image to machine B and (2) start the container again without losing any data. Your best bet in this scenario is to `commit` the changes in the container to an image, `save` the image to a tarball file, and `load` the image into docker on the new machine. The `save` command preserves the history, layers, and entrypoint so all you need to do is run the image once it is loaded. ``` PS C:\Users\kouey> docker run -d nginx f58edaad2a5a7b66af08d4c268a520063998312902d08b023c58e5651d48d579 PS C:\Users\kouey> docker exec -it f bash root@f58edaad2a5a:/# touch newfile.txt # add some container data PS C:\Users\kouey> docker commit f58 nginx-with-data sha256:1c93f0d5f515d509445b9708037495bdba3a4c348c1515b42dfce111b9efe037 PS C:\Users\kouey> docker save nginx-with-data -o c:\temp\nginx-bak PS C:\Users\kouey> docker container rm f58 -f; docker system prune -a -f PS C:\Users\kouey> docker load -i C:\temp\nginx-bak 488dfecc21b1: Loading layer [==================================================>] 72.48MB/72.48MB Loaded image: nginx-with-data:latest PS C:\Users\kouey> docker run -d --name new-nginx nginx-with-data a700cac31772381ce8b2848b076723bc8a8c66ff53398625f2d7c5cbd2788312 PS C:\Users\kouey> docker exec -it a700 ls bin dev home lib64 mnt opt root sbin sys usr boot etc lib media newfile.txt proc run srv tmp var PS C:\Users\kouey> docker container top new-nginx # PROOF PID USER TIME COMMAND 4736 root 0:00 nginx: master process nginx -g daemon off; 4781 101 0:00 nginx: worker process ``` The alternative is to `export` the running container to a tarball file and `import` it on the new machine. **Keep in mind that export flattens the image. It removes the history, layers, and entrypoint and just keeps the filesystem.** The `import` command imports the tarball **as an image**. To run a container based off the image you will need to exec in or specify a new entrypoint command. ``` > docker import c:\Users\kouey\Desktop\exported-nreese sha256:505a230f0382cddb0ebf1ac27b7fb26f12560febb2875a32f0a8377269388bbd > docker image ls -a REPOSITORY TAG IMAGE ID CREATED SIZE <none> <none> 505a230f0382 3 days ago 125MB nginx latest 2073e0bcb60e 12 days ago 127MB > docker run -d 505a230f0382 C:\Program Files\Docker\bin\docker.exe: Error response from daemon: No command specified. See 'C:\Program Files\Docker\bin\docker.exe run --help'. ``` This is particularly useful in situations where you just want to save the files on the system and have no interest in running the image as a container anymore. Export generates a smaller tarball file. ### Working with Networks You can't assume from minute to minute the ip addresses of the containers on Docker's private network to stay the same as containers are created and destroyed. That is why automatic DNS name resolution is a big deal. Virtual networks can be created like this: ``` docker network create my_app_net ``` **Note that automatic DNS name resolution is not available on the default bridge network without additional configuration.** That is why it is usually recommended to create your own network rather than use the default network, especially when deploying multiple containers that need to talk to each other. You can specify a network when creating a container: ``` docker container run -d --name nginx --network my_app_net nginx ``` Containers on the same network can find each other based on their hostnames (container names). Ping example: ``` > docker container exec -it openssh76 ping nginx PING nginx (172.18.0.2) 56(84) bytes of data. 64 bytes from nginx.my_app_net (172.18.0.2): icmp_seq=1 ttl=64 time=0.673 ms 64 bytes from nginx.my_app_net (172.18.0.2): icmp_seq=2 ttl=64 time=0.086 ms 64 bytes from nginx.my_app_net (172.18.0.2): icmp_seq=3 ttl=64 time=0.061 ms 64 bytes from nginx.my_app_net (172.18.0.2): icmp_seq=4 ttl=64 time=0.064 ms ^C > docker container exec -it nginx ping openssh76 PING openssh76 (172.18.0.3) 56(84) bytes of data. 64 bytes from openssh76.my_app_net (172.18.0.3): icmp_seq=1 ttl=64 time=0.069 ms 64 bytes from openssh76.my_app_net (172.18.0.3): icmp_seq=2 ttl=64 time=0.062 ms 64 bytes from openssh76.my_app_net (172.18.0.3): icmp_seq=3 ttl=64 time=0.119 ms ^C ``` Calling `docker network connect` effectively plugs in a NIC to the specified container. ## Docker Compose Configure relationships between containers! Why? Create one-liner development environment startups. Docker compose consists of two things: 1. YAML-formatted file that describes our solution options `docker-compose.yml` 2. A CLI tool `docker-compose` used for local dev/test automation Good for replacing scripts that call Docker `run`. With the beginning of v1.13 they can be used with `docker` directly with Swarm. A template for `docker-compose`: ```yml version: '3.1' # if no version is specificed then v1 is assumed. Recommend v2 minimum services: # containers. same as docker run servicename: # a friendly name. this is also DNS name inside network image: # Optional if you use build: command: # Optional, replace the default CMD specified by the image environment: # Optional, same as -e in docker run volumes: # Optional, same as -v in docker run servicename2: volumes: # Optional, same as docker volume create networks: # Optional, same as docker network create ``` Good for defining a multi-container service. Takes all the work out of creating `docker run` commands and simplifies your container startup scripts. You can even specify persistent data storage in a compose file. Many images on docker already have built-in support for databases by setting the appropriate configuration in environment variables. The below file is a good example: ```yml version: '2' services: wordpress: image: wordpress ports: - 8080:80 environment: WORDPRESS_DB_HOST: mysql WORDPRESS_DB_NAME: wordpress WORDPRESS_DB_USER: example WORDPRESS_DB_PASSWORD: examplePW volumes: - ./wordpress-data:/var/www/html # bindmount for live edits mysql: image: mariadb environment: MYSQL_ROOT_PASSWORD: examplerootPW MYSQL_DATABASE: wordpress MYSQL_USER: example MYSQL_PASSWORD: examplePW volumes: - mysql-data:/var/lib/mysql #volname:/path/on/container volumes: mysql-data: # definition ``` The `mysql` container stores the data we want to preserve in its `/var/lib/mysql` directory so we just specify **the name of a volume** and **a volume definition** to tell compose to create a volume for us. ### Image Building in a Compose File Another thing compose can do for you is build the images at runtime. It can optionally rebuild them every time but it uses the image cache by default. ```docker services: proxy: build: context: . dockerfile: nginx.Dockerfile image: nginx-custom ports: - '80:80' ``` In the above file, docker-compose will first look for an image called `nginx-custom` in the image cache and if it doesn't find it, it will use the `build:` options to create an image and name it `nginx-custom`. ### docker-compose CLI Compose comes with Docker for Windows but is a separate download for Linux. The two main commands that do everything are: * `docker compose up` sets up volumes/networks and starts all containers * `docker compose down` stops all containers and removes containers/volumes/networks. Volumes are not removed by default. You must specify the `--volume` option in `docker-compose down` to remove a volume. A lot of the commands you use in docker are available in docker-compose. For example, `-d` for detach, `logs` for logs, `--help`, etc. ### Developer onboarding just got easier If all your projects had a Dockerfile and a docker-compose.yml then "new developer onboarding" would be as simple as: ``` git clone github.com/some/repo docker-compose up ```
C++
UTF-8
1,503
3.109375
3
[]
no_license
/** * Title : HW3 * Author : Melike Demirci * ID: 21702346 * Section : 2 * Assignment : 3 * Description : simulator.cpp */ #if defined(M) #include "maxHeap1.h" #else #include "maxHeap2.h" #endif // defined #include <iostream> #include <fstream> using namespace std; void simulate( const string fileName, const int avrTime) { Patient* pArr; int id = 0; int pNum = 0; int arrTime = 0; int exTime = 0; int numP = 0; ifstream inFile; inFile.open((fileName).c_str()); if (!inFile) { cout << "Unable to open file"; } else{ inFile >> numP; pArr = new Patient[numP]; for (int i=0; i < numP; i ++){ inFile >> id; inFile >> pNum; inFile >> arrTime; inFile >> exTime; Patient p(id, pNum, arrTime, exTime); pArr[i] = p; } } maxHeap h1; //create maxHeap const int numDoc = h1.calcNumDoc(pArr,numP, avrTime); //calculate required number of doctors for given max avr waiting time if(numDoc == -1){ cout << "Error Occured" << endl; } else{ cout<<"Minimum number of doctors required: " << numDoc<< endl; h1.printSimulation(pArr, numP, numDoc);//print simulation result } delete [] pArr;//deallocation of pArr } int main(int argc, char* argv[]){ int avrTime = stoi(argv[2], 0, 10); simulate(argv[1], avrTime); return 0; }
Shell
UTF-8
767
3.96875
4
[ "MIT" ]
permissive
#!/bin/sh set -eu usage() { echo "Usage: $(basename $0) <initramfs file>" } if [ "$#" -eq 0 ] ; then usage >&2 exit 1 fi cpio_args="--extract --quiet --list" OPTIONS=`getopt -o hl --long help,long -n "$0" -- "$@"` # Check for non-GNU getopt if [ $? != 0 ] ; then echo "W: non-GNU getopt" >&2 ; exit 1 ; fi eval set -- "$OPTIONS" while true; do case "$1" in -h|--help) usage exit 0 ;; -l|--long) cpio_args="${cpio_args:+${cpio_args} --verbose}" shift ;; --) shift break ;; *) echo "Internal error!" >&2 exit 1 esac done for initramfs in "$@" ; do if ! [ -r "${initramfs}" ] ; then echo "Specified file could not be read." >&2 exit 1 else echo "${initramfs}" zcat "${initramfs}" | cpio ${cpio_args} fi done
TypeScript
UTF-8
837
2.703125
3
[]
no_license
Set fso=createobject("Scripting.FileSystemObject") 'Open the file "qtptest.txt" in writing mode. Set qfile=fso.OpenTextFile("C:\Documents and Settings\yogesh\Desktop\MyTest\temp\tempsub\tempfile.txt",2,True) 'write contents to the file into two newlines qfile.Writeline "Welcome to the World of QTP" 'will insert 4 new blank lines qfile.WriteBlankLines(2) qfile.Writeline "the file name is qtptest.txt" 'Open the file "qtptest.txt" in reading mode. Set qfile=fso.OpenTextFile("C:\Documents and Settings\yogesh\Desktop\MyTest\temp\tempsub\tempfile.txt",1,True) 'Read the entire contents of priously written file 'Do while qfile.AtEndOfStream <> true 'Output --> The file will be read file line by line. Msgbox qfile.ReadAll 'Loop 'Close the files qfile.Close 'Release the allocated objects Set qfile=nothing Set fso=nothing
Swift
UTF-8
440
3.140625
3
[]
no_license
https://leetcode.com/problems/top-k-frequent-elements/ class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: log_book = dict() for i in nums: if i in log_book: log_book[i] = log_book[i] + 1 else: log_book[i] = 1 sorted_keys = sorted(log_book, key=log_book.get, reverse=True) return sorted_keys[:k]
TypeScript
UTF-8
757
2.546875
3
[]
no_license
import { BaseByAttributeBinding } from "./base/BaseByAttributeBinding"; import { Property } from "../../reflection/Property"; import { Model } from "../../models/Model"; export class BaseFieldBinding extends BaseByAttributeBinding { get attribute(): string { return 'data-field'; } async binding(DOMObject: HTMLElement, model: Model): Promise<void> { let value = DOMObject.getAttribute(this.attribute); Property.redefine(model, value, (val) => val, (val) => { return val; }); var event = "#event:set[" + value + "]"; if (model[event]) { model[event].bind = () => { DOMObject.innerHTML = model[value]; }; } } }
Markdown
UTF-8
1,091
3.046875
3
[]
no_license
--- title: "注册(组建)公司" --- 通过组建公司,您将在英国设立一个被称为私人有限公司的独立法人实体。 [在英国注册(组建)私人有限公司](https://www.gov.uk/register-a-company-online)的过程很简单,所需时间通常不到24小时。 在英国注册(组建)私人有限公司之前,您需要: - 确定公司名称 - 确定用作公司注册地址的地址,可以是任何英国地址 - 至少有一位董事(董事不一定非得是英国居民) - 至少有一位股东(股东可以是公司或个人) 英国公司必须有公司组织大纲及章程(Memorandum and Articles of Association)。这些文件必须在组建时准备好。您可以在组建之日选择使用标准的公司组织大纲及章程,或者由专业顾问代表贵公司准备、提交定制的组织大纲及章程。 在英国开办公司时,虽然法律对董事或股东是否为英国居民不作要求,但很多银行在为贵公司开立英国公司银行账户时[IIGB LINK]希望董事或股东是英国居民。
Java
UTF-8
789
1.96875
2
[]
no_license
package com.guillenorway.eiv; import java.util.Arrays; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.guillenorway.eiv.edm.resources.PaisEdm; import com.sdl.odata.api.ODataException; import com.sdl.odata.api.edm.registry.ODataEdmRegistry; @Component public class EntityServiceRegistrar { public static final String NAME_SPACE = "com.guillenorway"; public static final String CONTAINER_NAME = "eiv"; @Autowired private ODataEdmRegistry oDataEdmRegistry = null; @PostConstruct public void registerEntities() throws ODataException { oDataEdmRegistry.registerClasses( Arrays.asList( PaisEdm.class ) ); } }
PHP
UTF-8
265
2.703125
3
[]
no_license
<?php declare(strict_types=1); namespace App\Exception; final class ItemNotFoundException extends \RuntimeException { public static function byItemName(string $itemName): self { return new self(sprintf('Item "%s" not found', $itemName)); } }
Markdown
UTF-8
2,031
2.609375
3
[ "MIT" ]
permissive
--- layout: post title: "Moving Vehicle Detection Using AdaBoost and Haar-Like Feature in Surveillance Videos" date: 2018-01-05 10:41:02 categories: arXiv_CV tags: arXiv_CV Tracking Detection author: Mohammad Mahdi Moghimi, Maryam Nayeri, Majid Pourahmadi, Mohammad Kazem Moghimi mathjax: true --- * content {:toc} ##### Abstract Vehicle detection is a technology which its aim is to locate and show the vehicle size in digital images. In this technology, vehicles are detected in presence of other things like trees and buildings. It has an important role in many computer vision applications such as vehicle tracking, analyzing the traffic scene and efficient traffic management. In this paper, vehicles detected based on the boosting technique by Viola Jones. Our proposed system is tested in some real scenes of surveillance videos with different light conditions. The experimental results show that the accuracy,completeness, and quality of the proposed vehicle detection method are better than the previous techniques (about 94%, 92%, and 87%, respectively). Thus, our proposed approach is robust and efficient to detect vehicles in surveillance videos and their applications. ##### Abstract (translated by Google) 车辆检测是一种技术,其目的是定位和显示数字图像的车辆大小。在这项技术中,车辆在树木和建筑物等其他物体的存在下被检测到。它在许多计算机视觉应用中起着重要的作用,如车辆跟踪,交通场景分析和高效的交通管理。在本文中,基于Viola Jones的助推技术检测车辆。我们提出的系统在不同光线条件下的监控视频真实场景中进行了测试。实验结果表明,所提出的车辆检测方法的准确性,完整性和质量优于先前的技术(分别为约94%,92%和87%)。因此,我们提出的方法在监视视频及其应用中检测车辆是稳健和高效的。 ##### URL [http://arxiv.org/abs/1801.01698](http://arxiv.org/abs/1801.01698) ##### PDF [http://arxiv.org/pdf/1801.01698](http://arxiv.org/pdf/1801.01698)
Markdown
UTF-8
600
2.703125
3
[]
no_license
# Updated-final This is a student portfolio based on me(Matthew To). It is designed to be responsive to the display of the viewer, to show information about me, my coding projects, as well as my contact info. ## Technologies Used github[href:"https://github.com/"] gitlab[href:"https://about.gitlab.com/"] git[href:"https://git-scm.com/"] CSS HTML VS Code[href:"https://git-scm.com/"] ## Credits Matthew To ## Working application <img src = "./screenshot.png"> ## Links github: [href:"https://github.com/MT722/Updated-Portfolio"] deployed site:[href:"https://mt722.github.io/Updated-Portfolio/"]
Java
UTF-8
2,384
3.484375
3
[]
no_license
import java.util.Scanner; import java.util.Random; public class rttta { public static void rttta() throws InterruptedException { Scanner input = new Scanner(System.in); System.out.println("Well, I have a couple different ideas in mind:"); System.out.println("The weather" + "\nFood" + "\nLet's play a game"); String userChoice; userChoice = input.nextLine(); if (userChoice.equalsIgnoreCase("The weather")) { System.out.println("How is the weather looking today? The weather is:" + "\nrainy" + "\nsunny" + "\ncloudy" + "\nfoggy"); userChoice = input.nextLine(); if (userChoice.equalsIgnoreCase("The weather is rainy")) { System.out.println("Oh dear, that's always a 50/50. Rain is cool and all, but I cannot stand in it " + "because I am a computer."); } else if (userChoice.equalsIgnoreCase("The weather is sunny")) { System.out.println("Sunny is always nice! It's nicer though that you're inside on such a beautiful day " + "talking to me!"); } else if (userChoice.equalsIgnoreCase("The weather is cloudy")) { System.out.println("I sure hope it doesn't rain! My circuits would get wet!"); } else if (userChoice.equalsIgnoreCase("The weather is foggy")) { System.out.println("Don't get lost out there! Maybe Akira Yamaoka can be your guide, he he."); } } else if (userChoice.equalsIgnoreCase("food")) { System.out.println("What kind of food do you enjoy?"); System.out.println("There is dry food, canned food, greasy food, and sweets (from what I have gathered.)"); userChoice = input.nextLine(); if (userChoice.equalsIgnoreCase("Dry food")) { System.out.println("This is animal food, silly!"); } } else if (userChoice.equalsIgnoreCase("Let's play a game")) { playGame(); } } private static void playGame() { games.games(); } }
Java
UTF-8
879
1.960938
2
[]
no_license
package com.yukai.test; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.yukai.beans.TestUser; import com.yukai.dao.TestUserMapper; import com.yukai.service.TestService; @Controller @RequestMapping("/test") public class TestController { //@Resource //private TestUserMapper testUserMapper; @Resource private TestService testsService; @RequestMapping("/testMethod") public String testMethod(Model model) { String msg="sdsa"; model.addAttribute("msg", msg); return "test"; } @RequestMapping("/insert") public String testInsert() { testsService.insertTest(); // TestUser user=TestUser.builder().name("asdahhh").build(); // testUserMapper.insertSelective(user); return "test"; } }
Java
UTF-8
536
1.773438
2
[]
no_license
package cfml.parsing.cfmentat.tag; import net.htmlparser.jericho.EndTagType; import net.htmlparser.jericho.ParseText; import net.htmlparser.jericho.Source; import net.htmlparser.jericho.StartTag; import net.htmlparser.jericho.StartTagTypeGenericImplementation; import net.htmlparser.jericho.Tag; final class cfargument extends GenericStartTagTypeCf { protected static final cfargument INSTANCE = new cfargument(); private cfargument() { super("CFML if tag", "<cfargument", ">", EndTagType.NORMAL, true, true, false); } }
TypeScript
UTF-8
1,198
3.3125
3
[]
no_license
/** Задача 2 * Необходимо реализовать асинхронную подгрузку модулей в браузере: * 1) Разнести классы SettingValue, Setting и Example по разным *.ts файлам * 2) После компиляции TypeScript должно получаться 3 файла формата *.js. * 3) Создать index.html, в котором необходимо указать ссылку на первый JavaScript файл, * все остальные файлы должны подгрузиться асинхронно по цепочке, используя requireJS. */ class SettingValue { public property1: string; public property2: string; constructor(p1: string, p2: string) { this.property1 = p1; this.property2 = p2; } } class Setting { public key: string; public value: SettingValue; constructor(k: string, ov: SettingValue) { this.key = k; this.value = ov; } } class Example { public title: string; public id: number; private _setting: Setting; constructor(s: Setting) { this._setting = s; } }
Java
UTF-8
9,791
1.710938
2
[ "BSD-2-Clause" ]
permissive
package org.mdpnp.devices.puritanbennett._840; import ice.ConnectionState; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.mdpnp.devices.serial.AbstractDelegatingSerialDevice; import org.mdpnp.devices.serial.SerialProvider; import org.mdpnp.devices.serial.SerialSocket.DataBits; import org.mdpnp.devices.serial.SerialSocket.FlowControl; import org.mdpnp.devices.serial.SerialSocket.Parity; import org.mdpnp.devices.serial.SerialSocket.StopBits; import org.mdpnp.devices.simulation.AbstractSimulatedDevice; import org.mdpnp.rtiapi.data.EventLoop; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DemoPB840 extends AbstractDelegatingSerialDevice<PB840> { private static final Logger log = LoggerFactory.getLogger(DemoPB840.class); private InstanceHolder<ice.SampleArray> flowSampleArray, pressureSampleArray; private class MyPB840Waveforms extends PB840Waveforms { public MyPB840Waveforms(InputStream input, OutputStream output) { super(input, output); } @Override public void receiveBreath(Collection<Number> flow, Collection<Number> pressure) { flowSampleArray = sampleArraySample(flowSampleArray, flow, rosetta.MDC_FLOW_AWAY.VALUE, 0, rosetta.MDC_DIM_L_PER_MIN.VALUE, 50, null); pressureSampleArray = sampleArraySample(pressureSampleArray, pressure, rosetta.MDC_PRESS_AWAY.VALUE, 0, rosetta.MDC_DIM_CM_H2O.VALUE, 50, null); } } public DemoPB840(int domainId, EventLoop eventLoop) { super(domainId, eventLoop, 2, PB840.class); AbstractSimulatedDevice.randomUDI(deviceIdentity); deviceIdentity.manufacturer = "Puritan Bennett"; deviceIdentity.model = "840"; writeDeviceIdentity(); } protected InstanceHolder<ice.Numeric> respRateSetting, respRate,exhaledTidalVolume; protected InstanceHolder<ice.AlarmSettings> inspPressure, exhaledMV, exhaledMandTidalVolume, exhaledSpontTidalVolume, respRateAlarm, inspiredTidalVolume; protected final List<InstanceHolder<ice.Numeric>> otherFields = new ArrayList<InstanceHolder<ice.Numeric>>(); private static final String[] fieldNames = new String[] { "PB_TIME", null, "PB_DATE", "PB_VENT_TYPE", "PB_MODE", "PB_MANDATORY_TYPE", "PB_SPONTANEOUS_TYPE", "PB_TRIGGER_TYPE", "PB_SETTING_RESP_RATE", "PB_SETTING_TIDAL_VOLUME", "PB_SETTING_PEAK_FLOW", "PB_SETTING_O2PCT", "PB_SETTING_PRESS_SENSITIVITY", "PB_SETTING_PEEP_CPAP", "PB_SETTING_PLATEAU", "PB_SETTING_APNEA_INTERVAL", "PB_SETTING_APNEA_TIDAL_VOLUME", "PB_SETTING_APNEA_RESPIRATORY_RATE", "PB_SETTING_APNEA_PEAK_FLOW", "PB_SETTING_APNEA_O2PCT", "PB_SETTING_PCV_APNEA_INSP_PRESSURE", "PB_SETTING_PCV_APNEA_INSP_TIME", "PB_SETTING_APNEA_FLOW_PATTERN", "PB_SETTING_MANDATORY", "PB_APNEA_IE_INSP_COMPONENT", "PB_SETTING_IE_EXP_COMPONENT", "PB_SETTING_SUPPORT_PRESSURE", "PB_SETTING_FLOW_PATTERN", "PB_SETTING_100PCT_O2_SUCTION", null /* insp press high alarm*/, null /* exp press low alarm*/, null /* exhaled MV high*/, null /* exhaled MV low*/, null /* exhaled mand tidal volume high*/, null /* exhaled mand tidal volume low*/, null /* exhaled spont tidal volume high*/, null /* exhaled spont tidal volume low*/, null /* high resp rate */, null /* high inspired tidal volume*/, "PB_SETTING_BASE_FLOW", "PB_SETTING_FLOW_SENSITIVITY", "PB_SETTING_PCV_INSP_PRESSURE", "PB_SETTING_PCV_INSP_TIME", "PB_SETTING_IE_INSP_COMPONENT", "PB_SETTING_IE_EXP_COMPONENT", "PB_SETTING_CONSTANT_DURING_RATE_CHANGE", "PB_SETTING_TUBE_ID", "PB_SETTING_TUBE_TYPE", "PB_SETTING_HUMIDIFICATION_TYPE", "PB_SETTING_HUMIDIFIER_VOLUME", "PB_SETTING_O2_SENSOR", "PB_SETTING_DISCONNECT_SENSITIVITY", "PB_SETTING_RISE_TIME_PCT", "PB_SETTING_PAVPCT_SUPPORT", "PB_SETTING_EXP_SENSITIVITY", "PB_SETTING_IBW", "PB_SETTING_TARGET_SUPP_VOLUME", }; protected static Float parseFloat(String s) { if(s == null || s.isEmpty() || "OFF".equals(s)) { return null; } else { return Float.parseFloat(s); } } private class MyPB840Parameters extends PB840Parameters { public MyPB840Parameters(InputStream input, OutputStream output) { super(input, output); } @Override public void receiveMiscF(List<String> fieldValues) { reportConnected("Received MISCF"); if(!fieldValues.get(1).equals(deviceIdentity.serial_number)) { deviceIdentity.serial_number = fieldValues.get(1); writeDeviceIdentity(); } inspPressure = alarmSettingsSample(inspPressure, parseFloat(fieldValues.get(30)), parseFloat(fieldValues.get(29)), "PB_INSP_PRESSURE"); exhaledMV = alarmSettingsSample(exhaledMV, parseFloat(fieldValues.get(32)), parseFloat(fieldValues.get(31)), "PB_EXHALED_MV"); exhaledMandTidalVolume = alarmSettingsSample(exhaledMandTidalVolume, parseFloat(fieldValues.get(34)), parseFloat(fieldValues.get(33)), "PB_EXHALED_MAND_TIDAL_VOLUME"); exhaledSpontTidalVolume = alarmSettingsSample(exhaledSpontTidalVolume, parseFloat(fieldValues.get(36)), parseFloat(fieldValues.get(35)), "PB_EXHALED_SPONT_TIDAL_VOLUME"); respRateAlarm = alarmSettingsSample(respRateAlarm, null, parseFloat(fieldValues.get(37)), "PB_RESP_RATE"); inspiredTidalVolume = alarmSettingsSample(inspiredTidalVolume, null, parseFloat(fieldValues.get(38)), "PB_INSPIRED_TIDAL_VOLUME"); markOldTechnicalAlertInstances(); for(int i = 0; i < fieldValues.size(); i++) { String name = i < fieldNames.length ? fieldNames[i] : ("PB_F_"+(i+5)); if(null != name) { try { float f = Float.parseFloat(fieldValues.get(i)); while(i >= otherFields.size()) { otherFields.add(null); } otherFields.set(i, numericSample(otherFields.get(i), f, name, rosetta.MDC_DIM_DIMLESS.VALUE, null)); } catch(NumberFormatException nfe) { writeTechnicalAlert(name, fieldValues.get(i)); } } } clearOldTechnicalAlertInstances(); } } private class RequestSlowData implements Runnable { public void run() { if (ice.ConnectionState.Connected.equals(getState())) { try { PB840Parameters params = (PB840Parameters) getDelegate(0); params.sendF(); } catch (Throwable t) { log.error(t.getMessage(), t); } } } } @Override protected void doInitCommands(int idx) throws IOException { super.doInitCommands(idx); switch(idx) { case 0: ((PB840Parameters)getDelegate(idx)).sendF(); break; default: } } private ScheduledFuture<?> requestSlowData; @Override protected void stateChanged(ConnectionState newState, ConnectionState oldState, String transitionNote) { if (ice.ConnectionState.Connected.equals(newState) && !ice.ConnectionState.Connected.equals(oldState)) { startRequestSlowData(); } if (!ice.ConnectionState.Connected.equals(newState) && ice.ConnectionState.Connected.equals(oldState)) { stopRequestSlowData(); } super.stateChanged(newState, oldState, transitionNote); } private synchronized void startRequestSlowData() { if (null == requestSlowData) { requestSlowData = executor.scheduleWithFixedDelay(new RequestSlowData(), 1000L, 1000L, TimeUnit.MILLISECONDS); log.trace("Scheduled slow data request task"); } else { log.trace("Slow data request already scheduled"); } } private synchronized void stopRequestSlowData() { if (null != requestSlowData) { requestSlowData.cancel(false); requestSlowData = null; log.trace("Canceled slow data request task"); } else { log.trace("Slow data request already canceled"); } } @Override protected PB840 buildDelegate(int idx, InputStream in, OutputStream out) { switch(idx) { case 0: return new MyPB840Parameters(in, out); case 1: return new MyPB840Waveforms(in, out); default: return null; } } @Override protected boolean delegateReceive(int idx, PB840 delegate) throws IOException { return delegate.receive(); } @Override public SerialProvider getSerialProvider(int idx) { SerialProvider serialProvider = super.getSerialProvider(idx).duplicate(); switch(idx) { case 0: serialProvider.setDefaultSerialSettings(9600, DataBits.Eight, Parity.None, StopBits.One, FlowControl.None); break; case 1: serialProvider.setDefaultSerialSettings(38400, DataBits.Eight, Parity.None, StopBits.One, FlowControl.None); break; } return serialProvider; } @Override protected long getMaximumQuietTime(int idx) { return 5000L; } @Override protected String iconResourceName() { return "pb840.png"; } }
JavaScript
UTF-8
3,357
3.09375
3
[ "MIT" ]
permissive
const inquirer = require('inquirer'); const fs = require('fs'); // const readME = require('./readME'); // array of questions for user const questions = [ { type: "input", message: "What is your project name? ", name: "title" }, { type: "input", message: "Write a short description of your project", name: "description" }, { type: "input", message: "What command should your project run to install dependencies? ", name: "installation" }, { type: "input", message: "What is your Github username?", name: "userName" }, { type: "input", message: "What is your email address? ", name: "email" }, { type: "input", message: "What are the steps to install the application?", name: "installation" }, { type: "list", message: "Choose the license you would like to use the MIT or Eclipse license and badge? ", choices: ["[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)", "[![License](https://img.shields.io/badge/License-EPL%201.0-red.svg)](https://opensource.org/licenses/EPL-1.0)GNU"], name: "license" }, { type: "input", message: "What does the user need to know about using the repo? ", name: "usage" }, { type: "input", message: "Who does the user want to credit on the repo ? ", name: "credits" }, { type: "input", message: "Would you like to list any contributors ?", name: "contributing" }, { type: "input", message: "What would a test run off the app entail ?", name: "test" } ]; // inquirer will run the series of questions from the array then the promise is that the information will be written into the md file with a .catch as well inquirer.prompt(questions) .then((response) => { console.log(response) writeToFile("samplereadme.md", response) }) .catch(function (err) { console.log(err); } ); // function to write README file function writeToFile(fileName, data) { console.log(fileName, data) console.log("In writeToFile") fs.writeFileSync(fileName, createReadMe(data), function (err) { if (err) { console.log(err.message) } else { console.log("Story Saved") } }) } // use of object deconstructing and temp lit to plug the const right into the text function createReadMe(newData) { const { userName, email, title, description, installation, usage, license, dependencies, repo, contributing, test, credits } = newData; // will return the text that will be used for the md file return ` # ${title.charAt(0).toUpperCase() + title.slice(1)} ## Description ${description} ## Table of Contents * [Installation](#installation) * [Usage](#usage) * [Credits](#credits) * [License](#license) ## Installation ${installation} ## Usage ${usage} ## Credits ${credits} ## License ${license} ## Badges ## Contributing ${contributing} ## Tests ${test} #Questions If you have any questions please feel free to reach out to me via my email ${email} or directly through my GitHub profile (http://github.com/${userName}) ` }
Java
UTF-8
777
2.3125
2
[]
no_license
package dev.nnnk.jtest1.funcs; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.ChatColor; import org.bukkit.entity.Player; // PlayerJoin event handler public class guelcombai implements Listener { @EventHandler public void onPlayerJoin(final PlayerJoinEvent e) { Player playerObj = e.getPlayer(); String jelou = ChatColor.AQUA+"Güelcom "+ChatColor.GOLD+playerObj.getDisplayName(); e.setJoinMessage(jelou); } @EventHandler public void onPlayerQuit(final PlayerQuitEvent e) { Player playerObj = e.getPlayer(); String kbai = ChatColor.AQUA+"Bai "+ChatColor.GOLD+playerObj.getDisplayName(); e.setQuitMessage(kbai); } }
Java
UTF-8
775
2.828125
3
[]
no_license
package com.epn; public class Nodo { String dato; private Nodo siguiente; private Nodo anterior; public Nodo(String dato,Nodo despues,Nodo atras ){ this.dato=dato; this.siguiente = despues; this.anterior=atras; } public Nodo(String dato){ this(dato,null,null);//primer Nodo } public String getDato() { return dato; } public void setDato(String dato) { this.dato = dato; } public Nodo getAtras() { return anterior; } public void setAtras(Nodo atras) { this.anterior = atras; } public Nodo getDespues() { return siguiente; } public void setDespues(Nodo despues) { this.siguiente = despues; } @Override public String toString() { return "Nodo [dato=" + dato; } }
Java
UTF-8
1,075
1.726563
2
[]
no_license
/* * $Id$ * -------------------------------------------------------------------------------------- * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com * * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.modules.xml.functional; import org.mule.tck.FunctionalTestCase; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; public abstract class AbstractXmlFunctionalTestCase extends FunctionalTestCase { public static final long TIMEOUT = 1000L; protected String getConfigAsString() throws IOException { return getResourceAsString(getConfigResources()); } protected String getResourceAsString(String resource) throws IOException { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); assertNotNull(resource, is); return IOUtils.toString(is); } }
Ruby
UTF-8
373
2.53125
3
[ "MIT" ]
permissive
module ApplicationHelper def sentence_of(things, opts = {}, &block) if block things = things.collect do |thing| capture(thing, &block) end end if opts[:connector] == :or things.to_sentence :last_word_connector => ", or ", :two_words_connector => " or " else things.to_sentence end end end
Python
UTF-8
1,159
2.890625
3
[]
no_license
from crossword import Crossword, Word, WordLengthDictionary def test_medium_crossword(): w = [ Word(6), # 1 Across Word(6), # 1 Down Word(3), # 2d Word(3), # 3d Word(6), # 4d Word(7), # 5a Word(3), # 6d Word(7), # 7a Word(3), # 8d Word(3), # 9d Word(6), # 10a ] w[0].addCollision(w[1], 0, 0) w[0].addCollision(w[2], 2, 0) w[0].addCollision(w[3], 4, 0) w[1].addCollision(w[5], 2, 0) w[1].addCollision(w[7], 4, 0) w[2].addCollision(w[5], 2, 2) w[3].addCollision(w[5], 2, 4) w[4].addCollision(w[5], 1, 6) w[4].addCollision(w[7], 3, 6) w[4].addCollision(w[10], 5, 5) w[5].addCollision(w[6], 3, 1) w[6].addCollision(w[7], 2, 3) w[7].addCollision(w[8], 2, 0) w[7].addCollision(w[9], 4, 0) w[8].addCollision(w[10], 2, 1) w[9].addCollision(w[10], 2, 3) dictionary = WordLengthDictionary() dictionary.loadFromFile("/usr/share/dict/words") xw = Crossword(w, dictionary) res = xw.solve() print(res) assert(res > 0) if __name__ == "__main__": test_medium_crossword()
Java
UTF-8
1,598
2.125
2
[]
no_license
package evalbasicfsm.revisitor.operations.evalbasicfsm.impl; import basicFsmEnv.VarDecl; import basicFsmEnv.revisitor.BasicFsmEnvRevisitor; import basicFsmEnv.runtime.Context; import evalbasicfsm.revisitor.operations.evalbasicfsm.ActionOperation; import evalbasicfsm.revisitor.operations.evalbasicfsm.GuardOperation; import evalbasicfsm.revisitor.operations.evalbasicfsm.InitialStateOperation; import evalbasicfsm.revisitor.operations.evalbasicfsm.MachineOperation; import evalbasicfsm.revisitor.operations.evalbasicfsm.StateOperation; import evalbasicfsm.revisitor.operations.evalbasicfsm.TransOperation; import evalbasicfsm.revisitor.operations.evalbasicfsm.VarDeclOperation; @SuppressWarnings("all") public class VarDeclOperationImpl implements VarDeclOperation { private VarDecl obj; private BasicFsmEnvRevisitor<? extends ActionOperation, ? extends GuardOperation, ? extends InitialStateOperation, ? extends MachineOperation, ? extends StateOperation, ? extends TransOperation, ? extends VarDeclOperation> alg; public VarDeclOperationImpl(final VarDecl obj, final BasicFsmEnvRevisitor<? extends ActionOperation, ? extends GuardOperation, ? extends InitialStateOperation, ? extends MachineOperation, ? extends StateOperation, ? extends TransOperation, ? extends VarDeclOperation> alg) { this.obj = obj; this.alg = alg; } @Override public void eval(final Context ctx) { boolean _containsKey = ctx.getEnv().containsKey(this.obj.getName()); boolean _not = (!_containsKey); if (_not) { ctx.bind(this.obj.getName(), this.obj.getValue()); } } }
Python
UTF-8
1,798
3.125
3
[ "MIT" ]
permissive
import pygame from random import randint from copy import deepcopy Res = WIDTH, HEIGHT = 1600,900 #设置窗口长和宽 TILE = 20 #数值 W, H = WIDTH // TILE, HEIGHT // TILE #设置一个小格子长和宽 fps = 10 #刷新频率 pygame. init()#初始化游戏 surface = pygame.display.set_mode(Res)#设置一个启动窗口res CLOCK = pygame.time.Clock() next_field = [[0 for i in range(W)]for j in range(H)] current_field = [[randint(0, 1)for i in range(W)]for j in range(H)]#初始领域 #current_field = [[1 if not i % 33 else 0 for i in range(W)]for j in range(H)] def check_cell(current_field, x, y,):#设置算法 count = 0 for j in range(y - 1, y + 2): for i in range(x - 1, x + 2): if current_field[j][i]: count += 1 if current_field[y][x]: count -= 1 if count == 2 or count == 3:#如果count等于2或者3则异常返回 return 1 return 0 else: if count == 3: return 1 return 0 while True: surface.fill(pygame.Color('black'))#设置游戏退出 for even in pygame.event.get(): if even.type == pygame.QUIT: exit() #绘画格子 [pygame.draw.line(surface, pygame.Color('dimgray'),(x, 0), (x, HEIGHT))for x in range(0, WIDTH, TILE)] [pygame.draw.line(surface, pygame.Color('dimgray'),(0, y), (WIDTH, y))for y in range(0,HEIGHT,TILE)] #绘画人生 for x in range(1, W - 1): for y in range(1, H - 1): if current_field[y][x]: pygame.draw.rect(surface, pygame.Color('forestgreen'),(x * TILE + 2, y * TILE + 2, TILE - 2, TILE - 2)) next_field[y][x] = check_cell(current_field, x, y) current_field = deepcopy(next_field) pygame.display.flip() CLOCK.tick(fps)
Python
UTF-8
815
3.40625
3
[]
no_license
from graphics import * import math win = GraphWin('Face', 1000, 500) # give title and dimensions Ans = [100] Bns = [-50] Sns = [0] points = [Point(450, 300)] lines = [] rect = Rectangle(points[0], Point(550, 250)) rect.setFill("red") rect.draw(win) def run(): for x in range(5): Ans.append(math.sqrt(Ans[x]**2 + Bns[x]*2)) Sns.append(Bns[x]**2/Ans[x+1]) Bns.append(-math.sqrt(Bns[x]**2-Sns[x+1]**2)) points.append(Point(Ans[x]+450, Bns[x]+300)) points.append(Point(Ans[x+1]+450, Bns[x+1]+300)) lines.append(Line(points[0], points[1])) lines.append(Line(points[1], points[2])) lines[0].draw(win) lines[1].draw(win) # Line3 = Line(Point(An, Bn), Point(450-Sn, win.getMouse() win.close() print(Ans) run()
Java
UTF-8
167
1.78125
2
[]
no_license
package com.bmg.vault.list; public class VaultListNotFoundException extends Throwable { VaultListNotFoundException(String message){ super(message); } }
Python
UTF-8
1,473
2.53125
3
[ "MIT" ]
permissive
import pandas as pd import re import joblib as jb from scipy.sparse import hstack, csr_matrix import numpy as np import json import os mdl_logr = jb.load("logisticRegression.pkl.z") mdl_lgbm = jb.load("lgbm.pkl.z") title_vec = jb.load("title_vectorizer.pkl.z") def compute_features(data): publish_date = pd.to_datetime(data['upload_date']) views = data['view_count'] title = data['title'] features = dict() features['tempo_desde_pub'] = (pd.Timestamp.today() - publish_date) / np.timedelta64(1, 'D') features['views'] = views features['views_por_dia'] = features['views'] / features['tempo_desde_pub'] del features['tempo_desde_pub'] vectorized_title = title_vec.transform([title]) num_features = csr_matrix(np.array([features['views'], features['views_por_dia']])) feature_array = hstack([num_features, vectorized_title]) return feature_array def compute_prediction(data): feature_array = compute_features(data) if feature_array is None: return 0 p_logr = mdl_logr.predict_proba(feature_array)[0][1] p_lgbm = mdl_lgbm.predict_proba(feature_array)[0][1] p = 0.3*p_logr + 0.7*p_lgbm #log_data(data, feature_array, p) return p def log_data(data, feature_array, p): #print(data) video_id = data.get('og:video:url', '') data['prediction'] = p data['feature_array'] = feature_array.todense().tolist() #print(video_id, json.dumps(data))
Shell
UTF-8
4,230
3.96875
4
[]
no_license
#!/usr/bin/env bash _file_memo_path="$HOME/.file-memo" _home_path="$(realpath ~)" main() { # 사용방법1: file-memo book1.jpg # 이렇게 사용하면 book1.jpg 의 설명을 vim에서 보여줘야 한다. 편집도 되고 읽기도 된다. # book1.jpg 파일의 내용을 읽고 해시값을 계산한다. # 계산한 해시값이 ff123 이라 하자. # ~/.file-memo/ff123 파일이 있다면, vim 에서 보여준다. # 파일이 없다면 ~/.file-memo/ff123 파일을 생성한다. # 생성할 때 첫 번째 줄에 book1.jpg 의 경로를 적어준다. - 파일과 설명 파일을 쌍으로 연결해준다. 필요없을지는 천천히 생각해보자. # 사용방법2: file-memo # 이렇게 사용하면 현재 디렉토리의 모든 파일 목록을 fzf에서 보여주고, # 화면 오른쪽 preview에 설명 파일의 내용을 보여준다. # 파일 하나를 골라 엔터를 치면 vim 으로 설명 파일을 열어준다? 또는 해당 이미지를 열어준다? # 제일 많이 사용하게 될 기능일듯 # 사용방법3: file-memo -f 검색어 # 검색어를 입력하면 해당 검색어를 포함하는 설명 파일을 fzf에서 보여주고, # 화면 오른쪽 preview에 설명 파일의 내용을 보여준다. (이미지를 보여주면 더 좋겠지만... 터미널에서 이미지를 보여주기가... 나중에 생각하자) # 설명 파일 안쪽에 #unix #javascript 이렇게 해시태그를 넣을 수도 있겠다. # 사용방법4: file-memo --orphan # 대상 파일이 사라진 설명 파일 목록을 보여준다. # 설명 파일 첫 줄에 대상 파일 경로가 있으므로 그걸 활용한다. mkdir -p "$_file_memo_path" if [[ "$1" == "" ]]; then # 모든 메모 목록을 fzf 미리보기로 보여주고, 선택하면 메모가 붙은 원본 파일을 open 으로 열어준다 find "$_file_memo_path" -type f \ | fzf --preview 'cat {}' \ | xargs head -1 \ | sed -E "s&^~&"$_home_path"&" \ | xargs open return 0 fi case "$1" in "-f"|"--find") # 검색어를 입력하면 해당 검색어를 포함하는 설명 파일을 fzf에서 보여주고, 선택하면 원본 파일을 열어준다 grep -rl "$2" "$_file_memo_path" \ | fzf --preview 'cat {}' \ | xargs head -1 \ | sed -E "s&^~&"$_home_path"&" \ | xargs open ;; "-o"|"--orphan") # 미구현 echo "option: orphan" ;; *) open-file-memo "$1" ;; esac } open-file-memo() { _file_name="$1" _file_path=`file-abs-path $_file_name` echo "file path: $_file_path" if [[ ! -f "$_file_path" ]]; then # 없는 파일이면 설명 파일을 작성하지 않는다. echo "File not found: $_file_path" return 1 fi _file_hash=$(file-hash "$_file_name") # echo "file hash: $_file_hash" _dir_path="$_file_memo_path/$(cut -c -2 <<< $_file_hash)" if [[ ! -f "$_dir_path/$_file_hash" ]]; then # 설명 파일이 없다면 파일을 생성한다. echo "File not found: ~/.file-memo/$_file_hash" echo "Create file memo? [y/n]" read -r _input if [[ "$_input" == "y" ]]; then mkdir -p $_dir_path echo "$(file-tilde-path $_file_name)" > $_dir_path/$_file_hash echo "File memo created: $_file_memo_path/$_file_hash" else return 0 fi fi $EDITOR "$_dir_path/$_file_hash" return 0 } file-abs-path() { # $1 파일의 절대 경로를 리턴합니다. realpath -s $1 } file-tilde-path() { # $1 파일의 경로를 리턴합니다. # 절대 경로가 아니라 ~ 로 시작하는 확장 전의 경로입니다. _tilde_path="~$(realpath -s $1 | sed "s&$_home_path&&")" printf "%s" "$_tilde_path" } file-hash() { # $1 파일의 해시를 리턴합니다. sha1sum $1 | awk '{print $1}' } main $@
Java
UTF-8
1,106
2.375
2
[]
no_license
package ru.otus.springstudentcheck4.dao; import org.springframework.context.MessageSource; import org.springframework.stereotype.Repository; import ru.otus.springstudentcheck4.configs.YamlProps; import ru.otus.springstudentcheck4.domain.Check; @Repository public class ChecksDaoCSV implements ChecksDao { private final Scanning scan; private final YamlProps props; private final MessageSource messageSource; public ChecksDaoCSV(Scanning scan, MessageSource messageSource, YamlProps props) { this.scan = scan; this.props = props; this.messageSource = messageSource; } @Override public Check getCheckByNum(int numCheck) throws CheckNotFoundException{ scan.setFilePathName(messageSource.getMessage("filePath", new String[]{}, props.getLocale())); for(String oneS : scan.getScannedCSV().split("\n")){ String[] check = oneS.split("\\*\\*\\*"); if(numCheck == Integer.valueOf(check[0].trim())){ return (new Check(numCheck, check[1], check[2])); } } return null; } }
Java
UTF-8
1,534
2.4375
2
[]
no_license
package com.dinosoftlabs.binder.PojoClass; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.io.Serializable; public class RegisterPhoneModel implements Serializable { @SerializedName("status") @Expose private String status; @SerializedName("message") @Expose private String message; @SerializedName("result") @Expose private RegisterPhoneResult registerPhoneResult; private final static long serialVersionUID = -3813853950181941641L; /** * No args constructor for use in serialization * */ public RegisterPhoneModel() { } /** * * @param registerPhoneResult * @param message * @param status */ public RegisterPhoneModel(String status, String message, RegisterPhoneResult registerPhoneResult) { super(); this.status = status; this.message = message; this.registerPhoneResult = registerPhoneResult; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public RegisterPhoneResult getRegisterPhoneResult() { return registerPhoneResult; } public void setRegisterPhoneResult(RegisterPhoneResult registerPhoneResult) { this.registerPhoneResult = registerPhoneResult; } }
PHP
UTF-8
1,313
3.0625
3
[]
no_license
<?php /** * @author Sam Waters <sam@samwaters.com> * @created 25/07/2016 14:11 */ namespace VindiciaPHP\Responses; use VindiciaPHP\Exceptions\CallException; abstract class BaseResponse { private $_returnCode; private $_returnString; private $_soapId; /** * Base for all responses * @param $returnObj */ public function __construct($returnObj) { $this->_returnCode = $returnObj->returnCode; $this->_returnString = $returnObj->returnString; $this->_soapId = $returnObj->soapId; } /** * @return string */ public function getReturnCode() { return $this->_returnCode; } /** * @return string */ public function getReturnString() { return $this->_returnString; } /** * @return string */ public function getSoapId() { return $this->_soapId; } /** * Make sure the response is valid and has all the required fields * @param $raw * @throws CallException */ public static function validate($raw) { if(!is_object($raw) || !isset($raw->return)) { throw new CallException("Invalid response from api"); } if(!isset($raw->return->returnCode) || !isset($raw->return->returnString) || !isset($raw->return->soapId)) { throw new CallException("Missing required fields in api response"); } } }
Python
UTF-8
286
2.796875
3
[]
no_license
# # @lc app=leetcode id=2710 lang=python3 # # [2710] Remove Trailing Zeros From a String # # @lc code=start class Solution: def removeTrailingZeros(self, num: str) -> str: while len(num) > 0 and num[-1] == '0': num = num[:-1] return num # @lc code=end
JavaScript
UTF-8
1,715
2.96875
3
[]
no_license
/** * Created by Zakary on 2016/9/26. */ var thunderObj = function () { this.x = []; this.y = []; this.h = []; this.alive = [];//bool }; thunderObj.prototype.num = 10; thunderObj.prototype.init = function () { for(var i = 0;i< score.energyFlag;i++){ this.bron( i ); } }; thunderObj.prototype.set = function ( i ) { this.bron( i ); }; thunderObj.prototype.draw = function () { var y1, y2; if(score.energyFlag > 0 && score.ThunderFlag && !score.Thunder){ this.alive[i] = score.energyFlag; score.ThunderFlag = false; } if(this.alive[i] > 0){ for( var i = 0; i < score.ThunderFlag ; i++){ for( var j = 0; j < this.num ; j++){ y1 = this.y[i]; y2 = y1 + this.h[i]; ctx2.save(); ctx2.strokeStyle = "#152BA8"; ctx2.lineWidth = parseInt(Math.random() * 10); ctx2.moveTo(this.x[i],y1); ctx2.lineTo(this.x[i],y2); ctx2.stroke(); ctx2.restore(); score.energyFlag--; this.alive[i]--; this.y[i] += score.level; if(score.energyFlag <= 0){ score.energyFlag = 0; for(var i = 0; i < 7; i++){ score.energy[i] = 0; } } }if(j == this.num) break; } // console.log(score.energyFlag+"T"); } }; thunderObj.prototype.bron = function (i) { this.x[i] = parseInt(Math.random() * canWidth); this.y[i] = 0; this.h[i] = parseInt(Math.random() * 100); this.alive[i] = score.energyFlag; };
JavaScript
UTF-8
2,057
2.8125
3
[]
no_license
import React, { useState, useEffect } from "react"; import axios from "axios"; import CocktailCard from '../cards/CocktailCard'; import DetailedCard from '../cards/DetailedCard'; const RandomCocktail = ({handleCardClick}) => { const [cocktailName, setCocktailName] = useState(""); const [cocktailPicture, setCocktailPicture] = useState(""); const [cocktailId, setCocktailId] = useState(""); const [instructions, setInstructions] = useState(""); const [category, setCategory] = useState(""); const [ingredients, setIngredients] = useState([]); useEffect(async() => { const response = await axios({ url: `http://localhost:8080/` }) const randomDrinkArray = response.data.drinks; setCocktailName(randomDrinkArray[0].strDrink); setCocktailPicture(randomDrinkArray[0].strDrinkThumb); setCocktailId(randomDrinkArray[0].idDrink); setInstructions(randomDrinkArray[0].strInstructions); setCategory(randomDrinkArray[0].strCategory); const measureList = []; const ingredientList = []; const recipe = []; const cocktailDetails = randomDrinkArray[0]; Object.keys(cocktailDetails).forEach(key => { if (key.startsWith('strIngredient') && cocktailDetails[key]!== null){ ingredientList.push(cocktailDetails[key]); } if (key.startsWith('strMeasure') && cocktailDetails[key]!== null){ measureList.push(cocktailDetails[key]); } }); for (let i = 0; i < ingredientList.length; i++) { recipe.push(measureList[i] + ingredientList[i]); } setIngredients(recipe); }, []); return ( <div className="random-cocktails"> <DetailedCard handleCardClick={handleCardClick} ingredients={ingredients} category={category} instructions={instructions} cocktailId={cocktailId} cocktailName={cocktailName} imgSrc={cocktailPicture} /> {/* imgSrc, cocktailName, instructions, category, ingredients */} </div> ); }; export default RandomCocktail;
Java
UTF-8
356
2.421875
2
[]
no_license
package automat; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class HerstellerImplTest { public final String HERSTELLERNAME = "hersteller"; @Test void getName() { Hersteller hersteller = new HerstellerImpl(HERSTELLERNAME); assertEquals(HERSTELLERNAME, hersteller.getName()); } }
Swift
UTF-8
1,411
3.390625
3
[]
no_license
// // City.swift // DemoTrie // // Created by Gaurav Tiwari on 21/06/19. // Copyright © 2019 Gaurav Tiwari. All rights reserved. // import UIKit struct City { var cityName : String var cityCountryName : String var cityCoordinates : CityCoordinates = CityCoordinates (latitude: 0.0, longitude: 0.0) init?(dictCity: Dictionary<String, AnyObject>) { self.cityName = dictCity["name"] as? String ?? "" self.cityCountryName = dictCity["country"] as? String ?? "" if let coord = dictCity["coord"] as? Dictionary<String, AnyObject>{ self.cityCoordinates = getCoordinate(coordinate: coord) } } } struct CityList { var cities = [City]() init(citiesTemp: Array<AnyObject>) { cities = citiesTemp.compactMap(){dict in if let typeDict = dict as? Dictionary<String,AnyObject>{ return City(dictCity: typeDict) } else { return nil } } } init(citiesTemp: Array<City>) { self.cities = citiesTemp } } extension City{ func getCoordinate(coordinate: Dictionary<String,AnyObject>) -> CityCoordinates { let coordinate = CityCoordinates(latitude: coordinate["lat"] as? Double ?? 0.0, longitude: coordinate["lon"] as? Double ?? 0.0) return coordinate } } struct CityCoordinates { let latitude : Double let longitude : Double }
Markdown
UTF-8
1,794
2.578125
3
[ "MIT" ]
permissive
<center><img src="./images/iaas_knight.png" width="200"></center> # Instructions de Jeu pour Iaas Knight [Créer une application Node.js sur Azure]('https://docs.microsoft.com/fr-fr/azure/app-service/app-service-web-get-started-nodejs') [Liste des commandes Azure CLI ]('https://docs.microsoft.com/fr-fr/azure/virtual-machines/linux/cli-manage') #Etapes Iaas pour Web UI et CLI: ##Créer un groupe de ressources (si exisidéjà définit passer à l'étape suivante): ##Web UI: Faire Groupes de ressources > Ajouter, puis suivre les instructions ##CLI: ``` az group create --name <testResourceGroup> --location <northeurope> ``` ##Créer une VM: ##Web UI: Faire Nouveau > Compute > puis choisir son type de distribution, puis suivre les instructions ##CLI: Ubuntu: ``` az vm create --resource-group <nomDuGroupeRessource> --name <nomDeVM> --image UbuntuLTS --generate-ssh-keys ``` ##CLI: Windows: ``` az vm create --resource-group myResourceGroup --name <nomDeVM> --image win2016datacenter --admin-username <nomUtilisateur> --admin-password <motDePasse> ``` [Info]('https://docs.microsoft.com/en-us/azure/virtual-machines/windows/cli-ps-findimage') ##Ouvrir le port 8080: ##Web UI: Faire Groupes de ressources > "Sa ressource" > "NomVM"NSG > "Inbound security rules", puis ajouter une nouvelle règle pour 8080 ##CLI: ``` az vm open-port --port 8080 --resource-group <nomDuGroupeRessource> --name <nomDeVM> ``` ##Sur la VM: * utiliser ssh pour s'y connecter ##Installer et configurer son environnement: * Node.js * Npm * Git * Editeur de texte (en option) ##Déploiement de l'application: * npm install * npm start ##Cloner dépôt Git: https://github.com/sqli-nantes/clouding-game ##Exécuter l'application. #Bon courage !! A disposition en cas de besoin :-)
C++
GB18030
1,646
2.734375
3
[]
no_license
//״ѹDP #include<iostream> #include<algorithm> using namespace std; const int maxst = (1 << 17); int ini[20]; int cover[maxst]; int dp[maxst]; int main() { int n; int Case = 1; while (~scanf("%d", &n)) { if (n == 0) break; for (int i = 0; i < n; i++) { ini[i] = 0|(1<<i);// int m; scanf("%d", &m); for (int j = 0; j < m; j++) { int k; scanf("%d", &k); ini[i] |= (1 << k);//ھ } } int total = (1 << n) - 1;//״̬ for (int i = 0; i <=total; i++) { cover[i] = 0; for (int j = 0; j < n; j++) { if (i&(1 << j))//״̬ܹ̱j̨ { cover[i] |= ini[j];//ôҲ̱ڽӵĵ } } } dp[0] = 0; for (int i = 1; i <= total; i++) { dp[i] = 0; //öӼ for (int j = i; j > 0; j = (j - 1)&i) { if (cover[j] == total)//Ӽ״̬ܹɵеĵ { dp[i] = max(dp[i], dp[i^j] + 1);//ô״̬ܹرյķΪmax{״̬رյķ,״̬iܹɵеĵԵӼIJܹرյķ+11ɸӼjṩ} } } } printf("Case %d: %d\n",Case, dp[total]); Case++; } return 0; }
C#
UTF-8
11,029
3.171875
3
[]
no_license
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Configuration; namespace TopTravel { //This class represents the entity of a flight with its methods and atributes listed below public class FlightCAD { //It provides with the information of all the flights contained in the DB public DataSet showFlights(FlightEN b) { string s; s = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); //String where it's stored the instructions for the connecton for the DB DataSet virtdb = new DataSet(); //Created the DataSet that is going to be returned with the information asked SqlConnection c = new SqlConnection(s); //The connection is effectuated try { SqlDataAdapter da = new SqlDataAdapter("select * from Flight", c); //The select in SQL language that is processed in the DB which will return all the rows from the table "Flight" da.Fill(virtdb, "flight"); //It introduces the information returned from the select into this virtual DB } catch (Exception ex) { ex.ToString(); //In case of an error it is printed here Console.WriteLine("ERROR: show flight"); } finally { c.Close(); //Closes the connection to the DB } return virtdb; //It returns the virtual DB with all the information needed inside } //It behaves like showFlights but it includes some restrictions in the shearch, providing the departure and destination cities public DataSet searchFlights(String b1, String b2) { string s; s = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); //String where it's stored the instructions for the connecton for the DB DataSet virtdb = new DataSet(); //Created the DataSet that is going to be returned with the information asked SqlConnection c = new SqlConnection(s); //The connection is effectuated try { //The select in SQL language that is processed in the DB which will return all the rows from the table "Flight" SqlDataAdapter da = new SqlDataAdapter("Select * from Flight where departureCity LIKE '%" + b1 + "%' and destinationCity LIKE '%" + b2 + "%'", c); da.Fill(virtdb, "flight"); //It introduces the information returned from the select into this virtual DB } catch (Exception ex) { ex.ToString(); //In case of an error it is printed here Console.WriteLine("ERROR: show flight"); } finally { c.Close(); //Closes the connection to the DB } return virtdb; //It returns the virtual DB with all the information needed inside } //Shows information about the flight with the provided id public DataSet searchIDFlights(String IDF) { string s; s = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); //String where it's stored the instructions for the connecton for the DB DataSet virtdb = new DataSet(); //Created the DataSet that is going to be returned with the information asked SqlConnection c = new SqlConnection(s); //The connection is effectuated try { //The select in SQL language that is processed in the DB which will return all the rows from the table "Flight" SqlDataAdapter da = new SqlDataAdapter("Select * from Flight where Id = '" + IDF + "'", c); da.Fill(virtdb, "flight"); //It introduces the information returned from the select into this virtual DB } catch (Exception ex) { ex.ToString(); //In case of an error it is printed here Console.WriteLine("ERROR: show flight"); } finally { c.Close(); //Closes the connection to the DB } return virtdb; //It returns the virtual DB with all the information asked inside } //Adds a new flight to the DB public DataSet addFlight(FlightEN b) { string s; s = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); //String where it's stored the instructions for the connecton for the DB SqlConnection c = new SqlConnection(s); //The connection is effectuated DataSet virtdb = new DataSet(); //Created the DataSet that is going to be returned with the information asked try { //The select in SQL language that is processed in the DB which will return all the rows from the table "Flight" SqlDataAdapter da = new SqlDataAdapter("select * from Flight", c); da.Fill(virtdb, "flight"); //It introduces the information returned from the select into this virtual DB DataTable dt = new DataTable(); //Creates a new instance of a table dt = virtdb.Tables["flight"]; //Fills it with the information obtained from the select DataRow newRow = dt.NewRow(); //Creates a new row newRow[0] = b.id; newRow[1] = b.DepartureTime; newRow[2] = b.ArrivalTime; //Fills it with the content of the new flight newRow[3] = b.DepartureCity; newRow[4] = b.DestinationCity; newRow[5] = b.classFlight; newRow[6] = b.Price; newRow[7] = b.Company; newRow[8] = b.Extras; newRow[9] = b.Image; dt.Rows.Add(newRow); SqlCommandBuilder cbuilder = new SqlCommandBuilder(da); //Elaborates the SQL command needed to make the changes da.Update(virtdb, "flight"); //Updates the DB with the new information added } catch (Exception ex) { ex.ToString(); //In case of an error it is printed here Console.WriteLine("ERROR: Add flight"); } finally { c.Close(); //Closes the connection to the DB } return virtdb; //It returns the virtual DB with all the information asked inside } //Removes all the information about an especific flight, provided its id public DataSet deleteFlight(FlightEN b, int i) // It will delete the index passed in the view { string s; s = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); //String where it's stored the instructions for the connecton for the DB SqlConnection c = new SqlConnection(s); //The connection is effectuated DataSet virtdb = new DataSet(); try { //The select in SQL language that is processed in the DB which will return all the rows from the table "Flight" SqlDataAdapter da = new SqlDataAdapter("select * from Flight", c); da.Fill(virtdb, "flight"); //It introduces the information returned from the select into this virtual DB DataTable t = new DataTable(); //Creates a new instance of a table t = virtdb.Tables["flight"]; //Fills it with the information obtained from the select t.Rows[i].Delete(); //Deletes the row SqlCommandBuilder cbuilder = new SqlCommandBuilder(da); //Elaborates the SQL command needed to make the changes da.Update(virtdb, "flight"); //Updates the DB with the new information } catch (Exception ex) { ex.ToString(); //In case of an error it is printed here Console.WriteLine("ERROR: Delete flight"); } finally { c.Close(); //Closes the connection to the DB } return virtdb; //It returns the virtual DB with all the information asked inside } //Updates the information of an especific flight provided its id public DataSet updateFlight(FlightEN b, int i) { string s; s = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); //String where it's stored the instructions for the connecton for the DB SqlConnection c = new SqlConnection(s); //The connection is effectuated DataSet virtdb = new DataSet(); //Created the DataSet that is going to be returned with the information asked try { //The select in SQL language that is processed in the DB which will return all the rows from the table "Flight" SqlDataAdapter da = new SqlDataAdapter("select * from Flight", c); da.Fill(virtdb, "flight"); //It introduces the information returned from the select into this virtual DB DataTable t = new DataTable(); //Creates a new instance of a table t = virtdb.Tables["flight"]; //Fills it with the information obtained from the select t.Rows[i]["Id"] = b.id; t.Rows[i]["departureTime"] = b.DepartureTime; t.Rows[i]["arrivalTime"] = b.ArrivalTime; t.Rows[i]["departureCity"] = b.DepartureCity; //Makes the changes in the atributes t.Rows[i]["destinationCity"] = b.DestinationCity; t.Rows[i]["ClassFlight"] = b.classFlight; t.Rows[i]["price"] = b.Price; t.Rows[i]["company"] = b.Company; t.Rows[i]["extras"] = b.Extras; t.Rows[i]["image"] = b.Image; SqlCommandBuilder cbuilder = new SqlCommandBuilder(da); //Elaborates the SQL command needed to make the changes da.Update(virtdb, "flight"); //Updates the DB with the new information } catch (Exception ex) { ex.ToString(); //In case of an error it is printed here Console.WriteLine("ERROR: Delete flight"); } finally { c.Close(); //Closes the connection to the DB } return virtdb; //It returns the virtual DB with all the information asked inside } } }
Python
UTF-8
16,932
2.71875
3
[]
no_license
import h5py import numpy as np from scipy.io import loadmat import time from sklearn.linear_model import LinearRegression from sklearn.linear_model import RidgeCV from sklearn.linear_model import LassoCV from sklearn.metrics import r2_score from UoI_Lasso import UoI_Lasso class Retina: def __init__(self, data_path, random_path): self.data_path = data_path self.random_path = random_path # load neural response data data = loadmat(self.data_path, struct_as_record=False) self.recordings = data['stimulus'].ravel() self.n_recordings = self.recordings.size self.spikes = data['spikes'] self.n_cells = np.asscalar( np.asscalar(data['datainfo']).Ncell ) def check_recording_idx(self, recording_idx): '''Check to see if recording index is correctly specified. Parameters ---------- recording_idx : int recording index ''' if not isinstance(recording_idx, int): raise ValueError('Recording index must be an integer.') if recording_idx < 0 or recording_idx >= self.n_recordings: raise IndexError('Recording index outside bounds.') return def check_cells(self, cells): '''Check 'cells' input, and potentially convert to numpy array if necessary. Parameters ---------- cells : int, list, np.ndarray or None the set of cell indices under consideration. if the first two, converts to a np.ndarray. if None, creates a np array of all cells. Returns ------- cells : np.ndarray the converted numpy array containing the cell indices ''' # None corresponds to using all cells if cells is None: cells = np.arange(self.n_cells) # only one cell elif isinstance(cells, int): cells = np.array([cells]) # multiple cells, but convert to numpy array elif isinstance(cells, list): cells = np.array(cells) elif not isinstance(cells, np.ndarray): raise ValueError('cells variable type is not correct.') return cells def get_n_frames_per_window(self, recording_idx, window_length=0.5): '''Returns the number of frames in a specified recording and window size. Parameters ---------- recording_idx : int recording index window_length : float length of window for which to calculate STRF, in seconds Returns ------- n_frames_per_window : float the number of stimuli frames per window length ''' # extract recording self.check_recording_idx(recording_idx=recording_idx) recording = self.recordings[recording_idx] # extract frame length frame_length = np.asscalar(recording.frame) # calculate number of frames per window, given specified size n_frames_per_window = int(np.round( window_length/frame_length )) return n_frames_per_window def get_timestamps_for_recording(self, recording_idx): '''Get timestamps for specified recording. Parameters ---------- recording_idx : int recording index Returns ------- timestamps : np.ndarray array of timestamps for each recording ''' # extract current recording self.check_recording_idx(recording_idx=recording_idx) recording = self.recordings[recording_idx] # get the number of samples by creating timestamps n_frames = np.asscalar(recording.Nframes) frame_length = np.asscalar(recording.frame) onset = np.asscalar(recording.onset) # calculate timestamps and number of samples timestamps = np.arange(n_frames) * frame_length + onset return timestamps def get_n_features_for_recording(self, recording_idx, window_length=0.5): '''Get number of features (distinct bar dimensions) for recording. Parameters ---------- recording_idx : int recording index window_length : float length of window for which to calculate STRF, in seconds Returns ------- n_features : int number of stimulus features ''' # extract current recording self.check_recording_idx(recording_idx=recording_idx) recording = self.recordings[recording_idx] # extract parameter information params = np.asscalar(recording.param) # number of x/y dimensions Nx = np.asscalar(params.x)/np.asscalar(params.dx) Ny = np.asscalar(params.y)/np.asscalar(params.dy) # calculate number of features n_features = int(Nx * Ny) return n_features def get_dimensions_for_recording(self, recording_idx, window_length=0.5): '''Gets both the number of features and samples for specified recording and window length. Parameters ---------- recording_idx : int recording index window_length : float length of window for which to calculate STRF, in seconds Returns ------- n_features : int number of stimulus features n_samples : int number of samples in dataset timestamps : np.ndarray timestamps for dataset ''' # get timestamps timestamps = self.get_timestamps_for_recording(recording_idx=recording_idx) n_samples = timestamps.size - 1 # get number of features n_features = self.get_n_features_for_recording( recording_idx=recording_idx, window_length=window_length ) return n_features, n_samples, timestamps def get_responses_for_recording(self, recording_idx, window_length=0.5, cells=None): '''Create response matrix for specified recording, window length, and choice of cells. Parameters ---------- recording_idx : int recording index window_length : float length of window for which to calculate STRF, in seconds cells : int, list, np.ndarray or None the set of cell indices under consideration. if the first two, converts to a np.ndarray. if None, creates a np array of all cells. Returns ------- responses : np.ndarray n_samples x n_cells array containing the responses for each cell in the recording. ''' # convert cells to numpy array, if necessary cells = self.check_cells(cells=cells) # set up responses matrix n_features, n_samples, timestamps = self.get_dimensions_for_recording( recording_idx=recording_idx, window_length=window_length ) n_cells = cells.size responses = np.zeros((n_samples, n_cells)) n_frames_per_window = self.get_n_frames_per_window( recording_idx=recording_idx, window_length=window_length ) # iterate over cells, grabbing responses for idx, cell in enumerate(cells): # extract spike times spike_times = self.spikes[cell, recording_idx] # binning binned_spikes, _ = np.histogram(spike_times, bins=timestamps) # zero out the delay binned_spikes[:n_frames_per_window-1] = 0 # put binned spike counts in response matrix n_spikes = np.sum(binned_spikes) responses[:, idx] = binned_spikes/n_spikes return responses def get_stims_for_recording(self, recording_idx, window_length=0.5): '''Create response matrix for specified recording and window length. Parameters ---------- recording_idx : int recording index window_length : float length of window for which to calculate STRF, in seconds Returns ------- stimuli : np.ndarray n_features x n_samples array containing white noise stimuli shown to the cells. ''' # get dimensions n_features, n_samples, _ = self.get_dimensions_for_recording( recording_idx=recording_idx, window_length=window_length ) # read in the random bits as bytes byte = np.fromfile( self.random_path, count=n_samples*n_features//8, dtype='uint8' ) # convert to bits stimuli = np.unpackbits(byte).astype('float32') # convert bits to +1/-1 stimuli = 2 * stimuli - 1 stimuli = stimuli.reshape((n_samples, n_features)).T return stimuli def calculate_strf_for_neurons_and_frame(self, method, recording_idx, frame, window_length=0.5, return_score=False, cells=None, **kwargs ): '''Calculates STRF for specified neurons. Parameters ---------- method : string regression method to use when calculating STRFs recording_idx : int recording index to obtain design and response matrices window_length : float number of seconds to fit in STRF window return_scores : bool flag indicating whether to return explained variance over window. cells : int, list, np.ndarray or None the set of cell indices under consideration. if the first two, converts to a np.ndarray. if None, creates a np array of all cells. Returns ------- strf : np.ndarray n_cells x n_frames_per_window x n_features array describing the spatio-temporal receptive field. intercepts : np.ndarray n_cells x n_frames_per_window array containing the intercepts for the STRFs. r2s : np.ndarray returned only if requested; n_cells x n_frames_per_window array containing the explained variance of the STRFfor each frame in the window. ''' # set up array of cells to iterate over cells = self.check_cells(cells=cells) # extract design and response matrices stimuli = self.get_stims_for_recording( recording_idx=recording_idx, window_length=window_length ) responses = self.get_responses_for_recording( recording_idx=recording_idx, window_length=window_length, cells=cells ) # create object to perform fitting if method == 'OLS': fitter = LinearRegression() elif method == 'Ridge': fitter = RidgeCV( cv=kwargs.get('cv', 5) ) elif method == 'Lasso': fitter = LassoCV( normalize=kwargs.get('normalize', True), cv=kwargs.get('cv', 5), max_iter=kwargs.get('max_iter', 10000) ) elif method == 'UoILasso': fitter = UoI_Lasso( normalize=kwargs.get('normalize', True), estimation_score=kwargs.get('estimation_score', 'BIC'), n_lambdas=kwargs.get('n_lambdas', 30), n_boots_sel=kwargs.get('n_boots_sel', 30), n_boots_est=kwargs.get('n_boots_est', 30), selection_thres_min=kwargs.get('selection_thres_min', 1.0), ) else: raise ValueError('method %g is not available.' %method) # extract dimensions and create storage n_features, n_samples = stimuli.shape n_cells = cells.size strf = np.zeros((n_cells, n_features)) intercept = np.zeros(n_cells) r2 = np.zeros(n_cells) bic = np.zeros(n_cells) # iterate over cells for cell_idx, cell in enumerate(cells): # copy response matrix responses = np.roll(responses, -frame, axis=0) # perform fit fitter.fit(stimuli.T, responses[:, cell_idx]) # extract coefficients strf[cell_idx, :] = fitter.coef_.T intercept[cell_idx] = fitter.intercept_ # scores r2[cell_idx] = r2_score( responses[:, cell_idx], fitter.intercept_ + np.dot(stimuli.T, fitter.coef_) ) # get rid of potential unnecessary dimensions strf = np.squeeze(strf) r2 = np.squeeze(r2) if return_score: return strf, intercept, r2 else: return strf, intercept def calculate_strf_for_neurons(self, method, recording_idx, window_length=0.5, return_scores=False, cells=None, **kwargs ): '''Calculates STRF for specified neurons. Parameters ---------- method : string regression method to use when calculating STRFs recording_idx : int recording index to obtain design and response matrices window_length : float number of seconds to fit in STRF window return_scores : bool flag indicating whether to return explained variance over window. cells : int, list, np.ndarray or None the set of cell indices under consideration. if the first two, converts to a np.ndarray. if None, creates a np array of all cells. Returns ------- strf : np.ndarray n_cells x n_frames_per_window x n_features array describing the spatio-temporal receptive field. intercepts : np.ndarray n_cells x n_frames_per_window array containing the intercepts for the STRFs. r2s : np.ndarray returned only if requested; n_cells x n_frames_per_window array containing the explained variance of the STRFfor each frame in the window. ''' # set up array of cells to iterate over cells = self.check_cells(cells=cells) # extract design and response matrices stimuli = self.get_stims_for_recording( recording_idx=recording_idx, window_length=window_length ) responses = self.get_responses_for_recording( recording_idx=recording_idx, window_length=window_length, cells=cells ) # number of frames that will appear in window length n_frames_per_window = self.get_n_frames_per_window( recording_idx=recording_idx, window_length=window_length ) # create object to perform fitting if method == 'OLS': fitter = LinearRegression() elif method == 'Ridge': fitter = RidgeCV( cv=kwargs.get('cv', 5) ) elif method == 'Lasso': fitter = LassoCV( normalize=kwargs.get('normalize', True), cv=kwargs.get('cv', 5), max_iter=kwargs.get('max_iter', 10000) ) elif method == 'UoILasso': fitter = UoI_Lasso( normalize=kwargs.get('normalize', True), estimation_score=kwargs.get('estimation_score', 'BIC'), n_lambdas=kwargs.get('n_lambdas', 30), n_boots_sel=kwargs.get('n_boots_sel', 30), n_boots_est=kwargs.get('n_boots_est', 30), selection_thres_min=kwargs.get('selection_thres_min', 1.0), ) else: raise ValueError('method %g is not available.' %method) # extract dimensions and create storage n_features, n_samples = stimuli.shape n_cells = cells.size strf = np.zeros((n_cells, n_frames_per_window, n_features)) intercepts = np.zeros((n_cells, n_frames_per_window)) # score storage r2s = np.zeros((n_cells, n_frames_per_window)) aics = np.zeros((n_cells, n_frames_per_window)) bics = np.zeros((n_cells, n_frames_per_window)) # iterate over cells for cell_idx, cell in enumerate(cells): # copy response matrix responses_copy = np.copy(responses) # iterate over frames in window for frame in range(n_frames_per_window): print(frame) # perform fit fitter.fit(stimuli.T, responses_copy[:, cell_idx]) # extract coefficients strf[cell_idx, frame, :] = fitter.coef_.T intercepts[cell_idx, frame] = fitter.intercept_ # scores y_true = responses_copy[:, cell_idx] y_pred = fitter.intercept_ + np.dot(stimuli.T, fitter.coef_) n_features = np.count_nonzero(fitter.coef_) + 1 # explained variance r2s[cell_idx, frame] = r2_score( y_true=y_true, y_pred=y_pred ) # bics bics[cell_idx, frame] = self.BIC( y_true=y_true, y_pred=y_pred, n_features=n_features ) # aics aics[cell_idx, frame] = self.AIC( y_true=y_true, y_pred=y_pred, n_features=n_features ) # roll the window up responses_copy = np.roll(responses_copy, -1, axis=0) # get rid of potential unnecessary dimensions strf = np.squeeze(strf) r2s = np.squeeze(r2s) bics = np.squeeze(bics) aics = np.squeeze(aics) if return_scores: return strf, intercepts, r2s, bics, aics else: return strf, intercepts @staticmethod def BIC(y_true, y_pred, n_features): '''Calculate the Bayesian Information Criterion under the assumption of normally distributed disturbances (which allows the BIC to take on the simple form below). Parameters ---------- y_true : np.ndarray array of true response values y_pred : np.ndarray array of predicted response values n_features : int number of features used in the model Returns ------- BIC : float Bayesian Information Criterion ''' n_samples = y_true.size # calculate residual sum of squares rss = np.sum((y_true - y_pred)**2) BIC = n_samples * np.log(rss/n_samples) \ + n_features * np.log(n_samples) return BIC @staticmethod def AIC(y_true, y_pred, n_features): '''Calculate the Akaike Information Criterion under the assumption of normally distributed disturbances. Utilizes a softer penalty on the model parsimony than the BIC. Parameters ---------- y_true : np.ndarray array of true response values y_pred : np.ndarray array of predicted response values n_features : int number of features used in the model Returns ------- AIC : float Akaike Information Criterion ''' n_samples = y_true.size # calculate residual sum of squares rss = np.sum((y_true - y_pred)**2) AIC = n_samples * np.log(rss/n_samples) \ + n_features * 2 return AIC @staticmethod def AICc(y_true, y_pred, n_features): '''Calculate the corrected Akaike Information Criterion under the assumption of normally distributed disturbances. Modifies the parsimony penalty. Useful in cases when the number of samples is small. Parameters ---------- y_true : np.ndarray array of true response values y_pred : np.ndarray array of predicted response values n_features : int number of features used in the model Returns ------- AICc : float corrected Akaike Information Criterion ''' n_samples = y_true.size # calculate residual sum of squares rss = np.sum((y_true - y_pred)**2) AICc = n_samples * np.log(rss/n_samples) \ + n_features * 2 \ + 2 * (n_features**2 + n_features)/(n_samples - n_features - 1) return AICc
C
UTF-8
691
2.65625
3
[]
permissive
/*$Header: /data/petsun4/data1/src_solaris/frame_align/RCS/slice_sequence.c,v 1.1 2011/07/26 05:24:02 avi Exp $*/ /*$Log: slice_sequence.c,v $ * Revision 1.1 2011/07/26 05:24:02 avi * Initial revision **/ #include <stdlib.h> #include <math.h> void slice_sequence (int interleaved, int force0, int reverse, int *seq, int nslice) { int i, j, k, istart, inc; istart = (force0 || !interleaved) ? 0 : (nslice + 1) % 2; inc = (interleaved) ? 2 : 1; k = 0; i = istart; while (k < nslice) { seq[k++] = i; if ((i += inc) >= nslice) i = (istart + 1) % 2; } if (reverse) for (i = 0, j = nslice - 1; i < nslice/2; i++, j--) { k = seq[i]; seq[i] = seq[j]; seq[j] = k; } }
JavaScript
UTF-8
776
3.6875
4
[]
no_license
const raw = require('fs').readFileSync(__dirname + '/input.txt', 'utf-8') const input = Uint32Array.from(raw.split(',').map(Number)) function findNthElement(playUntil = 2020) { let prevValue = 0; const lastIndexOf = new Uint32Array(playUntil); let i = 0; for (i; i < input.length; i++) { prevValue = input[i] lastIndexOf[prevValue] = i + 1 } for (i; i < playUntil; i++) { const prevIndex = lastIndexOf[prevValue] || -1 lastIndexOf[prevValue] = i prevValue = prevIndex === -1 ? 0 : i - prevIndex } return prevValue } console.time('Time') const resultA = findNthElement(2020) const resultB = findNthElement(30000000) console.timeEnd('Time') console.log('Part A:', resultA) console.log('Part B:', resultB)
JavaScript
UTF-8
523
3.578125
4
[]
no_license
let x = 10; console.log(x.lenght); let persona = { nombre: "juan", apellido: "lastra", email: "mewamata@wii.com", edad: 20, nombreCompleto: function() { return this.nombre + " " + this.apellido; } } console.log(persona.nombre); console.log(persona.edad) console.log(persona.apellido); console.log(persona); console.log(persona.nombreCompleto()); let persona2 = new Object(); persona2.nombre = "carla"; persona2.direccion = "Rosas 5555"; persona.tel = "+56 925845"; console.log(persona2.nombre);
Java
UTF-8
1,819
2.5
2
[]
no_license
package com.ee.parkinglot.search; import com.ee.parkinglot.model.Car; import com.ee.parkinglot.model.ParkingSlot; import com.ee.parkinglot.utils.TestUtils; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.*; public class SearchSlotByRegistrationNumberTest { private SearchSlotByRegistrationNumber searchSlotByRegistrationNumber; @Before public void setUp() { searchSlotByRegistrationNumber = new SearchSlotByRegistrationNumber(); } @Test public void shouldGetTheParkingSlotDetailsBasedOnRegistrationNumber() { Car carToBeParked = new Car("abc", Car.Color.Red); List<ParkingSlot> expectedParkingSlots = TestUtils.createMultipleFreeParkingLots(10); ParkingSlot allocatedSlot1 = expectedParkingSlots.get(0); allocatedSlot1.allocatedTo(carToBeParked); List<ParkingSlot> slots = searchSlotByRegistrationNumber.search("abc", expectedParkingSlots); assertEquals(Stream.of(allocatedSlot1).collect(Collectors.toList()), slots); } @Test public void shouldReturnParkingSlotListAsEmpty() { Car carToBeParked = new Car("abc", Car.Color.Red); List<ParkingSlot> expectedParkingSlots = TestUtils.createMultipleFreeParkingLots(10); ParkingSlot allocatedSlot1 = expectedParkingSlots.get(0); allocatedSlot1.allocatedTo(carToBeParked); List<ParkingSlot> slots = searchSlotByRegistrationNumber.search("", expectedParkingSlots); assertTrue(slots.isEmpty()); } @Test public void shouldReturnParkingSlotListAsEmptyWhenNoParkingSlotIsAllocated() { List<ParkingSlot> expectedParkingSlots = TestUtils.createMultipleFreeParkingLots(10); List<ParkingSlot> slots = searchSlotByRegistrationNumber.search("qwewe", expectedParkingSlots); assertTrue(slots.isEmpty()); } }
Markdown
UTF-8
7,980
2.875
3
[]
no_license
# Part Two (B): Deploy and Upgrade Gramola using [OLM](https://github.com/operator-framework/operator-lifecycle-manager) on OpenShift Most of the text is the same as in the other Part Two. I did it to avoid you going back and forth... Part Two is way easier and doesn't involve coding. If you skipped part one because you don't know if you want to spend the time it takes until you have a deeper understanding and how it all works you're at the right place. Here we will install and upgrade the Gramola Operator, an operator in charge of installing and upgrading an application that involves data (*that changes its schema over time In general, you see demos of operators that install a given system and that's it. This is not the case, Gramola, although it is a super-simple musical events system as explained before, stores events in a PostgreSQL database, more over, a change in the database schema is introduced in version 0.0.2 so the operator not only cares about installing the components (Deployments, ConfigMaps, Secrets, etc.) it also cares about updating the images of the different Deployments and, drum roll, upgrading the database schema if needed and migrating data if the schema suffered any changes. All this makes this demonstration, at least so I think, more interesting than the usual demo. We've divided this demo into: 1. Install the CatalogSource and deploy version 0.0.1 2. Generate some data 3. Upgrade the operator moving from version 0.0.1 to 0.0.2 End result: ![Gramola Deployment](./images/gramola-deployed.png) # Prerequisites It would be nice to have basic understanding of what an operator is to follow this guide, but it's not a requirement. Additionally, if you want to run the demo you also need: * Kubernetes/OpenShift Cluster (where you have administrative permissions) or use [Minikube](https://minikube.sigs.k8s.io/docs/start/) as we're going to do most of the time in this guide. **NOTE:** If you had had a look to the [other flavor](./part-2-1.md) of this guide you may have noticed there're fewer requirements here: no need to clone the repo, no need to install OLM, no need to install NGINX Ingress Controller... Why? OpenShift has it all installed and ready to use OOTB. # Deploy a CatalogSource pointing to Gramola Bundle Index 0.0.1 Log in the OpenShift console as a user with administrative privileges and go to `Home->Projects`. We need a project (namespace) to work on so click on `Create Project` and name your project `gramola-operator-system`. ![Create Project](./images/openshift-create-project.png) Now let's add a yaml describing a CatalogSource, click on the `+` sign at the top as in the picture. ![Import YAML](./images/openshift-import-yaml.png) Copy and paste the next content and click `Create`. ```yaml apiVersion: operators.coreos.com/v1alpha1 kind: CatalogSource metadata: name: atarazana-catalog spec: displayName: Atarazana Operators publisher: Atarazana Inc. sourceType: grpc image: quay.io/cvicens/gramola-operator-index:v0.0.1 ``` ![Create Catalog Source](./images/openshift-create-catalog-source.png) # Installing version 0.0.1 of Gramola Operator Now go to `Operators->OperatorHub`. Refresh until you see a new category: `Other`. Then click on it, you should see this. ![Other Catagory](./images/openshift-other-category.png) Click on the Gramola Operator. Once there, click on `Install`. > **NOTICE:** Version is `0.0.1` and Capability level is `Basic Install` ![Other Category](./images/openshift-gramola-operator.png) Make sure all this is selected, then click on `Install`: * Installation Mode: `A specific namespace in the cluster` * Installed Namespace: `gramola-operator-system` * Approval Strategy: `Automatic` ![Gramola Operator Install](./images/openshift-gramola-install.png) After a little while you should see this. Then click on `Gramola Operator`. ![Gramola Operator Installed](./images/openshift-gramola-installed.png) # Deploying Gramola 0.0.1 using the Gramola Operator In order to deploy Gramola we need to create an instance of AppService. The main and in this case only CRD handled by the operator: ![Gramola Operator New AppService](./images/openshift-gramola-new-appservice.png) Filling the form and creating the object. Have a look to the different attributes, make sure that if you play with `Platform` you select `openshift` before clicking on `Create`. ![Gramola Operator Filling Form](./images/openshift-gramola-filling-form.png) If you want to have a look to the AppService you have created. Click on the AppService: ![Gramola Operator AppService](./images/openshift-appservice.png) Now let's have a look to the Topology in the Developer view. Click on `Administrator` (upper left corner) and select `Developer`: > **NOTE:** You'll see the graph evolve and deployments change status. ![Gramola Operator AppService Resources](./images/opemshift-developer-1.png) # Testing Gramola 0.0.1 Once all elements are dark blue (as in the picture above), click on the `gateway` deployment. Then copy the Route link, we'll use it in a second. ![Gramola Operator AppService Resources](./images/openshift-gateway-route.png) As we did with the `operator` plugin, let's create some sample data. Use the url you just copied without the ending slash `/`!!!! > **NOTE:** Don't forget to delete the ending `/`. Don't say I didn't tell you. ```sh ./create-sample-data.sh <gateway-url> ``` Similarly, as we did for `gateway` copy the URL of `frontend`. ![Gramola Frontend url](./images/openshift-frontend-route.png) Open a browser pointing to the URL you just copied. Now you should see this: > **NOTE:** Pay attention to the date field, this will change with 0.0.2 ![Gramola Frontend with data](./images/frontend-2.png) Great! You have tested version 0.0.1 of your operator running automatically through the [Operator Lifecycle Manager](https://github.com/operator-framework/operator-lifecycle-manager). # Upgrading Gramola to 0.0.2 Let's edit the CatalogSource we created before. Go to `Search` and look for `CatalogSource` as in the picture. ![Search CatalogSource](./images/openshift-edit-catalogsource-1a.png) Then click on `atarazana-catalog`: ![Search CatalogSource](./images/openshift-edit-catalogsource-1b.png) And in order to edit the descriptor click on `YAML`. ![Search CatalogSource](./images/openshift-edit-catalogsource-1c.png) **Change 0.0.1 by 0.0.2** as in the picture then click on `Save`. ![Search CatalogSource](./images/openshift-edit-catalogsource-2.png) Please go to `Operators->Installed Operators->Gramola Operator`. Then click on `Subscription`. If you're fast enough you will see the operator upgrading, otherwise you'll find that 0.0.2 has been already installed. ![Gramola Operator Upgrade](./images/openshift-gramola-automatic-upgrade.png) Let's go to `Topology` and see the system being updated. ![Gramola Upgrading](./images/openshift-topology-transition-1.png) Transitioning... database upgrade, images update, etc. ![Gramola Upgrading](./images/openshift-topology-transition-2.png) # Testing version 0.0.2 Once the deployments have been stabilized (all dark blue) open a new browser/new tab and point to the `fronted` URL we used before. This time you should see something like this: > **NOTICE:** The event date has been split into Start and End dates... ![Frontend 0.0.2](./images/frontend-3.png) So you have deployed 0.0.1, created data and then moved to 0.0.2 and all components and database schema have been upgraded and data migrated all automatically. Awesome! # Final thoughts How is this demo different [to the ones on vanilla Kubernetes](./part-2-1.md)? In several aspects: * No need to install OLM because is part of OpenShift and as such is already installed and supported * No need to install NGINX Ingress Controller, OpenShift uses Routes by default. * Web Console integrates everything related to Operators although you can still use kubectl to deal with them.
C++
UTF-8
1,349
2.796875
3
[]
no_license
class Solution { public: int r,c; vector<pair<int,int>>dirs = {{0,1},{0,-1},{1,0},{-1,0}}; bool check(int i,int j){ return i>=0 && j>=0 && i<r && j<c; } void dfs(vector<vector<int>>& grid,int i,int j,vector<vector<int>>& visited){ visited[i][j] = 1; for(auto dir: dirs){ int ii = dir.first + i,jj = dir.second+j; if(check(ii,jj) && grid[ii][jj] && !visited[ii][jj]) dfs(grid,ii,jj,visited); } } bool isDisConnected(vector<vector<int>>& grid){ vector<vector<int>> visited(r,vector<int>(c)); int count = 0; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ if(grid[i][j] == 1 && !visited[i][j]){ dfs(grid,i,j,visited); if((++count) > 1) return true; } } } return false; } int minDays(vector<vector<int>>& grid) { r = grid.size(); c = grid[0].size(); if(isDisConnected(grid)) return 0; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ if(grid[i][j] == 1){ grid[i][j] = 0; if(isDisConnected(grid)) return true; grid[i][j] = 1; } } } return 2; } };
C#
UTF-8
3,203
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Data.Linq.SqlClient; using System.IO; using System.Linq; using System.Text; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support.UI; namespace WebScraper { class Program { static void Main(string[] args) { using (var driver = new ChromeDriver()) { driver.Navigate().GoToUrl("https://login.yahoo.com/?.intl=us&.lang=en-US&.src=finance&authMechanism=primary&done=https%3A%2F%2Ffinance.yahoo.com%2Fportfolio%2Fp_0%2Fview%2Fv1"); var userNameField = driver.FindElementById("login-username"); var userButton = driver.FindElementById("login-signin"); userNameField.SendKeys("webscrape.test@yahoo.com"); userButton.Click(); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); wait.Until((d) => { IWebElement element = d.FindElement(By.Id("login-passwd")); return element.Displayed && element.Enabled ? element : null; }); var userPasswordField = driver.FindElementById("login-passwd"); var loginButton = driver.FindElementByXPath("//button[@id='login-signin']"); userPasswordField.SendKeys("scrapepass1"); loginButton.Click(); wait.Until((d) => { IWebElement element = d.FindElement(By.Id("main")); return element.Displayed && element.Enabled ? element : null; }); // First fetch the table from which we want to scrape/parse indiv row data IWebElement table = driver.FindElement(By.XPath("//tbody")); // Second, parse indiv rows from table -- these will represent each stock row in our portfolio List<IWebElement> rows = new List<IWebElement>(table.FindElements(By.TagName("tr"))); String strRowData = ""; // Traverse each row... foreach (var row in rows) { // ... to fetch the columns List<IWebElement> tds = new List<IWebElement>(row.FindElements(By.TagName("td"))); // Then traverse each column foreach (var td in tds) { // "\t\t" for tabs between tds strRowData = strRowData + td.Text + "\t\t"; } Console.WriteLine(strRowData); strRowData = String.Empty; } } // TODO: Create Stock object from res data for each scraped ticker // TODO: Once object is created, can use with MySQL to create database // TODO: use MVC (create new MVC app) in visualstudio } } }
Java
UTF-8
1,028
1.71875
2
[]
no_license
package com.parvez_n_jabed_co.ccc_project.Activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import com.parvez_n_jabed_co.ccc_project.R; public class CommunicationActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_communication); } public void onClickMeetMayor(View view) { Intent intent = new Intent(CommunicationActivity.this, CommuwithMeyor.class); startActivity(intent); } public void onClickcccNumbers(View view) { Intent intent = new Intent(CommunicationActivity.this, WebViewActivity.class); intent.putExtra("URL", "https://goo.gl/wJDvTv"); //https://drive.google.com/file/d/0ByXcNtvRHMV6Ui1IQnNDSXR4Ylk/view intent.putExtra("visible",1); startActivity(intent); } }
C
UTF-8
3,545
3.265625
3
[]
no_license
/* * Sample file using the Linux kernel coding convention. * * https://www.kernel.org/doc/Documentation/CodingStyle * * General rules: * - Indents are tabs and must be 8 spaces wide. * - Each line must be at most 80 characters long. * - Use C-style comments. * - File names should be lower-case.c * * Copied from: * https://gist.github.com/davidzchen/9187984.js */ #include <stdlib.h> #include <stdbool.h> /* For macros, use ALL_CAPS separated by underscore: */ #define FLAG_FOO 0x0 /* * If a macro's replacement is not just a literal, enclose it in parentheses: */ #define FLAG_BAZ (0x1 << 3) /* * It appears that the Linux kernel codebase tends to use #defines for * constants. Global constants are treated similar to global variables. */ const int state_foo = 0; /* Enum values can either look like macros: */ enum mode { MODE_FOO, MODE_BAR, MODE_BAZ, MODE_QUX }; /* * Names of members of structs are lower_case and separated by underscores. * Avoid typedef-ing types unless the type is intended to be used as an opaque * type. */ struct sample { int first_field; int second_field; Mode mode; State state; struct sample *next; }; /* * Function names are lower_case. Opening braces on the next line. * Use gotos so that there is only one exit point for a given function. */ int sample_equal(struct sample *self, struct sample *other) { int ret = 0; /* Local variables are lower_case and separated by underscores. */ if (self == NULL && other == NULL) { ret = 1; goto out; } if (self == NULL || other == NULL) { goto out } /* * For statements that span multiple lines, use spaces for alignment * only. */ if (self->first_field == other->first_field && self->second_field == other->second_field && self->state == other->state && self->mode == other->mode && self->next == other->next) { ret = true; } out: return ret; } /* * For function declarations that span multiple lines, indent them * "substantially to the right." */ struct sample *sample_new(int first_field, int second_field, int mode, int state, struct sample *next) { struct sample *sample = (struct sample *) malloc(sizeof(*sample)); if (sample == NULL) { sample = NULL; goto out; } memset(sample, 0, sizeof(sample)); sample->first_field = first_field; sample->second_field = second_field; sample->mode = mode; sample->state = state; sample->next = next; out: return sample; } struct sample *sample_clone(struct sample *sample) { if (sample == NULL) { return NULL; } /* * For function calls that span multiple lines, align them to the * right. */ return sample_new(sample->first_field, sample->second_field, sample->mode, sample->state, sample->next); } /* * For function declarations (and function calls) where you cannot fit * the parameters with the first after the opening parentheses, then align * the parameters indented four spaces on the next line: */ static void sample_do_something_with_a_long_name( struct sample *sample, int parameter_with_a_long_name, int another_parameter, int another_parameter) { if (sample == NULL) { goto out; } /* * else and else if comes after the previous closing brace and not on * the next line. */ int local_variable; if (parameter_with_a_long_name == MODE_FOO) { local_variable = 1; } else { local_variable = 0; } sample->first_parameter += another_parameter; sample->second_parameter |= local_variable; out: return; }
C#
UTF-8
574
2.921875
3
[]
no_license
string temp = "Oliver/Christina=2373400019485 Ortosan/David=2373400019486"; var PersonstrList = temp.Split(' '); List<Test> PersonList = new List<Test>(); foreach (var p in PersonstrList) { Test t = new Test(); t.LastName = p.Substring(0,p.IndexOf("/")); t.FirstName = p.Substring(p.IndexOf("/"), p.IndexOf("/") - p.IndexOf("=")); t.Code = p.Substring(p.IndexOf("=")); PersonList.Add(t); }