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
Markdown
UTF-8
2,462
4.3125
4
[]
no_license
**Planning** -Goal is to create a program that checks if an integer is a prime number -A prime number is only dibisible by itself and 1 -1 is not a prime number **V1** -Given n is the input integer -If function to exclude 1 from being a prime number `` if n == 1: return False #1 is not a prime `` -For loop will check if n is prime by dividing with % operato with numbers in range 2-n. If at anypoint the answer to the divison is 0, it means the number was perfectly divisible by another number that wasnt itself or 0, therefore FALSE is returned, otherwise TRUE is returned to indicate that it is a prime number `` for d in range(2, n): if n % d == 0: return False return True `` -V1 is flawed as it takes a very long time to process large numbers. **V2** -To save time in the calculation, the program will only divide and check numbers 2 through the square root of n -This is done because the divisors between and after the multiplication of the square root of n will come out duplicate, meaning doing divisons after the sqrt n times sqrt n will be redundant. `` max_divisor = math.floor(math.sqrt(n)) for d in range(2, 1 + max_divisor): if n % d == 0: return False return True `` **v3** -There is no point testing even integers after 2, so to save more computing time test only odds. `` if n == 2: return True if n > 2 and n % 2 == 0: return False `` CODE `` import math def is_prime_v1(n): """return TRUE if 'n' is a prime number. False Otherwise. """ if n == 1: return False # 1 is not a prime for d in range(2, n): if n % d == 0: return False return True def is_prime_v2(n): """return TRUE if 'n' is a prime number. False Otherwise. """ if n == 1: return False # 1 is not a prime max_divisor = math.floor(math.sqrt(n)) for d in range(2, 1 + max_divisor): if n % d == 0: return False return True def is_prime_v3(n): """return TRUE if 'n' is a prime number. False Otherwise. """ if n == 1: return False # 1 is not the prime # If it's even and not 2, then it's not prime if n == 2: return True if n > 2 and n % 2 == 0: return False max_divisor = math.floor(math.sqrt(n)) for d in range(3, 1 + max_divisor, 2): if n % d == 0: return False return True ``
Rust
UTF-8
2,228
2.578125
3
[ "Apache-2.0", "MIT" ]
permissive
use std::time::Instant; use structopt::StructOpt; use crate::graph::undirected::simple_graph::graph::SimpleGraph; use crate::procedure::configuration::Configuration; use crate::procedure::procedure::GraphProperties; use crate::procedure::procedure_chain::ProcedureChain; use crate::procedure::procedure_registry::ProcedureRegistry; mod graph; mod procedure; mod service; mod tests; /// Simple tool for snark analysis. For more information visit `<https://github.com/jkbstrmen/snark-tool>` #[derive(StructOpt)] struct Cli { /// Command - e.g. 'run' command: String, /// The path to the configuration file - e.g. 'snark-tool.yml' #[structopt(parse(from_os_str))] config_file_path: std::path::PathBuf, } fn parse_yaml_config(source: &String) -> Configuration { let config = match Configuration::from_yaml_string(source) { Ok(configuration) => configuration, Err(error) => panic!("Configuration parse error: {}", error), }; config } fn main() { let args = Cli::from_args(); match args.command.as_ref() { "run" => { let begin = Instant::now(); let config_str = std::fs::read_to_string(&args.config_file_path).expect("could not read file"); let config = parse_yaml_config(&config_str); let registry = ProcedureRegistry::new_basic(); // add builder of own procedure impl to registry as shown below // registry.insert("read".to_string(), ReadProcedureBuilder{}); let chain = ProcedureChain::from_procedures_config(registry, config.procedures); if chain.is_err() { eprintln!("Error: {}", chain.err().unwrap()); return; } let chain = chain.unwrap(); let mut graphs_with_properties: Vec<(SimpleGraph, GraphProperties)> = vec![]; match chain.run(&mut graphs_with_properties) { Err(error) => { eprintln!("Error: {}", error); } Ok(()) => {} } println!("elapsed: {}ms", begin.elapsed().as_millis()); } _ => { println!("Unknown command"); } } }
C#
UTF-8
4,014
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace MemCachedLib.Cached { /// <summary> /// 一致性哈希 /// </summary> /// <typeparam name="T">节点类型</typeparam> public class ConsistentHash<T> { /// <summary> /// 缓存所有哈希键 /// </summary> private int[] hashKeys; /// <summary> /// 初始环大小 /// </summary> private int defaultReplicate = 100; /// <summary> /// 哈希键与节点字典 /// </summary> private SortedDictionary<int, T> keyHashNodeDic; /// <summary> /// 一致性哈希 /// </summary> public ConsistentHash() : this(null) { } /// <summary> /// 一致性哈希 /// </summary> /// <param name="nodes">节点</param> public ConsistentHash(IEnumerable<T> nodes) { this.keyHashNodeDic = new SortedDictionary<int, T>(); if (nodes != null) { foreach (T node in nodes) { this.Add(node, false); } this.hashKeys = keyHashNodeDic.Keys.ToArray(); } } /// <summary> /// 添加一个节点 /// </summary> /// <param name="node">节点</param> public void Add(T node) { this.Add(node, true); } /// <summary> /// 添加一个节点 /// </summary> /// <param name="node">节点</param> /// <param name="updateKeyArray">是否把键更新到局部变量进行缓存</param> private void Add(T node, bool updateKeyArray) { for (int i = 0; i < defaultReplicate; i++) { int hash = HashAlgorithm.GetHashCode(node.GetHashCode().ToString() + i); keyHashNodeDic[hash] = node; } if (updateKeyArray) { this.hashKeys = keyHashNodeDic.Keys.ToArray(); } } /// <summary> /// 删除一个节点 /// </summary> /// <param name="node">节点</param> public bool Remove(T node) { for (int i = 0; i < defaultReplicate; i++) { int hash = HashAlgorithm.GetHashCode(node.GetHashCode().ToString() + i); if (this.keyHashNodeDic.Remove(hash) == false) { return false; } } // 重新加载节点 this.hashKeys = this.keyHashNodeDic.Keys.ToArray(); return true; } /// <summary> /// 获取键对应的节点 /// </summary> /// <param name="key">键</param> /// <returns></returns> public T GetNode(string key) { int firstNode = this.GetHaskKeyIndex(key); return this.keyHashNodeDic[hashKeys[firstNode]]; } /// <summary> /// 获取键所对应的键哈希表的索引 /// </summary> /// <param name="key">键值</param> /// <returns></returns> private int GetHaskKeyIndex(string key) { int hashCode = HashAlgorithm.GetHashCode(key); int begin = 0; int end = this.hashKeys.Length - 1; if (this.hashKeys[end] < hashCode || this.hashKeys[0] > hashCode) { return 0; } int mid = begin; while (end - begin > 1) { mid = (end + begin) / 2; if (this.hashKeys[mid] >= hashCode) { end = mid; } else { begin = mid; } } return end; } } }
PHP
UTF-8
1,495
3.03125
3
[]
no_license
<?php require_once "ajax.php"; $ajax = ajax(); //see controllers/messages.php to view the code that handles this request. //call method controller_messages::messages() in controllers/messages.php $ajax->call("ajax.php?controller=messages&function=show_messages&a=HELLO WORLD"); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Displaying Ajax Messages</title> <?php echo $ajax->init();?> </head> <body> <h2>Response Messages</h2> <div id='msgs'></div> <br /> <br /> Controller: <?php echo $ajax->code(" class controller_messages { function show_messages(\$message) { \$ajax = ajax(); \$ajax->process(\"You are about to see the type of messages you can display on the screen..\",5); \$ajax->update(\"msgs\",\"You are about to see the type of messages you can display on the screen..\"); \$ajax->wait(5); \$ajax->success(\$message. \" Success message...\"); \$ajax->update(\"msgs\",\" Success message...\"); \$ajax->wait(5); \$ajax->warning(\$message.\" Warning message...\"); \$ajax->update(\"msgs\",\" Warning message...\"); \$ajax->wait(5); \$ajax->error(\$message. \" Error Message...\"); \$ajax->update(\"msgs\",\" Error Message...\"); \$ajax->wait(5); \$ajax->process(\$message. \" You can run and display lots of stuff..\",7); \$ajax->update(\"msgs\",\" You can run and display lots of stuff..\"); \$ajax->wait(3); \$ajax->update(\"msgs\",\" :) \"); } } ");?> </body> </html>
C#
UTF-8
740
2.9375
3
[ "MIT" ]
permissive
namespace T1.ParserKit.Core.Utilities { public static class AssertionExtensions { #region AssertNotNull public static void AssertNotNull<T>(this T instance, string message = "Expected a non-null object reference.") where T : class { if (instance == null) throw new NullReferenceException(message); } #endregion //AssertNotNull #region AssertNotNegative public static void AssertNotNegative(this int value, string message = "The specified value cannot be less than zero.") { if (value < 0) throw new InvalidOperationException(message); } #endregion //AssertNotNegative } }
C++
UTF-8
2,990
3.40625
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std; struct Item { Item(int v, Item* n) { val = v; next = n; } int val; Item* next; }; void readIntFile(char* filename, Item*& head1, Item*& head2); void readLine(ifstream& ifile, Item*& head); Item* concatenate(Item* head1, Item* head2); void removeEvens(Item*& head); Item* removeEvensHelper(Item* head); double findAverage(Item* head); double findAverageHelper(Item* head, int& size); void readIntFile(char* filename, Item*& head1, Item*& head2) { ifstream ifile(filename); if( ifile.fail()){ cout << "Couldn't open " << filename << endl; head1 = NULL; head2 = NULL; return; } readLine(ifile, head1); readLine(ifile, head2); ifile.close(); return; } void readLine(ifstream& ifile, Item*& head) { head = NULL; Item* tail = head; int v; string line; getline(ifile, line); stringstream ss(line); while(ss >> v){ Item* newptr = new Item(v, NULL); if(tail == NULL){ tail = newptr; head = newptr; } else { tail->next = newptr; tail = newptr; } } } void removeEvens(Item*& head) { head = removeEvensHelper(head); } Item* removeEvensHelper(Item* head) { if(head == NULL){ return NULL; } else { if(head->val % 2 != 0){ head->next = removeEvensHelper(head->next); return head; } else { Item* nextEven = removeEvensHelper(head->next); delete head; return nextEven; } } } Item* concatenate(Item* head1, Item* head2) { if (head1 == NULL && head2 == NULL){ return NULL; } else if (head1 == NULL && head2 != NULL){ return new Item(head2->val, concatenate(head1, head2->next)); } else { return new Item(head1->val, concatenate(head1->next, head2)); } } double findAverage(Item* head) { int size = 0; return findAverageHelper(head, size) / size; } double findAverageHelper(Item* head, int& size) { if(head == NULL) return 0.0; else { size++; return head->val + findAverageHelper(head->next, size); } } void printList(std::ostream& ofile, Item* head) { if(head == NULL) ofile << std::endl; else { ofile << head->val << " "; printList(ofile, head->next); } } int main(int argc, char* argv[]) { if(argc < 3){ cerr << "Usage: ./q4 input_file output_file" << endl; return 1; } Item* head1, *head2; readIntFile(argv[1], head1, head2); // outputList(cout, head1); // outputList(cout, head2); ofstream ofile(argv[2]); if(ofile.fail()){ cerr << "Couldn't open output file " << argv[2] << endl; } Item* head3 = concatenate(head1, head2); printList(ofile, head3); removeEvens(head3); printList(ofile, head3); double avg = findAverage(head3); printList(ofile, head3); //cout << avg << endl; //cout << avg << endl; //Item* headavg = new Item(avg,NULL); //printList(ofile,headavg); ofile<<avg; ofile.close(); return 0; }
Java
UTF-8
909
2.46875
2
[]
no_license
package com.williansiedschlag.course.services; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.williansiedschlag.course.entities.Order; import com.williansiedschlag.course.respositories.OrderRepository; //Essa anotacao define como um compenete do spring //Com isso vai poder ser injetado automaticamente com autowired @Service public class OrderService { @Autowired // Faça a injeção de dependencia private OrderRepository repository; // Método para retonar todos usuarios do banco de dados public List<Order>FindAll(){ return repository.findAll(); } // Chamar o Order pelo id public Order findById(Long id) { Optional<Order> obj = repository.findById(id); // Vai retorna um Objeto tipo <Order> que estiver dentro o obg return obj.get(); } }
Java
UTF-8
166
2.25
2
[]
no_license
package com.smoothstack.training.wk1day2; /* * An interface for Shape objects */ public interface Shape { public void calculateArea(); public void display(); }
C
UTF-8
6,934
2.546875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "SDL/SDL_image.h" #include "SDL/SDL_mixer.h" #include "SDL/SDL_ttf.h" #include "SDL/SDL.h" #include "fonctions.h" //utiliser des define pour W1,W2,H1 ET H2 const int W1=170; const int H1=309; const int W2=347; const int H2=169; int collision_trigo(SDL_Rect pos_perso,SDL_Rect pos_enemi) { //float W1,W2;//largeur resp du perso et de l enemi //float H1,H2;//hauteur resp du perso et de l enemi float X1,X2;//abscisse resp du cercle cirsconstrit au perso et de l enemi float Y1,Y2;//ordonnee resp du cercle cirsconstrit auperso et de l enemi float w1,w2;//demie largeur resp du perso et de l enemi float h1,h2;//demie hauteur resp du perso et de l enemi float x1,x2;//abscisse resp du perso et de l enemi float y1,y2;//ordonee resp du perso et de l enemi float R1,R2;//rayon du cercle circonstrit resp au perso et de l enemi float D1,D2; float result=0; //initialisation x1=pos_perso.x; y1=pos_perso.y; x2=pos_enemi.x; y2=pos_enemi.y; // 1-nous travaillons avec le cercle circonstrit a l'image //2-determinons (X1,Y1) puis R1 R1=W1/2; h1=H1/2; //coordonnees finales X1=x1+w1; Y1=y1+h1; // calcul de R1 //3-determinons (X2,Y2) puis R2 R2=W2/2; h2=H2/2; //coordonnees finales X2=x2+w2; y2=y2+h2; // calcul de R1 //4-calcul de D1 D1=sqrt(pow(X1-X2,2)+pow(Y1-Y2,2)); //5- calcul de D2 D2=R1+R2; //comparaison if(D1<=D2) { result=1; } return result; } void init_perso(PERSONAGE *perso) { int i; //initialisation for(i=0;i<5;i++) { perso->tab_img[i]=NULL; } for(i=0;i<4;i++) { perso->V.tab_img[i]=NULL; } perso->surface_perso=NULL; perso->V.surface_vie=NULL; //PERSONAGE //chargement surface perso perso->surface_perso=IMG_Load("detective.png"); if(perso->surface_perso==NULL) { printf("Unable to load perso->surface_perso:%s\n",SDL_GetError()); } //chargement tableau d images du perso perso->tab_img[0] = IMG_Load("detective.png"); if(perso->tab_img[0]==NULL) { printf("Unable to load tab_img[0]:%s\n",SDL_GetError()); } perso->tab_img[1] = IMG_Load("detective.png"); if(perso->tab_img[1]==NULL) { printf("Unable to load tab_img[1]:%s\n",SDL_GetError()); } perso->tab_img[2] = IMG_Load("detective.png"); if(perso->tab_img[2]==NULL) { printf("Unable to load tab_img[2]:%s\n",SDL_GetError()); } perso->tab_img[3] = IMG_Load("detective.png"); if(perso->tab_img[3]==NULL) { printf("Unable to load tab_img[3]:%s\n",SDL_GetError()); } perso->tab_img[4] = IMG_Load("detective.png"); if(perso->tab_img[4]==NULL) { printf("Unable to load tab_img[4]:%s\n",SDL_GetError()); } //VIE //chargement surface vie du perso perso->V.surface_vie=IMG_Load("vie0.png"); if(perso->V.surface_vie==NULL) { printf("Unable to load perso->V.surface_vie:%s\n",SDL_GetError()); } //chargement tableau d images de la vie du perso perso->V.tab_img[0]=IMG_Load("vie0.png"); if(perso->V.tab_img[0]==NULL) { printf("Unable to load image_vie,tab_img[0]:%s\n",SDL_GetError()); } perso->V.tab_img[1]=IMG_Load("vie1.png"); if(perso->V.tab_img[1]==NULL) { printf("Unable to load image_vie,tab_img[1]:%s\n",SDL_GetError()); } perso->V.tab_img[2]=IMG_Load("vie2.png"); if(perso->V.tab_img[2]==NULL) { printf("Unable to load image_vie,tab_img[2]:%s\n",SDL_GetError()); } perso->V.tab_img[3]=IMG_Load("vie3.png"); if(perso->V.tab_img[3]==NULL) { printf("Unable to load image_vie,tab_img[3]:%s\n",SDL_GetError()); } //initialisation des autres champs perso->score=0; strcpy(perso->nom_joueur,"joueur1"); perso->V.val=3;//nombre de vie //position perso perso->pos_perso.x=500; perso->pos_perso.y=300; //position vie du perso perso->V.pos_vie.x=250; perso->V.pos_vie.y=5; } void afficher_perso(PERSONAGE perso,SDL_Surface *screen) { SDL_BlitSurface(perso.V.surface_vie,NULL,screen,&(perso.V.pos_vie)); SDL_BlitSurface(perso.surface_perso,NULL,screen, &perso.pos_perso); } void depacer_perso(PERSONAGE *perso,SDL_Event event) { switch(event.type) { case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_UP: perso->pos_perso.y -=10; SDL_WaitEvent(&event); break; case SDLK_DOWN: perso->pos_perso.y +=10; SDL_WaitEvent(&event); break; case SDLK_LEFT: perso->pos_perso.x -=10; SDL_WaitEvent(&event); break; case SDLK_RIGHT: perso->pos_perso.x +=10; SDL_WaitEvent(&event); break; } break; case SDL_MOUSEBUTTONUP: if(event.button.button==SDL_BUTTON_LEFT) { if(event.button.y < perso->pos_perso.y && event.button.x < perso->pos_perso.x ) { while(perso->pos_perso.y > event.button.y) { perso->pos_perso.y-=10; } while(perso->pos_perso.x > event.button.x) { perso->pos_perso.x-=10; } } // if(event.button.x < perso->pos_perso.x && event.button.y > perso->pos_perso.y) { while(perso->pos_perso.x > event.button.x) { perso->pos_perso.x-=10; } while(perso->pos_perso.y < event.button.y) { perso->pos_perso.y+=10; } } // if(event.button.y < perso->pos_perso.y && event.button.x > perso->pos_perso.x) { while(perso->pos_perso.x < event.button.x) { perso->pos_perso.x+=10; } while(perso->pos_perso.y < event.button.y) { perso->pos_perso.y+=10; } } // if(event.button.x > perso->pos_perso.x && event.button.y > perso->pos_perso.y) { while(perso->pos_perso.x < event.button.x) { perso->pos_perso.x+=10; } while(perso->pos_perso.y < event.button.y) { perso->pos_perso.y+=10; } } }//fin if choix du boutton break; } }
C++
UTF-8
3,389
3.875
4
[]
no_license
///////////////////////// // Ian Fisher // CS 172 // 11/7/16 ///////////////////////// #include <iostream> #include "Circle.h" using namespace std; // I interpretted the end of this problem to mean to write a test of some of the operator overload functions in class Circle: // Testing int main() { Circle circle1; // create object circle1 Circle circle2(6.0); // create object circle2 with radius 6 Circle circle3(10.0); // create object circle3 with radius 10.0 Circle circle4; // creates object circle4 Circle circle5(10.0); // create object circle5 of radius 10 // cout what is being tested cout << "Testing:" << endl; cout << "Circle circle1" << endl; cout << "Circle circle2(6.0)" << endl; cout << "Circle circle3(10.0)" << endl; cout << "Circle circle4" << endl; cout << "Circle circle5(10.0)" << endl; cout << endl; cout << endl; // Testing < operator function if (circle1 < circle2) { cout << "circle2 is larger than circle1" << endl; cout << "The area of the circle of radius " << circle1.getRadius() << " is " << circle1.getArea() << endl; cout << "The area of the circle of radius " << circle2.getRadius() << " is " << circle2.getArea() << endl << endl; } else cout << "circle2 is smaller than circle1" << endl; cout << endl; // Testing <= operator function if (circle1 <= circle4) { cout << "circle1 is less than or equal to circle4" << endl; cout << "The area of the circle of radius " << circle1.getRadius() << " is " << circle1.getArea() << endl; cout << "The area of the circle of radius " << circle2.getRadius() << " is " << circle2.getArea() << endl << endl; } else cout << "circle1 is greater than circle4" << endl; cout << endl; // Testing == operator function if (circle3 == circle4) { cout << "circle3 is equal to circle4" << endl; cout << "The area of the circle of radius " << circle1.getRadius() << " is " << circle1.getArea() << endl; cout << "The area of the circle of radius " << circle2.getRadius() << " is " << circle2.getArea() << endl << endl; } else cout << "circle3 is not equal to circle4" << endl; cout << endl; // Testing != operator function if (circle1 != circle2) { cout << "circle1 is not equal to circle2" << endl; cout << "The area of the circle of radius " << circle1.getRadius() << " is " << circle1.getArea() << endl; cout << "The area of the circle of radius " << circle2.getRadius() << " is " << circle2.getArea() << endl << endl; } else cout << "circle1 is equal to circle2" << endl; cout << endl; // Testing > operator function if (circle3 > circle4) { cout << "circle3 is greater than circle4" << endl; cout << "The area of the circle of radius " << circle1.getRadius() << " is " << circle1.getArea() << endl; cout << "The area of the circle of radius " << circle2.getRadius() << " is " << circle2.getArea() << endl << endl; } else cout << "circle3 is not greater than circle4" << endl; cout << endl; // Testing >= operator function if (circle4 >= circle1) { cout << "circle4 is greater than or equal to circle1" << endl; cout << "The area of the circle of radius " << circle1.getRadius() << " is " << circle1.getArea() << endl; cout << "The area of the circle of radius " << circle2.getRadius() << " is " << circle2.getArea() << endl << endl; } else cout << "circle4 is less than circle1" << endl; cout << endl; }
Python
UTF-8
1,268
3.4375
3
[ "MIT" ]
permissive
# GPIOを制御するライブラリ import wiringpi # タイマーのライブラリ import time # 引数取得 import sys # GPIO端子の設定 motor1_pin = 23 motor2_pin = 24 # 引数 param = sys.argv # 第1引数 # go : 回転 # back : 逆回転 # break : ブレーキ order = param[1] # 第2引数 秒数 second = int(param[2]) # GPIO出力モードを1に設定する wiringpi.wiringPiSetupGpio() wiringpi.pinMode( motor1_pin, 1 ) wiringpi.pinMode( motor2_pin, 1 ) if order == "go": if second == 0: print("回転 止めるときはbreak 0コマンド!") else: print(str(second)+"秒回転") wiringpi.digitalWrite( motor1_pin, 1 ) wiringpi.digitalWrite( motor2_pin, 0 ) time.sleep(second) elif order == "back": if second == 0: print("逆回転 止めるときはbreak 0コマンド!") else: print(str(second)+"秒逆回転") wiringpi.digitalWrite( motor1_pin, 0 ) wiringpi.digitalWrite( motor2_pin, 1 ) time.sleep(second) # 第2引数が0の場合は、ブレーキをしない # 第1引数がbreakの場合は、ブレーキ if order == "break" or second != 0: print("ブレーキ!") wiringpi.digitalWrite( motor1_pin, 1 ) wiringpi.digitalWrite( motor2_pin, 1 )
Java
UTF-8
1,166
2.421875
2
[]
no_license
package com.klay.SecondExample_b_s; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.*; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; /** * @description: netty客户端初始化组件 * @author: KlayHu * @create: 2019/10/7 1:30 **/ public class MyClientInitializer extends ChannelInitializer<SocketChannel>{ @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //获取到对应pipeline对象 //往里添加handler,编解码,戳源码 pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)); pipeline.addLast(new LengthFieldPrepender(4)); pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8)); //字符串编解码 pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8)); pipeline.addLast(new MyClientHandler()); } }
C#
UTF-8
4,441
2.84375
3
[ "MIT" ]
permissive
using System; namespace BoletoNetCore { [CarteiraCodigo("1/A")] internal class BancoSicrediCarteira1 : ICarteira<BancoSicredi> { internal static Lazy<ICarteira<BancoSicredi>> Instance { get; } = new Lazy<ICarteira<BancoSicredi>>(() => new BancoSicrediCarteira1()); private BancoSicrediCarteira1() { } public string FormataCodigoBarraCampoLivre(Boleto boleto) { string CampoLivre = boleto.Carteira + "1" + boleto.NossoNumero + boleto.NossoNumeroDV + boleto.Banco.Beneficiario.ContaBancaria.Agencia + boleto.Banco.Beneficiario.ContaBancaria.OperacaoConta + boleto.Banco.Beneficiario.Codigo + "10"; CampoLivre += Mod11(CampoLivre); return CampoLivre; } public void FormataNossoNumero(Boleto boleto) { if (string.IsNullOrWhiteSpace(boleto.NossoNumero)) throw new Exception("Nosso Número não informado."); //Formato Nosso Número //AA/BXXXXX-D, onde: //AA = Ano(pode ser diferente do ano corrente) //B = Byte de geração(0 a 9). O Byte 1 só poderá ser informado pela Cooperativa //XXXXX = Número livre de 00000 a 99999 //D = Dígito verificador pelo módulo 11 // Nosso número não pode ter mais de 8 dígitos if (boleto.NossoNumero.Length == 7 || boleto.NossoNumero.Length > 8) throw new Exception($"Nosso Número ({boleto.NossoNumero}) deve conter até 5 dígitos ou exatamente 6 ou 8 dígitos."); else if (boleto.NossoNumero.Length <= 5) { boleto.NossoNumero = string.Format("{0}2{1}", boleto.DataEmissao.ToString("yy"), boleto.NossoNumero.PadLeft(5, '0')); } else if (boleto.NossoNumero.Length == 6) { if (boleto.NossoNumero.Substring(0, 1) == "1") { throw new Exception($"Nosso Número ({boleto.NossoNumero}) de 6 dígitos não pode começar com 1 (Reservado para Cooperativa)."); } boleto.NossoNumero = string.Format("{0}{1}", boleto.DataEmissao.ToString("yy"), boleto.NossoNumero); } else { if (boleto.NossoNumero.Substring(2, 1) == "1") { throw new Exception($"Nosso Número ({boleto.NossoNumero}) de 8 dígitos não pode ter o Byte (3a. posição) como 1 (Reservado para Cooperativa)."); } } boleto.NossoNumeroDV = Mod11(Sequencial(boleto)).ToString(); boleto.NossoNumeroFormatado = string.Format("{0}/{1}-{2}", boleto.NossoNumero.Substring(0, 2), boleto.NossoNumero.Substring(2, 6), boleto.NossoNumeroDV); } public int Mod11(string seq) { /* Variáveis * ------------- * d - Dígito * s - Soma * p - Peso * b - Base * r - Resto */ int d, s = 0, p = 2, b = 9; for (int i = seq.Length - 1; i >= 0; i--) { s = s + (Convert.ToInt32(seq.Substring(i, 1)) * p); if (p < b) p = p + 1; else p = 2; } d = 11 - (s % 11); if (d > 9) d = 0; return d; } public string Sequencial(Boleto boleto) { string agencia = boleto.Banco.Beneficiario.ContaBancaria.Agencia; //código da cooperativa de crédito/agência beneficiária (aaaa) string posto = boleto.Banco.Beneficiario.ContaBancaria.OperacaoConta; //código do posto beneficiário (pp) if (string.IsNullOrEmpty(posto)) { throw new Exception($"Posto beneficiário não preenchido"); } string beneficiario = boleto.Banco.Beneficiario.Codigo; //código do beneficiário (ccccc) string nossoNumero = boleto.NossoNumero; //ano atual (yy), indicador de geração do nosso número (b) e o número seqüencial do beneficiário (nnnnn); return string.Concat(agencia, posto, beneficiario, nossoNumero); // = aaaappcccccyybnnnnn } } }
Java
UTF-8
3,456
2.171875
2
[]
no_license
/* * Copyright (c) 2007 Thomas Weise for sigoa * Simple Interface for Global Optimization Algorithms * http://www.sigoa.org/ * * E-Mail : info@sigoa.org * Creation Date : 2007-11-29 * Creator : Thomas Weise * Original Filename: test.org.sigoa.refimpl.utils.testseries.successFilters.FirstObjectiveZeroFilter.java * Last modification: 2007-11-29 * by: Thomas Weise * * License : GNU LESSER GENERAL PUBLIC LICENSE * Version 2.1, February 1999 * You should have received a copy of this license along * with this library; if not, write to theFree Software * Foundation, Inc. 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA or download the license * under http://www.gnu.org/licenses/lgpl.html or * http://www.gnu.org/copyleft/lesser.html. * * Warranty : This software is provided "as is" without any * warranty; without even the implied warranty of * merchantability or fitness for a particular purpose. * See the Gnu Lesser General Public License for more * details. */ package org.sigoa.refimpl.utils.testSeries.successFilters; import java.io.Serializable; import org.sigoa.refimpl.utils.testSeries.ISuccessFilter; import org.sigoa.refimpl.utils.testSeries.IndividualEvaluator; import org.sigoa.spec.go.IIndividual; /** * A success filter for the gcd problem * * @author Thomas Weise */ public class FirstObjectiveZeroFilter implements ISuccessFilter<Serializable> { /** * the evaluator */ private final IndividualEvaluator m_eval; /** * create a new gcd success filter * * @param eval * the evaluator */ public FirstObjectiveZeroFilter(final IndividualEvaluator eval) { super(); this.m_eval = eval; } /** * Determine whether an output of a run would be considered as solution * judging by its objective values. * * @param objectives * an array containing the objective values of the individual * @return <code>true</code> if and only if the objective values * indicate success, <code>false</code> otherwise */ public boolean isSuccess(final double[] objectives) { return (objectives[0] <= 0d); } /** * Determine whether an output of a run would be considered as solution * judging by its objective values. * * @param individual * the individual record * @return <code>true</code> if and only if the objective values * indicate success, <code>false</code> otherwise */ public boolean isSuccess(final IIndividual<?, Serializable> individual) { return (individual.getObjectiveValue(0) <= 0d); } /** * Determine whether a successful individual is overfitted or not. * * @param phenotype * the phenotype to check * @return <code>true</code> if the phenotype does not represent a * general solution to the problem, <code>false</code> * otherwise */ @SuppressWarnings("unchecked") public boolean isOverfitted(final Serializable phenotype) { return !(this.isSuccess((IIndividual) (this.m_eval.evaluate(null, phenotype)))); } }
Java
UTF-8
1,085
2.59375
3
[]
no_license
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQXAConnectionFactory; import javax.jms.*; public class TopicProducer { public static final String ACTIVEMQ_URL="tcp://192.168.169.129:61616"; public static final String TOPIC_NAME="TOPIC01"; public static void main(String[] args) throws JMSException { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ACTIVEMQ_URL); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(TOPIC_NAME); MessageProducer messageProducer = session.createProducer(topic); for (int i = 1; i <= 6; i++) { TextMessage textMessage = session.createTextMessage("cherish " + i); messageProducer.send(textMessage); } messageProducer.close(); session.close(); connection.close(); System.out.println("*******消息发布到MQ完成"); } }
Java
UTF-8
1,477
2.34375
2
[]
no_license
package Subapps.Logger.MainScreenLogger.Menu; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.io.IOException; public class MenuController { @FXML private VBox Menu; @FXML public void Close(ActionEvent event) { SwichToScreen("/MainScreen/Main.fxml", "Main"); } @FXML void Addanewlogin(ActionEvent event) { SwichToScreen("/Subapps/Logger/Actions/AddLogin/AddLogin.fxml", "Add new Alarm id"); } @FXML void ImportLogin(ActionEvent event) { SwichToScreen("/Subapps/Logger/Actions/ImportLogin/ImportLogin.fxml", "Import Logins from file"); } @FXML void ExportLoginlist(ActionEvent event) { SwichToScreen("/Subapps/Logger/Actions/ExportLoginList/ExportLoginList.fxml", "Export Alarm list"); } @FXML void About(ActionEvent event) { SwichToScreen("/About/About.fxml", "About"); } private void SwichToScreen(String Path, String ScreenName) { try { Stage stage = (Stage) Menu.getScene().getWindow(); Parent parent = FXMLLoader.load(getClass().getResource(Path)); Scene scene = new Scene(parent); stage.setTitle(ScreenName); stage.setScene(scene); } catch (IOException e) { e.printStackTrace(); } } }
Java
UTF-8
3,559
2.390625
2
[ "Apache-2.0" ]
permissive
package com.qixing.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.qixing.R; import com.qixing.bean.RechargeRecordBean; import com.qixing.utlis.DateUtils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * Created by nuo-rui on 2017/6/8. */ public class RechargeRecordAdapter extends BaseAdapter { private Context mContext; private List<RechargeRecordBean> mList; public RechargeRecordAdapter(Context mContext, List<RechargeRecordBean> mList) { this.mContext = mContext; this.mList = mList; } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder mHolder=null; if(convertView==null){ convertView= LayoutInflater.from(mContext).inflate(R.layout.item_cash_record,null); mHolder=new ViewHolder(); mHolder.tv_recharge_name= (TextView) convertView.findViewById(R.id.item_cash_recharge_record_name); mHolder.tv_recharge_money= (TextView) convertView.findViewById(R.id.item_cash_recharge_record_money); mHolder.tv_recharge_time= (TextView) convertView.findViewById(R.id.item_cash_recharge_record_paymethod); mHolder.tv_recharge_status= (TextView) convertView.findViewById(R.id.item_cash_recharge_record_status); convertView.setTag(mHolder); }else{ mHolder= (ViewHolder) convertView.getTag(); } RechargeRecordBean recordBean=mList.get(position); if("1".equals(recordBean.getMethod())){ mHolder.tv_recharge_name.setText("支付宝"); mHolder.tv_recharge_money.setText("充值"+recordBean.getMoney()+"元"); }else if("2".equals(recordBean.getMethod())){ mHolder.tv_recharge_name.setText("微信"); mHolder.tv_recharge_money.setText("充值"+recordBean.getMoney()+"元"); }else if("3".equals(recordBean.getMethod())){ mHolder.tv_recharge_name.setText("退款"); mHolder.tv_recharge_money.setText("收入"+recordBean.getMoney()+"元"); }else if("4".equals(recordBean.getMethod())){ mHolder.tv_recharge_name.setText("花费"); mHolder.tv_recharge_money.setText("支出"+recordBean.getMoney()+"元"); }else if("5".equals(recordBean.getMethod())){ mHolder.tv_recharge_name.setText("积分"); mHolder.tv_recharge_money.setText("兑换"+recordBean.getMoney()+"元"); }else{ mHolder.tv_recharge_name.setText("平台充值"); mHolder.tv_recharge_money.setText("充值"+recordBean.getMoney()+"元"); } String format= DateUtils.TimeStamp2DateYYYYMMDD(recordBean.getTimes()); mHolder.tv_recharge_time.setText(format); if("1".equals(recordBean.getStatus())) { mHolder.tv_recharge_status.setText("交易成功"); }else{ mHolder.tv_recharge_status.setText("交易失败"); } return convertView; } class ViewHolder{ TextView tv_recharge_name,tv_recharge_money,tv_recharge_time,tv_recharge_status; } }
Python
UTF-8
5,697
3.28125
3
[]
no_license
# This took 2 hours to create # This script runs a sequence of functions to create the final training, validation, and test # sets that we will use for modeling import datetime import numpy as np import pandas as pd def read_in_games(): ''' Creates dataframe for all of the tables we're going to use and joins those tables together. ''' games_1 = pd.read_csv('../data/Games_1.csv') games_2 = pd.read_csv('../data/Games_2.csv') app_id_info = pd.read_csv('../data/App_ID_Info.csv') game_developers = pd.read_csv('../data/Games_Developers.csv') game_genres = pd.read_csv('../data/Games_Genres.csv') all_games = pd.concat((games_1, games_2), axis=0) all_games = ( all_games .merge(app_id_info, on='appid', how='left') .merge(game_developers, on='appid', how='left') .merge(game_genres, on='appid', how='left') ) return all_games def dummify_genres(all_games): ''' This function (1) Converts the game genre into dummy variables (2) aggregates rows on a customer/game basis (e.g. when there were multiple genres for a game) (3) Filters out rows with 0 playtime ''' dummy_genres = pd.get_dummies(all_games['Genre']) all_games = pd.concat((all_games, dummy_genres), axis=1) all_games = all_games.drop(['Genre'], axis=1).reset_index().drop(['index'], axis=1) aggregations = {val: 'max' for val in all_games.columns[2:]} all_games = all_games.groupby(['steamid', 'appid']).agg(aggregations).reset_index() all_games = all_games.loc[all_games.playtime_forever > 0, :] return all_games def get_holdout_games(dummied_games): ''' Adds a label and the associated appid to each customer's row. ''' current_steamid = -1 customer_prediction_apps = {} customer_labels = {} # Get the last row since the dataframe is sorted by customer and then date. for idx in range(dummied_games.shape[0])[::-1]: row = dummied_games.iloc[idx, :] if row.steamid != current_steamid: customer_prediction_apps[row.steamid] = row.appid customer_labels[row.steamid] = row.playtime_forever current_steamid = row.steamid labels = [] appids = [] for idx, row in dummied_games.iterrows(): labels.append(customer_labels[row.steamid]) appids.append(customer_prediction_apps[row.steamid]) dummied_games['labels'] = labels dummied_games['label_appid'] = appids return dummied_games def add_cutomer_level_aggregate_statistics(labeled_games): ''' Get Customer's Mean and Median playtime overall and add to the labeled_games dataframe. ''' # now let's create a dataframe for aggregating all the rows representing other games the player played other_games = labeled_games.loc[labeled_games.label_appid != labeled_games.appid] other_games = other_games.loc[:, ['steamid', 'playtime_forever']] other_games_mean = ( other_games .groupby('steamid') .mean() ) other_games_mean.columns = ['MeanPlaytime'] other_games_median = ( other_games .groupby('steamid') .median() ) other_games_median.columns = ['MedianPlaytime'] other_games_agg = other_games_mean.join(other_games_median, how='inner') other_games_agg.reset_index() labeled_games = labeled_games.merge(other_games_agg, on='steamid', how='left') labeled_games = labeled_games.loc[labeled_games.appid == labeled_games.label_appid] return labeled_games def create_train_test_split(labeled_games): ''' This function performs a temporal train-test split. ''' cutoff_date = datetime.datetime.strptime('2014-09-22', '%Y-%m-%d') games_df = labeled_games.copy() games_df['dateretrieved'] = ( games_df['dateretrieved'] .apply(lambda x: datetime.datetime.strptime(x[:10], '%Y-%m-%d')) ) training_data = games_df.loc[games_df.dateretrieved < cutoff_date] test_data = games_df.loc[games_df.dateretrieved > cutoff_date] filter_columns = [ 'steamid', 'appid', 'dateretrieved', 'labels', 'label_appid', 'Title', 'Type', 'Price', 'Release_Date', 'Developer', 'playtime_2weeks', 'Genre', 'playtime_forever' ] X_train = training_data.loc[:, [col for col in training_data.columns if col not in filter_columns]] X_test = test_data.loc[:, [col for col in training_data.columns if col not in filter_columns]] y_train = training_data.loc[:, 'labels'] y_test = test_data.loc[:, 'labels'] return X_train, X_test, y_train, y_test def save_results_to_csvs(X_train, X_test, y_train, y_test): X_train.to_csv('../data/X_train.csv', index=False, header=True) X_test.to_csv('../data/X_test.csv', index=False, header=True) y_train.to_csv('../data/y_train.csv', index=False, header=True) y_test.to_csv('../data/y_test.csv', index=False, header=True) if __name__ == "__main__": all_games = read_in_games() print("Read in and joined games dataframes.") dummied_games = dummify_genres(all_games) print("Transformed game genres into dummy variables.") labeled_games = get_holdout_games(dummied_games) print("Collected holdout games.") aggregated_games = add_cutomer_level_aggregate_statistics(labeled_games) print("Got aggregate statistics for each customer.") X_train, X_test, y_train, y_test = create_train_test_split(aggregated_games) print("Performed Train-Test split.") save_results_to_csvs(X_train, X_test, y_train, y_test) print("Saved results to csv files.")
Java
UTF-8
2,056
2.453125
2
[]
no_license
package com.cyntex.TourismApp.Logic; import com.cyntex.TourismApp.Beans.BaseResponse; import com.cyntex.TourismApp.Beans.RegistrationRequestBean; import com.cyntex.TourismApp.Beans.RegistrationResponseBean; import com.cyntex.TourismApp.Persistance.RegistrationDAO; import com.cyntex.TourismApp.Util.FSManager; import com.cyntex.TourismApp.Util.PasswordEncrypter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.UUID; @Component public class RegistrationRequestHandler { @Autowired private RegistrationDAO registrationDAO; public BaseResponse handle(RegistrationRequestBean requestBean){ RegistrationResponseBean response = new RegistrationResponseBean(); try{ String imageID = UUID.randomUUID().toString(); String pwdSalt = UUID.randomUUID().toString().substring(0, 8); String locationID = UUID.randomUUID().toString(); FSManager.saveImage(imageID, requestBean.getImage()); registrationDAO.addNewUser( requestBean.getEmail(), requestBean.getFirstName(), requestBean.getLastName(), requestBean.getGender(), requestBean.getCountry(), requestBean.getPhone(), imageID, locationID, pwdSalt, PasswordEncrypter.getsha256Securepassword(requestBean.getPassword(), pwdSalt.getBytes()) ); response.setStatus("SUCCESS"); String id = UUID.randomUUID().toString(); response.setId(id); response.setProfilePicID(imageID); response.setToken(PasswordEncrypter.getsha256Securepassword( id, PasswordEncrypter.SERVER_KEY.getBytes() )); }catch (Exception e) { response.setStatus("FAILED: Cannot register this user"); } return response; } }
JavaScript
UTF-8
704
4.90625
5
[]
no_license
// Write a function `stringSize` that accepts a string as an argument. The function should return the // string 'small' if the argument is shorter than 5 characters, 'medium' if it is exactly 5 characters, and // 'large' if it is longer than 5 characters. let stringSize = function (str) { if (str.length < 5) { return "small"; } else if (str.length > 5) { return "large"; } else { return "medium"; } }; console.log(stringSize("cat")); // 'small' console.log(stringSize("bell")); // 'small' console.log(stringSize("ready")); // 'medium' console.log(stringSize("shirt")); // 'medium' console.log(stringSize("shallow")); // 'large' console.log(stringSize("intelligence")); // 'large'
Python
UTF-8
1,052
2.671875
3
[]
no_license
__author__ = 'Mojca' from google.appengine.ext import ndb import uuid import hmac import hashlib class User(ndb.Model): ime = ndb.StringProperty() mail = ndb.StringProperty() coded_password = ndb.StringProperty() @classmethod def create (cls, ime, mail, password): user = cls(ime=ime, mail=mail, coded_password=cls.code_password(original_password=password)) user.put() return user @classmethod def code_password(cls, original_password): salt = uuid.uuid4().hex code = hmac.new(str(salt), str(original_password), hashlib.sha512).hexdigest() result = "%s:%s" % (code, salt) return result @classmethod def check_password(cls, user, password): code, salt = user.coded_password.split(":") new_code = hmac.new(str(salt), str(password), hashlib.sha512).hexdigest() if new_code == code: return True else: return False
C#
UTF-8
3,012
3.03125
3
[ "MIT" ]
permissive
// Copyright (c) Leonardo Brugnara // Full copyright and license information in LICENSE file using CmdOpt.Environment; namespace CmdOpt.Options { public delegate void OptionHandler<TEnvironment>(TEnvironment env, params string[] arguments) where TEnvironment : Environment<TEnvironment>; public abstract class Option<TEnvironment> where TEnvironment : Environment<TEnvironment> { public Option(string shortopt, string longopt, string description, OptionAttributes attributes) { ShortName = shortopt; LongName = longopt; Description = description; Attributes = attributes; } /// <summary> /// Option's short name /// </summary> public string ShortName { get; } /// <summary> /// Option's long name /// </summary> public string LongName { get; } /// <summary> /// Option description /// </summary> public string Description { get; } /// <summary> /// Option's attributes that determine the behavior /// </summary> public OptionAttributes Attributes { get; } /// <summary> /// Returns true if the option is required by checking if the <see cref="OptionAttributes.Optional"/> is missing and /// the option is not a <see cref="OptionAttributes.SubModule"/> /// </summary> /// <returns>True if the option is required</returns> public bool IsRequired => !Attributes.HasFlag(OptionAttributes.Optional) && !Attributes.HasFlag(OptionAttributes.SubModule); /// <summary> /// The delegate handler that will be called once the option has /// been parsed in order to update the TEnvironment /// </summary> public abstract OptionHandler<TEnvironment> Handler { get; } /// <summary> /// Returns the option description formatted to show in the /// help message /// </summary> /// <param name="neededpad"></param> /// <returns></returns> public string GetFormattedDescription(int neededpad) { if (Description == null) return "\t"; string desc = "\t"; bool needsBreak = false; for (int i=0; i < Description.Length; i++) { if (i > 0 && i % 120 == 0) { if (Description[i] == ' ') { desc += "\n\t".PadRight(neededpad, ' ') + "\t"; } else { needsBreak = true; } } else if (needsBreak && Description[i-1] == ' ') { needsBreak = false; desc += "\n\t".PadRight(neededpad, ' ') + "\t"; } desc += Description[i]; } return desc; } } }
Python
UTF-8
2,835
3.953125
4
[]
no_license
class Node: def __init__(self, value=None, next_node=None, prev_node=None): self.next_node = next_node self.prev_node = prev_node self.value = value def __str__(self): return str(self.value) class List: """ Двунаправленный связный список. """ def __init__(self): # Ограничитель self.top = Node() def append(self, value): """ Добавление нового элемента в конец двунаправленного списка. Время работы O(N). """ # Находим последнюю ячейку. current = self.top while current.next_node is not None: current = current.next_node # Вставляем новую ячеку после current и делаем обратную ссылку. new_node = Node(value) current.next_node = new_node new_node.prev_node = current def prepend(self, value): """ Добавление нового элемента в начало двунаправленного списка. """ new_node = Node(value) # Задаем связи для нового узла new_node.next_node = self.top.next_node new_node.prev_node = self.top # Ставим обратную связь для следующего узла (если он есть) # Связь на новый узел. if self.top.next_node: self.top.next_node.prev_node = new_node # Меняем ограничитель self.top.next_node = new_node def __str__(self): """ Возвращает все элементы связного списка в виде строки. """ current = self.top.next_node values = "[" while current is not None: end = ", " if current.next_node else "" values += str(current) + end current = current.next_node return values + "]" lst = List() lst.prepend(1) lst.prepend(2) lst.prepend(3) assert str(lst) == '[3, 2, 1]' lst = List() lst.append(1) lst.append(2) lst.append(3) lst.prepend(0) assert str(lst) == '[0, 1, 2, 3]' lst = List() lst.append(1) lst.append(2) lst.append(3) lst.append(5) lst.append(7) assert str(lst) == '[1, 2, 3, 5, 7]' lst.prepend(0) lst.prepend(-1) lst.prepend(-2) assert str(lst) == '[-2, -1, 0, 1, 2, 3, 5, 7]' zero = lst.top.next_node.next_node.next_node assert zero.value == 0 assert zero.next_node.value == 1 assert zero.prev_node.value == -1 assert zero.prev_node.prev_node.value == -2 first = lst.top.next_node assert first.value == -2 assert first.next_node.value == -1 assert first.prev_node.value == None
C++
UTF-8
1,974
2.734375
3
[]
no_license
#include "light.h" #include "phong_shader.h" #include "ray.h" #include "render_world.h" #include "object.h" vec3 Phong_Shader:: Shade_Surface(const Ray& ray,const vec3& intersection_point, const vec3& same_side_normal,int recursion_depth,bool is_exiting) const { vec3 color; //Calculate Ambient Color color = color_ambient * (world.ambient_color * world.ambient_intensity); Ray lightRay; vec3 lightColor; for(unsigned int i = 0; i < world.lights.size(); ++i) {//Loop through lights lightRay.direction = world.lights.at(i)->position - intersection_point;//Calculate Direction double sqrdLight = lightRay.direction.magnitude_squared(); lightRay.direction = lightRay.direction.normalized();//Normalize lightRay.endpoint = world.lights.at(i)->position;//Get the position if(world.enable_shadows) {//Check if shadows are on Hit passToShadow; Ray intToLight; intToLight.endpoint = intersection_point; intToLight.direction = lightRay.direction; intToLight.direction = intToLight.direction.normalized(); if(world.Closest_Intersection(intToLight, passToShadow)){//If there's something in the ray if(passToShadow.t < sqrt(sqrdLight)) {//If the object is closer than int_point continue; //skip adding diffuse and specular } } } //Calculate Diffuse and Add to color lightColor = world.lights.at(i)->Emitted_Light(lightRay); lightColor /= sqrdLight; double temp = std::max(dot(lightRay.direction, same_side_normal) , 0.0); color += (lightColor * color_diffuse * temp); //Calculate Specular and Add to color vec3 reflectDirection = (2 * dot(lightRay.direction, same_side_normal) * same_side_normal) - lightRay.direction; vec3 oppRayDir = ray.direction.normalized() * -1; double specInt = std::max(dot(reflectDirection,oppRayDir), 0.0); specInt = pow(specInt, specular_power); color += (lightColor * color_specular * specInt); } return color; }
Markdown
UTF-8
1,153
3.28125
3
[]
no_license
# pass_crypt ## Introduction pass\_crypt is a simple Ruby application that allows the secure storage and retrieval of usernames and passwords. Usernames and passwords are stored in an SQLite database, encrypted using AES 256-bit encryption with a personal passphrase. Passwords can be inserted and retrieved using the clipboard for convenience and security. ## Requirements - clipboard (gem) gem install clipboard # may require sudo - xclip & libsqlite3 (linux packages) sudo apt-get install xclip libsqlite3 - You also need a version of Ruby installed that includes the OpenSSL libraries. Refer to http://www.ruby-lang.org for help in installing Ruby. ## Installation This will soon become a *gem* with bundler support. Until then... Using Git, clone the repository: git clone git@github.com:jamesds/pass_crypt.git ## Usage Simply run pass\_crypt with no parameters to be shown brief usage instructions. The SQLite database containing the encrypted data is kept in '~/.pass\_crypt/crypt.db'. It may be wise to make backups of this file. ## License Use as you wish. I'll get a formal license when I release this as a gem.
Ruby
UTF-8
2,024
3.359375
3
[]
no_license
puts "###########################################" puts "### Welcome to Awesome Address Book 2.0 ###" puts "###########################################" puts # blank line for spacing ### Oops: You were missing the quotes around 'pry'. ### I went ahead and fixed it so that I could ### run the rest of the code. require 'pry' require_relative 'lib/connect' require_relative 'lib/models' ### IMO, it's still worthwhile to move the menu ### into a separate file. For instance, you might ### decide that you'd like to test the menu ### functionality in the future. So, having it ### in a separate file will make it easier to test ### that feature without executing the rest of ### the code. # technically not a reusable class, but a one-time model, so I'm treating it seperately. dunno if that's the best require_relative 'lib/menu_object' is_running = true invalid = "** Invalid Selection **" begin puts #new line for spacing # FOR TESTING ONLY Entry.delete_all m_select = run_menu # stores return value for menu selction if m_select == 1 puts # blank line puts "Adding a new entry..." e = Entry.new puts "First Name: " e.first_name = gets.chomp puts "Last Name: " e.last_name = gets.chomp e.save enter_phone = true begin ### lol print "Add a phone number? (yolo/no-no) : " # so that any string that begins with 'y' or 'n' is valid phone_choice = gets.chars.first.downcase.chomp if phone_choice == "y" p = PhoneNumber.new() p.entry_id = e.id print "Category: " p.category = gets.chomp print "Phone Number: " p.p_num = gets.chomp ### Oops. Debug code. binding.pry elsif phone_choice == "n" enter_phone = false else puts invalid end end while enter_phone == true elsif m_select == 2 elsif m_select == 3 else puts invalid end end while is_running == true
TypeScript
UTF-8
5,246
2.8125
3
[ "Apache-2.0", "MIT" ]
permissive
import type { ContractRequest, RunningTestsState, StartContractInterceptOptions, } from './types'; import { checkAndGetTestInfo } from './helpers/checkAndGetTestInfo'; import { generateEmptyTestState } from './helpers/generateEmptyTestState'; const runningTestState: RunningTestsState = {}; /** * A wrapper around `cy.intercept` that allows intercepting and recording the request/response series * that made up the contract. * * It could be useful for sharing the contract's fixtures with the server folks. * * Be aware of the current limitations: * 1. Only one test at the time is supported. `runningTestState` can store more tests at once but * the fixture files are all saved starting from "1 - ", even if related to different tests * 2. If you do not call cy.haltContractIntercept, no fixture files will be saved * * @see https://github.com/hasura/graphql-engine-mono/issues/4601 */ function startContractIntercept( startContractInterceptOptions: StartContractInterceptOptions, url: string ) { const { thisTest, mode, createFixtureName } = startContractInterceptOptions; const { testTitle, testPath } = checkAndGetTestInfo(thisTest); if (mode === 'disabled') { Cypress.log({ message: `*🤝 ❌ No Contract will be recorded for ${testTitle}*`, }); return; } Cypress.log({ message: `*🤝 ✅ Contract will be recorded for ${testTitle}*`, }); runningTestState[testTitle] ??= generateEmptyTestState(testPath, testTitle); if (Object.keys(runningTestState).length > 1) { throw new Error(`startContractIntercept support only one test at a time`); } // Start intercepting the requests cy.intercept(url, request => { // The recorded could have been halted if (runningTestState[testTitle].halted) { Cypress.log({ message: `*🤝 ❌ Contract recording has been halted for: ${testTitle}*`, }); return; } const fixtureName = createFixtureName(request); if (fixtureName.includes('\\') || fixtureName.includes('/')) { throw new Error( `createFixtureName cannot return names that includes / or \\ like ${fixtureName}` ); } const contractLength = runningTestState[testTitle].contract.length; // start from 1 const fixtureIndex = contractLength + 1; const fixtureFileName = `${fixtureIndex}-${fixtureName}.json`; const recorded: ContractRequest = { readme: '////////// This fixture has been automatically generated through cy.startContractIntercept //////////', request, fixtureName, fixtureFileName, // Temporary, empty, response response: { statusCode: undefined, headers: undefined, body: undefined, }, }; // Add the request to the Contract runningTestState[testTitle].contract.push(recorded); Cypress.log({ message: `*🤝 ✅ Recorded ${fixtureFileName} in the contract*`, consoleProps: () => request, }); request.continue(response => { // Add the request to the Contract too recorded.response = response; }); }); } /** * Halt recording the contract and save the fixture files. * Please note that it must be called just once */ function haltContractIntercept(options: { thisTest: Mocha.Context; saveFixtureFiles?: boolean; }) { const { thisTest, saveFixtureFiles = true } = options; const { testTitle, testPath } = checkAndGetTestInfo(thisTest); if (!saveFixtureFiles) { Cypress.log({ message: `*🤝 ❌ No fixtures will be saved for this test: ${testTitle}*`, }); return; } if (runningTestState[testTitle].halted) { Cypress.log({ message: `*🤝 ❌ Contract recording for this test has already been halted: ${testTitle}*`, }); } // Halt recording the requests for the current test. // Please note that must be done asynchronously because of the double-run nature of the Cypress tests. cy.wrap(null).then(() => { Cypress.log({ message: `*🤝 ❌ Halting the contract recording for this test: ${testTitle}*`, }); runningTestState[testTitle].halted = true; }); // Split the current path cy.task('splitPath', { path: testPath }).then(result => { const splittedPath = result as string[]; // Remove the file name splittedPath.pop(); // Create the directory cy.task('joinPath', { path: [...splittedPath, 'fixtures'] }).then(path => { cy.task('mkdirSync', { dir: path as string, }); }); const testState = runningTestState[testTitle]; // Save all the files for (let i = 0, n = testState.contract.length; i < n; i++) { const request = testState.contract[i]; cy.task('joinPath', { // Stores the fixture files close to the test file, in a "fixtures" directory path: [...splittedPath, 'fixtures', request.fixtureFileName], }).then(filePath => { // Save the fixture file cy.task('writeFileSync', { file: filePath as string, data: JSON.stringify(request, null, 2), }); }); } }); } Cypress.Commands.add('startContractIntercept', startContractIntercept); Cypress.Commands.add('haltContractIntercept', haltContractIntercept);
PHP
UTF-8
2,960
2.65625
3
[]
no_license
<!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <?php $miconexion = mysqli_connect('localhost', 'root', '', 'bbddblog', 3306); //Conprobar conexion if (!$miconexion) { echo 'La conexión ha fallado' . mysqli_error(); die('Connect Error: ' . mysqli_connect_errno()); exit(); } if ($_FILES['imagen']['error']) { //Ver las posibles consecuencias de error en la API de PHP switch ($_FILES['imagen']['error']) { case 1: //Error exceso de tamaño de archivo en php.ini echo 'El tamaño del archivo excede lo permitido por el servidor'; break; case 2: //Error tamaño archivo marcado desde formulario (imput hidden) echo 'El tamaño del archivo excede 2 MB'; break; case 3: //corrupcion de archivo echo 'El envío del archivo se interrumpió'; break; case 4: //No hay archivo echo 'No se ha enviado ningún archivo'; break; } }else{ echo 'Entrada subida correctamente<br/>'; if((isset($_FILES['imagen']['name']) && ($_FILES['imagen']['error']==UPLOAD_ERR_OK))){ $destino_ruta='imagenes/'; move_uploaded_file($_FILES['imagen']['tmp_name'], $destino_ruta . $_FILES['imagen']['name']); echo 'El archivo ' . $_FILES['imagen']['name'] . ' se ha copiado en el directorio de imágenes<br/>'; }else{ echo 'El archivo no se ha podido copiar al directorio de imágenes<br/>'; } } $eltitulo=$_POST['campo_titulo']; $lafecha= date("Y-m-d H:i:s"); $elcomentario=$_POST['area_comentarios']; $laimagen=$_FILES['imagen']['name']; $miconsulta="INSERT INTO CONTENIDO (TITULO, FECHA, COMENTARIO, IMAGEN) VALUES ('" . $eltitulo . "', '" . $lafecha . "', '" . $elcomentario . "', '" . $laimagen . "')"; $resultado= mysqli_query($miconexion, $miconsulta); /*Cerramos conexion*/ mysqli_close($miconexion); echo 'Se ha agregado el comentario con éxito'; ?> <a href="Formulario.php">añadir nueva entrada</a> <a href="Mostrar_blog.php">Ver blog</a> </body> </html>
Python
UTF-8
1,289
3.578125
4
[]
no_license
import numpy as np # sigmoid function def sigmoid(x,deriv = False): if (deriv == True): return x * (1 - x) return 1 / (1 + np.exp(-x)) def dsigmoid(x,deriv = False): if (deriv == True): return 1.0 - x**2 return x * (1 - x) # input dataset (输入数据集,形式为矩阵,每一行代表一个训练样本) X = np.array([ [0,0,1], [0,1,1], [1,0,1], [1,1,1] ]) # output dateset 输出数据集,形式为向量,每一行代表一个训练样本 y = np.array([[0,0,1,1]]).T # seed random number to make calculation # deterministic (just make a good practice) np.random.seed(1) # initialize weights randomly with mean 0 # 第一层权值,突触0,连接l0层与l1层 syn0 = 2 *np.random.random((3,1))-1 for iter in range(10000): # forward propagation # 网络第一层,即网络输入层 l0 = X # 网络第二层,即隐藏层 l1 = sigmoid(np.dot(l0,syn0)) # how much did we miss? l1_error = y - l1 # multiply how much we missed by the slope of the sigmoid at the value in l1 l1_deleta = l1_error * sigmoid(l1,True) # update weights syn0 += np.dot(l0.T,l1_deleta) print("Out After training :") print(l1)
PHP
UTF-8
1,111
2.78125
3
[ "MIT" ]
permissive
<?php function sig_handler($signo) { switch ($signo) { case SIGTERM: case SIGINT: exit; } } function isDaemonActive($pid_file) { if( is_file($pid_file) ) { $pid = file_get_contents($pid_file); //проверяем на наличие процесса if(posix_kill($pid,0)) { //демон уже запущен return true; } else { //pid-файл есть, но процесса нет if(!unlink($pid_file)) { //не могу уничтожить pid-файл. ошибка exit(-1); } } } return false; } if (isDaemonActive('/tmp/parser_daemon.pid')) { echo 'Daemon already active'; exit; } $pid = pcntl_fork(); declare(ticks=1); if ($pid == -1) { die('Error fork process' . PHP_EOL); } elseif ($pid) { exit(); } else { pcntl_signal(SIGTERM, "sig_handler"); pcntl_signal(SIGINT, "sig_handler"); while(true) { exec('php artisan command:parse'); sleep(600); } } posix_setsid();
C++
UTF-8
1,210
3.34375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int preced(char ch) { if(ch == '+' || ch == '-') return 1; else if(ch == '*' || ch == '/') return 2; else if(ch == '^') return 3; else return 0; } string inToPost(string st ) { stack<char> stk; stk.push('#'); string postfix = ""; for(int i=0; i<st.length(); i++) { if(isalnum(st[i])) postfix += st[i]; else if(st[i] == '(') stk.push('('); else if(st[i] == '^') stk.push('^'); else if(st[i] == ')') { while(stk.top() != '#' && stk.top() != '(') { postfix += stk.top(); stk.pop(); } stk.pop(); }else { if(preced(st[i]) > preced(stk.top())) stk.push(st[i]); else { while(stk.top() != '#' && preced(st[i]) <= preced(stk.top())) { postfix += stk.top(); stk.pop(); } stk.push(st[i]); } } } while(stk.top() != '#') { postfix += stk.top(); stk.pop(); } return postfix; } int main() { int T; cin>>T; while(T--){ string st; cin>>st; cout<<inToPost(st)<<endl; } }
C#
UTF-8
1,606
2.625
3
[]
no_license
using UnityEngine; using System; using UnityEngine.Audio; public class audioManager : MonoBehaviour { public Sound[] sound; // Start is called before the first frame update void Awake() { foreach (Sound item in sound) { item.source = gameObject.AddComponent<AudioSource>(); item.source.clip = item.clip; item.source.volume = item.volume; item.source.pitch = item.pitch; item.source.loop = item.loop; } } public void Play(string name) { Sound s = Array.Find(sound, sound => sound.name == name); if (s == null) { Debug.Log("Sound " + name + " Not found"); return; } else { s.source.Play(); } } public void PlayOneShot(string name) { Sound s = Array.Find(sound, sound => sound.name == name); name = s.clip.name; if (s == null) { Debug.Log("Sound " + name + " Not found"); return; } else { s.source.PlayOneShot(s.clip); } } public void Pause(bool sound) { AudioListener.pause = sound; } public void Stop(string name) { Sound s = Array.Find(sound, sound => sound.name == name); if (s == null) { Debug.Log("Sound " + name + " Not found"); return; } else { s.source.Stop(); } } void Update() { } }
TypeScript
UTF-8
2,282
2.546875
3
[ "Apache-2.0" ]
permissive
/* tslint:disable */ /* eslint-disable */ /* * Cloud Governance Api * * Contact: support@avepoint.com */ import { exists, mapValues } from '../runtime'; import { MessageCode, MessageCodeFromJSON, MessageCodeFromJSONTyped, MessageCodeToJSON, } from './'; /** * * @export * @interface ClonePermissionValidateResult */ export interface ClonePermissionValidateResult { /** * * @type {string} * @memberof ClonePermissionValidateResult */ siteId?: string; /** * * @type {string} * @memberof ClonePermissionValidateResult */ siteUrl?: string | null; /** * * @type {boolean} * @memberof ClonePermissionValidateResult */ isValid?: boolean; /** * * @type {string} * @memberof ClonePermissionValidateResult */ errorMessage?: string | null; /** * * @type {MessageCode} * @memberof ClonePermissionValidateResult */ messageCode?: MessageCode; } export function ClonePermissionValidateResultFromJSON(json: any): ClonePermissionValidateResult { return ClonePermissionValidateResultFromJSONTyped(json, false); } export function ClonePermissionValidateResultFromJSONTyped(json: any, ignoreDiscriminator: boolean): ClonePermissionValidateResult { if ((json === undefined) || (json === null)) { return json; } return { 'siteId': !exists(json, 'siteId') ? undefined : json['siteId'], 'siteUrl': !exists(json, 'siteUrl') ? undefined : json['siteUrl'], 'isValid': !exists(json, 'isValid') ? undefined : json['isValid'], 'errorMessage': !exists(json, 'errorMessage') ? undefined : json['errorMessage'], 'messageCode': !exists(json, 'messageCode') ? undefined : MessageCodeFromJSON(json['messageCode']), }; } export function ClonePermissionValidateResultToJSON(value?: ClonePermissionValidateResult | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'siteId': value.siteId, 'siteUrl': value.siteUrl, 'isValid': value.isValid, 'errorMessage': value.errorMessage, 'messageCode': MessageCodeToJSON(value.messageCode), }; }
PHP
UTF-8
4,822
2.796875
3
[]
no_license
<?php class BookModel extends Model { public function getBooks() { $sql = "SELECT * from books"; $query = $this->db->prepare( $sql ); $query->execute(); return $query->fetchAll(); } public function getBooksByAuthor( $authorId ) { $sql = "select b.id, b.name, b.price, b.image from books b, authors a, book_to_author ba where ba.book_id = b.id and a.id = ba.author_id and a.id = :authorId"; $query = $this->db->prepare( $sql ); $query->execute( [ ':authorId' => $authorId ] ); return $query->fetchAll(); } public function getBookById( $booksId ) { $sql = "select b.id, b.name, b.description, b.price, b.year, b.image, GROUP_CONCAT(DISTINCT g.name) as genre, GROUP_CONCAT(DISTINCT a.name) as author from books b, genres g, authors a, book_to_genre bg, book_to_author ba where bg.book_id = b.id and ba.book_id = b.id and g.id = bg.genre_id and a.id = ba.author_id and b.id = :bookId GROUP BY b.name"; $query = $this->db->prepare( $sql ); $query->execute( [ ':bookId' => $booksId ] ); return $query->fetch(); } public function deleteBookById( $bookId ) { $sql = "DELETE books,book_to_author, book_to_genre FROM books INNER JOIN book_to_author ON books.id = book_to_author.book_id inner JOIN book_to_genre ON books.id = book_to_genre.book_id WHERE books.id = :book_id; "; $query = $this->db->prepare( $sql ); return $query->execute( [ ':book_id' => $bookId ] ); } public function updateBookById( $bookId, $variables ) { $sql = "UPDATE books SET name = :name, description = :description, price = :price, year = :year, image = :image WHERE id = :id"; $query = $this->db->prepare( $sql ); $query->execute( [ ':name' => $variables['name'], ':description' => $variables['description'], ':price' => $variables['price'], ':year' => $variables['year'], ':image' => $variables['image'], ':id' => $bookId ] ); $sql = "DELETE FROM book_to_genre where book_id=:bookId"; $query = $this->db->prepare( $sql ); $query->execute( [ ':bookId' => $bookId ] ); $sql = "DELETE FROM book_to_author where book_id=:bookId"; $query = $this->db->prepare( $sql ); $query->execute( [ ':bookId' => $bookId ] ); foreach ($variables['authors'] as $authorId){ $sql = "INSERT INTO book_to_author (book_id, author_id) values (:bookId, :authorId)"; $query = $this->db->prepare( $sql ); $query->execute( [ ':bookId' => $bookId, ':authorId' => $authorId ] ); } foreach ($variables['genres'] as $genreId){ $sql = "INSERT INTO book_to_genre (book_id, genre_id) values (:bookId, :genreId)"; $query = $this->db->prepare( $sql ); $query->execute( [ ':bookId' => $bookId, ':genreId' => $genreId ] ); } } public function saveBook( $variables ) { $sql = "INSERT INTO books (name, description, image, price, year) values (:name, :description, :image, :price, :year)"; $query = $this->db->prepare( $sql ); $query->execute( [ ':name' => $variables['name'], ':description' => $variables['description'], ':price' => $variables['price'], ':year' => $variables['year'], ':image' => $variables['image'], ] ); $bookId = $this->db->lastInsertId(); foreach ($variables['authors'] as $authorId){ $sql = "INSERT INTO book_to_author (book_id, author_id) values (:bookId, :authorId)"; $query = $this->db->prepare( $sql ); $query->execute( [ ':bookId' => $bookId, ':authorId' => $authorId ] ); } foreach ($variables['genres'] as $genreId){ $sql = "INSERT INTO book_to_genre (book_id, genre_id) values (:bookId, :genreId)"; $query = $this->db->prepare( $sql ); $query->execute( [ ':bookId' => $bookId, ':genreId' => $genreId ] ); } } }
Python
UTF-8
6,584
2.859375
3
[ "MIT" ]
permissive
import argparse from collections import defaultdict import random import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler def str2bool(v): if isinstance(v, bool): return v elif v.lower() in ("yes", "true", "y", "1"): return True elif v.lower() in ("no", "false", "n", "0"): return False else: raise argparse.ArgumentTypeError("Boolean liked value expected...") def read_data(data_path, train_path, test_path, sep, header, label_col, train_frac, seed, implicit_threshold=0, neg_sample=False): if data_path is not None: loaded_data = pd.read_csv(data_path, sep=sep, header=header) if neg_sample: # for implicit data, convert all labels to 1 loaded_data.iloc[:, label_col] = 1 else: loaded_data.iloc[:, label_col] = ( loaded_data.iloc[:, label_col].apply( lambda x: 1 if x > implicit_threshold else 0 ) ) train_data, test_data = train_test_split( loaded_data, train_size=train_frac, random_state=seed ) train_data = train_data.to_numpy() test_data = test_data.to_numpy() elif train_path is not None and test_path is not None: train_data = pd.read_csv(train_path, sep=sep, header=header) test_data = pd.read_csv(test_path, sep=sep, header=header) if neg_sample: train_data.iloc[:, label_col] = 1 test_data.iloc[:, label_col] = 1 else: train_data.iloc[:, label_col] = train_data.iloc[:, label_col].apply( lambda x: 1 if x > implicit_threshold else 0) test_data.iloc[:, label_col] = test_data.iloc[:, label_col].apply( lambda x: 1 if x > implicit_threshold else 0) train_data = train_data.to_numpy() test_data = test_data.to_numpy() else: raise ValueError("must provide data_path or train_path && test_path") return train_data, test_data def normalize_data(train_data, test_data, num_cols): for col in num_cols: scaler = StandardScaler() # data is numpy format train_data[:, col] = scaler.fit_transform( train_data[:, col].reshape(-1, 1)).flatten() test_data[:, col] = scaler.transform( test_data[:, col].reshape(-1, 1)).flatten() return train_data, test_data def filter_data(train_data, test_data, cat_cols): print("test size before filtering: ", len(test_data)) out_of_bounds_row_indices = set() for col in cat_cols: unique_values_set = set(pd.unique(train_data[:, col])) for i, t in enumerate(test_data[:, col]): if t not in unique_values_set: out_of_bounds_row_indices.add(i) # filter test values that are not in train_data mask = np.arange(len(test_data)) test_data = test_data[~np.isin(mask, list(out_of_bounds_row_indices))] print("test size after filtering: ", len(test_data)) return train_data, test_data def index_data(train_data, cat_cols, num_cols): total_count = 0 total_cols = cat_cols + num_cols cat_unique_vals = defaultdict(dict) # format: {col: {val: index}} num_unique_vals = defaultdict(list) # format: {col: [index, min, max]} for col in total_cols: if col in cat_cols: unique_vals, indices = np.unique( train_data[:, col], return_inverse=True ) unique_indices = np.unique(indices) unique_indices += total_count cat_unique_vals[col].update(zip(unique_vals, unique_indices)) unique_vals_length = len(unique_vals) cat_unique_vals[str(col)+"_len"] = unique_vals_length cat_unique_vals[str(col)+"_idx"] = list(unique_indices) total_count += unique_vals_length elif col in num_cols: # may need to convert numpy data types to python data types col_min, col_max = min(train_data[:, col]), max(train_data[:, col]) num_unique_vals[col].extend([total_count, col_min, col_max]) total_count += 1 return cat_unique_vals, num_unique_vals def pos_gen_data(data, label_col, cat_cols, num_cols, cat_vals, num_vals, ffm): total_cols = cat_cols + num_cols label = data[label_col] sample = list(str(label)) for field, col in enumerate(total_cols): val = data[col] if col in cat_cols: idx_val_pair = ( "{}:{}:{}".format(field, cat_vals[col][val], 1) if ffm else "{}:{}".format(cat_vals[col][val], 1) ) elif col in num_cols: idx_val_pair = ( "{}:{}:{}".format(field, num_vals[col][0], val) if ffm else "{}:{}".format(num_vals[col][0], val) ) # noinspection PyUnboundLocalVariable sample.append(idx_val_pair) sample = " ".join(sample) return sample def neg_gen_data(cat_cols, num_cols, cat_vals, num_vals, ffm): total_cols = cat_cols + num_cols sample = list("0") for field, col in enumerate(total_cols): if col in cat_cols: vals = cat_vals[str(col)+"_idx"] n_unique_vals = cat_vals[str(col)+"_len"] # i = random.randrange(n_unique_vals) i = int(n_unique_vals * random.random()) idx_val_pair = ( "{}:{}:{}".format(field, vals[i], 1) if ffm else "{}:{}".format(vals[i], 1) ) elif col in num_cols and ( np.issubdtype(type(num_vals[col][1]), np.integer) ): min_val = num_vals[col][1] max_val = num_vals[col][2] val = random.randrange(min_val, max_val + 1) idx_val_pair = ( "{}:{}:{}".format(field, num_vals[col][0], val) if ffm else "{}:{}".format(num_vals[col][0], val) ) elif col in num_cols and ( np.issubdtype(type(num_vals[col][1]), np.floating) ): min_val = num_vals[col][1] max_val = num_vals[col][2] val = (max_val - min_val) * random.random() + min_val idx_val_pair = ( "{}:{}:{}".format(field, num_vals[col][0], val) if ffm else "{}:{}".format(num_vals[col][0], val) ) # noinspection PyUnboundLocalVariable sample.append(idx_val_pair) sample = " ".join(sample) return sample
C
UTF-8
6,012
2.53125
3
[ "Apache-2.0" ]
permissive
#include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit.h> /* Fit * * y = X c * * where X is an n x p matrix of n observations for p variables. * * The solution includes a possible standard form Tikhonov regularization: * * c = (X^T X + lambda^2 I)^{-1} X^T y * * where lambda^2 is the Tikhonov regularization parameter. * * The function multifit_linear_svd() must first be called to * compute the SVD decomposition of X * * Inputs: X - least squares matrix * y - right hand side vector * tol - singular value tolerance * lambda - Tikhonov regularization parameter lambda; * ignored if <= 0 * rank - (output) effective rank * c - (output) model coefficient vector * rnorm - (output) residual norm ||y - X c|| * snorm - (output) solution norm ||c|| * work - workspace * * Notes: * 1) The dimensions of X must match work->n and work->p which are set * by multifit_linear_svd() * 2) On input: * work->A contains U * work->Q contains Q * work->S contains singular values * 3) If this function is called from gsl_multifit_wlinear(), then * the input y points to work->t, which contains sqrt(W) y. Since * work->t is also used as scratch workspace by this function, we * do the necessary computations with y first to avoid problems. * 4) When lambda <= 0, singular values are truncated when: * s_j <= tol * s_0 */ static int multifit_linear_solve (const gsl_matrix * X, const gsl_vector * y, const double tol, const double lambda, size_t * rank, gsl_vector * c, double *rnorm, double *snorm, gsl_multifit_linear_workspace * work) { const size_t n = X->size1; const size_t p = X->size2; if (n != work->n || p != work->p) { GSL_ERROR("observation matrix does not match workspace", GSL_EBADLEN); } else if (n != y->size) { GSL_ERROR("number of observations in y does not match matrix", GSL_EBADLEN); } else if (p != c->size) { GSL_ERROR ("number of parameters c does not match matrix", GSL_EBADLEN); } else if (tol <= 0) { GSL_ERROR ("tolerance must be positive", GSL_EINVAL); } else { const double lambda_sq = lambda * lambda; double rho_ls = 0.0; /* contribution to rnorm from OLS */ size_t j, p_eff; /* these inputs are previously computed by multifit_linear_svd() */ gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p); gsl_matrix_view Q = gsl_matrix_submatrix(work->Q, 0, 0, p, p); gsl_vector_view S = gsl_vector_subvector(work->S, 0, p); /* workspace */ gsl_matrix_view QSI = gsl_matrix_submatrix(work->QSI, 0, 0, p, p); gsl_vector_view xt = gsl_vector_subvector(work->xt, 0, p); gsl_vector_view D = gsl_vector_subvector(work->D, 0, p); gsl_vector_view t = gsl_vector_subvector(work->t, 0, n); /* * Solve y = A c for c * c = Q diag(s_i / (s_i^2 + lambda_i^2)) U^T y */ /* compute xt = U^T y */ gsl_blas_dgemv (CblasTrans, 1.0, &A.matrix, y, 0.0, &xt.vector); if (n > p) { /* * compute OLS residual norm = || y - U U^T y ||; * for n = p, U U^T = I, so no need to calculate norm */ gsl_vector_memcpy(&t.vector, y); gsl_blas_dgemv(CblasNoTrans, -1.0, &A.matrix, &xt.vector, 1.0, &t.vector); rho_ls = gsl_blas_dnrm2(&t.vector); } if (lambda > 0.0) { /* xt <-- [ s(i) / (s(i)^2 + lambda^2) ] .* U^T y */ for (j = 0; j < p; ++j) { double sj = gsl_vector_get(&S.vector, j); double f = (sj * sj) / (sj * sj + lambda_sq); double *ptr = gsl_vector_ptr(&xt.vector, j); /* use D as workspace for residual norm */ gsl_vector_set(&D.vector, j, (1.0 - f) * (*ptr)); *ptr *= sj / (sj*sj + lambda_sq); } /* compute regularized solution vector */ gsl_blas_dgemv (CblasNoTrans, 1.0, &Q.matrix, &xt.vector, 0.0, c); /* compute solution norm */ *snorm = gsl_blas_dnrm2(c); /* compute residual norm */ *rnorm = gsl_blas_dnrm2(&D.vector); if (n > p) { /* add correction to residual norm (see eqs 6-7 of [1]) */ *rnorm = sqrt((*rnorm) * (*rnorm) + rho_ls * rho_ls); } /* reset D vector */ gsl_vector_set_all(&D.vector, 1.0); } else { /* Scale the matrix Q, QSI = Q S^{-1} */ gsl_matrix_memcpy (&QSI.matrix, &Q.matrix); { double s0 = gsl_vector_get (&S.vector, 0); p_eff = 0; for (j = 0; j < p; j++) { gsl_vector_view column = gsl_matrix_column (&QSI.matrix, j); double sj = gsl_vector_get (&S.vector, j); double alpha; if (sj <= tol * s0) { alpha = 0.0; } else { alpha = 1.0 / sj; p_eff++; } gsl_vector_scale (&column.vector, alpha); } *rank = p_eff; } gsl_blas_dgemv (CblasNoTrans, 1.0, &QSI.matrix, &xt.vector, 0.0, c); /* Unscale the balancing factors */ gsl_vector_div (c, &D.vector); *snorm = gsl_blas_dnrm2(c); *rnorm = rho_ls; } return GSL_SUCCESS; } }
Java
UTF-8
4,394
2.40625
2
[ "MIT" ]
permissive
package com.qiyei.android.http.dialog; import android.util.Log; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.qiyei.android.http.common.HttpLog; /** * @author Created by qiyei2015 on 2017/10/25. * @version: 1.0 * @email: 1273482124@qq.com * @description: */ public class LoadingManager { public static final String TAG = "LoadingManager"; /** * 显示对话框 * @param manager * @param tag */ public static void showLoadingDialog(FragmentManager manager, String tag){ if (manager == null){ return; } try { LoadingDialog dialog = new LoadingDialog(); dialog.setCancelable(false); FragmentTransaction fragmentTransaction = manager.beginTransaction(); fragmentTransaction.add(dialog, tag); fragmentTransaction.commitNowAllowingStateLoss(); HttpLog.d(TAG,"showLoadingDialog tag:" + tag); } catch (Exception e) { e.printStackTrace(); HttpLog.e(TAG,"showLoadingDialog Exception:" + e.getMessage()); } } /** * 取消对话框显示 * @param manager * @param tag */ public static void dismissLoadingDialog(FragmentManager manager, String tag){ if (manager == null){ return; } try { Fragment fragment = manager.findFragmentByTag(tag); if (fragment instanceof LoadingDialog){ LoadingDialog dialog = (LoadingDialog) fragment; dialog.dismissAllowingStateLoss(); HttpLog.d(TAG,"dismissLoadingDialog tag:" + tag); } else { HttpLog.w(TAG,"dismissLoadingDialog error,tag:" + tag + " is not a LoadingDialog"); } } catch (Exception e) { e.printStackTrace(); HttpLog.e(TAG,"dismissLoadingDialog Exception:" + e.getMessage()); } } /** * 显示对话框 * @param manager * @param tag */ public static void showProgressDialog(FragmentManager manager, String tag){ if (manager == null){ return; } try { ProgressDialog dialog = new ProgressDialog(); dialog.setCancelable(false); FragmentTransaction fragmentTransaction = manager.beginTransaction(); fragmentTransaction.add(dialog, tag); fragmentTransaction.commitNowAllowingStateLoss(); HttpLog.d(TAG,"showProgressDialog tag:" + tag); } catch (Exception e) { e.printStackTrace(); HttpLog.e(TAG,"showProgressDialog Exception:" + e.getMessage()); } } /** * 取消对话框显示 * @param manager * @param tag */ public static void dismissProgressDialog(FragmentManager manager,String tag){ if (manager == null){ return; } Fragment fragment = manager.findFragmentByTag(tag); try { if (fragment instanceof ProgressDialog){ ProgressDialog dialog = (ProgressDialog) fragment; dialog.dismissAllowingStateLoss(); HttpLog.d(TAG,"dismissProgressDialog tag:" + tag); } else { HttpLog.w(TAG,"dismissProgressDialog error,tag:" + tag + " is not a ProgressDialog"); } } catch (Exception e) { HttpLog.e(TAG,"dismissProgressDialog Exception:" + e.getMessage()); } } /** * 取消对话框显示 * @param manager * @param tag * @param progress */ public static void setProgress(FragmentManager manager,String tag,int progress){ if (manager == null){ return; } Fragment fragment = manager.findFragmentByTag(tag); try { if (fragment instanceof ProgressDialog){ ProgressDialog dialog = (ProgressDialog) fragment; dialog.setProgress(progress); HttpLog.d(TAG,"setProgress tag:" + tag + " progress=" + progress); } else { HttpLog.w(TAG,"setProgress error,tag:" + tag + " is not a ProgressDialog"); } } catch (Exception e) { HttpLog.e(TAG,"setProgress Exception:" + e.getMessage()); } } }
PHP
UTF-8
1,550
2.84375
3
[]
no_license
<?php require_once 'src/bootstrap.php'; /** * Classes to use in this example. */ use \tripsort\assets\CardFactory; use \tripsort\assets\CardAbstract; use \tripsort\assets\transportable\Person; use \tripsort\assets\TransportableAbstract; use \tripsort\modules\travel\Travel; #creating tickets $tickets = array( CardFactory::create(array( 'source' => 'São Paulo Metro Station', 'destination' => 'São Paulo Airport', 'vehicle' => 'metro', 'seat' => null, 'gate' => null )), CardFactory::create(array( 'source' => 'Marina', 'destination' => 'São Paulo Metro Station', 'vehicle' => 'taxi', 'seat' => null, 'gate' => null )), CardFactory::create(array( 'source' => 'São Paulo Airport', 'destination' => 'Dubai Airport', 'vehicle' => 'taxi', 'seat' => '112b', 'gate' => '30XB' )) ); #add passagers $passengers = array( new Person('Fabio'), new Person('William'), new Person('Conceição') ); #Give the correct order to the crowd $travel = new Travel($passengers, $tickets); $route = $travel->sortTickets()->getTickets(); $passenger = $travel->getPassengers(); print("{$passenger}: \n"); foreach ($route as $key => $value) { print_r("From: {$value->source}\n"); print_r("Destination: {$value->destination}\n"); print_r("Vehicle: {$value->vehicle}\n"); if ($value->seat) { print_r("Seat: {$value->seat}\n"); } if ($value->gate) { print_r("Gate: {$value->gate}\n"); } print_r("\n----------------------------------\n"); }
Shell
UTF-8
1,150
3.796875
4
[]
no_license
# Cleaning up echo "Cleaning up working files" rm replacements.sed rm pages.index rm pages.paths rm pages.categorieswithextension # Pull markdown from Github echo "Pulling content from Github" cd content git pull origin # Render HTML echo "Rendering HTML from Markdown" cd .. markdoc build # Build index echo "Indexing pages" cd rendered find -name \*.html > "../pages.paths" sed 's|[./]*||' "../pages.paths" > "../pages.categorieswithextension" sed 's|\.html$||' "../pages.categorieswithextension" > "../pages.index" # Create sed script for auto-linking echo "Building Replacement Script" for linkedTitle in $(< "../pages.index");do # Build hyperlink for linkedTitle hyperlink="<a href=\"/$linkedTitle\">$linkedTitle</a>" # Append replacment string to file echo "s|$linkedTitle|$hyperlink|g" >> "../replacements.sed" done # Auto-link each HTML page echo "Auto-linking pages" for title in $(< "../pages.index");do # Determine page path htmlPagePath="$title.html" # Replace all occurrences of linkedTitle with hyperlink echo "Auto-linking $title" sed -i.bak -f "../replacements.sed" $htmlPagePath done # All done echo "Done!"
SQL
UTF-8
173
3.515625
4
[ "MIT" ]
permissive
# Write your MySQL query statement below select a.id,IFNULL(b.student,a.student) as student from seat as a left join seat as b on a.id = (b.id-1+(b.id&1)*2) order by id asc;
Python
UTF-8
509
3.640625
4
[]
no_license
def ExcelColumn(n): s = '' i = 0 while n > 0: rem = n % 26 if rem == 0: s += 'Z' i += 1 n = (n // 26) - 1 else: s += chr((rem - 1) + ord('A')) i += 1 n = n // 26 return s[::-1] if __name__ == '__main__': t = int(input('Enter the number of test cases:- ')) for i in range(t): n = int(input('Enter the number to see its equivalent column alphabet:- ')) print(ExcelColumn(n))
C#
UTF-8
1,897
3.25
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BasicFileIO { public partial class Form1 : Form { public Form1() { InitializeComponent(); InitVariable(); } private void InitVariable() { textBoxDisplay.Text = "Hi, Hello, Good, \r\nNext Line."; } private void Form1_Load(object sender, EventArgs e) { } private void buttonBinaryWriter_Click(object sender, EventArgs e) { BinaryWriter bw = new BinaryWriter(new FileStream("a.dat", FileMode.Create)); bw.Write(1234); bw.Close(); } private void buttonBinaryReader_Click(object sender, EventArgs e) { BinaryReader br = new BinaryReader(new FileStream("a.dat", FileMode.Open)); int num1 = br.ReadInt32(); Console.WriteLine("Read int = " + num1); br.Close(); } private void buttonStreamWriter_Click(object sender, EventArgs e) { StreamWriter sw = new StreamWriter(new FileStream("a.txt", FileMode.Create)); sw.Write("김개똥"); } private void buttonStreamReader_Click(object sender, EventArgs e) { StreamReader sr = new StreamReader(new FileStream("a.txt", FileMode.Open)); textBoxDisplay.Text = ""; while (sr.EndOfStream == false) { textBoxDisplay.Text += sr.ReadLine(); textBoxDisplay.Text += "\r\n"; } sr.Close(); } private void textBox1_TextChanged(object sender, EventArgs e) { } } }
Java
UTF-8
2,609
3.484375
3
[]
no_license
package protoType; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class ProtoType implements Cloneable,Serializable { private static final long serialVersionUID = 1L; private String string; private SerializableObject obj; public String getString() { return string; } public void setString(String string) { this.string = string; } public SerializableObject getObj() { return obj; } public void setObj(SerializableObject obj) { this.obj = obj; } //浅复制 public Object clone() throws CloneNotSupportedException { ProtoType proto = (ProtoType) super.clone(); return proto; } /* 深复制 */ public Object deepClone() throws IOException, ClassNotFoundException { /* 写入当前对象的二进制流 */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); /* 读出二进制流产生的新对象 */ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return ois.readObject(); } //第二种深复制的方法,属性为应用对象的,该引用对象需要重写clone方法。 public Object deepClone2() throws CloneNotSupportedException{ ProtoType proto = (ProtoType) super.clone(); proto.setObj((SerializableObject) (this.getObj().clone())); return proto; } public static void main(String[] args) throws CloneNotSupportedException, ClassNotFoundException, IOException { ProtoType protoType = new ProtoType(); protoType.setObj(new SerializableObject()); ProtoType protoType2 = (ProtoType) protoType.clone(); //浅复制,引用对象是同一个对象 System.out.println(protoType.getObj().equals(protoType2.getObj())); ProtoType protoType3 = (ProtoType) protoType.deepClone2(); //深复制,所有的属性都是新的,引用对象不同 System.out.println(Objects.equals(protoType.getObj(), protoType3.getObj())); List<String> a = new ArrayList<String>(); a.add("1"); a.add("2"); a.add("3"); for (String temp : a) { if ("2".equals(temp)) { a.remove(temp); } } System.out.println(a.size()); } }
Python
UTF-8
697
3.078125
3
[]
no_license
#!/usr/bin/python import sys, os, re, shutil pivot = int(sys.argv[1]) direction = sys.argv[2] if len(sys.argv) > 2 else '+' dir_path = os.getcwd() paths = os.listdir(dir_path) paths_with_numbered_filenames = sorted([path for path in paths if re.match('^[0-9]+', path)]) def increment_path(path, value): match = re.match('^([0-9]+)(.+)', path) if match is None: return num_str, base_path = match.group(1), match.group(2) num = int(num_str) num += value new_path = '{}{}'.format(str(num).zfill(2), base_path) shutil.move(path, new_path) for path in paths_with_numbered_filenames[pivot:]: if direction == '+': increment_path(path, 1) else: increment_path(path, -1)
Java
UTF-8
1,106
2.25
2
[]
no_license
/* * Cribbed from http://vafer.org/blog/20061010091658/ */ package org.jruby.ext.jmxwrapper; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; import java.rmi.server.RMIServerSocketFactory; import javax.net.ServerSocketFactory; public class RMIServerSocketFactoryImpl implements RMIServerSocketFactory { private final InetAddress localAddress; public RMIServerSocketFactoryImpl(final String address) throws UnknownHostException { localAddress = InetAddress.getByName(address); } public RMIServerSocketFactoryImpl(final InetAddress address) { localAddress = address; } public ServerSocket createServerSocket(final int port) throws IOException { return ServerSocketFactory.getDefault().createServerSocket(port, 0, localAddress); } public boolean equals(Object obj) { return obj != null && obj.getClass().equals(getClass()); } public int hashCode() { return RMIServerSocketFactoryImpl.class.hashCode(); } }
Shell
UTF-8
2,345
3.125
3
[]
no_license
#!/bin/bash [% c("var/set_default_env") -%] output_dir=[% dest_dir %]/[% c('filename') %] gradle_repo=$rootdir/[% c('input_files_by_name/gradle-dependencies') %] # The download script assumes artifact package name is the complete URL path. # In some cases this is incorrect, so copy those artifacts to correct location cp -r $gradle_repo/guardianproject/gpmaven/master/* $gradle_repo cp -r $gradle_repo/dl/android/maven2/* $gradle_repo cp -r $gradle_repo/maven2/* $gradle_repo cp -r $gradle_repo/plugins-release/* $gradle_repo mkdir -p /var/tmp/build $output_dir [% pc(c('var/compiler'), 'var/setup', { compiler_tarfile => c('input_files_by_name/' _ c('var/compiler')) }) %] tar -C /var/tmp/build -xf [% project %]-[% c('version') %].tar.gz # Patch projects cd /var/tmp/build/[% project %]-[% c('version') %] # Gradle patch provided so that when generating a gradle dependency list, the # build will pull down the correct android tool versions patch -p1 < $rootdir/gradle.patch patch -p1 < $rootdir/0001-Bug-33931-Filter-bridges-in-stream-by-type.patch patch -p1 < $rootdir/0001-Bug-30318-Add-snowflake-support.patch [% FOREACH arch = ['armv7', 'aarch64', 'x86', 'x86_64'] -%] # Extract obfs4proxy from TorBrowser/Tor/PluggableTransports/obfs4proxy tar --strip-components=4 -xf $rootdir/[% c('input_files_by_name/obfs4-' _ arch) %] # Extract snowflake from TorBrowser/Tor/PluggableTransports/snowflake tar --strip-components=4 -xf $rootdir/[% c('input_files_by_name/snowflake-' _ arch) %] # Overwrite the obfs4proxy binary provided by Pluto and add Snowflake [% IF arch == "armv7" -%] cp obfs4proxy external/pluto/bin/armeabi-v7a/ cp obfs4proxy external/pluto/bin/armeabi/ cp snowflake-client external/pluto/bin/armeabi-v7a/ cp snowflake-client external/pluto/bin/armeabi/ [% ELSIF arch == "aarch64" -%] cp obfs4proxy external/pluto/bin/arm64-v8a/ cp snowflake-client external/pluto/bin/arm64-v8a/ [% ELSE -%] cp obfs4proxy external/pluto/bin/[% arch %]/ cp snowflake-client external/pluto/bin/[% arch %]/ [% END -%] rm obfs4proxy rm snowflake-client [% END -%] # Build Android Libraries and Apps gradle --offline --no-daemon -P androidplugin=3.6.0 -Dmaven.repo.local=$gradle_repo assembleRelease -x lint # Package cp universal/build/libs/* android/build/outputs/aar/* $output_dir
Markdown
UTF-8
2,648
3.140625
3
[ "MIT" ]
permissive
date: February 2 2014 # Pastebin for photos A dozen of entrepreneurs already talked to me about their idea for solving the photo mess. Which means that there are at least 20,000 entrepreneurs out there trying all possible angles to attack this problem. Yet, no one has nailed it yet. Someone will, someday. Here is my take on it. ![Photobin](public/img/photobin.png) I love simple products that are easy to understand. The more easy they are to explain to someone else, the more effective the word of mouth is going to be, which is key to get traction. So to keep it simple, my goal here is not to address the entire photo mess problem but only to address the particular issue of gathering pictures from multiple people for an event that you care about (the perfect example of such event is a birthday party or a wedding). I don't have the time to build it so feel free to give life to this idea if you like it. It's all copyleft. We need a pastebin for photos. A place where I can quickly create a bucket where I can "copy paste" (it's more uploading in this case) the pictures I have about a shared event and invite others to contribute with their pictures. Here is how it would work: I go to PhotoBin.io, I create a new bin by simply entering a title. It redirects me to the final private url of that album (something like pastebin.io/hash(title,salt)) that I can already copy paste and share by email or IM to my friends. Whoever opens that url get to drag and drop any image without any authentication. Once you have uploaded photos it asks you for an email if you want to be notified whenever someone ads new photos to the album. You also have the opportunity to favorite a few pictures to help everyone quickly identify what the best shots are. Once you are done (let's say after you gave everybody a week or two), you can send an automatic photo montage of the best pictures to everyone who contributed. Every one can also, if they want to, download the entire album or order a printed copy ($$). No authentication, no friction. It's pastebin for photo sharing. I can see that working. I would totally use that for the coming wedding of my brother. Talking of which, I believe that the wedding industry is the perfect ITM ([Initial Target Market](initial-target-market)). Weddings is the obvious use case where you have both photos that everyone would want to get (the ones of the professional photographer) and photos from dozen of amateur photographers that a few, including the bride and groom, want to easily gather in one place. And all participants would gladly receive a short photo montage of the best shots. Hack away!
Java
UTF-8
8,514
2.25
2
[]
no_license
package com.renke.rdbao.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; public class SFTPUtil { public static void main(String[] args) { try { // upload("test.pdf", new File("E://lookadd.pdf")); downSftp("118.178.183.216", "4396", "renke", "renosdata123-3", "/usr/rdbao/mns_consumer/rdbao-center-mns-consumer-0.0.1-SNAPSHOT", "rdbao-center-mns-consumer-0.0.1-SNAPSHOT.jar", "E:\\QQPCmgr\\Desktop\\web音视频插件/rdbao-center-mns-consumer-0.0.1-SNAPSHOT.jar"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // public static void upload(String remoteFileName, File localFile) throws // FileNotFoundException, JSchException, SftpException { // upload(SFTPProperties.host, SFTPProperties.port, SFTPProperties.username, // SFTPProperties.password, SFTPProperties.remotePath, remoteFileName, // localFile); // } public static void upload(String host, String port, String account, String pwd, String remotePath, String remoteFileName, File localFile) throws JSchException, FileNotFoundException, SftpException { SFTPHandle sftp = null; try { sftp = new SFTPHandle(host, port, account, pwd); sftp.connect(); sftp.upload(localFile, remotePath, remoteFileName); } finally { sftp.disconnect();// 关闭连接 } } // public static void downSftp(String remoteFileName, String localPath) // throws JSchException, SftpException, IOException { // downSftp(SFTPProperties.host, SFTPProperties.port, // SFTPProperties.username, SFTPProperties.password, // SFTPProperties.remotePath, remoteFileName, localPath); // } public static void downSftp(String host, String port, String account, String pwd, String remotePath, String remoteFileName, String localPath) throws JSchException, SftpException, IOException { SFTPHandle sftp = null; try { sftp = new SFTPHandle(host, port, account, pwd); sftp.connect(); sftp.download(remotePath, remoteFileName, localPath); } finally { sftp.disconnect();// 关闭连接 } } // public static void deleteFileSftp(String remoteFileName) throws // JSchException, SftpException, IOException { // deleteFileSftp(SFTPProperties.host, SFTPProperties.port, // SFTPProperties.username, SFTPProperties.password, // SFTPProperties.remotePath, remoteFileName); // } public static void deleteFileSftp(String host, String port, String account, String pwd, String remotePath, String remoteFileName) throws JSchException, SftpException, IOException { SFTPHandle sftp = null; try { sftp = new SFTPHandle(host, port, account, pwd); sftp.connect(); sftp.delete(remotePath, remoteFileName); } finally { sftp.disconnect();// 关闭连接 } } // public static void deleteDirSftp(String dir) throws JSchException, // SftpException, IOException { // deleteDirSftp(SFTPProperties.host, SFTPProperties.port, // SFTPProperties.username, SFTPProperties.password, // SFTPProperties.remotePath, dir); // } public static void deleteDirSftp(String host, String port, String account, String pwd, String remotePath, String dir) throws JSchException, SftpException, IOException { SFTPHandle sftp = null; try { sftp = new SFTPHandle(host, port, account, pwd); sftp.connect(); sftp.deleteDir(remotePath, dir); } finally { sftp.disconnect();// 关闭连接 } } } class SFTPHandle { private Logger log = LoggerFactory.getLogger(SFTPHandle.class); private ChannelSftp sftp = null; private Session sshSession = null; private String userName; private String host; private int port; private String password; public SFTPHandle() { super(); } public SFTPHandle(String host, String port, String userName, String password) { this.userName = userName; this.host = host; this.password = password; this.port = Integer.valueOf(port); } /** * connect server via sftp * * @throws JSchException */ public void connect() throws JSchException { JSch jsch = new JSch(); jsch.getSession(userName, host, port); sshSession = jsch.getSession(userName, host, port); // System.out.println("Session created."); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); // System.out.println("Session connected."); // System.out.println("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; log.info("Connected to " + host + "."); } /** * Disconnect with server */ public void disconnect() { if (sftp != null) { if (sftp.isConnected()) { log.info("close Channel---------------------------------"); System.out.println("关闭Channel连接"); sftp.disconnect(); } } if (sshSession != null) { if (sshSession.isConnected()) { log.info("close sshSession---------------------------------"); sshSession.disconnect(); } } } public void delete(String directory, String remoteFileName) throws SftpException, IOException { sftp.cd(directory); sftp.rm(remoteFileName); } public void deleteDir(String directory, String dir) throws SftpException, IOException { sftp.cd(directory); sftp.rmdir(dir); } public void download(String directory, String downloadFile, String saveFile) throws SftpException, IOException { sftp.cd(directory); File file = new File(saveFile); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } OutputStream out = new FileOutputStream(file); sftp.get(downloadFile, out); out.flush(); out.close(); } public void upload(File localFile, String remotePath, String remoteFileName) throws FileNotFoundException, SftpException { log.info("------------remotePath--------" + remotePath); log.info("------------remotePath--------" + remotePath); log.info("------------remoteFileName--------" + remoteFileName); log.info("------------remoteFile--------" + remotePath + "/" + remoteFileName); log.info("------------remotePath.substring(1)--------" + remotePath.substring(1)); String remoteFile = remotePath + "/" + remoteFileName; createDir(remotePath.substring(1)); sftp.put(new FileInputStream(localFile), remoteFile); } private boolean createDir(String remotePath) { if (remotePath != null || remotePath.trim().length() > 0) { log.info("------------remotePath--------" + remotePath); } else { log.info("------------remotePath==null--------" + remotePath); } String[] dirs = remotePath.split("/"); if (remotePath.startsWith("/")) { dirs[0] = "/"; } for (int j = 0; j < dirs.length; j++) { boolean cdFlag = false; boolean mkFlag = false; try { sftp.cd(dirs[j]); cdFlag = true; } catch (SftpException e) { cdFlag = false; } // 如果进不了文件夹,那就创建文件夹 if (!cdFlag) { try { sftp.mkdir(dirs[j]); mkFlag = true; } catch (SftpException e) { mkFlag = false; } if (!mkFlag) { log.error("mkdir fail!"); return false; } else { try { sftp.cd(dirs[j]); } catch (SftpException e) { log.error("cd dir fail!", e); return false; } } } } return true; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName * the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the host */ public String getHost() { return host; } /** * @param host * the host to set */ public void setHost(String host) { this.host = host; } /** * @return the port */ public int getPort() { return port; } /** * @param port * the port to set */ public void setPort(int port) { this.port = port; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } }
JavaScript
UTF-8
27,680
2.59375
3
[]
no_license
!function(){ window.lcg = window.lcg || {}; //组件表 var modules = {}; //调试模式 lcg.debug = true; //整体提示 lcg.log = function(str){ if(lcg.debug == true) console.log("LCG.JS:"+str); } //绑定组件 lcg.bind = function(key,init){ if(modules[key] != null) lcg.log("覆盖了原有的'"+key+"'组件!"); modules[key] = init; } //给现有组件添加插件 lcg.bind.plugin = function(key,func){ if(modules[key] == null) return; if(modules[key].plugins == null) modules[key].plugins = []; modules[key].plugins.push(func); } //创建组件 lcg.create = function(key){ //判断组件是否存在 if(modules[key] == null) { lcg.log("'"+key+"'组件不存在!"); return; } //截取参数表 var vals = []; for(var i = 1;i < arguments.length;i++) vals.push(arguments[i]); //构建 return new Builder(key,vals); } //附着组件 lcg.use = function(proxy,key){ //截取参数表 var vals = []; for(var i = 2;i < arguments.length;i++) vals.push(arguments[i]); lcg.create.option(key,{proxy:proxy},vals); } //带参数创建 lcg.create.option = function(key,option,vals){ //判断组件是否存在 if(modules[key] == null) { lcg.log("'"+key+"'组件不存在!"); return; } //构建 return new Builder(key,vals,option); } //组件是否存在 lcg.hasModule = function(key){ if(modules[key] == null) return false; return true; } //=======构建器====== var Builder = function(key,vals,option){ //记录配置 var option = this._option = option || {}; var proxy = option.proxy || this._proxy; //加入getModule方法 if(proxy == null || proxy.lModule == null) { this.getModule = function(key){ return this.getModule.modules[key]; }.bind(this); this.getModule.modules = {}; } else this.getModule = proxy.lModule; //加入到组件表中 this.getModule.modules[key] = this; //附着指定对象 if(proxy) this.proxy(proxy); //执行构造 modules[key].apply(this,vals); //循环执行插件 if(modules[key].plugins) for(var i in modules[key].plugins) modules[key].plugins[i].apply(this,vals); //如无代理则以自身为代理 if(this._proxy == null) this.proxy(this); //返回代理对象 return this._proxy; } //构建器核心 Builder.prototype = { //代理 proxy:function(proxy){ if(this._proxy == null) { this._proxy = proxy; //加入lModule方法 this._proxy.lModule = this.getModule; //强制继承 if(this._option.extends) for(var i in this._option.extends) this.extend(this._option.extends[i]); } return this._proxy; }, //继承 extend:function(key){ //如果没有组件 if(modules[key] == null){ lcg.log("没有'"+key+"'组件,无法继承!"); return; } //截取参数表 var vals = []; for(var i = 1;i < arguments.length;i++) vals.push(arguments[i]); modules[key].apply(this,vals); //循环执行插件 if(modules[key].plugins) for(var i in modules[key].plugins) modules[key].plugins[i].apply(this,vals); }, //绑定消息 message:function(key,value){ //判断是否有代理 if(this._proxy == null) { lcg.log("没有代理对象,自动使用空对象!"); this._proxy = {}; } //参数类型判断 var vals = {}; if(typeof key != "string") vals = key; else vals[key] = value; //循环加入内容 for(var i in vals) addMessage(this._proxy,i,vals[i]); }, //发送消息 sendMessage:function(name){ //截取参数表 var vals = []; for(var i = 1;i < arguments.length;i++) vals.push(arguments[i]); if(this._proxy[name] == null) return; this._proxy[name].apply(this._proxy,vals); } }; //创建消息处理函数 var addMessage = function(target,key,value){ //消息处理主体 var message = function(){ for(var i in message._messages) message._messages[i].apply(target,arguments); } //判断是否已经生成过处理方法 if(target[key] == null || target[key]._messages == null){ target[key] = message; message._messages = []; } //插入消息内容 target[key]._messages.push(value); } }();//======钩子模块====== //用于数据变化帧听 !function(){ var hook = {}; lcg.hook = hook; //复制数组 lcg.copyArray = function(arr,end,start){ var end = end || 9999999; var start = start || 0; var re = []; for(var i = start;i < arr.length && i<end;i++) re.push(arr[i]); return re; } //绑定数组 hook.bindArray = function(arr,cbp,cbd){ var push = arr.push; var splice = arr.splice; //重写push arr.push = function(){ //执行原来的方法 push.apply(arr,arguments); cbp(arguments); } //重写 splice arr.splice = function(start,del,add){ //执行原来的方法 splice.apply(arr,arguments); //如果删除了 if(del > 0) cbd(start,del); //如果插入了 if(arguments.length > 2) { var adds = lcg.copyArray(arguments,null,2); cbp(adds,start); } } return {push:push,splice:splice}; } //绑定对象的key hook.bindKeySet = function(dom,key,set,data){ var myvals = dom[key]; var getter = function(){ return myvals; }; var setter = function(val){ myvals = val; if(set) set(val,key,data); } //添加getter、setter if (Object.defineProperty){ Object.defineProperty(dom, key, {get: getter,set: setter}); }else{ Object.prototype.__defineGetter__.call(dom, key, getter); Object.prototype.__defineSetter__.call(dom, key, setter); } } }();!function(){ //======事件系统====== //事件表 var events = { "bind":[] }; //帧听事件 lcg.on = function(name,cb){ if(events[name] == null) events[name] = []; events[name].push(cb); //初始化 if(name == "ready" && isReady == true) cb(); } //触发事件 var trigger = function(name,vals){ if(events[name] == null) events[name] = []; var isEnd = false; vals = vals || {}; vals.stop = function(){ isEnd = true; } vals.type = name; //循环触发回调 var es = events[name]; for(var i in events[name]) { //去除空回调 if(!es[i]) es.splice(i,1); //触发回调 var re = es[i](vals); if(isEnd) return re; } } lcg.trigger = trigger; //文档载入完毕事件 var ready = function(fn){ if(document.addEventListener){//兼容非IE document.addEventListener("DOMContentLoaded",function(){ //注销事件,避免反复触发 document.removeEventListener("DOMContentLoaded",arguments.callee,false); fn();//调用参数函数 },false); }else if(document.attachEvent){//兼容IE document.attachEvent("onreadystatechange",function(){ if(document.readyState==="complete"){ document.detachEvent("onreadystatechange",arguments.callee); fn(); } }); } //if(document.readyState == "complete" || document.readyState == "interactive") // fn(); } var isReady = false; //帧听文档事件触发ready lcg._ready = function(){ if(isReady) return; //触发插件准备事件 trigger("plugin-ready"); //触发准备完毕事件 trigger("ready"); isReady = true; } ready(lcg._ready); //全局时钟间隔 lcg.delayTime = 20; //全局时钟 var step = function(){ setTimeout(step,lcg.delayTime); trigger("dt"); } step(); //Dom节点事件 lcg.domEvent = function(dom,name,cb){ if(typeof name == "string") name = [name]; for(var i in name){ if(dom.addEventListener) dom.addEventListener(name[i],cb,false); else dom.attachEvent("on"+name[i],cb); } } }();//======DOM组件系统====== !function(){ //Dom组件核心 var dm = {}; lcg.domModule = dm; lcg.dm = dm; //绑定组件 //Dom组件 lcg.bind("dom-module",function(){ this.initLists = function(){ //初始化数组侦听 initLists(this._proxy,this); } this.initIDS = function(){ //初始化编号获取 initIDS(this._proxy,this); } this.initModuleRoot = function(){ //初始化子节点的ModuleRoot initModuleRoot(this._proxy,this); } this.initDomVal = function(){ //记录绑定内容的哈希表 var hash = {}; //初始化数据绑定 initDomVal(this._proxy,null,hash); //设置内容对象 this.setDomJSON = function(vals){ for(var i in vals) if(hash[i] == true) this._proxy[i] = vals[i]; }.bind(this); //获取内容对象 this.getDomJSON = function(){ var re = {}; for(var i in hash) re[i] = this._proxy[i]; return re; }.bind(this); } this.initFab = function(){ //初始化预制 initFab(this._proxy); } //初始化所有功能 this.initAll = function(){ this.initLists(); this.initIDS(); this.initModuleRoot(); this.initDomVal(); this.initFab(); } }); //组件表 var prefabs = {}; //预制关键字属性 var keyssFab = { "type":true, "values":true, "dom-prefab":true }; //添加一个组件表 lcg.dm.add = function(key,dom){ prefabs[key] = dom.outerHTML; //直接初始化 if(dom.getAttribute("init") != null){ var fab = document.createElement("div"); fab.setAttribute("dom-prefab",key); if(dom.getAttribute("values") != null) fab.setAttribute("values",dom.getAttribute("values")); dom.parentNode.insertBefore(fab,dom); } //删除原本的节点 if(dom.parentNode) dom.parentNode.removeChild(dom); if(fab != null) initFab(fab); } //初始化预制 var initFab = function(dom){ //创建相应的预制 var fabs = dom.querySelectorAll("dom-prefab,*[dom-prefab]"); if(dom && dom.getAttribute && dom.getAttribute("dom-prefab") != null) fabs = [dom]; for(var i = 0;i < fabs.length;i++) { try{ //从属性中获取预制 var vals = {}; if(fabs[i].getAttribute("values")) { try{ vals = eval("("+fabs[i].getAttribute("values")+")"); }catch(e){ vals = fabs[i].getAttribute("values"); } } var type = fabs[i].getAttribute("dom-prefab") || fabs[i].getAttribute("type"); //初始化组件 dm.init(type,fabs[i],vals); }catch(e){ lcg.log(type+"初始化异常"); console.log(e); } } } //转移属性 var moveAttribute = function(from,to){ //从属性获取初值 for(var j = 0;j < from.attributes.length;j++) { var atts = from.attributes[j]; if(keyssFab[atts.name] != true) to.setAttribute(atts.name,atts.value); } } dm.create = function(name,vals,option){ return dm.init(name,null,vals,option); } //创建初始化一个组件 dm.init = function(name,dom,vals,option){ option = option || {}; //判断是否已经定义了组件结构 if(prefabs[name] == null) { lcg.log("没有定义'"+name+"'组件的结构,无法创建相关的预制!"); return; } //创建Dom结构 if(dom == null) dom = document.createElement("div"); dom.innerHTML = prefabs[name]; var domz = dom.querySelector("*"); moveAttribute(dom,domz); //删除原本的DOM if(dom.parentNode) { dom.parentNode.insertBefore(domz,dom); dom.parentNode.removeChild(dom); } dom = domz; //附着组件 var values = [vals]; if(option.vals) for(var i in option.vals) values.push(option.vals[i]); var re = lcg.create.option(name,{proxy:dom,extends:["dom-module"]},values); //触发初始化事件 lcg.trigger("dom-module-init",{name:name,dom:dom,vals:vals}); return re; } //直接通过字符串绑定组件 dm.bind = function(name,domText,func){ prefabs[name] = domText; return lcg.bind(name,func); } //初始化ID表 var initIDS = function(dom,module){ var ids = {}; var idoms = dom.querySelectorAll("*[lid]"); for(var i = 0;i < idoms.length;i++) { var attr = idoms[i].getAttribute("lid"); if(ids[attr] == null) ids[attr] = idoms[i]; } module.ids = ids; } //======组件列表====== //初始化所有组件列表 var initLists = function(dom,module){ var lists = dom.querySelectorAll("*[dom-list]"); for(var i = 0;i < lists.length;i++) initList(lists[i],module); if(dom.getAttribute && dom.getAttribute("dom-list") != null) initList(dom,module); } //初始化组件列表 var initList = function(dom,root){ var vals = dom.getAttribute("dom-list"); var kv = vals.split(":"); var domList = []; //获取数组 var arr = root[kv[0]]; if(arr == null) return; arr.fabList = domList; arr.module = root; //删除方法 arr.del = function(module){ for(var i in domList) { if(domList[i] == module) arr.splice(Number(i),1); if(domList[i] == module._proxy) arr.splice(Number(i),1); } } //指定module arr.bind = function(key){ kv[1] = key; return arr; } //从数组替换 arr.copy = function(arrt){ arr.splice(0,arr.length); for(var i = 0;i < arrt.length;i++) arr.push(arrt[i]); } //生成一个fab var create = function(datas){ //创建并阻止初始化 var fab = dm.init(kv[1],null,datas,{vals:[arr,root]}); return fab; } //初始化数组原有内容 for(var i = 0;i < arr.length;i++){ var fab = create(arr[i]); dom.appendChild(fab); domList.push(fab); } //绑定数组方法 lcg.hook.bindArray(arr, //插入数据 function(datas,start){ //加入非插入 if(start == null || start == 0) for(var i in datas){ //初始化组件 var fab = create(datas[i]); dom.appendChild(fab); domList.push(fab); } else { //插入 var startDom = domList[start]; for(var i in datas){ //初始化组件 var fab = create(datas[i]); //插入相应内容 dom.insertBefore(fab,startDom); domList.splice(start+i,0,fab); } } }, //删除数据 function(start,len){ for(var i = 0;i < len;i++) dom.removeChild(domList[start + i]); domList.splice(start,len); }); } //======moduleRoot传递====== var initModuleRoot = function(dom,module){ var dlist = dom.querySelectorAll("*"); for(var i = 0;i < dlist.length;i++) if(dlist[i].$root == null) dlist[i].moduleRoot = dlist[i].$root = module; } //======对象绑定====== var initDomVal = function(dom,root,hash){ root = root || dom; //如果是注解 if(dom.nodeName == "#comment") return; //如果是shadowDom if(dom.nodeName == "#document-fragment") { //判断子节点 for(var i = 0;i < dom.childNodes.length;i++) initDomVal(dom.childNodes[i],root,hash) return; } //如果是文本 if(dom.nodeName == "#text"){ var re = dom.data.match(/{{(.*?)}}/); if(re && re.length > 0) { hash[re[1]] = true; listenerText(dom,root); } return; } //判断是否需要绑定 var re = dom.outerHTML.match(/{{.*?}}/); if(re && re.length > 0) { //判断子节点 for(var i = 0;i < dom.childNodes.length;i++) initDomVal(dom.childNodes[i],root,hash) } //判断属性是否绑定 for(var i = 0;i < dom.attributes.length;i++){ var atts = dom.attributes[i]; var re = atts.value.match(/{{(.*?)}}/); if(re && re.length > 0) { hash[re[1]] = true; listenerAttr(atts,root); } } } //侦听文本变化 var listenerText = function(dom,root){ var jxList = dom.data.match(/{{.*?}}|[\s\S]/g); for(var i in jxList) if(jxList[i].length > 3) listenerOnce(jxList[i],root,function(val,i){ jxList[i] = val; dom.data = jxList.join(""); },i); } //侦听属性变化 var listenerAttr = function(atts,root){ var jxList = atts.value.match(/{{.*?}}|[\s\S]/g); for(var i in jxList) if(jxList[i].length > 3) listenerOnce(jxList[i],root,function(val,i){ jxList[i] = val; atts.value = jxList.join(""); },i); } //侦听一次变化 var listenerOnce = function(str,root,cb,data){ root.__bindKeyList = root.__bindKeyList || {}; var key = str.match(/{{(.*?)}}/)[1]; //初始化绑定列表 if(root.__bindKeyList[key] == null) root.__bindKeyList[key] = []; var list = root.__bindKeyList[key]; //加入回调 cb._data = data; list.push(cb); cb(root[key],data); //如果没有绑定过 if(!list._isbind) { list._isbind = true; //绑定变化 lcg.hook.bindKeySet(root,key,function(val){ for(var i=0;i < list.length;i++) list[i](val,list[i]._data); }); } } //文档载入事件,放在最后防止立即触发 lcg.on("ready",function(){ //保存组件相应的HTML var doms = document.querySelectorAll("*[dom-module]"); for(var i = 0;i < doms.length;i++){ var dom = doms[i]; var key = dom.getAttribute("dom-module"); dom.removeAttribute("dom-module"); lcg.dm.add(key,dom); } //初始化所有预制 initFab(document); }); }(); //======预载入HTML====== !function(){ //插件载入事件 lcg.on("plugin-ready",function(){ var loaders = document.querySelectorAll("loader,*[dom-loader]"); for(var i = 0;i < loaders.length;i++) { var src = loaders[i].getAttribute("src") || loaders[i].getAttribute("dom-loader"); loadOne(loaders[i],src); } }); //属性字符串转属性 var str2Attr = function(dom,str){ var kvs = str.match(/[a-zA-Z0-9\-]*=".*?"/g); if(kvs == null) return; for(var i = 0;i < kvs.length;i++) { var kv = kvs[i].match(/([a-zA-Z0-9\-]*)="(.*?)"/); dom.setAttribute(kv[1],kv[2]); } } var setStyleText = function(style,str){ style.loadingStr = str; try{ var textNode = document.createTextNode(str); style.appendChild(textNode); }catch(e){ if(style.styleSheet) style.styleSheet.cssText = str; else { var set = function(){ try{ style.styleSheet.cssText = str; }catch(e){ } } setTimeout(set); } } } //载入一个节点 var loadOne = function(dom,src){ lcg.ajax.get(src,function(res){ var scripts = res.match(/<script.*?>[\s\S]*?<\/script>/g); var styles = res.match(/<style.*?>[\s\S]*?<\/style>/g); res = res.replace(/<script.*?>[\s\S]*?<\/script>|<style.*?>[\s\S]*?<\/style>/g,""); dom.innerHTML = res; for(var i = dom.childNodes.length - 1;i >= 0;i--) dom.parentNode.insertBefore(dom.childNodes[i],dom); //执行脚本 if(scripts) for(var i = 0;i < scripts.length;i++) eval(scripts[i].match(/<script.*?>([\s\S]*?)<\/script>/)[1]); //加入样式 if(styles) for(var i = 0;i < styles.length;i++) { var style = document.createElement("style"); setStyleText(style,styles[i].match(/<style.*?>([\s\S]*?)<\/style>/)[1]); str2Attr(style,styles[i].match(/<style(.*?)>[\s\S]*?<\/style>/)[1]); dom.parentNode.insertBefore(style,dom); } //删除载入的标记节点 dom.parentNode.removeChild(dom); },false); } }();/*Ajax扩展*/ !function(){ //默认参数 var initOptions = { //地址 url:"", //方法类型 method:"GET", //是否异步 async:true, //用户名 user:"", //密码 password:"", //头部表 headers:null, //成功返回 onSuccess:null, //返回失败 onError:null, //参数 vars:null }; //ajax核心方法 var ajax = function(option) { //参数设置 for(var i in initOptions) if(option[i] == null) option[i] = initOptions[i]; //ajax定义 var xmlhttp; if (window.XMLHttpRequest) { //高版本浏览器 xmlhttp=new XMLHttpRequest(); } else { //低版本IE xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //状态变化时事件 xmlhttp.onreadystatechange=function() { //执行结束 if(xmlhttp.readyState==4){ //返回成功 if(xmlhttp.status==200){ if(option.onSuccess) option.onSuccess(xmlhttp); } else { //返回失败 if(option.onError) option.onError(xmlhttp); } } } //设置头部 if(option.headers) for(var i in option.headers) xmlhttp.setRequestHeader(i,option.headers[i]); //参数生成 var vars = []; var sendVar = null; if(option.vars) for(var i in option.vars) vars.push(encodeURI(i)+"="+encodeURI(option.vars[i])); //POST传值 if(option.method == "POST") sendVar = vars.join("&"); //GET传值 if(option.method == "GET") { if(/\?/.test(option.url)) option.url += "&" + vars.join("&"); else option.url += "?" + vars.join("&"); } //打开方法 xmlhttp.open("GET",option.url,option.async); //发送 xmlhttp.send(sendVar); } //发送GET数据 ajax.get = function(url,vars,cb,async){ //参数缺省 if(typeof vars == "function") { async = cb; cb = vars; } //使用参数 var option = { url:url, vars:vars, method:"GET", onSuccess:function(res){ if(cb) cb(res.responseText,false,res); }, onError:function(res){ if(cb) cb("",true,res); }, async:async } ajax(option); } //发送POST数据 ajax.post = function(url,vars,cb,async){ //参数缺省 if(typeof vars == "function") { async = cb; cb = vars; } //使用参数 var option = { url:url, vars:vars, method:"POST", onSuccess:function(res){ if(cb) cb(res.responseText,false,res); }, onError:function(res){ if(cb) cb("",true,res); }, async:async } ajax(option); } lcg.ajax = ajax; }();//======Dom构造器====== //可以把形如a[a:www,b:ddd]{b[aaa:aaa,bbb:bbb]:aaaa}构造成dom结构 !function(){ //构造Dom核心函数 lcg.buildDom = function(str){ return arr2Dom(str2Arr(str)); } //特殊词 var tag = { "[":true, "]":true, ",":true, ":":true, "{":true, "}":true, ";":true }; //JSON生成Dom var arr2Dom = function(dom,root){ //生成标签 var d = document.createElement(dom.tag); if(root == null) { root = d; d.ids = {}; } //设置属性 if(dom.attr) for(var i in dom.attr) { d.setAttribute(i,dom.attr[i]); if(i == "lid") root.ids[dom.attr[i]] = d; } //设置text if(dom.text) d.innerText = dom.text; //加入子节点 if(dom.childs) for(var i in dom.childs) d.appendChild(arr2Dom(dom.childs[i],root)); return d; } //字符串分析为数组 var str2Arr = function(str){ var dom = {}; var now = ""; var state = 0; var level = 0; var list = []; //根据关键字设置状态 var setState = function(key){ if(key == "[") state = 1; if(key == "{") state = 2; if(key == ":") state = 3; } //循环分析 for(var i = 0;i < str.length;i++) { //获取标签名 if(state == 0) { if(tag[str[i]]) { if(dom.tag == null) dom.tag = now; now = ""; setState(str[i]); continue; } now += str[i]; } //获取属性 else if(state == 1) { if(str[i] == "]") { dom.attr = str2Attr(now); state = 0; continue; } now += str[i]; } //解析子项 else if(state == 2) { if(str[i] == "{") level--; if(str[i] == "}") { level++; if(level >= 1) { if(now != "") list.push(now); dom.childs = []; for(var i in list) dom.childs.push(str2Arr(list[i])); break; } } if(str[i] == ";" && level == 0) { list.push(now); now = ""; continue; } now += str[i]; } //解析innerText else if(state == 3){ dom.text = str.substr(i); break; } } if(dom.tag == null) dom.tag = now; return dom; } //解析出属性 var str2Attr = function(str){ var re = {}; var list = str.split(","); for(var i in list){ var kv = list[i].split(":"); re[kv[0]] = kv[1]; } return re; } }();
Markdown
UTF-8
1,965
2.96875
3
[ "Unlicense" ]
permissive
# Background The file `munge.pl` processes a CSV file from Lending Club's secondary market. It generates a new CSV file that can be used for factor analysis in R. # Amalog Features This section expounds on Amalog features seen in the example. ## handle Makes a predicate (`err` in this case) the active condition handler for the current lexical scope. If code executed in this dynamic scope signals a condition, `err` gets a chance to respond. ## pipe Like a DCG. It creates a pipeline of predicates. The first predicate is called with a single, extra argument. The predicate should bind its output to this argument. The final predicate is called with a single, extra argument whose value is the output of the pipeline's penultimate stage. All other predicates are called with two extra arguments: the input from the previous stage (first) and the output for the next stage (second). `pipe` processes only the first successful result of the pipeline. To run a failure driven loop over all solutions, see `pipe_all`. ## pipe_all Just like `pipe` but it runs a failure driven loop across all solutions. In this example, `csv_read` iterates rows on backtracking. We want to process all rows in the file so we must use `pipe_all` instead of `pipe`. The predicate itself is deterministic. This is conceptually similar to Prolog's `findall/3` predicate. ## arg Like arg/3 in Prolog. It relates a named property, a term and that property's value. ## rx A macro that compiles a regular expression into some internal representation so that it can be matched against inputs (or used to generate matching outputs). ## . Functional sugar for accessing a term's named property. For example, ```amalog say Foo.bar ``` is sugar for ```amalog arg bar Foo X say X ``` ## math A macro that expands mathematical notation into Amalog goals. For example, ```amalog say (math `1 + 2 + 3`) ``` is sugar for ```amalog plus 1 2 X plus X 3 Y say Y ```
Python
UTF-8
1,646
3.078125
3
[]
no_license
""" When passing data to the built-in training loops of a model, you should either use Numpy arrays (if your data is small and fits in memory) or tf.data Dataset objects. """ from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import tensorflow as tf from tensorflow import keras inputs = keras.Input(shape=(784,), name='digits') x = keras.layers.Dense(64, activation='relu', name='dense1')(inputs) x = keras.layers.Dense(64, activation='relu', name='dense2')(x) outputs = keras.layers.Dense(10, activation='relu', name='output')(x) model = keras.Model(inputs=inputs, outputs=outputs) (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() x_train = x_train.reshape(60000, 784).astype('float32') / 255.0 x_test = x_test.reshape(10000, 784).astype('float32') / 255.0 # reserve 10k samples for validation x_val, y_val = x_train[-10000:], y_train[-10000:] x_train, y_train = x_train[:-10000], y_train[:-10000] # y is not one hot encoded so we use the sparse versions below!!! model.compile(optimizer=keras.optimizers.RMSprop(), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['sparse_categorical_accuracy']) history = model.fit(x_train, y_train, batch_size=64, epochs=3, validation_data=(x_val, y_val)) print('\nhistory dictionary:', history.history) print('\n# Evaluate on test data') results = model.evaluate(x_test, y_test, batch_size=128) print('test loss: {}, test accuracy: {}'.format(results[0], results[1])) predictions = model.predict((x_test[:5])) print('shape of predictions: {}'.format(predictions.shape))
Java
UTF-8
4,610
1.820313
2
[ "EPL-1.0", "Classpath-exception-2.0", "ISC", "GPL-2.0-only", "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-generic-cla", "0BSD", "LicenseRef-scancode-sun-no-high-risk-activities", "LicenseRef-scancode-free-unknown", "JSON", "LicenseRef-scancode-unicode", "CC-BY-SA-3.0", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-westhawk", "CDDL-1.1", "BSD-2-Clause", "EPL-2.0", "CDDL-1.0", "GCC-exception-3.1", "MPL-2.0", "CC-PDDC", "MIT", "LicenseRef-scancode-unicode-icu-58", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.query.aggregation.hyperloglog; import com.google.common.collect.ImmutableMap; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import org.apache.druid.hll.HyperLogLogCollector; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.query.Druids; import org.apache.druid.query.aggregation.CountAggregatorFactory; import org.apache.druid.query.aggregation.cardinality.CardinalityAggregatorFactory; import org.apache.druid.query.dimension.DefaultDimensionSpec; import org.apache.druid.query.timeseries.TimeseriesQuery; import org.apache.druid.query.timeseries.TimeseriesQueryQueryToolChest; import org.apache.druid.segment.column.ColumnType; import org.apache.druid.segment.column.RowSignature; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; import java.util.Collections; import java.util.Random; /** */ public class HyperUniqueFinalizingPostAggregatorTest { private final HashFunction fn = Hashing.murmur3_128(); @Test public void testCompute() { Random random = new Random(0L); HyperUniqueFinalizingPostAggregator postAggregator = new HyperUniqueFinalizingPostAggregator( "uniques", "uniques" ); HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector(); for (int i = 0; i < 100; ++i) { byte[] hashedVal = fn.hashLong(random.nextLong()).asBytes(); collector.add(hashedVal); } double cardinality = (Double) postAggregator.compute(ImmutableMap.of("uniques", collector)); Assert.assertTrue(cardinality == 99.37233005831612); } @Test public void testComputeRounded() { Random random = new Random(0L); HyperUniqueFinalizingPostAggregator postAggregator = new HyperUniqueFinalizingPostAggregator( "uniques", "uniques" ).decorate( ImmutableMap.of( "uniques", new CardinalityAggregatorFactory( "uniques", null, Collections.singletonList(DefaultDimensionSpec.of("dummy")), false, true ) ) ); HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector(); for (int i = 0; i < 100; ++i) { byte[] hashedVal = fn.hashLong(random.nextLong()).asBytes(); collector.add(hashedVal); } Object cardinality = postAggregator.compute(ImmutableMap.of("uniques", collector)); Assert.assertThat(cardinality, CoreMatchers.instanceOf(Long.class)); Assert.assertEquals(99L, cardinality); } @Test public void testResultArraySignature() { final TimeseriesQuery query = Druids.newTimeseriesQueryBuilder() .dataSource("dummy") .intervals("2000/3000") .granularity(Granularities.HOUR) .aggregators( new CountAggregatorFactory("count"), new HyperUniquesAggregatorFactory("approxCount", "col"), new HyperUniquesAggregatorFactory("approxCountRound", "col", false, true) ) .postAggregators( new HyperUniqueFinalizingPostAggregator("a", "approxCount"), new HyperUniqueFinalizingPostAggregator("b", "approxCountRound") ) .build(); Assert.assertEquals( RowSignature.builder() .addTimeColumn() .add("count", ColumnType.LONG) .add("approxCount", null) .add("approxCountRound", null) .add("a", ColumnType.DOUBLE) .add("b", ColumnType.LONG) .build(), new TimeseriesQueryQueryToolChest().resultArraySignature(query) ); } }
Markdown
UTF-8
1,469
2.53125
3
[]
no_license
# hw6 1) ![](https://github.com/subna/hw6/blob/master/ngrams11.png) 2) ![](https://github.com/subna/hw6/blob/master/ngrams22.png) 3) ![](https://github.com/subna/hw6/blob/master/ngrams3.jpg) На третьем скриншоте видно, что предположение, основанное на данных Оксфордского словаря (heavy cream более характерно для американского английского, double cream - для британского), подтверждается. Почему в американской литературе это понятие встречается гораздо чаще? (График показывает долю для каждого корпуса). Загадка. Дело в представленности нехудожественных (кулинарных книг? фитнес-пособий? и т.д.) текстов в каждом корпусе? ## Scetch Engine 1) Modifiers: Word Scetch ![](https://github.com/subna/hw6/blob/master/modifiers.png) 2) Scetch diff ![](https://github.com/subna/hw6/blob/master/objects.jpg) ![](https://github.com/subna/hw6/blob/master/objects2.jpg) Видно, что местоимения употребляются только с leave, названия транспортных пунктов преимущественно с depart (heathrow), а названия городов (london) с обоими
Markdown
UTF-8
5,221
2.734375
3
[]
no_license
--- doc_date: '1983-02-28' doc_num: 264 doc_order: 264 naa_refs: [] title: Telegram from Francis to Ministry of Foreign Affairs vol_full_title: 'Volume 23: The Negotiation of the Australia New Zealand Closer Economic Relations Trade Agreement, 1983' vol_id: 23 vol_title: 'Volume 23: The Negotiation of the Australia New Zealand Closer Economic Relations Trade Agreement 1983' --- Canberra, 28 February 1983 No 586. SECRET IMMEDIATE **Signing of CER Treaty** Further to my telephone conversations with the Hon Hugh Templeton, here follows scenario and précis of conversations. Firstly, at approximately l0am on Saturday last, Mr Jim Scully of Trade telephoned to state that the Australian Government had decided that the CER Treaty should not be signed until after the election.[1](#f1) He confirms that Mr Anthony was of this opinion. The reason given was that apparently a senior Labour Member had indicated that the Australian Government was being too hasty in signing the agreement with an election imminent. Mr Scully expressed his deep disappointment that the decision had been taken. On Friday afternoon previously, having agreed upon a text for the interchange of letters for signing the CER Treaty, I had been informed, certainly unofficially, that the signing could take place on Tuesday evening 1st March. The Saturday morning information and Friday information was conveyed to Mr Templeton immediately. I then attempted to contact Doug Anthony and Messrs Hawke and Keating. Late Saturday afternoon I contacted Mr Anthony at the Picton Show and was able to give Mr Templeton a Sydney telephone number to enable him to ring him on Saturday afternoon. Yesterday, Sunday, I had great difficulty in contacting Messrs Hawke and Keating. Mr Hawke was in Melbourne early in the morning but later went to Brisbane. Mr Keating was in transit from Brisbane to Sydney. At approximately 7:30pm on Sunday 27th, I had a reassuring telephone conversation with Mr Hawke. My preamble to both Mr Hawke and Keating was simply that the New Zealand Government was concerned that apparently a prominent Labor member had indicated to the Australian Government his opinion that signing the treaty before the election was unduly hasty, and informed both Hawke and Hayden that the New Zealand Government was under attack by the Leader of the New Zealand Labour Party for failing to have the CER Treaty signed. Mr Hawke's response was forthright and friendly. He said that he was replying to me in a confidential, personal capacity knowing, of course, that I would be relaying the conversation to Minister Templeton and the Prime Minister. He indicated that he did not wish any election matter to arise out of his conversation with me and his responses were made on that basis. He indicated quite firmly that the ALP accepted in principle the CER Agreement and was quite happy to adopt it. At the same time he would ensure that if he became the Government the ALP would go through the agreement and would not just accept blindly what the present government had agreed to. He did not specify any item of disagreement but he indicated that if his party became the government he would give the CER Treaty signing the utmost urgency. Quite clearly, after talking to Hawke, I sensed no antipathy whatsoever. Neither Hawke nor Keating indicated who the senior Labor person was who had given notice of 'undue haste.' Paul Keating telephoned me from Sydney at the New Zealand Residence about 9:30pm last night. His reply was even more forthright and he did not ask for any protection.[2](#f2) He indicated that he thought the agreement had been signed. I pointed out that, in fact it had[3](#f3) and that all that remained was for the agreement to be put in treaty form for signature. He indicated firmly that he fully supported the CER proposals and that when the matter had been raised in the House two Labor speakers had spoken in support and he saw no reason for himself to speak. He indicated that in the course of the current election campaign he had been asked by the Metal Trades officials whether in view of the promised protection policy of the ALP, that the 'freeing up' proposals for CER would still continue. He gave an unequivocal assurance that as far as the Metal Trades enquiry was concerned, the proposals of CER would be kept in place and unaltered. I would add that Paul Keating has on at least two occasions since his trip to New Zealand as a VIP guest, assured me that he would always be able to sell CER to the ALP.[4](#f4) There has been no press comment here on this matter. _[AALR 873, W4446/Boxes 312-313, 61/Aus/2/2/1 Part 5 Archives New Zealand/Te Whare Tohu Tuhituhinga 0 Aotearoa, Head Office, Wellington]_ * 1 The Australian Federal elections were to be held on 5 March. * 2 'protection'-i.e. he was not speaking off the record and would not object to being named or quoted. * 3 Presumably a reference to the signing of the Heads of Agreement on 14 December 1982. * 4 Despite these encouraging responses from Hawke and Keating (of which Muldoon may have been unaware) Muldoon announced on the same day (28 February) that signature would be delayed until after the Australian elections. In the event the agreement was signed on 28 March.
Python
UTF-8
1,112
3.5625
4
[]
no_license
""" CP1404/CP5632 Practical Extension - Check for missing files """ # import shutil import os def main(): """Demo file renaming with the os module.""" print("Current directory is", os.getcwd()) for dir_name, subdir_list, file_list in os.walk('.'): if dir_name == '.': continue os.chdir(dir_name) dir_name = dir_name[2:] for file in file_list: char_list = [] with open(file) as temp_file: for count in range(5): char_list.append(temp_file.readline(2)) temp_file.readline() # Move cursor to start of next line if '.i' not in char_list: print("{} from the {} directory is missing copyright information".format(file, dir_name)) os.chdir('..') print('\n') # Separate the directories for dir_name, subdir_list, file_list in os.walk('.'): print("In", dir_name) print("\tcontains subdirectories:", subdir_list) print("\tand files:", file_list) if __name__ == '__main__': main()
C#
UTF-8
5,340
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; namespace ZeroCDN_Client { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow : Window { ApiZeroCDN api = new ApiZeroCDN(); private DispatcherTimer timer = null; public MainWindow() { InitializeComponent(); TimerIsInternetConnection(); } private async void SendDataAuth_Click(object sender, RoutedEventArgs e) { String login = InputAuthLogin.Text; String password = InputAuthPassword.Text; var auth = api.AuthLoginKey(login, password); //var auth = api.AuthLoginPassword(login, password); if (await ConnectionAvailable() == true) { if (auth == "429") { MessageBox.Show("Жди пять минут, слишком много некорректных запросов. \nКод 429."); } else if (auth == HttpStatusCode.Forbidden.ToString()) { MessageBox.Show("Учётные данные пользователя не верны!"); } else if (auth.Contains("{\"meta\":{\"previous\":null,\"next\":null,\"limit\":100,\"offset\":0}")) { this.Visibility = Visibility.Collapsed; WordkingWindow wind = new WordkingWindow(api); wind.Closed += (sender2, e2) => { this.Close(); }; wind.ShowDialog(); } else { MessageBox.Show($"Error: {auth}"); } } else { MessageBox.Show("Проверьте подключение к сети интернет"); } } /// <summary> /// Is internet connection /// </summary> private void TimerIsInternetConnection() { timer = new DispatcherTimer(); timer.Tick += new EventHandler(CorrectImageSource); timer.Interval = new TimeSpan(0, 0, 0, 1, 0); timer.Start(); } private async void CorrectImageSource(object sender, EventArgs e) { if (await ConnectionAvailable() == true) { IsInternetConnection.Source = new BitmapImage(new Uri("Image/InternetConnection.png", UriKind.Relative)); } else { IsInternetConnection.Source = new BitmapImage(new Uri("Image/NoInternetConnection.png", UriKind.Relative)); } } private async Task<Boolean> ConnectionAvailable() { Ping ping = new Ping(); PingReply pingReply = null; return await Task.Run(() => { try { pingReply = ping.Send("8.8.8.8"); return pingReply.Status == IPStatus.Success ? true : false; } catch (PingException) { return false; } }); } private async void SendDataAuthPassword_Click(object sender, RoutedEventArgs e) { String login = InputAuthLogin_Copy.Text; String password = InputAuthPassword_Copy.Text; MessageBox.Show(login + password); var auth = api.AuthLoginPassword(login, password); if (await ConnectionAvailable() == true) { if (auth == "429") { MessageBox.Show("Жди пять минут, слишком много некорректных запросов. \nКод 429."); } else if (auth == HttpStatusCode.Forbidden.ToString()) { MessageBox.Show("Учётные данные пользователя не верны!"); } else if (auth.Contains("{\"meta\":{\"previous\":null,\"next\":null,\"limit\":100,\"offset\":0}")) { this.Visibility = Visibility.Collapsed; WordkingWindow wind = new WordkingWindow(api); wind.Closed += (sender2, e2) => { this.Close(); }; wind.ShowDialog(); } else { MessageBox.Show($"Error: {auth}"); } } else { MessageBox.Show("Проверьте подключение к сети интернет"); } } } }
Java
UTF-8
2,004
3
3
[]
no_license
import javax.sound.midi.Soundbank; import java.awt.print.Book; import java.io.IOException; import java.net.*; import java.util.Arrays; public class UDPThread implements Runnable { int port; BookServer bookServer; DatagramSocket datagramSocket; public UDPThread(int port, BookServer bookServer){ System.out.println("Made a thread to listen on:" + port); this.port = port; this.bookServer = bookServer; datagramSocket = null; try { datagramSocket = new DatagramSocket(port); } catch (SocketException e) { e.printStackTrace(); } } byte[] buf = new byte[1024]; @Override public void run() { DatagramPacket packet = new DatagramPacket(buf, buf.length); while (true) { try { System.out.println("waiting for a packet"); datagramSocket.receive(packet); System.out.println("got a packet"); String received = new String(packet.getData(), 0, packet.getLength()); System.out.println("got:" + received); String returnMessage = bookServer.messageHandler(received); System.out.println(returnMessage); if(returnMessage.equals("EXIT")) { sendPacket(packet, datagramSocket, returnMessage); datagramSocket.close(); return; } sendPacket(packet, datagramSocket, returnMessage); } catch (IOException e) { e.printStackTrace(); } } } private void sendPacket(DatagramPacket packet, DatagramSocket newSocket, String message){ byte[] toSend = (message).getBytes(); DatagramPacket p = new DatagramPacket(toSend,toSend.length, packet.getAddress(), packet.getPort()); try { newSocket.send(p); } catch (IOException e) { e.printStackTrace(); } } }
Python
UTF-8
827
2.71875
3
[]
no_license
import hashlib import time import random from httprunner import __version__ from httprunner.response import ResponseObject def get_httprunner_version(): return __version__ def sum_two(m, n): return m + n def sleep(n_secs): time.sleep(n_secs) def get_documents_num(response:ResponseObject): resp_json = response.resp_obj.json() document_num = len(resp_json['data'].get("documents")) print("document_num===",document_num) return document_num def gen_token(phone,password,timestamp): s = "".join([phone,password,str(timestamp)]) token = hashlib.md5(s.encode("utf-8")).hexdigest() print("签名是~~~~~",token) return token def gen_random_title(): return f"喵喵喵→{random.randint(1,7777777)}" def gen_doc_titles(num): return [gen_random_title() for _ in range(num)]
C#
UTF-8
2,561
2.8125
3
[ "Apache-2.0" ]
permissive
using System; namespace DBFlute.JavaLike.Lang { /** * This exception may be thrown by methods that have detected concurrent * modification of an object when such modification is not permissible. * <p> * For example, it is not generally permissible for one thread to modify a Collection * while another thread is iterating over it. In general, the results of the * iteration are undefined under these circumstances. Some Iterator * implementations (including those of all the general purpose collection implementations * provided by the JRE) may choose to throw this exception if this behavior is * detected. Iterators that do this are known as <i>fail-fast</i> iterators, * as they fail quickly and cleanly, rather that risking arbitrary, * non-deterministic behavior at an undetermined time in the future. * <p> * Note that this exception does not always indicate that an object has * been concurrently modified by a <i>different</i> thread. If a single * thread issues a sequence of method invocations that violates the * contract of an object, the object may throw this exception. For * example, if a thread modifies a collection directly while it is * iterating over the collection with a fail-fast iterator, the iterator * will throw this exception. * * <p>Note that fail-fast behavior cannot be guaranteed as it is, generally * speaking, impossible to make any hard guarantees in the presence of * unsynchronized concurrent modification. Fail-fast operations * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i><tt>ConcurrentModificationException</tt> * should be used only to detect bugs.</i> * * @author Josh Bloch * @version %I%, %G% * @see Collection * @see Iterator * @see ListIterator * @see Vector * @see LinkedList * @see HashSet * @see Hashtable * @see TreeMap * @see AbstractList * @since 1.2 */ public class ConcurrentModificationException : Exception { public ConcurrentModificationException() : base() { } public ConcurrentModificationException(string message) : base(message) { } public ConcurrentModificationException(string message, Exception cause) : base(message, cause) { } } }
Markdown
UTF-8
875
2.640625
3
[]
no_license
# Marketing Analytics *** ### Market-Basket-Analysis-and-Recommendation-System `Market basket analysis` is the process of discovering frequent item sets in large transactional database. <br>`Recomendation System` is algorithm that seeks to predict the '*rating*' or '*preference*' a user would give to an item ### List of Source Code in the folder code : >**Market Basket Analysis (Apriori)** <br>**Collaborative Filtering** <br>**Content Based Filtering** <br>**Hybrid Filtering** <br>**A/B Testing** ### List of Dataset in the folder data : >**form2.csv** for Market Basket Analysis (Apriori) <br>**film2.csv** for Collaborative Filtering <br>**apa.csv** for Content Based Filtering dan Hybrid Filtering <br>**apa3.csv** for Hybrid Filtering <br>**ab_data.csv** for A/B Testing All Source Code in this repository use `Python` language and run in `Jupyter Notebook` ***
Java
UTF-8
2,194
3.640625
4
[]
no_license
/** * */ package collections.set; import java.util.Iterator; /** * @author naveen.kumar * */ public class TreeSetDemo { /** * @param args */ public static void main(String[] args) { TreeSet.addValue("one"); TreeSet.addValue("two"); TreeSet.addValue("three"); TreeSet.addValue("four"); TreeSet.addValue("five"); System.out.println("Set Stats after 5 entries: "); System.out.println("Set Size: " + TreeSet.getTreeSet().size()); System.out.println("Set Values: " + TreeSet.getTreeSet()); TreeSet.addValue("six"); TreeSet.addValue("seven"); TreeSet.addValue("eight"); TreeSet.addValue("nine"); TreeSet.addValue("ten"); System.out.println("Set Stats after 10 entries: "); System.out.println("Set Size: " + TreeSet.getTreeSet().size()); System.out.println("Set Values: " + TreeSet.getTreeSet()); TreeSet.addValue("eleven"); TreeSet.addValue("twelve"); TreeSet.addValue("thirteen"); TreeSet.addValue("fouteen"); TreeSet.addValue("fifteen"); System.out.println("Set Stats after 15 entries: "); System.out.println("Set Size: " + TreeSet.getTreeSet().size()); System.out.println("Set Values: " + TreeSet.getTreeSet()); TreeSet.addValue("sixteen"); TreeSet.addValue("seventeen"); TreeSet.addValue("eighteen"); TreeSet.addValue("ninteen"); TreeSet.addValue("twenty"); TreeSet.addValue("twenty"); System.out.println("Set Stats after 20 entries: "); System.out.println("Set Size: " + TreeSet.getTreeSet().size()); System.out.println("Set Values: " + TreeSet.getTreeSet()); for (Iterator<Object> iterator = TreeSet.getTreeSet().iterator(); iterator .hasNext();) { Object object = iterator.next(); if (object.equals("ten")) { iterator.remove(); } } System.out.println("Set Values after removing ten: " + TreeSet.getTreeSet()); } }
Java
UTF-8
1,574
1.578125
2
[]
no_license
package org.apel.show.attach.test.web; import java.util.List; import org.apel.gaia.commons.jqgrid.QueryParams; import org.apel.gaia.commons.pager.PageBean; import org.apel.gaia.util.jqgrid.JqGridUtil; import org.apel.show.attach.service.domain.FileInfo; import org.apel.show.attach.service.service.FileInfoProviderService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.alibaba.dubbo.config.annotation.Reference; @Controller @RequestMapping("/attachTest") public class AttachTestController { @Reference(timeout=30000) private FileInfoProviderService fileInfoProviderService; @RequestMapping(value="index",method={RequestMethod.GET,RequestMethod.POST}) public String index(){ System.out.println(); // List<FileInfo> findByBusinessId = fileInfoProviderService.findByBusinessId("111111"); // List<FileInfo> findFileByBusinessId = fileInfoProviderService.findFileByBusinessId("111111"); // // String filters = "{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"businessId\",\"op\":\"EQ\",\"data\":\"111111\"}]}"; // // QueryParams queryParams = new QueryParams(); // queryParams.setFilters(filters); // queryParams.setNd("1504590288083"); // // JqGridUtil.getPageBean(queryParams); // PageBean pageBean = JqGridUtil.getPageBean(queryParams); // PageBean findFileInfo = fileInfoProviderService.findFileInfo(pageBean); // // System.out.println(); return "index"; } }
Java
UTF-8
5,527
3.03125
3
[]
no_license
package s0c13ty_MAsK.controladores; import s0c13ty_MAsK.enumerates.Horas; import s0c13ty_MAsK.enumerates.MemBros; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class Sistema { private static ArrayList<MemBros> listaMembros = new ArrayList<>(); public static void run() throws IOException { Horas horarioatual = Horas.NORMAL; Scanner scanner = new Scanner(System.in); boolean iniciar = true; System.out.println("Bem vindo ao sistema da MAsK_s0c13ty"); System.out.println("Seu horário atual é: " + horarioatual); System.out.println("====================================="); while(iniciar) { System.out.println("Qual opção deseja executar?\n" + "1 - Mudar seu horario atual \n" + "2 - Cadastro de membros novos \n" + "3 - Saber seu horário atual \n" + "4 - Remocao de membro \n" + "5 - Postar mensagens dos membros \n" + "6 - Apresentação dos membros\n" + "7 - Terminar sistema"); int resp = scanner.nextInt(); switch (resp){ case 1: if (horarioatual == Horas.NORMAL){ horarioatual = Horas.EXTRA; System.out.println("Seu horário foi alterado com sucesso!"); } else{ horarioatual = Horas.NORMAL; System.out.println("Seu horário foi alterado com sucesso!"); } System.out.println("Seu horário é: " + horarioatual); break; case 2: cadastroMembros(); break; case 3: System.out.println("Seu horário é: " + horarioatual); break; case 4: removerMembro(); System.out.println("Membro removido!"); break; case 5: for (MemBros membro : listaMembros) { System.out.println(membro.getNome()); membro.Mensagem(horarioatual); } break; case 6: for (MemBros membro: listaMembros) { membro.apresentacao(); } break; case 7: TesteControl TesteControl = new TesteControl(); TesteControl.Control(listaMembros); iniciar = false; System.out.println("===============\n" + "0br1g4d0 por usar o sistema.\n" + "Finalizando o sistema! Bons códigos."); } } } public static void cadastroMembros () throws FileNotFoundException { Scanner scanner = new Scanner(System.in); System.out.println("Deseja adicionar um novo membro?\n" + "1 - Sim \n" + "2 - Não"); int resposta = scanner.nextInt(); while (resposta == 1) { System.out.println("Que tipo de membro gostaria de adicionar?\n" + "1 - Mobile Members\n" + "2 - Heavy Lifters\n" + "3 - Script Guys \n" + "4 - Big Brothers"); int add = scanner.nextInt(); System.out.println("Qual o nome do membro?"); String nome = scanner.next(); System.out.println("Qual o email?"); String email = scanner.next(); System.out.println("Qual o ID?"); int ID = scanner.nextInt(); switch (add) { case 1: listaMembros.add(new Mobile(nome, email, ID, MemBros.Mobile_Members)); break; case 2: listaMembros.add(new Heavy(nome, email, ID, MemBros.Heavy_Lifters)); break; case 3: listaMembros.add(new Script(nome, email, ID, MemBros.Script_Guys)); break; case 4: listaMembros.add(new Big(nome, email, ID, MemBros.Big_Brothers)); break; } System.out.println("Você deseja cadastrar outro membro?\n" + "1 - Sim \n" + "2 - Não"); resposta = scanner.nextInt(); } } public static void removerMembro(){ Scanner scanner = new Scanner(System.in); System.out.println("Deseja excluir um membro?\n" + "1 - Sim \n" + "2 - Não"); int resposta = scanner.nextInt(); while (resposta == 1) { System.out.println("Você deseja apagar qual posição?"); int excluir = scanner.nextInt(); listaMembros.remove(excluir); System.out.println("Voce deseja remover outro membro?\n" + "1 - Sim \n" + "2 - Não"); resposta = scanner.nextInt(); } } }
JavaScript
UTF-8
1,216
2.546875
3
[]
no_license
var app = app || {}; /** * @description Collection of foods that have been added, synced to firebase * @description In hindsight, would have organized data differently and * @description Rather than make calls to new collection, would have written filter methods * @description and used queries * @constructor */ var FoodList = Backbone.Firebase.Collection.extend({ model: app.Food, url:'https://my-nutrition-tracker.firebaseio.com/foodList/test', urlStr: 'https://my-nutrition-tracker.firebaseio.com/foodList/', /** * @description syncs data with server based on day in focus * @description a workaround since fetch is disabled on firebase when autosync is active */ initialize: function() { this.url = this.urlStr + app.dateModel.get('todayFileStr'); var self = this; setTimeout( function(self) { //Just enough time to wait for listeners to be updated to new instance of Foodlist self.trigger('new'); },10, self); //Error Handling var foodTimeout = setTimeout(function() { alert("No food for you! There's been an error syncing your food data. Try again in a bit"); },8000); this.on('sync', function() { clearTimeout(foodTimeout); }); } }); app.foodList = new FoodList();
Python
UTF-8
482
2.875
3
[ "Apache-2.0" ]
permissive
from tkinter import * class StatusBar(): def __init__(self, master): frame = Frame(master, bd=0) frame.pack(side=BOTTOM, anchor=W, fill=X, padx=2) self.label = Label(frame, bd=1, relief=SUNKEN, anchor=W) self.label.pack(fill=X) def set(self, format, *args): self.label.config(text=format % args) self.label.update_idletasks() def clear(self): self.label.config(text="") self.label.update_idletasks()
Markdown
UTF-8
2,607
3.328125
3
[]
no_license
<h1>What is UML Parser</h1> <p> UML Parser is a parsing tool used for generating UML diagrams as the output after taking source code as the input</p> <p> UML Parser helps visualize the structure of the code and the inter-relation between the classes and hierarchical structure</p> <p> In this project, we develop a UML parser using java parser and YUML diagram generator to create class diagrams for a given set of java classes</p> <h1>Requirements</h1> The Java version requirement is Java 8. <h1>Tools Used</h1> This project has two fundamental models - 1. Parser 2. UML Diagram Generator The parser is used to parse the java source code classes and create a grammar language which will be provided as input to the UML diagram generator. The UML diagram generator uses the parsed grammar as the input and generates a class diagram as the resultant image output. Parser tool : The parser tool I have used for this project is Java Parser (https://github.com/javaparser/javaparser) library. This parser is highly efficient in parsing the code and is completely open source. It makes use of a compilation unit to ensemble the structural units of the Java program. It also provides access to sub-unit of the code by using various methods and classes. We make use of Java Parser to develop the Parser in the application which helps in understanding the relations between the classes. UML diagram : The UML Generator tool used is yUML Diagram generator (https://yuml.me/). yUML is a free online tool which provides us with the API to generate the class diagram. After parsing the java classes, it returns a grammar which is a set of instructions outlining the relations between the classes and interfaces along with other details such a methods and attributes. We make a GET request to the URL : https://yuml.me/diagram/plain/class/ and this generates the class diagram. Thus, you need a working internet connection to generate the diagram. <h1>Running the project</h1> In order to run the project, extract the executable JAR file to a folder. Command: java -jar umlparser.jar class "<insert path to test classes>" class_diagram This command will generate a class diagram with the name class_diagram.png Open the image file to view the relation between the different classes. Example for running the project java -jar umlparser.jar class "C:\Users\Vivek Agarwal\UMLParser\src\test\test4\test4.zip" class_diagram
PHP
UTF-8
8,547
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Store; use App\Models\Product; use App\Models\ProductStore; use App\Models\User; use App\Models\Url; use Illuminate\Support\Facades\Validator; use Redirect; class ProductController extends Controller { public function product() { $uniqueCode = base_convert(sha1(uniqid(mt_rand())), 16, 36); $stores = Store::where('is_deleted', 0)->get(); $data = [ 'uniqueCode' => $uniqueCode, 'stores' => $stores, ]; return view('create_product')->with($data); } public function create_product(Request $request) { $uniqueCode = base_convert(sha1(uniqid(mt_rand())), 16, 36); $custom_url = uniqid(mt_rand()); $user = auth()->user(); $validator = Validator::make($request->all(), [ 'prod_name' => 'required|min:5', 'product_price' => 'required|numeric', // 'url' => 'unique:urls,url' ]); // Getting the urls that are assosiated to the selected store/stores if ($request->input('store_names') != 'Nothing selected') { if (is_array($request->input('store_names'))) { $stores = Store::whereIn('name', $request->input('store_names'))->where('is_deleted', 0)->get(); $store_ids = Store::whereIn('name', $request->input('store_names'))->pluck('id')->toArray(); $product_ids = ProductStore::whereIn('store_id', $store_ids)->pluck('product_id')->toArray(); $urls = Url::whereIn('urlable_id', $product_ids)->where('urlable_type','App\Models\Product')->pluck('url')->toArray(); } else { $stores = Store::where('name', $request->input('store_names'))->where('is_deleted', 0)->get(); $store_ids = Store::where('name', $request->input('store_names'))->pluck('id')->toArray(); $product_ids = ProductStore::where('store_id', $store_ids)->pluck('product_id')->toArray(); $urls = Url::where('urlable_id', $product_ids)->where('urlable_type','App\Models\Product')->pluck('url')->toArray(); } } else { $urls = Url::get(); } // Validation if ($validator->fails()) { return response()->json($validator->errors()); } else { // Validation 2 - URL if (in_array($request->input('product_custom_url'), $urls )) { //checking if the url already exists in the DB $uniqueCode = base_convert(sha1(uniqid(mt_rand())), 16, 36); $error_message = True; return response()->json([$uniqueCode, $error_message]); } else { // // Creating new Product object $new_product = new Product; $new_product->name = $request->input('prod_name'); $new_product->sku = $request->input('sku'); $new_product->price = $request->input('product_price'); $new_product->user_id = $user->id; $new_product->user_name = $user->name; $new_product->description = $request->input('product_description'); $new_product->save(); // Creating new ProductStore relation foreach ($stores as $store) { $new_product_store = new ProductStore; $new_product_store->product_id = $new_product->id; $new_product_store->store_id = $store->id; $new_product_store->is_deleted = 0; $new_product_store->save(); }; // Saving the url in the URL model $new_url = new Url; if ($request->input('product_custom_url') != null) { $new_url->url = $request->input('product_custom_url'); } else { $new_url->url = $custom_url; } $new_url->urlable_id = $new_product->id; $new_url->urlable_type = "App\Models\Product"; $new_url->save(); return response()->json($uniqueCode); } } } public function product_details($store_name, $store_id, $product_name, $product_id, $custom_url) { $product = Product::find($product_id); $user = User::find($product->user_id); $url = Url::where('urlable_id', $product_id )->get()->first(); return view('product_details', compact('product', 'user','url', 'store_id')); } public function unassigned_product_details($product_name, $product_id, $custom_url) { $product = Product::find($product_id); $user = User::find($product->user_id); $url = Url::where('urlable_id', $product_id )->get()->first(); return view('product_details', compact('product', 'user', 'url')); } public function delete_product(Request $request) { // Deleting store_product relationship $store_product = ProductStore::where('product_id', $request->product_id)->first(); if (!is_null($store_product)) { $store_product->is_deleted = 1; $store_product->save(); } $stores = Store::where('is_deleted', 0)->paginate(4); $products = Product::paginate(4); $delete_message = 'Product has been deleted'; return view('home', compact('stores', 'products', 'delete_message')); } public function edit_product($product_name, $product_id, $custom_url, $store_id) { $product = Product::find($product_id); $stores = Store::where('is_deleted', 0)->get(); $product_store = ProductStore::where('product_id', $product_id)->where('is_deleted', 0)->get()->first(); $url = Url::where('urlable_id', $product_id)->get()->first(); $uniqueCode = $product->sku; $is_edit = True; return view('create_product', compact('stores', 'store_id', 'uniqueCode', 'is_edit', 'url', 'product', 'product_store')); } public function save_edit_product(Request $request) { $validator = Validator::make($request->all(), [ 'product_name' => 'required|min:5', 'product_price' => 'required|numeric', // 'url' => 'unique:urls,url' ]); if ($validator->fails()) { return Redirect::back()->withErrors($validator->errors()); } else { // Validation - URL $product_ids = ProductStore::where('store_id', $request->input('store_id'))->pluck('product_id')->toArray(); if (is_array($product_ids)) { $urls = Url::whereIn('urlable_id', $product_ids)->where('urlable_type','App\Models\Product')->pluck('url')->toArray(); } else { $urls = Url::where('urlable_id', $product_ids)->where('urlable_type','App\Models\Product')->pluck('url')->toArray(); } $urls_diff = array_diff($urls, array($request->input('current_store_url'))); // all the urls except the current one if (in_array($request->input('product_custom_url'), $urls_diff)) { //checking if the url already exists in the DB $error_message = 'The selected URL already exist in the database. Please select a new one.'; return Redirect::back()->withErrors($error_message); } else { // Updating product $product = Product::where('sku', $request->sku)->get()->first(); $product->name = $request->input('product_name'); $product->price = $request->input('product_price'); $product->description = $request->input('product_description'); $product->save(); // Updating url $url = Url::where('urlable_id', $product->id)->get()->first(); $url->url = $request->input('product_custom_url'); $url->save(); $success_message = "Product has been successfully updated."; }; }; $stores = Store::where('is_deleted', 0)->paginate(4); $products = Product::paginate(4); return view('home', compact('stores', 'products', 'success_message')); } }
Ruby
UTF-8
1,048
3.515625
4
[]
no_license
require_relative "list" require_relative "task" # Create list list = List.new # Create tasks and add them to the list list.add_task(Task.new("Feed the cat",7)) list.add_task(Task.new("Take out trash",2)) list.add_task(Task.new("Mow the lawn",5)) # Print out the second task in the list puts "Second task:" puts list.tasks[1].name puts "---------" # Get an array containing the names of all incomplete tasks from the list puts "Incomplete Tasks:" puts list.incomplete_task_names puts "--------" # add toggle stuff here list.tasks[0].toggle_complete! puts "--------" puts list.incomplete_task_names # Mark the first task from the list as complete list.tasks[0].complete! # Print out the incomplete tasks again puts "Incomplete Tasks:" puts list.incomplete_task_names # Print out number of incomplete tasks puts list.number_of_incomplete_tasks # Delete completes and print out list puts list.delete_complete_tasks # Returns priority p "--------" puts list.tasks[0].priority # Sort by priority p "---PRIORITY ---" p list.sorted_tasks
Java
UTF-8
1,566
2.8125
3
[]
no_license
package domein; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.value.ChangeListener; public class TellerThread implements Runnable { private IntegerProperty teller = new SimpleIntegerProperty(); private Lock accessLock = new ReentrantLock(); private Condition kanDoorgaan = accessLock.newCondition(); private boolean pauze = false; private boolean going = true; public void addObserver(ChangeListener<? super Number> listener) { teller.addListener(listener); } public void suspend() { accessLock.lock(); try { pauze = true; } finally { accessLock.unlock(); } } public void resume() { accessLock.lock(); try { pauze = false; kanDoorgaan.signal(); } finally { accessLock.unlock(); } } public void stop() { accessLock.lock(); try { going = false; } finally { accessLock.unlock(); } } @Override public void run() { while (going) { teller.set(teller.get()+1); try { Thread.sleep(100); //TODO nagaan of er moet gepauzeerd worden // en indien zo Thread in await toestand brengen // + lock accessLock.lock(); while (pauze) { kanDoorgaan.await(); } } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } finally { // TODO: DO NOT FORGET ME: accessLock.unlock(); } } } }
C#
UTF-8
2,512
2.90625
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace sudoku { class Program { static void Main(string[] args) { string s = // "xxx|4x5|xx1\n" + // "6x5|198|xxx\n" + // "xx9|xx7|x5x\n" + // // "x6x|8xx|517\n" + // "x7x|xxx|x9x\n" + // "581|xx3|x4x\n" + // // "x9x|2xx|8xx\n" + // "xxx|519|4x2\n" + // "2xx|7x6|xxx\n"; // "x72|xx5|4xx\n" + // "6xx|x2x|xxx\n" + // "4xx|x3x|x5x\n" + // // "x58|xx2|xx1\n" + // "x6x|xxx|x8x\n" + // "7xx|5xx|23x\n" + // // "x4x|x9x|xx5\n" + // "xxx|x1x|xx4\n" + // "xx7|4xx|92x"; // "x3x|xx5|xx2\n" + // "1xx|34x|xxx\n" + // "xx8|xxx|3xx\n" + // // "5x9|xxx|x1x\n" + // "7xx|x1x|xx4\n" + // "x1x|xxx|2x5\n" + // // "xx7|xxx|8xx\n" + // "xxx|x23|xx6\n" + // "8xx|6xx|x2x"; // "xxx|x14|xx9\n" + // "4x5|xxx|32x\n" + // "xx9|x3x|41x\n" + // // "xx2|64x|x7x\n" + // "xxx|x8x|xxx\n" + // "x6x|x29|5xx\n" + // // "x54|x9x|1xx\n" + // "x93|xxx|8x5\n" + // "8xx|45x|xxx"; // "6xx|7xx|x4x\n" + // "x35|xx6|xxx\n" + // "xxx|2xx|x3x\n" + // // "9xx|x3x|xxx\n" + // "xx8|1xx|xx7\n" + // "x1x|xx5|2xx\n" + // // "xxx|821|xx4\n" + // "7xx|xxx|x1x\n" + // "xx4|xxx|5xx"; "xx6|7xx|1xx\n" + "x8x|x6x|xx3\n" + "9xx|4x1|x8x\n" + "xxx|x53|xxx\n" + "2xx|xxx|x4x\n" + "x7x|6xx|xx2\n" + "xxx|xx2|xx5\n" + "xx4|x9x|x1x\n" + "x9x|3xx|7xx"; var stopwatch = new Stopwatch(); stopwatch.Start(); var sudoku = new Sudoku(s).Solve(); stopwatch.Stop(); Console.WriteLine(sudoku); Console.WriteLine("Elapsed: {0}", stopwatch.ElapsedMilliseconds); } } }
Java
UTF-8
755
2.0625
2
[]
no_license
package crud.sample.app.config; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; @Configuration public class WebConfig extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/css/**").addResourceLocations("classpath:/templates/css/"); registry.addResourceHandler("/js/**").addResourceLocations("classpath:/templates/js/"); registry.addResourceHandler("/js/third-party/**").addResourceLocations("classpath:/templates/js/third-party/"); } }
Markdown
UTF-8
2,634
3.109375
3
[]
no_license
# Sequential-Forward-Floating-Selection The aim of this project was to implement a feature selector algorithm - Sequential Forward Floating Selector (SFFS) from scratch in python. SFS is also implemented The code also supports to choose from either a wrapper method or filter method to calculate the significance of features. For the wrapper method 1-NN algorithm is used and for the filter method Mahalanobis distance method is used. ## Parameters supported The python code supports the below parameters, | Option | Description | Default Value | | ---------------- | ----------------------------------------- | ------------------------------ | | -h, --help | show this help message and exit | | | --dataset | path_to_dataset | mushroom.csv | | --objective_type | wrapper/filter | wrapper | | --features | K-best features to select | 5 | | --folds | K-Folds cross validation. Used in wrapper | 5 | | --floating | Select SFFS or SFS | False. SFS by default is used | ## Run To run the Sequential Forward Selection (SFS) algorithm with wrapper method (1-NN) using 5 fold cross validation to select 10 best features execute,\ `python feature_selection.py --dataset mushroom.csv --objective_type wrapper --features 10 --folds 5` To run the Sequential Forward Selection (SFS) algorithm with filter method (mahalanobis distance) to select 10 best features execute,\ `python feature_selection.py --dataset mushroom.csv --objective_type filter --features 10` To run the Sequential Forward Floating Selection (SFFS) algorithm with wrapper method (1-NN) using 5 fold cross validation to select 10 best features execute,\ `python feature_selection.py --dataset mushroom.csv --objective_type wrapper --features 10 --folds 5 --floating` To run the Sequential Forward Floating Selection (SFFS) algorithm with filter method (mahalanobis distance) to select 10 best features execute,\ `python feature_selection.py --dataset mushroom.csv --objective_type filter --features 10 --floating` The implemetation is based on [this research paper](http://library.utia.cas.cz/separaty/historie/somol-floating%20search%20methods%20in%20feature%20selection.pdf). For explanation of the algorithm and results please check the [Report folder](https://github.com/ajaygk95/Sequential-Forward-Floating-Selection/tree/master/Report)
Python
UTF-8
5,827
2.90625
3
[]
no_license
# -*- coding: UTF-8 -*- import wx import os import json import yaml class APP(wx.Frame): def __init__(self): super().__init__(None, title="Convert Data Format", pos=(200, 200), size=(1000, 600)) self.Center() self.setup_menu_bar() self.split_window = wx.SplitterWindow(self) self.left_panel = wx.Panel(self.split_window) self.right_panel = wx.Panel(self.split_window) self.left_panel.SetBackgroundColour(colour="#F5F5F5") self.right_panel.SetBackgroundColour(colour="#F5F5F5") self.split_window.SplitVertically(self.left_panel, self.right_panel, 490) self.split_window.SetMinimumPaneSize(50) self.left_box = None self.right_box = None self.radio_box = None self.convert_data_text = None self.convert_button = None self.convert_result = None self.setup_left_panel() self.setup_right_panel() self.Show() def setup_menu_bar(self): menu_bar = wx.MenuBar() file_menu = wx.Menu() about_menu = wx.Menu() menu_open = file_menu.Append(wx.ID_OPEN, "Open", "Open File") file_menu.AppendSeparator() menu_exit = file_menu.Append(wx.ID_EXIT, "Exit", "Exit Application") menu_bar.Append(file_menu, "File") menu_about = about_menu.Append(wx.ID_ABOUT, 'Info', 'Information') menu_bar.Append(about_menu, "About") self.Bind(wx.EVT_MENU, self.exit_app, menu_exit) self.Bind(wx.EVT_MENU, self.show_info, menu_about) self.Bind(wx.EVT_MENU, self.open_file, menu_open) self.SetMenuBar(menu_bar) # https://github.com/wxWidgets/Phoenix/issues/476 def setup_left_panel(self): self.left_box = wx.BoxSizer(wx.VERTICAL) convert_type_message = wx.StaticText(self.left_panel, label="Select type to convert", style=wx.ALIGN_CENTRE) self.left_box.Add(convert_type_message, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, border=10) convert_type_list = ["Format Json", "Json to Yaml"] self.radio_box = wx.RadioBox(self.left_panel, choices=convert_type_list, majorDimension=1, style=wx.RA_SPECIFY_ROWS) self.left_box.Add(self.radio_box, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, border=1) self.convert_button = wx.Button(self.left_panel, pos=(300, 20), size=(80, 40), label="Convert") self.convert_button.Bind(wx.EVT_BUTTON, self.convert_data) self.left_box.Add(self.convert_button, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, border=1) self.convert_data_text = wx.TextCtrl(self.left_panel, style=wx.TE_MULTILINE, size=(300, 500)) self.left_box.Add(self.convert_data_text, flag=wx.ALL | wx.EXPAND, border=10) self.left_panel.SetSizerAndFit(self.left_box) def setup_right_panel(self): self.right_box = wx.BoxSizer(wx.VERTICAL) self.convert_result = wx.TextCtrl(self.right_panel, style=wx.TE_READONLY | wx.TE_MULTILINE, size=(300, 600)) self.right_box.Add(self.convert_result, flag=wx.ALL | wx.EXPAND, border=10) self.right_panel.SetSizerAndFit(self.right_box) def convert_data(self, e): to_convert_text = self.convert_data_text.GetValue() convert_type = self.radio_box.GetStringSelection() if to_convert_text != "" and convert_type != "": try: if convert_type == "Format Json": result = json.dumps(json.loads(to_convert_text), indent=4, sort_keys=False, ensure_ascii=False) elif convert_type == "Json to Yaml": result = yaml.safe_dump(json.loads(to_convert_text), default_flow_style=False, indent=2) self.convert_result.SetValue(result) except Exception as err: if str(err).find("Expecting property name enclosed in double quotes") >= 0: try: if convert_type == "Format Json": result = json.dumps(json.loads(to_convert_text.replace("“", "\"").replace("”", "\"")), indent=4, sort_keys=False, ensure_ascii=False) elif convert_type == "Json to Yaml": result = yaml.safe_dump(json.loads(to_convert_text.replace("“", "\"").replace("”", "\"")), default_flow_style=False, indent=2) self.convert_result.SetValue(result) except Exception as err: self.convert_result.SetValue("cannot convert data, please check the error message below:\n" + str(err)) else: self.convert_result.SetValue("cannot convert data, please check the error message below:\n" + str(err)) else: wx.MessageBox(message="No data or type to convert!", caption="Error", style=wx.OK | wx.ICON_ERROR) e.Skip() def exit_app(self, e): self.Close() def open_file(self, e): files_filter = "All files (*.*)|*.*" file_dialog = wx.FileDialog(self, message="select single file", defaultDir=os.getcwd(), wildcard=files_filter, style=wx.FD_OPEN) file_dialog.ShowModal() file_path = file_dialog.GetPath() self.convert_data_text.SetEditable(False) with open(file_path, "r") as f: file_content = f.read() self.convert_data_text.SetValue("") self.convert_data_text.SetValue(file_content) self.convert_result.SetValue("") self.convert_data_text.SetEditable(True) e.Skip() def show_info(self, e): message_info = 'Author:bj\nDate:2020/12/04\nVersion:0.1' message = wx.MessageDialog(self, message_info, "INFO", wx.OK) message.ShowModal() message.Destroy() if __name__ == "__main__": app = wx.App() APP() app.MainLoop()
PHP
UTF-8
889
2.53125
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateUsersTable extends Migration { public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('full_name', 32); $table->string('username', 32); $table->string('password', 128); $table->string('email',64); $table->text('address'); $table->string('phone', 32); $table->string('user_type', 32)->default('user'); $table->float('balance',8,2); //$table->string('remember_token', 128)->nullable(); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); }); } public function down() { Schema::drop('users'); } }
JavaScript
UTF-8
4,560
2.5625
3
[]
no_license
/** * Created by 93701 on 2016/9/13. */ /** * Created by 93701 on 2016/9/12. */ var treatList = { init: function () { var that = this; that.initDatePicker(); //初始化时间选择控件 that.initTable(); //初始化列表 that.bindEvent(); //绑定时间 }, initDatePicker: function () { jQuery('.datepicker-autoclose').datepicker({ autoclose: true, todayHighlight: true, format: 'yyyy-mm-dd' }); }, initTable: function () { this.dataTable = $('#myTable').dataTable({ sAjaxSource: base+'/treat/list', //ajax地址 fnServerParams: function (aoData) { //将form中的查询条件加到提交参数中 aoData.push({name: "search", value: $('input[name="keyword"]').val()}); aoData.push({name: "status", value: $('select[name="status"]').val()}); aoData.push({name: "startTime", value: $('input[name="startTime"]').val()}); aoData.push({name: "endTime", value: $('input[name="endTime"]').val()}); }, aaSorting: [[5,"desc"]], //排序,[第几列,正序或倒序] aoColumns: [ //列定义 { mDataProp: 'telephone', sTitle: '联系方式', bSortable: false, mRender: function (data, type, full) { //渲染函数,即 td 内显示的内容 return '<a href="javascript: treatDetail(' + full.id + ')">' + full.telephone + '</a>'; } }, { mDataProp: 'name', sTitle: '名称', bSortable: false, }, { mDataProp: 'email', sTitle: '邮箱', bSortable: false, }, { mDataProp: 'status', sTitle: '状态', mRender: function (data, type, full) { //渲染函数,即 td 内显示的内容 if (data == 0) { return '失效'; } else if (data == 1) { return '未认证'; } else if (data == 2) { return '待审核'; } else if (data == 3) { return '已认证'; } else if (data == -1) { return '认证失败'; } }, bSortable: false, }, { mDataProp: 'createTime', sTitle: '注册时间', mRender: function (data, type, full) { //渲染函数,即 td 内显示的内容 return dateFormat(data,'yyyy-MM-dd hh:mm',true); } }, { mDataProp: null, sTitle: '操作', mRender: function (data, type, full) { var status = full.status; var html = ''; if(status == 2){ html += '<button class="btn btn-outline btn-danger" onClick="toTreatModel(' + full.id + ')">实名认证</button>'; } if(status == 1 || status == 2 || status == 3){ html += '<button class="btn btn-outline btn-info" onClick="treatDetail(' + full.id + ')">详情</button>'; } html += '<button class="btn btn-outline btn-info" onClick="deleteUser('+full.id+')">删除</button>'; return html; }, bSortable: false } ] }); }, bindEvent: function () { var that = this; $('.search').on('click', function () { that.dataTable.fnDraw(); }); $('.reset').on('click',function(){ $('#searchForm')[0].reset(); that.dataTable.fnDraw(); }); } }; /** * 刷新数据列表 */ var refreshList = function () { treatList.dataTable.fnDraw(); }; /** * 康复师详情 * @param accoutId */ var treatDetail = function (data){ toTreatModel(data); }; $(function () { treatList.init(); });
TypeScript
UTF-8
1,936
2.765625
3
[]
no_license
import { Injectable } from '@angular/core'; import {Router} from '@angular/router'; @Injectable() export class PageService { private nowPage = 1; // 当前页码 private max: number; // 最大页码 private min = 1; // 最小页码 private countNumber: number; // 计数总数 private Row = 20; // 每页行数 private url: string; constructor(private router: Router) { // 默认当前第一页,最小页码为一页 } setPage(countNumber) { // 输入总数, 设置最大页码 this.countNumber = countNumber; if (countNumber % this.Row === 0 ) { this.max = countNumber / this.Row; } else { countNumber -= countNumber % this.Row; this.max = countNumber / this.Row + 1; } } setRow(row: number) { this.Row = row; } setNowPage(nowPage: number) { this.nowPage = nowPage; } setUrl(url: string) { this.url = url; } getNowPage(): number { return this.nowPage; } getMax(): number { return this.max; } getMin(): number { return this.min; } getNumber(): number { return this.countNumber; } getRow(): number { return this.Row; } nextPage(): boolean { console.log('nextPage'); if (this.nowPage < this.max) { this.nowPage++; this.router.navigate([this.url + '/' + this.nowPage]); return true; } return false; } lastPage(): boolean { console.log('lastPage'); if (this.nowPage > this.min) { this.nowPage--; this.router.navigate([this.url + '/' + this.nowPage]); return true; } return false; } skipPage(skipNumber: number): boolean { console.log('skipPage'); if (skipNumber < this.min || skipNumber > this.max) { return false; } else { if (skipNumber * 10 % 10 !== 0) { return false; } else { this.nowPage = skipNumber; this.router.navigate([this.url + '/' + this.nowPage]); } } } }
Java
UTF-8
759
3.71875
4
[]
no_license
package javaStudy.ch08_예외처리; public class ExceptionEx7 { /* * 예외처리의 정의 -> 프로그램 실행 시 발생할 수 있는 예외에 대비한 코드를 작성 * 예외처리의 목적 -> 프로그램의 비정상 종료를 막고, 정상적인 실행상태를 유지 * * */ public static void main(String[] args) { System.out.println(1); System.out.println(2); try { System.out.println(3); System.out.println(0/0); System.out.println(4); } catch (ArithmeticException ae) { if(ae instanceof ArithmeticException) System.out.println("true"); System.out.println("ArithmeticException"); } catch (Exception e ) { System.out.println("Exception"); }//try-catch of end System.out.println(6); } }
C#
UTF-8
1,571
2.640625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using System.Linq; using Schedule.CSP.CSP; namespace Schedule.CSP.Inference { public class DomainLog<Var, Val> : IInferenceLog<Var, Val> where Var : Variable { private readonly List<KeyValuePair<Var, Domain<Val>>> _savedDomain; private HashSet<Var> _affectedVariables; private bool _emptyDomainObserved; public DomainLog() { _savedDomain = new List<KeyValuePair<Var, Domain<Val>>>(); _affectedVariables = new HashSet<Var>(); } public void Clear() { _savedDomain.Clear(); _affectedVariables.Clear(); } public void StoreDomainFor(Var var, Domain<Val> domain) { if (!_affectedVariables.Contains(var)) { _savedDomain.Add(new KeyValuePair<Var, Domain<Val>>(var,domain)); _affectedVariables.Add(var); } } public void SetEmptyDomainFound(bool b) { _emptyDomainObserved = b; } public DomainLog<Var, Val> Compactify() { _affectedVariables = null; return this; } public bool IsEmpty() { return !_savedDomain.Any(); } public void Undo(CSP<Var, Val> csp) { _savedDomain.ForEach(pair => csp.SetDomain(pair.Key, pair.Value)); } public bool IsConsistencyFound() { return _emptyDomainObserved; } } }
Java
UTF-8
3,002
4
4
[]
no_license
package ee.taltech.iti0200.introduction; import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class Introduction { /** * Method gets a string that contains x words. * The first character of the string starts a new word, next words always start with a capital letter. * Words are not separated by whitespace. * Words (including the first character) can contain all kinds of symbols. * The function should find and return x . * * @param string Given string that contains x words. * @return The number of words in the given string. */ public int camelCaseWordCounter(String string) { int wordcount; if (string.equals("")) { return 0; } else if (Character.isUpperCase(string.charAt(0))) { wordcount = 0; } else { wordcount = 1; } for (int i = 0; i < string.length(); i++) { if (Character.isUpperCase(string.charAt(i))) { wordcount += 1; } } return wordcount; } /** * Method gets a list of numbers. * Return a list containing only even numbers of the given list. * If the given list does not contain any even numbers, return an empty list. * * @param numbers given list that contains numbers. * @return list of even numbers. */ public List<Integer> findEvenNumbersList(List<Integer> numbers) { ArrayList<Integer> evens = new ArrayList<Integer>(); for (Integer i : numbers) { if (i % 2 == 0) { evens.add(i); } } return evens; } /** * Method gets an array of numbers. * Return an array containing only even numbers of the given array. * If the given array does not contain any even numbers, return an empty array. * * You must not use the previous function in this function! * * @param numbers given array that contains numbers. * @return array of even numbers. */ public int[] findEvenNumbersArray(int[] numbers) { int evens = 0; for (int i: numbers) { if (i % 2 == 0) { evens++; } } int[] evensArray = new int[evens]; int index = 0; for (int i : numbers) { if (i % 2 == 0) { evensArray[index] = i; index++; } } return evensArray; } public static void main(String[] args) { Introduction introduction = new Introduction(); System.out.println(introduction.camelCaseWordCounter("A")); // 3 List<Integer> nums = new ArrayList<>(Arrays.asList(4, 7, 5, 2, 1, 2, -2, 0)); System.out.println(introduction.findEvenNumbersList(nums)); // [4, 2, 2, -2, 0] int[] array = {9, 0, 24, -6, 3}; System.out.println(Arrays.toString(introduction.findEvenNumbersArray(array))); // [0, 24, -6] } }
Go
UTF-8
2,235
3.453125
3
[ "Apache-2.0" ]
permissive
package easy_http import ( "io/ioutil" "net/http" ) type BuildResponse func(resp *http.Response, err error) IResponse //使用client发去请求后,返回一个实现了这个接口的对象 //只要实现这个接口,就能作为返回值 //在 `BuildResponse` 函数中构造出返回的对象 //默认提供了 `HttpResponse` 实现了这个接口 //可以根据自己的需求自己重新实现这个接口 type IResponse interface { //返回这个请求的错误 Error() error //返回这个请求的http状态码 StatusCode() int //返回HTTP请求的header信息 Header() http.Header //返回HTTP内容长度 ContentLength() int64 //返回HTTP的内容 Content() []byte //返回HTTP包中的 response信息 Resp() *http.Response //返回这次请求的request信息 Request() *http.Request //根据name 返回response的cookie Cookie(name string) *http.Cookie } type HttpResponse struct { err error ResponseContent []byte httpResp *http.Response } func (h *HttpResponse) Error() error { return h.err } func (h *HttpResponse) StatusCode() int { if h.httpResp == nil { return 0 } return h.httpResp.StatusCode } func (h *HttpResponse) Header() http.Header { if h.httpResp == nil { return nil } return h.httpResp.Header } func (h *HttpResponse) ContentLength() int64 { if h.httpResp == nil { return 0 } return h.httpResp.ContentLength } func (h *HttpResponse) Content() []byte { return h.ResponseContent } func (h *HttpResponse) Resp() *http.Response { return h.httpResp } func (h *HttpResponse) Request() *http.Request { if h.httpResp == nil { return nil } return h.httpResp.Request } func (h *HttpResponse) Cookie(name string) *http.Cookie { for _, cookie := range h.httpResp.Cookies() { if cookie.Name == name { return cookie } } return nil } //默认构造HTTP response的函数 func EasyBuildResponse(resp *http.Response, err error) IResponse { response := new(HttpResponse) if err != nil { response.err = err return response } response.httpResp = resp all, err := ioutil.ReadAll(resp.Body) if err != nil { response.err = err return response } response.ResponseContent = all _ = resp.Body.Close() return response }
C++
UTF-8
1,985
2.65625
3
[]
no_license
#ifndef _GORM_THREAD_POOL_H__ #define _GORM_THREAD_POOL_H__ #include "gorm_sys_inc.h" #include "gorm_type.h" #include "gorm_mempool.h" namespace gorm{ class GORM_Log; class GORM_ThreadPool; class GORM_Thread { public: GORM_Thread(GORM_Log *logHandle, shared_ptr<GORM_ThreadPool>& pPool); virtual ~GORM_Thread(); void SetLogHandle(GORM_Log* logHandle); void SetThreadPool(); virtual void Work(mutex *m) = 0; // 通知事件回调 // 用于在本线程处理io等待阶段(epoll_wait),别的线程唤醒本线程的时候的回调 virtual void SignalCB() = 0; virtual void Stop(); virtual void BeginToUpgrade() = 0; public: virtual void Join(); virtual void Detach(); public: string m_strThreadName; shared_ptr<thread> m_pSysThread; shared_ptr<GORM_ThreadPool> m_pThreadPool = nullptr; atomic_bool m_bJoined; atomic_bool m_bDetached; std::thread::id m_threadId; shared_ptr<GORM_MemPool> m_pMemPool = nullptr; // 线程自己的内存池 GORM_Log *logHandle = nullptr; shared_ptr<GORM_Thread> sharedSelf = nullptr; // stop中置为nullptr,去掉自引用 int stopFlag = 0; // 为1则表示外界想让线程结束了 mutex threadMutex; // 本线程的锁 }; class GORM_ThreadPool { public: GORM_ThreadPool(); virtual ~GORM_ThreadPool(); void SetLogHandle(GORM_Log *logHandle); void Stop(); // 创建iNum个线程 virtual int CreateThread(GORM_Log *logHandle, int threadNum) = 0; // m 为 void StartWork(shared_ptr<GORM_Thread> pThread); private: void StopThreadGroup(); public: mutex m_Mutex; string m_strThreadType; unordered_map<std::thread::id, shared_ptr<GORM_Thread>> m_mapThreadGroup; GORM_Log *logHandle = nullptr; private: atomic_bool m_bRunning; once_flag m_OnceFlag; }; } #endif
C++
SHIFT_JIS
2,714
2.546875
3
[]
no_license
#include "pch.h" #include "GraphicsDeviceDX11.h" #include "Context/Win/DirectX11/ContextDX11.h" namespace Phoenix { namespace Graphics { // std::shared_ptr<IGraphicsDevice> IGraphicsDevice::Create() { return std::make_shared<GraphicsDeviceDX11>(); } // bool GraphicsDeviceDX11::Initialize(OS::IDisplay* display) { device = Phoenix::Graphics::IDevice::Create(); if (!device->Initialize()) { return false; } context = Phoenix::Graphics::IContext::Create(); if (!context->Initialize(device.get())) { return false; } swapChain = Phoenix::Graphics::ISwapChain::Create(); Phoenix::Graphics::SwapChainDesc desc = {}; desc.width = display->GetWidth(); desc.heigth = display->GetHeight(); desc.windowHandle = reinterpret_cast<void*>(display->GetHandle()); if (!swapChain->Initialize(device.get(), desc)) { return false; } return true; } // I void GraphicsDeviceDX11::Finalize() { swapChain->Finalize(); context->Finalize(); device->Finalize(); } // _OꂽC[W\ void GraphicsDeviceDX11::Present(int syncInterval) { swapChain->Present(syncInterval); } // `Jn void GraphicsDeviceDX11::RenderBegin() { Phoenix::Graphics::IRenderTargetSurface* nullRTS[8] = {}; Phoenix::Graphics::IDepthStencilSurface* nullDSS[8] = {}; Phoenix::Graphics::ITexture* nullTexture[8] = {}; context->SetRenderTargets(8, nullRTS, 0); context->SetShaderResources(ShaderType::Vertex, 0, 8, nullTexture); context->SetShaderResources(ShaderType::Pixel, 0, 8, nullTexture); ContextDX11* contextDX11 = static_cast<ContextDX11*>(context.get()); ISampler* samplers[] = { contextDX11->GetSamplerState(SamplerState::LinearWrap) }; context->SetSamplers(ShaderType::Vertex, 0, 1, samplers); context->SetSamplers(ShaderType::Pixel, 0, 1, samplers); context->SetRasterizer(contextDX11->GetRasterizerState(RasterizerState::SolidCullNone)); context->SetBlend(contextDX11->GetBlendState(BlendState::AlphaBlend), 0, 0xFFFFFFFF); float color[] = { 0.5f, 0.5f, 0.5f, 1.0f }; Phoenix::Graphics::IRenderTargetSurface* rts = swapChain->GetRenderTargerSurface(); Phoenix::Graphics::IDepthStencilSurface* dss = swapChain->GetDepthStencilSurface(); context->ClearRenderTargetView(rts, color); context->ClearDepthStencilView(dss, 1.0f, 0); context->SetRenderTargets(1, &rts, dss); context->SetDepthStencil(contextDX11->GetDepthStencilState(DepthState::TestAndWrite), 1); } // `I void GraphicsDeviceDX11::RenderEnd() { // No Data. } } // namespace Graphics } // namespace Phoenix
Java
UTF-8
1,104
2.359375
2
[]
no_license
package com.blazedemo.steps; import com.blazedemo.pages.LoginPage; import com.blazedemo.pages.ResultPage; import com.blazedemo.pages.SearchPage; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.junit.Assert; public class SearchScenarioSteps { LoginPage loginPage; SearchPage searchPage; ResultPage resultPage; @Given("^user opens the site$") public void givenUserOpensTheSite() { loginPage.open(); } @When("user choose (.*)") public void whenGivenUserChoose(String text){ searchPage.chooseDeparture(text); } @When("user clicks on ChooseFlight button") public void andGivenUserClickOnButton(){ searchPage.clickChooseFlightButton(); } @Then("user sees Flight list") public void thenUserSeesFlightList(){ Assert.assertTrue(resultPage.isResultDisplayed()); } @Then("(.*) should be displayed") public void thenShouldBeDisplayed(String expectedDepCity){ Assert.assertEquals(resultPage.choosenDepCity(), expectedDepCity); } }
Java
UTF-8
8,795
2.703125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package academico; import api.Pregunta; import api.Respuesta; import java.util.ArrayList; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Martin */ public class AcademicManagerTest { public AcademicManagerTest() { } /** * Test of addPregunta method, of class AcademicManager. */ @Test public void testAddPregunta() { System.out.println("addPregunta"); Pregunta p = new Pregunta ("¿Cambio en el método, y ahora?"); AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); boolean expResult = false; Pregunta result = instance.addPregunta(p); System.out.println ("Id de la pregunta agregada:" + result.IdNodo); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of delPregunta method, of class AcademicManager. */ @Test public void testDelPregunta() { System.out.println("delPregunta"); Pregunta p = new Pregunta(""); p.IdNodo = "#31:6"; AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); boolean expResult = false; boolean cascade = true; boolean result = instance.delPregunta(p,cascade); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of updPregunta method, of class AcademicManager. */ @Test public void testUpdPregunta() { System.out.println("updPregunta"); Pregunta old = null; Pregunta upd = null; AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); boolean expResult = false; boolean result = instance.updPregunta(old, upd); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPreguntaByText method, of class AcademicManager. */ @Test public void testGetPreguntaByText() { System.out.println("getPreguntaByText"); String texto = ""; AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); Pregunta expResult = null; Pregunta result = instance.getPreguntaByText(texto); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPreguntaById method, of class AcademicManager. */ @Test public void testGetPreguntaById() { System.out.println("getPreguntaById"); String Id = "#31:2"; AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); Pregunta expResult = null; Pregunta result = instance.getPreguntaById(Id); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of addRespuesta method, of class AcademicManager. */ @Test public void testAddRespuesta() { System.out.println("addRespuesta"); AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); Pregunta p = instance.getPreguntaById("#31:6"); Respuesta r = new Respuesta ("Segunda respuesta a #31:6"); Respuesta expResult = null; Respuesta result = instance.addRespuesta(r, p); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of delRespuesta method, of class AcademicManager. */ @Test public void testDelRespuesta() { System.out.println("delRespuesta"); Respuesta r = new Respuesta (""); r.IdNodo = "#32:1"; AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); boolean expResult = false; boolean result = instance.delRespuesta(r); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of updRespuesta method, of class AcademicManager. */ @Test public void testUpdRespuesta() { System.out.println("updRespuesta"); Respuesta old = null; Respuesta upd = null; AcademicManager instance = null; boolean expResult = false; boolean result = instance.updRespuesta(old, upd); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getRespuestaByText method, of class AcademicManager. */ @Test public void testGetRespuestaByText() { System.out.println("getRespuestaByText"); String texto = ""; AcademicManager instance = null; Respuesta expResult = null; Respuesta result = instance.getRespuestaByText(texto); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getRespuestaById method, of class AcademicManager. */ @Test public void testGetRespuestaById() { System.out.println("getRespuestaById"); String Id = ""; AcademicManager instance = null; Respuesta expResult = null; Respuesta result = instance.getRespuestaById(Id); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getPreguntas method, of class AcademicManager. */ @Test public void testGetPreguntas() { System.out.println("getPreguntas"); AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); ArrayList<Pregunta> expResult = null; ArrayList<Pregunta> result = instance.getPreguntas(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getRespuestas method, of class AcademicManager. */ @Test public void testGetRespuestas() { System.out.println("getRespuestas"); AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); ArrayList<Respuesta> expResult = null; ArrayList<Respuesta> result = instance.getRespuestas(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getRespuestasByPregunta method, of class AcademicManager. */ @Test public void testGetRespuestasByPregunta() { System.out.println("getRespuestasByPregunta"); Pregunta p = new Pregunta(); p.IdNodo = "#31:1"; AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); ArrayList<Respuesta> expResult = null; ArrayList<Respuesta> result = instance.getRespuestasByPregunta(p); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getRespuestasCount method, of class AcademicManager. */ @Test public void testGetRespuestasCount() { System.out.println("getRespuestasCount"); Pregunta p = new Pregunta(); p.IdNodo = "#31:4"; AcademicManager instance = new AcademicManager ("remote:localhost/PPR","admin","admin"); int expResult = 0; int result = instance.getRespuestasCount(p); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
Python
UTF-8
889
3.578125
4
[]
no_license
#start #vakna upp vaken = "n" while vaken == "n": print("Du sover som en stock. Zzz") vaken = input("Vaknar du? [y/n]").lower() #duscha print("Du masar dig upp och släpar in dig i duschen") print("Någon har lömnat en brödrost i din dusch") duscha = input("Flyttar du på brödrosten? [y/n]").lower() if duscha == "n": exit("Du elchokas till döds.") elif duscha == "y": print("Du blir ren") else: print ("ERROR") #årstid season = False while season == False: season = input("Vilken årstid är det? [vinter, vår, sommar, höst]").lower() if season == "vår" or season == "vinter" or season == "höst": print("Det är kallt som fan") print("Du tar på dig en vinterjacka") elif season == "sommar": print("Du svettas satan") print("Du tar på dig en t-shirt och shorts") else: season = False
Python
UTF-8
2,209
2.59375
3
[]
no_license
import logging import inspect from os import path class SokLog(object): def __init__(self, module, log_name): self.setUpModule(module, log_name) def _get_args_as_string(self, args): args = list(args) args = [str(arg) for arg in args] return ' '.join(args) def info(self, *args, **kwargs): msg = self._get_args_as_string(args) self.log.info(msg, **kwargs) def warning(self, *args, **kwargs): msg = self._get_args_as_string(args) self.log.warning(msg, **kwargs) def debug(self, *args, **kwargs): level = kwargs.get('level', 1) msg = self._get_args_as_string(args) main_path = path.dirname(self.module.__file__) src_path = inspect.stack()[level][1] src_path = '.' + src_path[len(main_path):] line = inspect.stack()[level][2] msg = '%s:%d %s' % (src_path, line, msg) self.log.debug(msg, **kwargs) def error(self, *args, **kwargs): self.log.error(*args, **kwargs) def start_file_logging(self, path): hdlr = logging.FileHandler(path) fmt = logging.Formatter("%(asctime)-10s %(message)s") hdlr.setFormatter(fmt) self.log.addHandler(hdlr) self.log.setLevel(logging.DEBUG) def start_stdout_logging(self): logging.basicConfig( level=logging.DEBUG, format="%(asctime)-10s %(message)s", datefmt="%H:%M:%S" ) def setUpModule(self, module, log_name): self.module = module self.log = logging.getLogger(log_name) _DEFAULT = SokLog(None, None) def init(module, log_name): _DEFAULT.__init__(module, log_name) def info(*args, **kwargs): return _DEFAULT.info(*args, **kwargs) def warning(*args, **kwargs): return _DEFAULT.warning(*args, **kwargs) def debug(*args, **kwargs): kwargs['level'] = 2 return _DEFAULT.debug(*args, **kwargs) def error(*args, **kwargs): return _DEFAULT.error(*args, **kwargs) def start_file_logging(*args, **kwargs): return _DEFAULT.start_file_logging(*args, **kwargs) def start_stdout_logging(*args, **kwargs): return _DEFAULT.start_stdout_logging(*args, **kwargs)
Python
UTF-8
663
3.25
3
[ "BSD-3-Clause" ]
permissive
""" Normalized Stacked Bar Chart ----------------------- This example shows how to make a normalized stacked bar chart. """ import altair as alt from vega_datasets import data source = data.population() chart = alt.Chart(source).mark_bar().encode( x = alt.X('age:O', scale = alt.Scale(rangeStep = 17)), y = alt.Y('sum(people):Q', axis = alt.Axis(title = 'population'), stack = 'normalize'), color = alt.Color('gender:N', scale=alt.Scale( range = ["#EA98D2", "#659CCA"])) ) chart.transform = [{"filter": "datum.year == 2000"}, {"calculate": "datum.sex == 2 ? 'Female' : 'Male'", "as": "gender"}]
Ruby
UTF-8
1,733
3.125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Song attr_accessor :name, :artist_name @@all = [] def self.all @@all end def self.create song = Song.new @@all << song song end def self.new_by_name(name) song = Song.new song.name = name song end def self.create_by_name(name) song = self.new song.name = name @@all << song return song end def self.find_by_name(name) self.all.detect{|song| song.name == name} end def save self.class.all << self end def self.find_or_create_by_name(name) song = self.find_by_name(name) if song then return song else self.create_by_name(name) end end def self.alphabetical self.all.sort_by{|s| s.name} end # def self.new_from_filename(filename) # array=[] # new_ar=[] # array=filename.split("- ") # artist_name=array[0] # # @artist_name=artist_name # new_ar=array[1].partition(".mp3") # name=new_ar[0] # song = self.new # song.artist_name = artist_name # @@all << song # song = self.new # song.name = name # @@all << song # return @@all # end def self.new_from_filename(file_name) new_song = self.new new_song.name = file_name.split(" - ")[1].split(".")[0] new_song.artist_name = file_name.split(" - ")[0] new_song end def self.create_from_filename(mp3_formatted_file) new_song = self.new new_song.name = mp3_formatted_file.split(/[^a-zA-Z\s]|\s-\s/)[1] new_song.artist_name = mp3_formatted_file.split(/[^a-zA-Z\s]|\s-\s/)[0] @@all << new_song end def self.destroy_all @@all.clear end end
Java
UTF-8
136
1.632813
2
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
package org.apache.ibatis.submitted.parent_childs; import java.util.List; public interface Mapper { List<Parent> getParents(); }
Java
UTF-8
1,817
2.625
3
[]
no_license
package com.example.kvstore.repository; import com.example.kvstore.service.KeyValueData; import org.apache.commons.lang3.tuple.Pair; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; public class DataDao { private final String expiryFilePath; private final Long dataTimeOutMs; private final KeyValueData keyValueData; public DataDao(String expiryFilePath, String dataTimeOutMs, KeyValueData keyValueData) { this.expiryFilePath = expiryFilePath; this.dataTimeOutMs = Long.valueOf(dataTimeOutMs); this.keyValueData = keyValueData; } public void removeExpired() { Timestamp current = new Timestamp(System.currentTimeMillis()); Long currentMs = current.getTime(); Map<String, Pair<Integer, Timestamp>> toRemove = new HashMap<>(); for (Map.Entry<String, Pair<Integer, Timestamp>> entry: keyValueData.getData().entrySet()) { Timestamp keyTimeStamp = entry.getValue().getRight(); Long keyMs = keyTimeStamp.getTime(); if (currentMs - dataTimeOutMs >= keyMs) { toRemove.put(entry.getKey(), entry.getValue()); } } removeFromDataStore(toRemove); writeToFile(toRemove); } private void removeFromDataStore(Map<String, Pair<Integer, Timestamp>> toRemove) { for (Map.Entry<String, Pair<Integer, Timestamp>> entry: toRemove.entrySet()) { keyValueData.removeKey(entry.getKey()); } } // not writing in file currently private void writeToFile(Map<String, Pair<Integer, Timestamp>> toRemove) { for (Map.Entry<String, Pair<Integer, Timestamp>> entry: toRemove.entrySet()) { keyValueData.saveExpiredEntry(entry.getKey(), entry.getValue().getLeft()); } } }
C++
UTF-8
2,762
3.390625
3
[]
no_license
// // Train.hpp // DB Trains // // Created by Marina Polishchuk on 3/9/19. // Copyright © 2019 Marina Polishchuk. All rights reserved. // #ifndef Train_hpp #define Train_hpp #include <string> #include <iostream> struct Date { int day; int month; int year; bool operator<(const Date& rhs){ int d1 = this->day + this->month * 31 + this->year * 365; int d2 = rhs.day + rhs.month * 31 + rhs.year * 365; if (d1 < d2) { return true; } return false; } }; struct Time { int hours; int minutes; bool operator<(const Time& rhs){ int t1 = this->minutes + this->hours * 60; int t2 = rhs.minutes + rhs.hours * 60; if (t1 < t2) { return true; } return false; } }; enum class Type {INTERNATIONAL, FAST, ORDINARY, SUBURBAN}; class Train { private: static int count; int id; short train_number; std::string name; Type type; Date arrival_date; Time arrival_time; Date departure_date; Time departure_time; int ticket_requests; int num_of_seats; double popularity; public: Train() { count++; id = count; }; ~Train() = default; void SetNumber(int); void SetName(std::string); void SetType(Type); void SetArrival(Date, Time); void SetDeparture(Date, Time); void SetTicketReq(int); void SetNumOfSeats(int); void SetPopularity() { popularity = (double)ticket_requests/num_of_seats; } short GetNumber() { return train_number; } std::string GetName() { return name; } Type GetType() { return type; } Date GetArrDate() { return arrival_date; } Time GetArrTime() { return arrival_time; } Date GetDepDate() { return departure_date; } Time GetDepTime() { return departure_time; } int GetTicketReq() { return ticket_requests; } int GetNumOfSeats() { return num_of_seats; } double GetPopularity() { return popularity; } int GetID() { return id; } std::string Serialize(); void Unserialize(std::string); void PrintTrain() { std::cout << "\nTrain's name: " << name << "\nID: " << id << " Number: " << train_number << "\nType (International/Fast/Ordinary/Suburban) (0/1/2/3): " << static_cast<int>(type) << "\nArrival date and time: " << arrival_date.day << '.' << arrival_date.month << '.' << arrival_date.year << ' ' << arrival_time.hours << ':' << arrival_time.minutes << "\nDeparture date and time: " << departure_date.day << '.' << departure_date.month << '.' << departure_date.year << ' ' << departure_time.hours << ':' << departure_time.minutes << "\nTrain popularity: " << popularity << std::endl; } }; #endif /* Train_hpp */
Java
UTF-8
313
1.71875
2
[ "Apache-2.0" ]
permissive
package org.iglooproject.basicapp.core.business.upgrade.service; import org.iglooproject.jpa.exception.SecurityServiceException; import org.iglooproject.jpa.exception.ServiceException; public interface IDataUpgradeManager { void autoPerformDataUpgrades() throws ServiceException, SecurityServiceException; }
Java
UTF-8
242
1.703125
2
[ "MIT" ]
permissive
package com.sq.io.aio; import java.io.IOException; /** * @author Leon * @date 2021/1/1 */ public class Bootstrap { public static void main(String[] args) throws IOException { new Thread(new AioServer(8080)).start(); } }
Python
UTF-8
1,013
2.828125
3
[]
no_license
#!/usr/bin/env python3 from os import listdir from os.path import isdir, isfile, join def is_problem_dir(path): if isdir(path) is False: return False if isfile(path + 'README.md') is False: return False # Need problem info file. if isdir(path + 'testdata/') is False: return False # Need problem input and output data return True # Finally, path seems problem dir def get_test_list(path): if is_problem_dir(path) is False: return None d_dir = path + 'testdata/' # for all files in testdata/ d_files = [f for f in listdir(_d_dir) if isfile(join(d_dir, f))] # filter *.in and *.out files in_files = list(map(lambda x: x.rsplit('.', 1)[0], \ list(filter(lambda f: f.endswith('.in'), d_files)))) out_files = list(map(lambda x: x.rsplit('.', 1)[0], \ list(filter(lambda f: f.endswith('.out'), d_files)))) # find .in and .out paired names return list(filter(lambda t:t in in_files, out_files))
C
UTF-8
3,446
2.9375
3
[]
no_license
#include "message_parser.h" char *get_json_string_username_password(const char *username, const char *password) { JSON_Value *root_value = json_value_init_object(); JSON_Object *root_object = json_value_get_object(root_value); // adauga detaliile necesare json_object_set_string(root_object, "username", username); json_object_set_string(root_object, "password", password); // converteste obiectul creat intr-un string char *serialized_string = json_serialize_to_string_pretty(root_value); json_value_free(root_value); return serialized_string; } char *get_json_string_book(const char *title, const char *author, const char *genre, int page_count, const char *publisher) { JSON_Value *root_value = json_value_init_object(); JSON_Object *root_object = json_value_get_object(root_value); // adauga detaliile necesare json_object_set_string(root_object, "title", title); json_object_set_string(root_object, "author", author); json_object_set_string(root_object, "genre", genre); json_object_set_number(root_object, "page_count", page_count); json_object_set_string(root_object, "publisher", publisher); // converteste obiectul creat intr-un string char *serialized_string = json_serialize_to_string_pretty(root_value); json_value_free(root_value); return serialized_string; } char *get_session_cookie(char *msg) { // se cauta pozitia de inceput si de final a cookie-ului char *posStartCookie = strstr(msg, CONNECT_SID); char *posEndCookie = strchr(posStartCookie, ';'); // se aloca memorie pentru cookie-ul ce va fi extras int cookieLen = posEndCookie - posStartCookie; char *cookie = (char *) calloc((cookieLen + 1), sizeof(char)); // se extrage cookie-ul memcpy(cookie, posStartCookie, cookieLen); return cookie; } char *get_token_from_body(const char *body) { JSON_Value *json_body = json_parse_string(body); char *local_token = (char *) json_object_get_string(json_object(json_body), TOKEN); char *token = calloc(strlen(local_token) + 1, sizeof(char)); memcpy(token, local_token, strlen(local_token)); json_value_free(json_body); return token; } char *get_message_body(const char *msg) { // se afla pozitia lungimii body-ului char *posStartLen = strstr(msg, CONTENT_LEN); posStartLen += LEN_NUMBER_OFFSET; /* pentru o functionare corecta a functiei atoi se plaseaza '\0' la finalul numarului */ char *posEndLen = strchr(posStartLen, '\r'); *posEndLen = '\0'; int bodyLen = atoi(posStartLen); *posEndLen = '\r'; // se afla pozitia de inceput a body-ului char *posStartBody = strstr(msg, BODY_START_STRING); posStartBody += BODY_OFFSET; // se extrage body-ul char *body = calloc(bodyLen, sizeof(char)); memcpy(body, posStartBody, bodyLen); return body; } int get_status_code(const char *msg) { // se afla pozitia de inceput a status code char *posStatusCodeStart = strchr(msg, ' '); ++posStatusCodeStart; // se extrage status code char *statusCode = calloc(STATUS_CODE_LEN + 1, sizeof(char)); memcpy(statusCode, posStatusCodeStart, STATUS_CODE_LEN); int statusCodeInt = atoi(statusCode); free(statusCode); return statusCodeInt; }
Swift
UTF-8
2,419
2.78125
3
[]
no_license
// // AVTableDataSource.swift // AVLighterTableViewController // // Created by Angel Vasa on 31/12/15. // Copyright © 2015 Angel Vasa. All rights reserved. // import UIKit import Foundation protocol AVCellProtocol { func data(items: AnyObject) } class AVTableDataSource: NSObject, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! @IBInspectable var cellHeight: NSNumber! = 44 var cellIdentifier: String = "" var tableViewCellClass : AnyClass! var tableCellNibName : String = "" var delegate : AVCellProtocol? var objects: [AnyObject] = [] var selectedObject: AnyObject -> Void = {_ in } // MARK: Cell Register func registerTableCellClass(tableViewCell: AnyClass, cellIdentifier : String) { self.cellIdentifier = cellIdentifier self.tableViewCellClass = tableViewCell self.tableView!.registerClass(tableViewCell, forCellReuseIdentifier: cellIdentifier) } func registerTableCellNib(tableCellNibName : String, cellIdentifier: String) { self.cellIdentifier = cellIdentifier self.tableCellNibName = tableCellNibName self.tableView!.registerNib(UINib(nibName: tableCellNibName, bundle: nil), forCellReuseIdentifier: cellIdentifier) } // MARK: Set Data func setupData(objects: [AnyObject]!) { self.objects = objects } // MARK: Table Delegate & DataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return self.cellHeight! as CGFloat } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as (UITableViewCell) self.delegate = cell as! AVBaseTableViewCell self.delegate!.data(objects[indexPath.row]) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.selectedObject(self.objects[indexPath.row]) } // MARK: Blocks func selectedObject(selectedObject: AnyObject -> Void) { self.selectedObject = selectedObject } }
Python
UTF-8
478
4.5625
5
[]
no_license
# 8 kyu / Reversed Strings # Details # Complete the solution so that it reverses the string value passed into it. # solution('world') # returns 'dlrow' def solution(strng): result = '' if len(strng) == 0: return result else: for i in range(1, len(strng)): result += strng[-i] result += strng[0] return result print(solution('world')) # OR def solution(strng): return strng[::-1] print(solution('world'))
Python
UTF-8
4,158
3.9375
4
[]
no_license
import pickle from typing import List class Trie(object): # Based on: https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of # -code-a877ea23c1a1 """ Our trie node implementation. Very basic. but does the job """ def __init__(self, char: str): self.char = char self.children: [Trie] = [] # Is it the last character of the word.` self.word_finished = False def merge(self, trie): vals1 = trie.get_all() vals2 = self.get_all() self.add_multiple(words = [x for x in vals1 if not x in vals2]) def intersection(self, trie): vals1 = trie.get_all() vals2 = self.get_all() new_trie = Trie(char = "") new_trie.add_multiple(words = [x for x in vals1 if x in vals2]) return new_trie def add_multiple(self, words: List[str]): for word in words: self.add(word) def save(self, trie_file: str): pickle.dump(obj = self.get_all(), file = trie_file) def load(self, trie_file: str): self.add_multiple(words = pickle.load(trie_file)) def add(self, word: str): root = self def _add(): """ Adding a word in the trie structure """ node = root for char in word: found_in_child = False # Search for the character in the children of the present `node` for child in node.children: if child.char == char: # We found it, increase the counter by 1 to keep track that another # word has it as well # And point the node to the child that contains this char node = child found_in_child = True break # We did not find it so add a new chlid if not found_in_child: new_node = Trie(char) node.children.append(new_node) # And then point node to the new child node = new_node # Everything finished. Mark it as the end of a word. node.word_finished = True return _add() def get_all(self) -> [str]: root = self def __get_all(node, path: [str], acc: [str]): path.append(node.char) if root.word_finished: acc.append("".join(path)) for c in root.children: child: Trie = c for i in __get_all(child, path, acc): acc.append(i) return acc return __get_all(root, path = [], acc = []) def contains(self, prefix: str) -> bool: root = self def _contains(): """ Check and return 1. If the prefix exsists in any of the words we added so far 2. If yes then how may words actually have the prefix """ node = root # If the root node has no children, then return False. # Because it means we are trying to search in an empty trie if not root.children: return False for char in prefix: char_not_found = True # Search through all the children of the present `node` for child in node.children: if child.char == char: # We found the char existing in the child. char_not_found = False # Assign node as the child containing the char and break node = child break # Return False anyway when we did not find a char. if char_not_found: return False # Well, we are here means we have found the prefix. Return true to indicate that # And also the counter of the last node. This indicates how many words have this # prefix return True return _contains()
Java
UTF-8
4,125
1.945313
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.server.integrationtests.drools; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import org.junit.After; import org.junit.BeforeClass; import org.junit.Test; import org.kie.server.api.model.KieContainerResource; import org.kie.server.api.model.Message; import org.kie.server.api.model.ReleaseId; import org.kie.server.api.model.ServiceResponse; import org.kie.server.api.model.Severity; import org.kie.server.integrationtests.shared.KieServerAssert; import org.kie.server.integrationtests.shared.KieServerDeployer; public class CombinedUpdateIntegrationTest extends DroolsKieServerBaseIntegrationTest { private static ClassLoader classLoader = CombinedUpdateIntegrationTest.class.getClassLoader(); private static final ReleaseId kjar1 = new ReleaseId("org.kie.server.testing", "update-kjar", "1.0.0.Final"); private static final ReleaseId kjar101 = new ReleaseId("org.kie.server.testing", "update-kjar", "1.0.1.Final"); private static final ReleaseId kjar102 = new ReleaseId("org.kie.server.testing", "update-kjar", "1.0.2.Final"); private static final String CONTAINER_ID = "container-update"; @BeforeClass public static void deployArtifacts() { String personClassContent = readFile("Person.java"); KieServerDeployer.createAndDeployKJar(kjar1, Collections.singletonMap("src/main/java/org/kie/server/testing/Person.java", personClassContent)); KieServerDeployer.createAndDeployKJar(kjar101, new HashMap<>()); KieServerDeployer.createAndDeployKJar(kjar102, Collections.singletonMap("src/main/java/org/kie/server/testing/Person.java", personClassContent)); } @After public void cleanContainers() { disposeAllContainers(); } @Test public void testMultipleContainerUpdate() throws Exception { KieContainerResource containerResource = new KieContainerResource(CONTAINER_ID, kjar1); ServiceResponse<KieContainerResource> createContainer = client.createContainer(CONTAINER_ID, containerResource); verifyResourceResult(createContainer); ServiceResponse<ReleaseId> updateReleaseId = client.updateReleaseId(CONTAINER_ID, kjar101); KieServerAssert.assertSuccess(updateReleaseId); ServiceResponse<KieContainerResource> containerInfo = client.getContainerInfo(CONTAINER_ID); verifyResourceResult(containerInfo); updateReleaseId = client.updateReleaseId(CONTAINER_ID, kjar102); KieServerAssert.assertSuccess(updateReleaseId); containerInfo = client.getContainerInfo(CONTAINER_ID); verifyResourceResult(containerInfo); } private void verifyResourceResult(ServiceResponse<KieContainerResource> response) { KieServerAssert.assertSuccess(response); assertThat(response.getResult().getMessages()).as("Shound have one message").hasSize(1); Message message = response.getResult().getMessages().get(0); assertThat(message.getSeverity()).as("Message should be of type info").isEqualTo(Severity.INFO); } private static String readFile(String resourceName) { try { URI resourceUri = classLoader.getResources(resourceName).nextElement().toURI(); return new String(Files.readAllBytes(Paths.get(resourceUri))); } catch (Exception e) { throw new RuntimeException(e); } } }
Ruby
UTF-8
246
2.59375
3
[]
no_license
module ApplicationHelper def timestring_to_int(timestring) if timestring.length<1 return 0 end start = Time.parse "00:00:00" duration = Time.parse timestring return (duration - start).to_i end end