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
Java
UTF-8
2,229
2.46875
2
[]
no_license
package com.example.noteproject; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import androidx.annotation.NonNull; public class FirebaseAuthAdapter { private static FirebaseAuthAdapter instace; private Context context; boolean correct = false; private FirebaseAuthAdapter(Context context) { this.context = context; } public static FirebaseAuthAdapter getInstace (Context context) { if(instace == null) instace = new FirebaseAuthAdapter(context); return instace; } public boolean checkAuth () { if(getAuth().getCurrentUser() != null) { return true; } return false; } public boolean login(String email, String password) { getAuth().signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()) { correct = true; }else { Toast.makeText(context, "check your data", Toast.LENGTH_LONG).show(); correct = false; } } }); return correct; } public boolean signUp(String email, String password) { getAuth().createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()) { correct= true; }else { Toast.makeText(context,"check your data", Toast.LENGTH_LONG).show(); correct = false; } } }); return correct; } public void logout () { getAuth().signOut(); } private FirebaseAuth getAuth() { return FirebaseAuth.getInstance(); } }
C
UTF-8
1,327
3.84375
4
[]
no_license
//16进制转10进制 #include<stdio.h> #include<string.h> int convert(char *p) { int n; if(*p >= '0'&&*p <= '9') { n = *p-'0'; p++; } else if (*p =='a'||*p =='A') { n = 10; p++; } else if(*p =='b'||*p =='B') { n = 11; p++; } else if(*p =='c'||*p =='C') { n = 12; p++; } else if(*p =='d'||*p =='D') { n = 13; p++; } else if(*p == 'e'||*p =='E') { n = 14; p++; } else if(*p =='f'||*p =='F') { n = 15; p++; } while(*p) { switch(*p) { case '0':case '1':case '2':case '3':case '4':case '5': case '6':case '7':case '8' :case '9': n = n * 16 + *p - '0'; p++; break; case 'a':case'A': n = n * 16 + 10; p++; break; case 'b':case'B': n = n * 16 + 11; p++; break; case 'c':case'C': n = n * 16 + 12; p++; break; case 'D':case'd': n = n * 16 + 13; p++; break; case 'e':case'E': n = n * 16 + 14; p++; break; case 'f':case'F': n = n * 16 + 15; p++; break; } } return n; } void youhua(char *p) { while(*p) { if(*p == '\n') { *p = '\0'; break; } p++; } return; } int main() { char s[20]; printf("please enter a string s\n"); fgets(s, 20, stdin); youhua(s); puts(s); int ret = convert(s); printf("the number is %d\n", ret); return 0; }
C
UTF-8
27,019
2.71875
3
[]
no_license
// // main.c // homework_NN2 // // Created by 末廣勇祐 on 2020/04/16. // Copyright © 2020 末廣勇祐. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define COUNT_SIZE 20000 void input_data(int *num); //データの入力をする関数 void output_w(int innum, int outnum, int mid_width, int mid_height, double ***w); //重みwを出力する関数 void free_array(int innum, int outnum, int mid_width, int mid_height, double ***w); void free_array_sum(int innum, int outnum, int datanum, int mid_width, int mid_height, double ***w); //多次元配列wを解放する関数 double sigmoid(double s); void fill_v(double ***array, int i, int j, int k, double num); int main(int argc, const char * argv[]) { int innum=0, outnum=0, datanum=0, data2num, mid_height=0, mid_width=0; FILE *fp; int **data, *result; double ***sum_z, ***sum_u; int para1=0, flag=0; int i=0, j=0; double learning=0.01; printf("入力データ数を"); //入力数を入力 input_data(&innum); printf("出力データ数を"); //出力数を入力 input_data(&outnum); printf("教師データ数を"); //教師データ数を入力 input_data(&datanum); printf("未学習データ数を"); //教師データ数を入力 input_data(&data2num); printf("中間層の素子数を"); //中間層の素子数を入力 input_data(&mid_height); printf("中間層の層数を"); //中間層の層数を入力 input_data(&mid_width); printf("一括(1)、逐次(2)を"); //中間層の層数を入力 input_data(&flag); fp=fopen("data.txt","r"); if (fp == NULL) { printf("ファイルがオープンできません\n"); return 0; } data=malloc((datanum+data2num)*sizeof(int *)); //データセット分、領域確保 for (int i=0;i<datanum+data2num;i++) { data[i]=(int *)malloc((innum+1)*sizeof(int *)); //入力数分、領域確保 } result=malloc((datanum+data2num)*sizeof(int *)); //データセット分、領域確保 sum_z=malloc((datanum+data2num)*sizeof(double *)); //データセット分、領域確保 for (int i=0;i<datanum+data2num;i++) { sum_z[i]=malloc((mid_width+1)*sizeof(double *)); //入力数分、領域確保 } for (int i=0;i<datanum+data2num;i++) { for (int j=0;j<mid_width+1;j++) { sum_z[i][j]=malloc((mid_height+1)*sizeof(double *)); //入力数分、領域確保 } } sum_u=malloc((datanum+data2num)*sizeof(double *)); //データセット分、領域確保 for (int i=0;i<datanum+data2num;i++) { sum_u[i]=malloc((mid_width+2)*sizeof(double *)); //入力数分、領域確保 } for (int i=0;i<datanum+data2num;i++) { for (int j=0;j<mid_width+2;j++) { sum_u[i][j]=malloc((mid_height+1)*sizeof(double *)); //入力数分、領域確保 } } double ***mid, ***w, *error; mid=malloc((datanum+data2num)*sizeof(double *)); //中間層、領域確保 for (int i=0;i<datanum+data2num;i++) { mid[i]=malloc((mid_width+2)*sizeof(double *)); //入力数分、領域確保 } for (int i=0;i<datanum+data2num;i++) { for (int j=0;j<mid_width+2;j++) { mid[i][j]=malloc((mid_height+1)*sizeof(double *)); //入力数分、領域確保 } } error=malloc((datanum)*sizeof(double *)); //誤差算数、領域確保 int random=0; srand((int)time(0)); w=malloc((mid_width+1)*sizeof(double *)); //重み、領域確保 w[0]=malloc((innum+1)*sizeof(double *)); //重み、領域確保 for (int i=0;i<innum+1;i++) { w[0][i]=malloc((mid_height+1)*sizeof(double *)); //重み、領域確保 for (int j=0;j<mid_height+1;j++) { //重みwを-1~1の乱数に初期化 w[0][i][j]=(double)rand()/(double)RAND_MAX; random=rand(); if (random % 2 ==0) { w[0][i][j]=-1*w[0][i][j]; } } } for (int k=1;k<mid_width+1;k++) { w[k]=malloc((mid_height+1)*sizeof(double *)); //重み、領域確保 for (int i=0;i<mid_height+1;i++) { w[k][i]=malloc((mid_height+1)*sizeof(double *)); //重み、領域確保 for (int j=0;j<mid_height+1;j++) { //重みwを-1~1の乱数に初期化 w[k][i][j]=(double)rand()/(double)RAND_MAX; random=rand(); if (random % 2 ==0) { w[k][i][j]=-1*w[k][i][j]; } } } } while (fscanf(fp,"%d", &para1)!=EOF) { if (j >= innum+1) { result[i]=para1; i+=1; j=0; } else { if (j==0 ) { data[i][j]=1; j+=1; } data[i][j]=para1; j+=1; } } if (flag==1) { //一括学習 printf("計算中...\n\n"); for (int cnt=0;cnt<COUNT_SIZE;cnt++) { int count=0; double eor=0; //初期化 for (int num=0;num<datanum+data2num;num++) { for (int i=0;i<mid_width+1;i++) { for (int j=0;j<mid_height+1;j++) { sum_z[num][i][j]=0; } } } for (int num=0;num<datanum+data2num;num++) { for (int i=0;i<mid_width+2;i++) { for (int j=0;j<mid_height+1;j++) { sum_u[num][i][j]=0; if (j==0) { if (i<mid_width+1) { mid[num][i][j]=1; } else { mid[num][i][j]=0; } } else { mid[num][i][j]=0; } } } } //順方向伝搬 for (int num=0;num<datanum;num++) { for (int layer=0;layer<mid_width+2;layer++) { if (layer==0) { for (int now=0;now<innum+1;now++) { mid[num][layer][now]=(double)data[num][now]; } for (int now=0;now<innum+1;now++) { for (int next=1;next<mid_height+1;next++) { sum_u[num][layer+1][next]+=mid[num][layer][now]*w[layer][now][next]; } } } else { if (layer < mid_width+1 ) { for (int now=1;now<mid_height+1;now++) { mid[num][layer][now]=sigmoid(sum_u[num][layer][now]); } for (int now=0;now<mid_height+1;now++) { for (int next=1;next<mid_height+1;next++) { sum_u[num][layer+1][next]+=mid[num][layer][now]*w[layer][now][next]; } } } else { mid[num][layer][1]=sigmoid(sum_u[num][layer][1]); eor+=(mid[num][mid_width+1][1]-result[num])*(mid[num][mid_width+1][1]-result[num]); } } } } printf("cnt %d : %lf\n",cnt,eor); for (int num=0;num<datanum;num++) { for (int layer=0;layer<mid_width+2;layer++) { if (eor < 0.001) { count+=1; if (count==datanum) { cnt=COUNT_SIZE; } } //逆伝搬 for (int layer=mid_width+1;layer>0;layer--) { if (layer==mid_width+1) { for (int next=0;next<mid_height+1;next++) { //sum_z[num][layer-1][next]+=(mid[num][layer][1]-result[num])*mid[num][layer][1]*(1-mid[num][layer][1])*w[layer-1][next][1]; sum_z[num][layer-1][next]+=(mid[num][layer][1]-result[num])*mid[num][layer][1]*(1-mid[num][layer][1])*w[layer-1][next][1]; } for (int next=0;next<mid_height+1;next++) { double tmp=0; tmp+=(mid[num][layer][1]-result[num])*mid[num][layer-1][next]*mid[num][layer][1]*(1-mid[num][layer][1]); w[layer-1][next][1]=w[layer-1][next][1]-2*learning*tmp; } } else { if (layer == 1) { for (int now=1;now<mid_height+1;now++) { for (int next=0;next<innum+1;next++) { sum_z[num][layer-1][next]+=sum_z[num][layer][now]*w[layer-1][next][now]*mid[num][layer][now]*(1-mid[num][layer][now]); } } for (int now=1;now<mid_height+1;now++) { for (int next=0;next<innum+1;next++) { double tmp=0; tmp+=sum_z[num][layer][now]*mid[num][layer-1][next]*mid[num][layer][now]*(1-mid[num][layer][now]); w[layer-1][next][now]=w[layer-1][next][now]-learning*tmp; } } } else { for (int now=1;now<mid_height+1;now++) { for (int next=0;next<mid_height+1;next++) { sum_z[num][layer-1][next]+=sum_z[num][layer][now]*w[layer-1][next][now]*mid[num][layer][now]*(1-mid[num][layer][now]); } } for (int now=1;now<mid_height+1;now++) { for (int next=0;next<innum+1;next++) { double tmp=0; tmp+=sum_z[num][layer][now]*mid[num][layer-1][next]*mid[num][layer][now]*(1-mid[num][layer][now]); w[layer-1][next][now]=w[layer-1][next][now]-learning*tmp; } } } } } } } } printf ("計算が終了しました\n\n"); printf("一括学習 結果\n\n"); //初期化 for (int num=0;num<datanum+data2num;num++) { for (int i=0;i<mid_width+1;i++) { for (int j=0;j<mid_height+1;j++) { sum_z[num][i][j]=0; } } } for (int num=0;num<datanum+data2num;num++) { for (int i=0;i<mid_width+2;i++) { for (int j=0;j<mid_height+1;j++) { sum_u[num][i][j]=0; if (j==0) { if (i<mid_width+1) { mid[num][i][j]=1; } else { mid[num][i][j]=0; } } else { mid[num][i][j]=0; } } } } for (int num=0;num<datanum+data2num;num++) { for (int layer=0;layer<mid_width+2;layer++) { if (layer==0) { for (int now=0;now<innum+1;now++) { mid[num][layer][now]=(double)data[num][now]; } for (int now=0;now<innum+1;now++) { for (int next=1;next<mid_height+1;next++) { sum_u[num][layer+1][next]+=mid[num][layer][now]*w[layer][now][next]; } } } else { if (layer < mid_width+1 ) { for (int now=1;now<mid_height+1;now++) { mid[num][layer][now]=sigmoid(sum_u[num][layer][now]); } for (int now=0;now<mid_height+1;now++) { for (int next=1;next<mid_height+1;next++) { sum_u[num][layer+1][next]+=mid[num][layer][now]*w[layer][now][next]; } } } else { mid[num][layer][1]=sigmoid(sum_u[num][layer][1]); if (num < datanum) { printf("教師データ 出力  %d :%lf\n",num+1,mid[num][layer][1]); printf("教師データ データ %d :%d\n\n",num+1,result[num]); } else { printf("未学習データ 出力  %d :%lf\n",num-datanum+1,mid[num][layer][1]); printf("未学習データ データ %d :%d\n\n",num-datanum+1,result[num]); } } } } } } else { //逐次学習 printf("計算中...\n\n"); for (int cnt=0;cnt<COUNT_SIZE;cnt++) { int count=0; double eor=0; //初期化 for (int num=0;num<datanum+data2num;num++) { for (int i=0;i<mid_width+1;i++) { for (int j=0;j<mid_height+1;j++) { sum_z[num][i][j]=0; } } } for (int num=0;num<datanum+data2num;num++) { for (int i=0;i<mid_width+2;i++) { for (int j=0;j<mid_height+1;j++) { sum_u[num][i][j]=0; if (j==0) { if (i<mid_width+1) { mid[num][i][j]=1; } else { mid[num][i][j]=0; } } else { mid[num][i][j]=0; } } } } //順方向伝搬 for (int num=0;num<datanum;num++) { for (int layer=0;layer<mid_width+2;layer++) { if (layer==0) { for (int now=0;now<innum+1;now++) { mid[num][layer][now]=(double)data[num][now]; } for (int now=0;now<innum+1;now++) { for (int next=1;next<mid_height+1;next++) { sum_u[num][layer+1][next]+=mid[num][layer][now]*w[layer][now][next]; } } } else { if (layer < mid_width+1 ) { for (int now=1;now<mid_height+1;now++) { mid[num][layer][now]=sigmoid(sum_u[num][layer][now]); } for (int now=0;now<mid_height+1;now++) { for (int next=1;next<mid_height+1;next++) { sum_u[num][layer+1][next]+=mid[num][layer][now]*w[layer][now][next]; } } } else { mid[num][layer][1]=sigmoid(sum_u[num][layer][1]); eor+=(mid[num][mid_width+1][1]-result[num])*(mid[num][mid_width+1][1]-result[num]); } } } //printf("cnt %d : %lf\n",cnt,eor); for (int layer=0;layer<mid_width+2;layer++) { if (eor < 0.001) { count+=1; } //逆伝搬 for (int layer=mid_width+1;layer>0;layer--) { if (layer==mid_width+1) { for (int next=0;next<mid_height+1;next++) { //sum_z[num][layer-1][next]+=(mid[num][layer][1]-result[num])*mid[num][layer][1]*(1-mid[num][layer][1])*w[layer-1][next][1]; sum_z[num][layer-1][next]+=(mid[num][layer][1]-result[num])*mid[num][layer][1]*(1-mid[num][layer][1])*w[layer-1][next][1]; } for (int next=0;next<mid_height+1;next++) { double tmp=0; tmp+=(mid[num][layer][1]-result[num])*mid[num][layer-1][next]*mid[num][layer][1]*(1-mid[num][layer][1]); w[layer-1][next][1]=w[layer-1][next][1]-2*learning*tmp; } } else { if (layer == 1) { for (int now=1;now<mid_height+1;now++) { for (int next=0;next<innum+1;next++) { sum_z[num][layer-1][next]+=sum_z[num][layer][now]*w[layer-1][next][now]*mid[num][layer][now]*(1-mid[num][layer][now]); } } for (int now=1;now<mid_height+1;now++) { for (int next=0;next<innum+1;next++) { double tmp=0; tmp+=sum_z[num][layer][now]*mid[num][layer-1][next]*mid[num][layer][now]*(1-mid[num][layer][now]); w[layer-1][next][now]=w[layer-1][next][now]-learning*tmp; } } } else { for (int now=1;now<mid_height+1;now++) { for (int next=0;next<mid_height+1;next++) { sum_z[num][layer-1][next]+=sum_z[num][layer][now]*w[layer-1][next][now]*mid[num][layer][now]*(1-mid[num][layer][now]); } } for (int now=1;now<mid_height+1;now++) { for (int next=0;next<innum+1;next++) { double tmp=0; tmp+=sum_z[num][layer][now]*mid[num][layer-1][next]*mid[num][layer][now]*(1-mid[num][layer][now]); w[layer-1][next][now]=w[layer-1][next][now]-learning*tmp; } } } } } } } // printf("cnt %d : %lf\n",cnt,eor); if (count==datanum) { cnt=COUNT_SIZE; } } printf ("計算が終了しました\n\n"); printf("逐次学習 結果\n\n"); //初期化 for (int num=0;num<datanum+data2num;num++) { for (int i=0;i<mid_width+1;i++) { for (int j=0;j<mid_height+1;j++) { sum_z[num][i][j]=0; } } } for (int num=0;num<datanum+data2num;num++) { for (int i=0;i<mid_width+2;i++) { for (int j=0;j<mid_height+1;j++) { sum_u[num][i][j]=0; if (j==0) { if (i<mid_width+1) { mid[num][i][j]=1; } else { mid[num][i][j]=0; } } else { mid[num][i][j]=0; } } } } for (int num=0;num<datanum+data2num;num++) { for (int layer=0;layer<mid_width+2;layer++) { if (layer==0) { for (int now=0;now<innum+1;now++) { mid[num][layer][now]=(double)data[num][now]; } for (int now=0;now<innum+1;now++) { for (int next=1;next<mid_height+1;next++) { sum_u[num][layer+1][next]+=mid[num][layer][now]*w[layer][now][next]; } } } else { if (layer < mid_width+1 ) { for (int now=1;now<mid_height+1;now++) { mid[num][layer][now]=sigmoid(sum_u[num][layer][now]); } for (int now=0;now<mid_height+1;now++) { for (int next=1;next<mid_height+1;next++) { sum_u[num][layer+1][next]+=mid[num][layer][now]*w[layer][now][next]; } } } else { mid[num][layer][1]=sigmoid(sum_u[num][layer][1]); if (num < datanum) { printf("教師データ 出力  %d :%lf\n",num+1,mid[num][layer][1]); printf("教師データ データ %d :%d\n\n",num+1,result[num]); } else { printf("未学習データ 出力  %d :%lf\n",num-datanum+1,mid[num][layer][1]); printf("未学習データ データ %d :%d\n\n",num-datanum+1,result[num]); } } } } } } free_array(innum, outnum, mid_width, mid_height, w); free_array_sum(innum, outnum, datanum, mid_width, mid_height, sum_z); free_array_sum(innum, outnum, datanum+data2num, mid_width, mid_height, mid); free(data); free(result); free(mid); free(w); free(error); free(sum_z); fclose(fp); return 0; } void input_data(int *num) { printf("入力してください:"); scanf("%d",num); } void output_w(int innum, int outnum, int mid_width, int mid_height, double ***w) { for (int k=0;k<mid_width+1;k++) { if (k==0) { for (int i=0;i<innum+1;i++) { for (int j=0;j<mid_height;j++) { printf("%lf ",w[k][i][j]); } printf("\n"); } } else if (k==mid_width) { for (int i=0;i<mid_height;i++) { for (int j=0;j<outnum;j++) { printf("%lf ",w[k][i][j]); } printf("\n"); } } else { for (int i=0;i<mid_height;i++) { for (int j=0;j<mid_height;j++) { printf("%lf ",w[k][i][j]); } printf("\n"); } } printf("\n"); } } void free_array(int innum, int outnum, int mid_width, int mid_height, double ***w) { for (int i=0;i<innum+1;i++) { free(w[0][i]); } free(w[0]); for (int k=1;k<mid_width;k++) { for (int i=0;i<mid_height;i++) { free(w[k][i]); } free(w[k]); } for (int i=0;i<mid_height;i++) { free(w[mid_width][i]); } free(w[mid_width]); } void free_array_sum(int innum, int outnum, int datanum, int mid_width, int mid_height, double ***w) { for (int num=0;num<datanum;num++) { for (int i=0;i<mid_width;i++) { free(w[num][i]); } free(w[num]); } } double sigmoid(double s) { return 1.0/(1.0+exp(-1*s)); } void fill_v(double ***array, int i, int j, int k, double num) { for (int x=0;x<i;x++) { for (int y=0;y<j;y++) { for (int z=0;z<k;z++) { array[x][y][z]=num; } } } }
PHP
UTF-8
590
2.515625
3
[]
no_license
<?php include("../funciones/librerias.php"); extract($_GET); $conexion = conectar(); $sql="SELECT * FROM personal WHERE id = " .$p." "; $result = consultar($conexion,$sql); $row = asociativo($result); echo "<table border='1'> <tr> <th>Firstname:</th> <th>Lastname</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; echo "<tr>"; echo "<td>" . $row['nombre'] . "</td>"; echo "<td>" . $row['apellido'] . "</td>"; echo "<td>" . $row['cargo'] . "</td>"; echo "<td>" . $row['NFicha'] . "</td>"; echo "<td>" . $row['usuario'] . "</td>"; echo "</tr>"; echo "</table>"; ?>
PHP
UTF-8
267
2.625
3
[]
no_license
<?php class View { function __construct() { } function render($carp,$vista){ $file='Views/'.$carp.'/'.$vista.'.php'; if (file_exists($file)) { include_once $file; }else{ echo "404"; } } } ?>
JavaScript
UTF-8
145
3.65625
4
[]
no_license
let fahrenheit = 50 let celsius = (fahrenheit - 32) * 5 / 9 console.log(celsius) let kelvin = (fahrenheit + 459.67) * 5 / 9 console.log(kelvin)
Markdown
UTF-8
1,682
2.546875
3
[]
no_license
##项目运营形式 1.成员自愿参与 2.成员下载代码进行代码修改 (修改方式见 "编写和修改方式” 一节)。 3.成员fork 我的git代码 修改提交后,经审核后合并到主体包中。 4.团队氛围:团队以文字沟通为主,有问题直接提出(写在/doc/...文件夹下)。 5.联系方式:要参加的成员把 S[编号]_微信号_手机号 发给shawn,shawn进行统一整理。 ##工程信息 1.github 地址:https://github.com/shawnxjf1/scalersForum.git -(成员fork后请替换成自己的地址) 2.下载代码 git clone https://github.com/shawnxjf1/scalersForum.git 3.提交代码 git remote add origin https://github.com/shawnxjf1/scalertalk_blog.git git push -u origin master ##工程结构 1.scalers包为主体包. 2.下面两个包以 称呼命令,如xiangzi 提交了代码或者添加了新的模块就放在"xiangzi"包中 pengyong xiangzi 3.全局test包 用来测试基本函数 ##"代码编写和修改需要注意的地方"" 1.文件头 一定要说明python的版本号 2.模块一定要说明该模块的作用 (一个模块只解决某一环节或者某一具体问题) 3.每个函数需要保证测试通过且标明注释,在自己package中保留测试用例 比如在"xiangzi/test.py"中测试 4.在/doc/ 文件夹下以自己文件命名 的文件中写上工作日志,如果内容多建一个文件夹 比如: /doc/xiangzi/疑问问题.md ./工作日志.md ##技术点及其改进的地方 1. 多线程拉取网页(成员量1000多单线程拉太长了) - 正好学习 协程和多线程 2. 拉取折叠区域的数据 3. 采用第三方数据库存储数据
Java
GB18030
6,650
2.875
3
[]
no_license
package jlist; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListDemo extends JPanel implements FocusListener,ListSelectionListener{ private JList list; private DefaultListModel listModel; private static final String hireString="Hire"; private static final String fireString="Fire"; private JButton fireButton; private JTextField employeeName; public ListDemo() { super(new BorderLayout()); listModel = new DefaultListModel(); listModel.addElement("Jane Doe"); listModel.addElement("John smith"); listModel.addElement("Kathy Green"); //create the list and put it in a scroll pane list = new JList(listModel); //ѡб //SINALE_SELECTION SINGLE_INTERVAL_SELECTION MULTIPLE_INTERVAL_SELECTION list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setSelectedIndex(0); list.addListSelectionListener(this); list.setVisibleRowCount(5); JScrollPane pane = new JScrollPane(list); JButton hireBtn = new JButton(hireString); HireListener hireListener = new HireListener(hireBtn); hireBtn.setActionCommand(hireString); hireBtn.addActionListener(hireListener); hireBtn.setEnabled(false); fireButton = new JButton(fireString); fireButton.setActionCommand(fireString); fireButton.addActionListener(new FireListener()); employeeName = new JTextField(10); employeeName.addFocusListener(this); employeeName.addActionListener(hireListener); employeeName.getDocument().addDocumentListener(hireListener); //create a panel that uses boxlayout JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.add(fireButton); buttonPane.add(Box.createHorizontalStrut(5)); buttonPane.add(new JSeparator(SwingConstants.VERTICAL)); buttonPane.add(Box.createHorizontalStrut(5)); buttonPane.add(employeeName); buttonPane.add(hireBtn); buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); add(pane,BorderLayout.CENTER); add(buttonPane,BorderLayout.PAGE_END); } class FireListener implements ActionListener{ @Override //this method can be called only if //there's a valid selection //so go ahead and remove whatever's selected public void actionPerformed(ActionEvent e) { int index = list.getSelectedIndex(); System.out.println(listModel.getSize()); System.out.println(index); listModel.remove(index); System.out.println(listModel.getSize()); int size = listModel.getSize(); if(size==0){//nobody's left ,disable firing fireButton.setEnabled(false); }else {//select an index if(index==listModel.getSize()){ //remove item in last position index--; } list.setSelectedIndex(index); list.ensureIndexIsVisible(index); } } } //this listener is shared by the text field and hire btn class HireListener implements ActionListener,DocumentListener{ private boolean alreadyEnable = false; private JButton btn; public HireListener(JButton btn) { this.btn = btn; } @Override public void insertUpdate(DocumentEvent e) { enableBtn(); } private void enableBtn() { if(!alreadyEnable){ btn.setEnabled(true); } } @Override public void removeUpdate(DocumentEvent e) { handleEmptyTextField(e); } private boolean handleEmptyTextField(DocumentEvent e) { if(e.getDocument().getLength()==0){ btn.setEnabled(false); alreadyEnable=false; return true; } return false; } @Override public void changedUpdate(DocumentEvent e) { if(!alreadyEnable){ btn.setEnabled(true); } } @Override public void actionPerformed(ActionEvent e) { String name = employeeName.getText(); //user didn't type in a unique name if(name.equals("")||alreadyInList(name)){ Toolkit.getDefaultToolkit().beep(); employeeName.requestFocusInWindow();//Ƶı employeeName.selectAll();//ѡȫ return; } int index = list.getSelectedIndex();//get selected index if(index==-1){//no selection,so insert at beginning index=0; }else{ //add after the selected item index++; } listModel.insertElementAt(employeeName.getText(),index); //if we just wanted to add to the end //listmodel.addElement(employeeName.getText()) //reset the text field employeeName.requestFocusInWindow(); employeeName.setText(""); //select the new item and make it visible list.setSelectedIndex(index); list.ensureIndexIsVisible(index); } protected boolean alreadyInList(String name){ return listModel.contains(name); } } @Override public void valueChanged(ListSelectionEvent e) { if(e.getValueIsAdjusting()==false){ if(list.getSelectedIndex()==-1){ fireButton.setEnabled(false); }else{ fireButton.setEnabled(true); } } } private static void createAndShowGUI(){ //create and set up the window JFrame frame = new JFrame("ListDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //create and set up the content pane JComponent content = new ListDemo(); content.setOpaque(true); frame.setContentPane(content); //display the window frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } @Override public void focusGained(FocusEvent e) { JTextField field = (JTextField)e.getSource(); field.setBorder(BorderFactory.createLineBorder(Color.MAGENTA, 2)); } @Override public void focusLost(FocusEvent e) { JTextField field = (JTextField)e.getSource(); field.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2)); } }
Python
UTF-8
1,434
3.265625
3
[]
no_license
#!/usr/bin/env python import rospy from rospy_tutorials.srv import AddTwoInts, AddTwoIntsResponse, AddTwoIntsRequest # Messages used in the node must be imported. rospy.init_node('service_client_node_py',anonymous=True) #initialzing the node with name "service_client_node_py". The second arugument "anonymous" is optional. If anonymous is set to true, then you can run this node in more than one terminal simultanously. rate = rospy.Rate(1) # 1 hz x=0 y=1 element=1 rospy.wait_for_service('add_py') # wait_for_service(service_name) will wait until the serivce node is ready and running. ''' A service client is created in the below line. First argument is the name of the service to be regitered Second argument is the message type of the service ''' add=rospy.ServiceProxy('add_py', AddTwoInts) rospy.loginfo("Fibanocci series element 0: 0") while not rospy.is_shutdown() and element < 81: ''' In the below line, client is requesting for service. The argument order is the same as the order of the fields in the Message, and you must provide a value for all of the fields. In this case rospy_tutorials.srv.AddTwoIntsRequest has two integer fields, hence add(x,y). "resp" will be assigned with the response message. ''' resp = add(x,y) rospy.loginfo("Fibanocci series element %d: %d", element, resp.sum) x=y y=resp.sum element+=1 rate.sleep() # This makes the loop to iterate at 1 Hz i.e., once in 1 sec.
Markdown
UTF-8
9,707
3.09375
3
[]
no_license
#肥皂水的效应:将批评夹在赞美中   美国前总统约翰•卡尔文•柯立芝提出肥皂水效应:**评夹在赞美中**。对他人的批评夹裹在前后肯定的话语之中,减少批评的负面效应,使被批评者愉快地接受对自己的批评。以赞美的形式巧妙地取代批评,以看似间接的方式达到直接的目的。 ## 肥皂水效应的来源   约翰•卡尔文•柯立芝于1923年成为美国总统,他有一位漂亮的女秘书,人虽长得很好,但工作中却常因粗心而出错。一天早晨,柯立芝看见秘书走进办公室,便对她说:“今天你穿的这身衣服真漂亮,正适合你这样漂亮的小姐。”这句话出自柯立芝口中,简直让女秘书受宠若惊。柯立芝接着说:“但也不要骄傲,我相信你同样能把公文处理得像你一样漂亮的。”果然从那天起,女秘书在处理公文时很少出错了。一位朋友知道了这件事后,便问柯立芝:“这个方法很妙,你是怎么想出的?”柯立芝得意洋洋地说:“这很简单,你看见过理发师给人刮胡子吗?他要先给人涂些肥皂水,为什么呀,就是为了刮起来使人不觉痛。” ##运用事例 ###麦金利在一八五六年竞选总统时所采用的方法,就运用了这项原理。   共和党一位重要党员,绞尽脑汁,撰写了一篇演讲稿,他觉得自己写得非常成功。他很高兴的在麦金利面前,先把这篇演讲稿朗诵了一遍——他认为这是他的不朽之作这篇演讲稿虽然有可取之点,但并不尽善尽美,麦金利听后感到并不合适,如果发表出去,可能会引起一场批评的风波。麦金利不愿辜负他的一番热忱,可是,他又不能不说这个「不」字现在,看他如何应付这个场面。   麦金利这样说:“我的朋友,这真是一篇少有见到,精彩绝伦的演讲稿,我相信再也不会有人比你写得更好了。就许多场合来讲,这确实是一篇非常适用的演讲稿,可是,如果在某种特殊的场合,是不是也很适用呢?   从你的立场来讲,那是非常合适、慎重的;可是我必需从党的立场,来考虑这份演讲稿发表所产生的影响。现在你回家去,按照我所特别提出的那几点,再撰写一篇,并送一份给我。”   他果然那样做了,麦金利用蓝笔把他的第二次草稿再加以修改,结果那位党员在那次竞选活动中,成为最有力的助选员。 ###林肯第二封最著名的信件   这里是林肯所写的第二封最著名的信件。一林肯第一封最著名的信件,是写给毕克斯贝夫人的,为她五个儿子牺牲在战场而表示哀悼。一林肯写那封信,可能只花了五分钟时间。可是,那封信在一九二六年公开拍卖时,售价高达一万二千元,这个数目比林肯五十年所能积蓄的钱还多。   这封信,是林肯在一八六三年四月二十六日,内战最黑暗的期间所写的。那时已是第十八个月了——林肯的将领们,带着联军屡遭惨败,一切都只是无用的、愚蠢的人类大屠杀。那时人心惶惶,全国哗然震惊,数以千计的士兵,临阵脱逃,甚至参议院里共和党议员,也起了内讧叛乱。更令人注意的是,他们要强迫林肯离开白宫。   林肯这样说:“我们现在已走到毁灭的边缘——我似乎感觉到上帝也在反对我们,我看不到一丝希望的曙光。”这封信就是在如此黑暗、混乱的时期写出来的。   我摘录出这封信的主要目的,是为了说出林肯如何设法改变一位固执的将领,原因是全国成败的命运,就依赖在这将领的身上。   这该是林肯任职总统后,写信措辞最锐利而不客气的一封信。但你仍可注意到,林肯在指出他严重的错误前,先称赞了这位霍格将军。   是的,那些是他严重的错误,可是林肯并不作那样的措辞。林肯落笔稳健,具有保守和外交的手腕,他是这样写的:“有些事,我对你并不十分满意。”他用机智的手腕,加上外交的词汇。   这里就是写给霍格将军的信:   “我已任命你作包脱麦克军队的司令官,当然,我这样做是根据我所有的充分的理由。可是我希望你也知道,有些事,我对你并不十分满意。我相信你是一个睿智善战的军人,当然,这点是我所感到欣慰的。同时我也相信,你不至于把政治和你的职守,掺混在一起,这方面你是对的。你对你自己有坚强的信心——那是一种有价值、可贵的美德。   你很有野心,那在某种范围内,是有益而无害的。可是在波恩雪特将军带领军队的时候,你放纵你的野心行事,而加以阻挠他。在这一件事上,你对你的国家,对一位极有功勋而光荣的同僚军官,犯下一桩极大的错误。   我曾经听说,并且听得使我相信,你说军队和政府需要一位独裁的领袖。当然,我给你军队指挥权,并非是出于这个原因。同时,我也没有想到那些。   只有战争中获得胜利的将领,才有当独裁者的资格。目前,我对你的期望,是军事上的胜利。到时,我会冒着危险,授予你独裁权。   政府将会尽其所能赞助你,就像赞助其他将领一样。我深恐你灌输于军队和长官,那种不信任上司的思想,会落到你自己的身上,所以我愿意竭力帮助你,平息你这种危险的思想。   军队中如果有这种思想存在,即使是拿破仑还活在这世界上,他能从军队中得到些什么?现在切莫轻率推进,也不要过于匆忙,需要小心谨慎,不眠不休去争取我们的胜利。 ###你想知道这种哲理在日常商业上,对你真的有用吗?   你不是柯立芝,不是麦金利,更不是林肯,你想知道这种哲理在日常商业上,对你真的有用吗?我们现在以费城华克公司卡伍先生为例。卡伍先生就像你我一样普通的人,他是我在费城所举办的一个讲习班里的学员。这是他在讲习班里演讲过的一个故事。   华克公司在费城,承包建筑一座办公大厦,而且指定在某一天必需竣工完成。这项工程,每一件事进行得都非常顺利,眼看这座建筑物就快要完成了。突然,承包外面铜工装饰的商人,说他不能如期交货。什么!整个建筑工事都要停顿下来!不能如期完工,就要交付巨额的罚款!惨重的损失——仅仅是为了那个承包铜工装饰的商人。   长途电话,激烈的争辩,都没有半点用处,于是卡伍被派往纽约,找那个人当面交涉。   卡伍走进这位经理的办公室,第一句话就这样说:“你该知道,你的姓名在勃洛克林市中,是绝无仅有的?”这位经理听到这话,感到惊讶、意外,他摇摇头说:“不,我不知道。”   卡伍说:“今晨我下了火车,查电话簿找你的地址,发现勃洛克林市里,只有你一个人叫这个名字。”   那经理说:“我从来没有注意过。”于是他很感兴趣的把电话簿拿来查看,果然一点也不错,真有这回事。那经理很自傲的说:“是的,这是个不常见到的姓名,我的祖先原籍是荷兰,搬来纽约已有两百年了。”接着就谈论他的祖先和家世的情形。   卡伍见他把这件事谈完了,又找了个话题,赞美他拥有这样一家规模庞大的工厂。卡伍说:“这是我所见过的铜器工厂中最整洁、完善的一家。”   那经理说:“是的,我花去一生的精力经营这家工厂,我很引以为荣,你愿意参观我的工厂吗?”   参观的时候,卡伍连连盛赞这工厂的组织系统,且指出那一方面要比别家工厂优良,同时也赞许几种特殊的机器。这位经理告诉卡伍,那几项机器是他自己发明的。他花了很长的时间,说明这类机器的使用方法,和它的特殊功能。他坚持请卡伍一起午餐!这一点你必需记住,直到现在,卡伍对于他这次的来意还只字未提。   午餐后,那位经理说:“现在,言归正传。当然,我知道你来这里的目的。可是想不到,我们见面后,会谈得这样的愉快。”他脸上带着笑容,接着说:“你可以先回费城,我保证你的定货,会准时运送到你们那里,即使牺牲了别家生意,我也愿意的。”   卡伍并没有任何的要求,可是他的目的都很顺利的达到了。那些材料,全部如期运到,而那座建筑也没有受到任何的影响而如期完成。现在话又说回来如果卡伍当时用了激烈争辩的方法,会不会有这样满意的结果?所以,不使对方难堪、反感,而改变一个人的意志。 ##启示   批评是进步的明灯,因为有批评才有进步。俗语说得好 :人非圣贤,孰能无过 ?圣贤都会有过错,何况我们这些凡人呢 !而有了过错,就得有人来指正,这样才会有进步。有句话 :当局者迷,旁观者清。往往我们做错了事,自己却不知而需借助别人的批评、指正。赞美要看时机,批评要靠技巧。我们不要用恶语中伤他人,劝告他人时,如果能态度诚恳,语出谨慎,那我们将会得到更多的友谊,为我们的人缘加分。
Java
UTF-8
2,775
3.1875
3
[]
no_license
import BreezySwing.*; import java.awt.Font; import javax.swing.*; @SuppressWarnings("serial") public class ItemCompareDialog extends GBDialog{ //class objects private Library lib; private JLabel instructions = addLabel("Click item to compare it",1,1,1,1); private JList<String> itemList = addList(2,1,1,1); private JLabel beforeLabel = addLabel("Items before:",1,2,1,1); private JTextArea itemBeforeArea = addTextArea("",2,2,1,1); private JLabel afterLabel = addLabel("Items after:",1,3,1,1); private JTextArea itemAfterArea = addTextArea("",2,3,1,1); private JLabel equalsLabel = addLabel("Items that equal:",1,4,1,1); private JTextArea itemEqualsArea = addTextArea("",2,4,1,1); private JButton closeButton = addButton("Close",3,4,1,1); private Item selected; //button event listener public void buttonClicked(JButton button) { if(button == closeButton) { dispose(); } } //constructor public ItemCompareDialog(JFrame parent, Library l) { super(parent); lib = l; itemBeforeArea.setEditable(false); itemBeforeArea.setFont(new Font("SansSerif", Font.PLAIN, 14)); itemAfterArea.setEditable(false); itemAfterArea.setFont(new Font("SansSerif", Font.PLAIN, 14)); itemEqualsArea.setEditable(false); itemEqualsArea.setFont(new Font("SansSerif", Font.PLAIN, 14)); populateList(); this.setTitle("Compare Items"); this.setSize(800,500); this.setVisible(true); } //adds items to list private void populateList() { if(lib.getItems().size() == 0)return; for(Item i : lib.getItems()) { addItemToList(i.info()); } } //helper method to add single String to list private void addItemToList(String add) { DefaultListModel<String> model = (DefaultListModel<String>)itemList.getModel(); model.addElement(add); } //list event listeners public void listItemSelected(JList<String> list) { selected = lib.getItem(list.getSelectedIndex()); compare(); } public void listDoubleClicked(JList<String> list, String itemClicked) { selected = lib.getItem(list.getSelectedIndex()); compare(); } //compare items private void compare() { //reset text areas itemBeforeArea.setText(""); itemAfterArea.setText(""); itemEqualsArea.setText(""); for(Item i : lib.getItems()) { //skip same item as selected if(i == selected)continue; int compare; //if type of class does not match skip try { compare = selected.compareTo(i); }catch (ClassCastException e){ continue; } if(compare < 0) { //add to before itemBeforeArea.append(i.print() + "\n\n"); }else if (compare > 0) { //add to after itemAfterArea.append(i.print() + "\n\n"); }else { //same itemEqualsArea.append(i.print() + "\n\n"); } } } }
Java
UTF-8
900
2.90625
3
[]
no_license
package com.mlx.administrator.myapplication; import java.util.Arrays; import java.util.Collections; public class Test { int a=1000,b=600; @org.junit.Test public void main(){ testReverse(); } private void testReverse() { System.out.println(System.currentTimeMillis()); System.out.println(Arrays.toString(tempString)); System.out.println(System.currentTimeMillis()); Collections.reverse(Arrays.asList(tempString)); System.out.println(System.currentTimeMillis()); System.out.println(Arrays.toString(tempString)); System.out.println(System.currentTimeMillis()); } String[] tempString={"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"}; private void swap(int a,int b ){ int temp; temp=a; a=b; b=temp; System.out.println("a:"+a+",b:"+b); } }
Python
UTF-8
2,420
2.9375
3
[]
no_license
#!/usr/bin/python3 ######################################################################################### # Simple server ... almost ######################################################################################### import socket import json import base64 S_IP = "192.168.0.13" S_PORT = 9091 class ServerN1F: def __init__(self, ip, port): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind((ip, port)) server.listen(1) print("[+] Waiting for connections") self.conn, addr = server.accept() print(f"[+] Client connected {str(addr)}") # ################################## MENU print("[+] qq : exit") print("[+] ddw : download file") print("[+] soon... : basic info") print("\n") # ################################## # ##################################################################################### # JSON serialization ... def reliable_send(self, data): json_data = json.dumps(data) print(f"[+] Command: {data} \ttype: {type(data)}") self.conn.sendall(bytes(json_data, encoding="utf-8")) def reliable_recv(self): json_data = self.conn.recv(8000) return json.loads(json_data) # ##################################################################################### def write_file(self, path, content): with open(path, "wb") as file: #content = bytes(content, encoding="utf-8") content = base64.b64decode(content) try: file.write(content) #print(content) except: print("[+] Server ERROR") return f"[+] Download completed." def execute_command(self, command): #print(command[0]) self.reliable_send(command) if command[0] == "qq": self.conn.close() exit() resp = self.reliable_recv() return resp def run_server(self): while True: command = input("$ ") command = command.split(" ") result = self.execute_command(command) if command[0] == "ddw": result = self.write_file(command[1], result) print(result) if __name__ == "__main__": s = ServerN1F(S_IP, S_PORT) s.run_server()
C++
UTF-8
8,101
2.59375
3
[]
no_license
/* _ (_)___ ____ _____ ____ ___ ____ _ / / __ \/ __ `/ __ \/ __ `__ \/ __ `/ / / / / / /_/ / /_/ / / / / / / /_/ / __/ /_/ /_/\__, /\____/_/ /_/ /_/\__,_/ /___/ /____/ */ # include "../include/sound.hpp" # include <iostream> # include <unistd.h> //Foreward declerations void playSFX(sf::Music &buffer); void setSound(sf::Music &buffer, sf::Music &buffer1, sf::Music &buffer2); /* Parameters: void Return: void Synopsis: Sound deconstructor */ Sound::~Sound(){} /* Parameters: void Return: void Synopsis: Sound constructor */ Sound::Sound() :_loop(1) { //Initiates all sounds used in the game LoadSound(this->_ost1, "bomberman_assets/sounds/On the Precipice of Defeat.wav"); LoadSound(this->_loop1, "bomberman_assets/sounds/Devil Eyes.wav"); LoadSound(this->_loop2, "bomberman_assets/sounds/loop2.wav"); LoadSound(this->_loop3, "bomberman_assets/sounds/loop3.wav"); LoadSound(this->_loop4, "bomberman_assets/sounds/loop4.wav"); LoadSound(this->_loop5, "bomberman_assets/sounds/loop5.wav"); LoadSound(this->_loop6, "bomberman_assets/sounds/loop6.wav"); LoadSound(this->_loop7, "bomberman_assets/sounds/loop7.wav"); LoadSound(this->_loop8, "bomberman_assets/sounds/loop8.wav"); LoadSound(this->_loop9, "bomberman_assets/sounds/loop9.wav"); LoadSound(this->_ghost, "bomberman_assets/sounds/ghost.wav"); LoadSound(this->_swipe, "bomberman_assets/sounds/swipe.wav"); LoadSound(this->_bomb, "bomberman_assets/sounds/drop.wav"); LoadSound(this->_fucked, "bomberman_assets/sounds/fucked.wav"); LoadSound(this->_bassdrop, "bomberman_assets/sounds/BombBlast.wav"); LoadSound(this->_bb8_death, "bomberman_assets/sounds/bb8_death.wav"); LoadSound(this->_bb8_sound, "bomberman_assets/sounds/bb8_sound.wav"); LoadSound(this->_bb8_sound1, "bomberman_assets/sounds/bb8_sound1.wav"); LoadSound(this->_bb8_sound2, "bomberman_assets/sounds/bb8_sound2.wav"); LoadSound(this->_bb8_sound3, "bomberman_assets/sounds/bb8_sound3.wav"); LoadSound(this->_bb8_sound4, "bomberman_assets/sounds/bb8_sound4.wav"); LoadSound(this->_bb8_sound5, "bomberman_assets/sounds/bb8_sound5.wav"); } /* Parameters: int sound- A MACRO defining which sound to play Return: void Synopsis: Plays a sound based on the value passed in */ void Sound::playFX(int sound){ switch (sound){ case GHOST: playSFX(this->_ghost); break; case SWIPE: playSFX(this->_swipe); break; case BLAST: playSFX(this->_bomb); break; case BASS: playSFX(this->_bassdrop); break; case BB8_DEATH: playSFX(this->_bb8_death); break; case FUCKED: playSFX(this->_fucked); break; case BB8_MISC: srand (time(NULL)); int randomNumber = (rand() % 6 + 1); if (randomNumber == 1) playSFX(this->_bb8_sound); else if (randomNumber == 2) playSFX(this->_bb8_sound1); else if (randomNumber == 3) playSFX(this->_bb8_sound2); else if (randomNumber == 4) playSFX(this->_bb8_sound3); else if (randomNumber == 5) playSFX(this->_bb8_sound4); else if (randomNumber == 6) playSFX(this->_bb8_sound5); break; } } /* Parameters: int sound- A MACRO defining which sound to play Return: void Synopsis: Plays a sound based on the value passed in */ void Sound::playOST(int sound){ switch (sound){ case PRECIPICE: playSFX(this->_ost1); break; case SWIPE: playSFX(this->_swipe); break; case BLAST: playSFX(this->_bomb); break; case BASS: playSFX(this->_bassdrop); break; } } /* Parameters: void Return: int- Active loop Synopsis: Returns the value of active loop */ int Sound::getLoopValue() const{ return (this->_loop); } /* Parameters: void Return: void Synopsis: Incrementes the value of the current loop playing the next loop */ void Sound::nextLoop(){ this->_loop++; playloop(); } /* Parameters: void Return: void Synopsis: Decrementes the value of the current loop playing the previous loop */ void Sound::prevLoop(){ if(this->_loop > 1){ this->_loop--; playloop(); } } /* Parameters: void Return: void Synopsis: Plays the current loop and pauses the niebouring loops */ void Sound::playloop(){ switch (this->_loop) { case 1: setSound(this->_loop1, this->_loop2, this->_loop9); break; case 2: setSound(this->_loop2, this->_loop1, this->_loop3); break; case 3: setSound(this->_loop3, this->_loop2, this->_loop4); break; case 4: setSound(this->_loop4, this->_loop3, this->_loop5); break; case 5: setSound(this->_loop5, this->_loop4, this->_loop6); break; case 6: setSound(this->_loop6, this->_loop5, this->_loop7); break; case 7: setSound(this->_loop7, this->_loop6, this->_loop8); break; case 8: setSound(this->_loop8, this->_loop7, this->_loop9); break; case 9: setSound(this->_loop9, this->_loop8, this->_loop1); break; default: setSound(this->_loop1, this->_loop1, this->_loop9); break; } } /* Parameters: sf::Music &buffer- Buffer to load sound into std::string filepath- Path to the sound file to load Return: void Synopsis: Loads sound into buffer. Prints error message on failure */ void Sound::LoadSound(sf::Music &buffer, std::string filepath){ if(!buffer.openFromFile(filepath)) std::cout << RED << "error: \n" << "Could not open " << filepath << '\n'; } /* Parameters: std::string type- Sound type float level- Sound level Return: void Synopsis: Sets the volume level of various sounds */ void Sound::setVolumeLevel(std::string type, float level){ if (type == "LOOP"){ this->_loop1.setVolume(this->getVolumeLevel("LOOP") + level); this->_loop2.setVolume(this->getVolumeLevel("LOOP") + level); this->_loop3.setVolume(this->getVolumeLevel("LOOP") + level); this->_loop4.setVolume(this->getVolumeLevel("LOOP") + level); this->_loop5.setVolume(this->getVolumeLevel("LOOP") + level); this->_loop6.setVolume(this->getVolumeLevel("LOOP") + level); this->_loop7.setVolume(this->getVolumeLevel("LOOP") + level); this->_loop8.setVolume(this->getVolumeLevel("LOOP") + level); this->_loop9.setVolume(this->getVolumeLevel("LOOP") + level); this->_ost1.setVolume(this->getVolumeLevel("LOOP") + level); } if (type == "SFX"){ this->_bomb.setVolume(this->getVolumeLevel("SFX") + level); this->_swipe.setVolume(this->getVolumeLevel("SFX") + level); this->_ghost.setVolume(this->getVolumeLevel("SFX") + level); this->_oneup.setVolume(this->getVolumeLevel("SFX") + level); this->_death.setVolume(this->getVolumeLevel("SFX") + level); this->_bassdrop.setVolume(this->getVolumeLevel("SFX") + level); this->_bb8_death.setVolume(this->getVolumeLevel("SFX") + level); this->_bb8_sound.setVolume(this->getVolumeLevel("SFX") + level); this->_bb8_sound1.setVolume(this->getVolumeLevel("SFX") + level); this->_bb8_sound2.setVolume(this->getVolumeLevel("SFX") + level); this->_bb8_sound3.setVolume(this->getVolumeLevel("SFX") + level); this->_bb8_sound4.setVolume(this->getVolumeLevel("SFX") + level); this->_bb8_sound5.setVolume(this->getVolumeLevel("SFX") + level); } else return; } /* Parameters: std::string type- Sound type Return: float- Current sound level of the defined sound type, or -1.0f on failure Synopsis: Returns the sound level of the defined sound type */ float Sound::getVolumeLevel(std::string type){ if (type == "LOOP") return(this->_loop1.getVolume()); if (type == "SFX") return(this->_bomb.getVolume()); else return (-1.0f); } /* Parameters: sf::Music &buffer- Sound buffer Return: void Synopsis: Plays the sound buffer passed in */ void playSFX(sf::Music &buffer){ buffer.stop(); buffer.play(); } /* Parameters: sf::Music &buffer- Current sound buffer sf::Music &buffer1- Neibouring sound buffer sf::Music &buffer2- Neibouring sound buffer Return: void Synopsis: Plays current sound buffer in a loop and stops the neibouring sound buffers */ void setSound(sf::Music &buffer, sf::Music &buffer1, sf::Music &buffer2){ buffer.stop(); buffer1.stop(); buffer2.stop(); buffer.setLoop(true); buffer.play(); }
C#
UTF-8
1,829
3.125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using WindowsFormsApp1.Classes; namespace WindowsFormsApp1.Classes { class Validation { //Allows only postive digits for a textbox public void OnlyDigit(KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } } //Allows only digits and - symbol for a textbox public void OnlyDigitWithNegatives(object sender,KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '-')) { e.Handled = true; } // only allow one decimal point if ((e.KeyChar == '-') && ((sender as TextBox).Text.IndexOf('-') > -1)) { e.Handled = true; } } //If the textbox text is null will set to a value public void SetNullTo(object sender) { if ((sender as TextBox).Text == "") { (sender as TextBox).Text = "0"; } } public void SetNullTo(object sender, string setTo) { if ((sender as TextBox).Text == "") { (sender as TextBox).Text = setTo; } } //checks if the label has teh same text and if not will change it to the new text public void CheckIfSame(object label, string newText) { if((label as Label).Text != newText) { (label as Label).Text = newText; } } } }
C
UTF-8
103
2.734375
3
[]
no_license
#include<stdio.h> int main() { int no; scanf("%d",&no); (no%7==0)?printf("yes"):printf("no"); }
Swift
UTF-8
2,339
2.75
3
[]
no_license
// // LabelTableViewCell.swift // IssueTracker // // Created by 임승혁 on 2020/06/11. // Copyright © 2020 Cloud. All rights reserved. // import UIKit final class LabelTableViewCell: UITableViewCell { // MARK: - Properties static let identifier: String = "LabelTableViewCell" private var label: BadgeLabel! private var labelDescription: UILabel! // MARK: - LifeCycle override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) configure() makeConstraints() } required init?(coder: NSCoder) { super.init(coder: coder) configure() makeConstraints() } // MARK: - Methods func apply(title: String, description: String?, backgroundColor: UIColor?) { label.text = title label.backgroundColor = backgroundColor labelDescription.text = description } // MARK: Configure private func configure() { selectionStyle = .none accessoryType = .disclosureIndicator configureLabel() configureLabelDescription() } private func configureLabel() { label = BadgeLabel(font: .boldSystemFont(ofSize: 13), textColor: .black) label .setContentHuggingPriority(.required, for: .vertical) addSubview(label) } private func configureLabelDescription() { labelDescription = UILabel(font: .systemFont(ofSize: 17), textColor: .systemGray) addSubview(labelDescription) } // MARK: Constraints private func makeConstraints() { makeConstraintsLabel() makeConstraintsLabelDescription() } private func makeConstraintsLabel() { label.snp.makeConstraints { make in make.top.equalToSuperview().offset(12) make.leading.equalToSuperview().offset(24) } } private func makeConstraintsLabelDescription() { labelDescription.snp.makeConstraints { make in make.top.equalTo(label.snp.bottom).offset(8) make.leading.equalTo(label.snp.leading) make.bottom.equalToSuperview().inset(8) } } }
Python
UTF-8
4,400
4.53125
5
[]
no_license
# 04_type3.py ''' 5. 딕셔너리(Dictionary) 사전!! 형태 : {key1:value1, key2:value2, ...} > key와 value는 한 쌍 key = 단어, value = 뜻 - 문자열 포매팅 함수(format)에서 {키워드} 사용했었음 "{name}".format(name="한수창") 이와 비슷한 느낌! - 요소가 여러 개 나열된 자료형이긴 한데... 문자열,리스트,튜플은 '순서'가 있어서 인덱스로 인덱싱 딕셔너리는 '순서'가 없고, 'key'를 가지고 인덱싱한다. - 주의사항 1. key 값은 중복되면 안 된다. 2. key 값으로는 리스트,딕셔너리를 사용할 수 없다. > key : 변하지 않는 성질의 자료(값) - 숫자,문자,튜플 > value : 아무거나 상관 없음 ''' print("[딕셔너리 만들기]") my_dict = {"축구":"Soccer", 2002:"한일", (1,2):("원","투"), "16강":[2002,2010]} ''' key value ------------------ "축구" "Soccer" 문자열:문자열 2002 "한일" 정수:문자열 (1,2) ("원","투") 튜플:튜플 "16강" [2002,2010] 문자열:리스트 ''' print( my_dict ) print( my_dict["축구"] ) # key를 통해서 value 값을 얻어낸다. # 문자열,리스트,튜플에서 인덱싱할 때 사용했던 index 값들은, 딕셔너리에서는 key와 같다. # 하나 하나의 요소들은, 딕셔너리에서는 value와 같다. a = ["Soccer"] print( a[0] ) # 인덱스(key)를 가지고 "Soccer" (value)를 얻어낸다. print( my_dict["16강"][1] ) # 2010 출력! # key가 "16강"인 요소의 value가 '리스트' [2002,2010] 이다. 여기서 두번째 요소 인덱싱! print("딕셔너리 요소 추가/삭제") my_dict[2018] = "F조-3위" print(my_dict) del( my_dict[(1,2)] ) # key가 튜플 - 하나의 요소가 통째로 제거! print(my_dict) print() # 관리자에 관련된 항목들을 key:value 형태로 admin_dict = { "id":"admin", "pw":"1234", "name":"관리자" } print("관리자 id : " + admin_dict["id"]) print("관리자 pw : " + admin_dict["pw"]) print("관리자 name : " + admin_dict["name"]) print() ''' 6. 집합(Set) - 수학에서의 집합을 의미 > 교집합, 합집합, 차집합 등을 구할 수 있다. - 중복된 값을 허용하지 않는다. > 중복 제거 용도 사용 - 순서가 없다. (인덱싱 불가능) ''' my_set = {1,2,3,1,1,1,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,1,1,2} print( my_set ) my_set2 = {1,1,2,2,"안녕","안녕","ㅋㅋ","ㅋㅋ"} print( my_set2 ) my_str = "Hello" my_set = set(my_str) # 문자열 -> 집합(set) 변환 print(my_set) my_int = 112233 # int는 정수 (integer) #my_set = set(my_int) # 오류! 숫자(정수+실수 등)는 유일한 하나의 값 #print( my_int[0] ) # 오류! > 인덱싱 같은 행위 하지 못함 # 자료형끼리의 변환은 서로 비슷한 성질의 자료끼리 가능 my_list = [1,2,3,1,1,1,1,1,2,1,1,1,3,1,1,2,3,1,2,1,1,1,1,2] print( my_list ) # 리스트의 중복된 값을 쉽게 제거하고 싶다면! my_set = set(my_list) # list -> set my_list = list(my_set) # set -> list print( my_list ) ''' int() --> 정수로 변환 float() --> 실수로 변환 > bin(), oct(), hex() -> 2,8,16진수 변환 str() ---> 문자열 list() tuple() dict() set() bool() ''' ''' 7. bool - (참고) Java에선 boolean 자료형, C언어에는 없다. - 참(True)과 거짓(False)을 표현하는 자료형 - 자료형의 값에 따른 참과 거짓 값 True/False ------------------- 1 True 0 False "11" True "" False [1,2] True [] False () False None False (함수 진도 나갈 때 자주 볼 예정) ------------------- 거짓인 경우는 1. 요소가 없다. (문자열, 리스트 등) 2. 숫자가 0이다. (0만 아니면 참) 3. None : 값이 없다는걸 의미하는 '자료형/값' ''' print() print( bool(1) ) # 이때 출력되는 True는 문자열이 아니라 bool 자료형의 '값' print( bool(0) ) # False(거짓)도 마찬가지
Java
UTF-8
719
2.515625
3
[]
no_license
package com.gdkm.converter; import com.gdkm.dto.CourseCommentDto; import com.gdkm.model.CourseComment; import org.springframework.beans.BeanUtils; import java.util.List; import java.util.stream.Collectors; public class CourseToCourseDotConverter { public static CourseCommentDto convert(CourseComment courseComment) { CourseCommentDto courseCommentDto = new CourseCommentDto(); BeanUtils.copyProperties(courseComment, courseCommentDto); return courseCommentDto; } public static List<CourseCommentDto> convert(List<CourseComment> courseCommentList) { return courseCommentList.stream().map(e -> convert(e) ).collect(Collectors.toList()); } }
C#
UTF-8
798
2.734375
3
[]
no_license
using System.Diagnostics; namespace TraceHogger { class Program { static void Main(string[] args) { const int repeats = 3; for (var i = 0; i < repeats; i++) { var witcher = new Stopwatch(); witcher.Start(); witcher.Stop(); Debug.WriteLine("## BOX - NEW time: " + witcher.ElapsedMilliseconds); witcher.Reset(); } for (var i = 0; i < repeats; i++) { var witcher = new Stopwatch(); witcher.Start(); witcher.Stop(); Debug.WriteLine("## BOX - OLD time: " + witcher.ElapsedMilliseconds); witcher.Reset(); } } } }
Markdown
UTF-8
2,642
2.515625
3
[]
no_license
# Markdown文件 http://markdown.tw/#img < span style="color:red;"> 這裡是紅色… < /span> This is [an example](http://example.com/ "Title") inline link. ------ I get 10 times more traffic from [Google] [1] than from [Yahoo] [2] or [MSN] [3]. [1]: http://google.com/ "Google" [2]: http://search.yahoo.com/ "Yahoo Search" [3]: http://search.msn.com/ "MSN Search" ------ <address@example.com> *single asterisks* _single underscores_ **double asterisks** __double underscores__ # 高中職生資安研習營 > * MyFirstLinux+CTF:FromLinux2CTF(3~4小時) > * MyFirstWebSecurity:網站安全初體驗(3小時) > * MyFirstNetworSecurity:network Forensics 網路鑑識(3小時) > * MyFirstCryptanalysis:Crypto破密分析(3小時) > * MyFirstPenetration:Windows滲透測試(3小時) > * MyFirstLinuxPenetration:Linux滲透測試(3小時) # MyFirstSummerCamp::my valentine summer > * MyFirstReversing:逆向工程研習營(2天) > * MyFirstWindowsReversing:Windows逆向工程研習營(2天) > * MyFirstPwn:漏洞攻擊研習營(2天) > 請保留此份 Cmd Markdown 的歡迎稿兼使用說明,如需撰寫新稿件,點擊頂部工具列右側的 <i class="icon-file"></i> **新文稿** 或者使用快速鍵 ‘Ctrl+Alt+N’。 分割不同的段落,**粗体** 或者 *斜体* 某些文字,更棒的是,它还可以 - [ ] 支持以 PDF 格式导出文稿 - [ ] 改进 Cmd 渲染算法,使用局部渲染技术提高渲染效率 - [x] 新增 Todo 列表功能 - [x] 修复 LaTex 公式渲染问题 - [x] 新增 LaTex 公式编号功能 > * 整理知識,學習筆記 > * 發佈日記,雜文,所見所想 > * 撰寫發佈技術文稿(代碼支援) > * 撰寫發佈學術論文(LaTeX 公式支持) 工具列上的五個圖示依次為: <i class="icon-list"></i> 目錄:快速導航當前文稿的目錄結構以跳轉到感興趣的段落 <i class="icon-chevron-sign-left"></i> 視圖:互換左邊編輯區和右邊預覽區的位置 <i class="icon-adjust"></i> 主題:內置了黑白兩種模式的主題,試試 **黑色主題**,超炫! <i class="icon-desktop"></i> 閱讀:心無旁騖的閱讀模式提供超一流的閱讀體驗 <i class="icon-fullscreen"></i> 全屏:簡潔,簡潔,再簡潔,一個完全沉浸式的寫作和閱讀環境 ![cmd-markdown-logo](https://www.zybuluo.com/static/img/logo.png) https://www.zybuluo.com/mdeditor ### 2. 书写一个质能守恒公式[^LaTeX] $$E=mc^2$$ ### 3. 高亮一段代码[^code] ```python @requires_authorization class SomeClass: pass if __name__ == '__main__': # A comment print 'hello world'
Java
UTF-8
5,802
2.96875
3
[]
no_license
package cn.zz.NIO.compareBuffer; import java.io.*; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.Date; public class TestIONIO { public static void main(String[] args) throws IOException { File file = new File("F:\\testIO\\1.mp4"); //3929685000 /*long fileLength1 = readByFis(file); System.out.println(fileLength1);*/ /*long fileLength2 = readByBos(file); System.out.println(fileLength2);*/ /*long fileLength3 = readByChannel(file); System.out.println(fileLength3);*/ /*long fileLength4 = readByDirectChannel(file); System.out.println(fileLength4);*/ /*long fileLength5 = readByAssChannel(file); System.out.println(fileLength5);*/ long fileLength6 = readByMapChannel(file); System.out.println(fileLength6); } // IO 字节io private static long readByFis(File file) throws FileNotFoundException, IOException { //读取3G文件在 4m内存下耗时4.5s // 8m内存 2.9s Date date1 = new Date(); long start = date1.getTime(); System.out.println(start); InputStream is = new FileInputStream(file); byte[] buff = new byte[4096]; long counts = 0; int offset = 0; while ((offset = is.read(buff)) != -1) { counts = counts + offset; } is.close(); Date date2 = new Date(); long stop = date2.getTime(); System.out.println(stop); System.out.println(stop-start); return counts; } // IO 字节缓冲io private static long readByBos(File file) throws FileNotFoundException, IOException { //BufferedInputStream 字符处理流,自带缓冲区 // 增大字节数组 4M - 8M 性能提升不大, 3s - 2.9s Date date1 = new Date(); long start = date1.getTime(); System.out.println(start); long counts = 0; int offset = 0; BufferedInputStream bos = new BufferedInputStream(new FileInputStream(file)); byte[] buff = new byte[4096]; while((offset= bos.read(buff)) != -1) { counts = counts + offset; } bos.close(); Date date2 = new Date(); long stop = date2.getTime(); System.out.println(stop); System.out.println(stop-start); return counts; } private static long readByChannel(File file) throws FileNotFoundException, IOException { //不使用直接内存,和fileInputStream差不多 Date date1 = new Date(); long start = date1.getTime(); System.out.println(start); long counts = 0; FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bbuf = ByteBuffer.allocate(8192); int offset = 0; while((offset = fc.read(bbuf)) != -1) { counts = counts + offset; bbuf.clear(); } fc.close(); fis.close(); Date date2 = new Date(); long stop = date2.getTime(); System.out.println(stop); System.out.println(stop-start); return counts; } private static long readByDirectChannel(File file) throws FileNotFoundException, IOException { //使用直接内存,和fileInputStream差不多 //4m提升0.2s,8m提升0.5s Date date1 = new Date(); long start = date1.getTime(); System.out.println(start); long counts = 0; FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bbuf = ByteBuffer.allocateDirect(8192); int offset = 0; while((offset = fc.read(bbuf)) != -1) { counts = counts + offset; bbuf.clear(); } fc.close(); fis.close(); Date date2 = new Date(); long stop = date2.getTime(); System.out.println(stop); System.out.println(stop-start); return counts; } private static long readByAssChannel(File file) throws FileNotFoundException, IOException { //和 NIO fileInputStream差不多 Date date1 = new Date(); long start = date1.getTime(); System.out.println(start); long counts = 0; RandomAccessFile fis = new RandomAccessFile(file,"r"); FileChannel fc = fis.getChannel(); ByteBuffer bbuf = ByteBuffer.allocateDirect(8192); int offset = 0; while((offset = fc.read(bbuf)) != -1) { counts = counts + offset; bbuf.clear(); } fc.close(); fis.close(); Date date2 = new Date(); long stop = date2.getTime(); System.out.println(stop); System.out.println(stop-start); return counts; } private static long readByMapChannel(File file) throws FileNotFoundException, IOException { //使用直接内存,和fileInputStream差不多 //4m提升0.2s,8m提升0.5s Date date1 = new Date(); long start = date1.getTime(); System.out.println(start); long counts = 0; FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bbuf = ByteBuffer.allocateDirect(4096); fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); int offset = 0; while((offset = fc.read(bbuf)) != -1) { counts = counts + offset; bbuf.clear(); } fc.close(); fis.close(); Date date2 = new Date(); long stop = date2.getTime(); System.out.println(stop); System.out.println(stop-start); return counts; } }
C++
UTF-8
1,599
2.625
3
[]
no_license
#include "Missile.hpp" Missile::Missile(int x, int y, int speed, std::string pattern, e_type type) : AGameEntity(x, y, speed, type) { std::string *tsprite = new std::string[1]; tsprite[0] = "+=-"; this->_pattern.set(pattern); this->_moveCtrl = MoveController(this->_pos, this->_pattern); this->_hb.setWidth(0); this->_hb.setHeight(0); this->_sp.set(tsprite, 1); return ; } Missile::Missile(Position pos, int speed, std::string pattern, e_type type) : AGameEntity(pos.getX(), pos.getY(), speed, type) { std::string *tsprite = new std::string[1]; tsprite[0] = "+=-"; this->_pattern.set(pattern); this->_moveCtrl = MoveController(this->_pos, this->_pattern); this->_hb.setWidth(0); this->_hb.setHeight(0); this->_sp.set(tsprite, 1); return ; } Missile::Missile(Missile const & src) : AGameEntity(src) { *this = src; return ; } Missile::~Missile( void ) { } Missile & Missile::operator=(Missile const & rhs) { this->AGameEntity::operator=(rhs); this->_moveCtrl = rhs._moveCtrl; return (*this); } void Missile::refresh(void) { if (this->_speed == 0) { DisplaySprite::erase(this->_sp, this->_pos, AGameEntity::_window); this->_moveCtrl.move(); this->_checkOutOfBound(); this->_speed = this->_maxspeed; DisplaySprite::display(this->_sp, this->_pos, 6,AGameEntity::_window); } else this->_speed--; } void Missile::_checkOutOfBound() { if (this->_pos.getX() <= -3 || this->_pos.getX() >= AGameEntity::_winX) this->_dead = true; } void Missile::destroy(void) { } Pattern const & Missile::getPattern( void ) const { return (this->_pattern); }
Java
UTF-8
1,515
3.140625
3
[ "MIT" ]
permissive
package de.m_bleil.javafx.layout; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.*; import javafx.stage.Stage; public class StackAndFlowPaneDemo extends Application { @Override public void start(Stage primaryStage) { StackPane defaultStackPane = new StackPane( new Label("default StackPane\nlayout set with \n#relocate and #setPrefSize")); defaultStackPane.relocate(10, 10); defaultStackPane.setPrefSize(200, 120); defaultStackPane.setStyle("-fx-background-color: blanchedalmond"); FlowPane defaultFlowPane = new FlowPane( new Label("default FlowPane\nlayout set with \n#relocate and #setPrefSize")); defaultFlowPane.relocate(10, 140); defaultFlowPane.setPrefSize(200, 120); defaultFlowPane.setStyle("-fx-background-color: blanchedalmond"); FlowPane flowPaneWithComputedSize = new FlowPane(new Label("FlowPane with prefSize = USE_COMPUTED_SIZE")); flowPaneWithComputedSize.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE); flowPaneWithComputedSize.relocate(10, 280); // flowPaneWithComputedSize.setPrefSize(200, 120); flowPaneWithComputedSize.setStyle("-fx-background-color: blanchedalmond"); Pane root = new Pane(); root.getChildren().addAll(defaultStackPane, defaultFlowPane, flowPaneWithComputedSize); Scene scene = new Scene(root, 800, 600); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
C++
UTF-8
3,203
2.5625
3
[]
no_license
#include "modeling_model.h" #include "modeling_object.h" #include "serial.h" #include "platform.h" #include <stdlib.h> #include <stdio.h> #include <assert.h> Serial file = serial_make((char *)malloc(10000), 10000); static void _serialize_former(Former *former) { serial_write_f32(&file, &former->x, 1); /* former position */ Curve *curves = former->shape.curves; for (int k = 0; k < SHAPE_CURVES; ++k) { /* curves */ serial_write_f64(&file, &curves[k].x, 1); serial_write_f64(&file, &curves[k].y, 1); serial_write_f64(&file, &curves[k].w, 1); } } static void _deserialize_former(Former *former) { serial_read_f32(&file, &former->x, 1); /* former position */ Curve *curves = former->shape.curves; for (int k = 0; k < SHAPE_CURVES; ++k) { /* curves */ serial_read_f64(&file, &curves[k].x, 1); serial_read_f64(&file, &curves[k].y, 1); serial_read_f64(&file, &curves[k].w, 1); } shape_update_curve_control_points(curves); } void model_serial_dump(Model *model, const char *path) { serial_clear(&file); /* objects */ serial_write_i32(&file, &model->objects_count, 1); for (int i = 0; i < model->objects_count; ++i) { Object *o = model->objects[i]; /* object position */ serial_write_f32(&file, o->p.v, 3); /* collision formers */ serial_write_i32(&file, &o->def.formers_count, 1); for (int j = 0; j < o->def.formers_count; ++j) _serialize_former(o->def.formers + j); /* skin formers */ _serialize_former(&o->def.t_skin_former); _serialize_former(&o->def.n_skin_former); serial_write_f32(&file, &o->def.t_endp_dx, 1); serial_write_f32(&file, &o->def.n_endp_dx, 1); } serial_write_to_file(&file, path); } void model_serial_load(Model *model, const char *path) { model_clear(model); serial_read_from_file(&file, path); /* objects */ int objects_count; serial_read_i32(&file, &objects_count, 1); for (int i = 0; i < objects_count; ++i) { Object *o = new Object(); model_add_object(model, o); /* object position */ serial_read_f32(&file, o->p.v, 3); /* collision formers */ serial_read_i32(&file, &o->def.formers_count, 1); for (int j = 0; j < o->def.formers_count; ++j) _deserialize_former(o->def.formers + j); /* skin formers */ _deserialize_former(&o->def.t_skin_former); _deserialize_former(&o->def.n_skin_former); serial_read_f32(&file, &o->def.t_endp_dx, 1); serial_read_f32(&file, &o->def.n_endp_dx, 1); object_finish(o); } } void model_serial_dump_mesh(Model *model, const char *path) { FILE *file = (FILE *)platform_fopen(path, "w"); /* vertices */ for (int i = 0; i < model->skin_verts_count; ++i) fprintf(file, "%g %g %g\n", model->skin_verts[i].x, model->skin_verts[i].y, model->skin_verts[i].z); /* panels */ for (int i = 0; i < model->panels_count; ++i) fprintf(file, "%d %d %d %d\n", model->panels[i].v1, model->panels[i].v2, model->panels[i].v3, model->panels[i].v4); fclose(file); }
Java
UTF-8
3,824
2.03125
2
[]
no_license
package com.galinc.hardtraining2.ui; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import android.os.Bundle; import android.view.MenuItem; import com.galinc.hardtraining2.R; import com.google.android.material.navigation.NavigationView; public class MainActivity extends AppCompatActivity {//implements NavigationView.OnNavigationItemSelectedListener{ private NavController navController; private DrawerLayout mDrawer; private Toolbar toolbar; private AppBarConfiguration mAppBarConfiguration; @Override public boolean onSupportNavigateUp() { NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); //navController.getCurrentDestination(). if (navController.popBackStack(R.id.newTrainingEditExFragment,true)){ navController.navigate(R.id.nav_document); } return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp(); } @Override public void onBackPressed() { super.onBackPressed(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); NavigationView navigationView = findViewById(R.id.navigation); // navigationView.setNavigationItemSelectedListener(this); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); mDrawer = findViewById(R.id.drawer_layout); //drawerToggle = setupDrawerToggle(); // mDrawer.addDrawerListener(setupDrawerToggle()); mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_document, R.id.nav_setting).setDrawerLayout(mDrawer).build(); navController = Navigation.findNavController(this, R.id.nav_host_fragment); // mAppBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).setDrawerLayout(mDrawer).build(); NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration); NavigationUI.setupWithNavController(navigationView, navController); } public NavController getNavController() { return navController; } // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { // int id = menuItem.getItemId(); //// //// if (id == R.id.nav_document) { //// navController.navigate(R.id.trainingListFragment); //// } else if (id == R.id.nav_setting) { //// navController.navigate(R.id.downloadFragment); //// } // // DrawerLayout drawer = findViewById(R.id.drawer_layout); // drawer.closeDrawer(GravityCompat.START); // return true; // // } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } private ActionBarDrawerToggle setupDrawerToggle() { // Примечание: Убедитесь, что вы передаёте допустимую ссылку // на toolbar // ActionBarDrawToggle() не предусматривает в ней // необходимости и не будет отображать иконку гамбургера без // неё return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close); } }
PHP
UTF-8
1,946
2.640625
3
[]
no_license
<?php namespace app\models; use Yii; /** * This is the model class for table "themes". * * @property int $id * @property int|null $parental_id * @property string|null $title * @property string|null $info * * @property Themesbulletins[] $themesbulletins */ class ThemesRecord extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'themes'; } /** * {@inheritdoc} */ public function rules() { return [ [['parental_id'], 'integer'], [['info'], 'string'], [['title'], 'string', 'max' => 255], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'parental_id' => 'Parental ID', 'title' => 'Title', 'info' => 'Info', ]; } /** * @return \yii\db\ActiveQuery */ public function getThemesbulletins() { return $this->hasMany(ThemesbulletinsRecord::className(), ['themes_id' => 'id']); } public function getThemesBullCount() { //return $this->getThemesbulletins()->count(); return count($this->getBullCurrTheme()); } public function getBullCurrTheme() { $bull=array(); $themesbulletins= $this->themesbulletins; foreach ($themesbulletins as $tb) if($tb->bulletins->status=='public') array_push($bull, $tb->bulletins); return $bull; } public function setDeleteThemesBullRecord() { $themesbulletins= $this->themesbulletins; foreach ($themesbulletins as $thb) $thb->delete(); } public function setNewRecord($form){ $this->title= $form->title; $this->info= $form->info; if($form->parental_id>0) $this->parental_id= $form->parental_id; } }
Java
UTF-8
572
2.296875
2
[]
no_license
package com.linkwee.web.enums; /** * * @描述:投资者新手任务 * * */ public enum InvestorNewcomerTaskEnum { INVESTOR_INVITE_CUSTOMER("INVESTOR_INVITE_CUSTOMER","邀请客户"), FIRST_INVEST("FIRST_INVEST","首次投资"), BIND_CARD("BIND_CARD","绑卡认证"); InvestorNewcomerTaskEnum(String code,String message){ this.code = code; this.message = message; } private String code; private String message; public String getCode() { return code; } public String getMessage() { return message; } }
Java
UTF-8
2,383
3.34375
3
[]
no_license
package com.company; class Car { private String name; private boolean engine; private int cylinders; private int wheel; public Car(String name, int cylinders) { this.name = name; this.cylinders = cylinders; this.wheel = 4; this.engine = true; } public int getCylinders() { return cylinders; } public String getName() { return name; } public void startEngine(){ System.out.println("Engine status: " + engine); } public void acclerate(){ System.out.println("No Acceleration here"); } public void brake(){ System.out.println("No Brake pressed"); } } class Verna extends Car{ public Verna(String name, int cylinders) { super(name, cylinders); } public void startEngine(){ System.out.println("Engine started - Verna"); } public void acclerate(){ System.out.println("Accleration on! - Verna"); } public void brake(){ System.out.println("No Brake pressed - Verna"); } } class Fortuner extends Car{ public Fortuner(String name, int cylinders) { super(name, cylinders); } public void startEngine(){ System.out.println("Engine started - Fortuner"); } public void acclerate(){ System.out.println("Accleration on! - Fortuner"); } public void brake(){ System.out.println("No Brake pressed - Fortuner"); } } class Mazda extends Car{ public Mazda(String name, int cylinders) { super(name, cylinders); } public void startEngine(){ System.out.println("Engine started - mazda"); } public void acclerate(){ System.out.println("Accleration on! - mazda"); } public void brake(){ System.out.println("No Brake pressed - Mazda"); } } public class Main { public static void main(String[] args) { Car car = new Car("Base car", 6); car.startEngine(); car.acclerate(); car.brake(); Verna verna = new Verna("Verna", 4); verna.startEngine(); verna.acclerate(); verna.brake(); Fortuner fortuner = new Fortuner("Fortuner", 4); fortuner.startEngine(); fortuner.acclerate(); fortuner.brake(); Mazda mazda = new Mazda("Mazda", 6); mazda.startEngine(); mazda.acclerate(); mazda.brake(); } }
C#
UTF-8
907
2.65625
3
[]
no_license
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Linq; namespace Service.Migrations { public partial class InitialData : Migration { protected override void Up(MigrationBuilder migrationBuilder) { var random = new Random(); const int intervalInHours = 12; const int daysOfData = 90; var now = DateTimeOffset.Now; Enumerable.Range(0, daysOfData * (24 / intervalInHours)) .Select(i => new { When = now.AddHours(-intervalInHours * i), ValueInCelsius = random.Next(15, 32) }) .ToList() .ForEach(o => migrationBuilder.Sql($"insert into Temperatures ([When], ValueInCelsius) values ('{o.When:o}', {o.ValueInCelsius})")); } protected override void Down(MigrationBuilder migrationBuilder) { } } }
Java
UTF-8
1,278
2.28125
2
[]
no_license
package com.css.msgcenter.common; /** * IM 消息内容 * * @author wfm * */ public class IMMessage { private String title = "";//标题 private String text = "";//正文 private String targetUser = "";//接收方用户id private String selfUser = "";//发送方 private String realName = "";//发送方真实姓名 private String type = "";//消息类型 7 8 9 10 邮件 代办 督办 日程 private String url = "";//打开的连接 public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTargetUser() { return targetUser; } public void setTargetUser(String targetUser) { this.targetUser = targetUser; } public String getSelfUser() { return selfUser; } public void setSelfUser(String selfUser) { this.selfUser = selfUser; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
Python
UTF-8
946
2.90625
3
[]
no_license
# -*- coding:utf-8 -*- import urllib import urllib2 def loadPage(url,filename): print '正在下载'+filename headers = {'User-Agent':"Mozilla/5.0"} request = urllib2.Request(url,headers=headers) return urllib2.urlopen(request).read() def writePage(html,filename): with open(filename,"w") as f: f.write(html) def tiebaSpider(url,beginPage,endPage): for page in range(beginPage,endPage+1): pn = (page-1)*50 filename = '第'+str(pn)+'页.html' fullurl = url + "$pn=" + str(pn) html = loadPage(fullurl,filename) writePage(html,filename) if __name__ == '__main__': kw = raw_input('请输入爬取的贴吧名:') beginPage = int(raw_input('请输入开始页:')) endPage = int(raw_input('请输入结束页:')) url = 'https://tieba.baidu.com/f?' key = urllib.urlencode({"kw":kw}) fullurl = url + key tiebaSpider(fullurl,beginPage,endPage)
Markdown
UTF-8
628
2.90625
3
[]
no_license
# redux-thunk-state-adapter A utility to provide a facade of getState to an externally owned thunk. This is useful when you are sharing action creators which compose selectors that assume a certain state shape. ## Usage ```javascript import { createThunkAdapter } from 'redux-thunk-state-adapter'; import { externalThunkCreator } from 'some-module'; // provide a transform function to map InternalState -> ExternalState const externalThunkAdapter = createThunkAdapter((state) => ({ user: { timezone: state.environment.userTimezone } })); const adaptedExternalThunk = externalThunkAdapter(externalThunkCreator); ```
Java
UTF-8
3,199
2.25
2
[]
no_license
package com.njuse.uctaserver.controller; import com.njuse.uctaserver.dto.PlaceCommentDTO; import com.njuse.uctaserver.model.entity.PlaceComment; import com.njuse.uctaserver.service.CommentService; import io.swagger.annotations.*; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; @Api(tags = "Place Comment Controller") @Controller @RequestMapping("/comment/place/") public class PlaceCommentController { private final CommentService commentService; @Autowired public PlaceCommentController(CommentService commentService) { this.commentService = commentService; } @ApiOperation(value = "获取指定id地点的所有评论") @ApiImplicitParam(name = "place", value = "地点名", required = true, dataType = "String", paramType = "path") @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Not FOUND") }) @GetMapping(value = "/{place}") public @ResponseBody ResponseEntity<List<PlaceComment>> getAllByUserId(@PathVariable String place) { List<PlaceComment> placeComments = commentService.getAllByPlace(place); HttpStatus resCode = placeComments.isEmpty() ? HttpStatus.NOT_FOUND : HttpStatus.OK; return new ResponseEntity<>(placeComments, resCode); } @ApiOperation(value = "创建指定id地点的评论") @ApiImplicitParams({ @ApiImplicitParam(name = "place", value = "地点名", required = true, dataType = "String", paramType = "path"), @ApiImplicitParam(name = "placeCommentDTO", value = "地点评论详情DTO类", required = true, dataType = "PlaceCommentDTO", paramType = "body") }) @ApiResponses({ @ApiResponse(code = 201, message = "Created"), @ApiResponse(code = 304, message = "Not Modified"), @ApiResponse(code = 404, message = "Not Found") }) @PostMapping(value = "/{place}") public @ResponseBody ResponseEntity<String> create(@PathVariable String id, @RequestBody PlaceCommentDTO placeCommentDTO) { PlaceComment placeComment = new PlaceComment(); BeanUtils.copyProperties(placeCommentDTO, placeComment); HttpStatus resCode = commentService.addCommentOnPlace(placeComment); return new ResponseEntity<>(resCode.getReasonPhrase(), resCode); } @ApiOperation(value = "获取指定id地点的评分") @ApiImplicitParam(name = "place", value = "地点名", required = true, dataType = "String", paramType = "path") @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Not FOUND") }) @GetMapping(value = "/{id}/score") public @ResponseBody ResponseEntity<Double> getScore(@PathVariable String place) { Double placeComment = commentService.getScoreByPlace(place); return new ResponseEntity<>(placeComment, HttpStatus.OK); } }
Java
UTF-8
1,067
2.265625
2
[ "MIT" ]
permissive
/* Copyright (c) 2011-2013 GZapps Grzegorz Żur */ package com.gzapps.shopping.app.fragment; import com.gzapps.shopping.core.Product; import com.gzapps.shopping.core.Shopping; import java.util.List; import static com.gzapps.shopping.app.ShoppingApplication.CORRELATION; public class SuggestionsAdapter extends ProductsAdapter { private float limit; SuggestionsAdapter(Shopping shopping, float limit, ProductsFragment fragment) { super(shopping, fragment); this.limit = limit; } public void limit(float limit) { this.limit = limit; refresh(); } @Override List<Product> list() { long time = System.currentTimeMillis(); return shopping.suggestions(time, CORRELATION, limit); } @Override boolean separate() { return false; } @Override boolean tick() { return false; } @Override public int getViewTypeCount() { return 1; } @Override public boolean areAllItemsEnabled() { return true; } }
Java
UTF-8
495
2.25
2
[]
no_license
package Config; import Services.Impl.Circle; import Services.Impl.Rectangle; import Services.Shape; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Created by student on 2016/03/27. */ @Configuration public class AppConfig { @Bean(name = "Rectangle") public Shape getRectangle(){ return new Rectangle(); } @Bean(name = "Circle") public Shape getCircle(){ return new Circle(); } }
C
UTF-8
3,797
2.953125
3
[ "BSD-3-Clause" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <stdbool.h> #include <time.h> #include "../../src/AwFmIndexStruct.h" #include "../../src/AwFmIndex.h" #include "../../src/AwFmOccurrence.h" uint32_t numQueries = 0; uint32_t dbSizeInWindows = 0; bool requestOccupancyPrefetching = false; void parseArgs(int argc, char **argv){ int option = 0; while((option = getopt(argc, argv, "pq:s:")) != -1){ printf("option: %c ", option); switch(option){ case 'p': printf("prefetching requested\n"); requestOccupancyPrefetching = true; break; case 'q': numQueries = atoi(optarg); printf("num queries: %d\n", numQueries); break; case 's': dbSizeInWindows = atoi(optarg); printf("db size in windows: %d\n", dbSizeInWindows); break; case '?': printf("unknown option flag given: %c is not a supported flag.\n", optopt); break; } } } void checkArgs(){ bool allArgumentsParsed = true; if(numQueries == 0){ printf("Num queries was not given (or was given 0). please provide the number of queries to perform with the -q flag\n"); allArgumentsParsed = false; } if(dbSizeInWindows == 0){ printf("database size was not given (or was given 0). please provide the size of the db to test with the -s flag\n"); allArgumentsParsed = false; } if(!allArgumentsParsed){ exit(-1); } } void performDbQueries(const struct AwFmIndex *restrict const index, uint64_t positionsInDb){ size_t ptrs[2]; ptrs[0] = rand() % positionsInDb; ptrs[1] = rand() % positionsInDb; if(requestOccupancyPrefetching){ for(uint32_t i = 0; i < numQueries; i++){ uint8_t letter = rand()% 20; ptrs[0] = awFmGetOccupancy(index, ptrs[0], letter) + index->rankPrefixSums[letter]; ptrs[0] = ptrs[0] % positionsInDb; awFmOccupancyDataPrefetch(index, ptrs[0]); ptrs[1] = awFmGetOccupancy(index, ptrs[1], letter) + index->rankPrefixSums[letter]; ptrs[1] = ptrs[1] % positionsInDb; awFmOccupancyDataPrefetch(index, ptrs[1]); } } else{ for(uint32_t i = 0; i < numQueries; i++){ uint8_t letter = rand()% 20; ptrs[0] = awFmGetOccupancy(index, ptrs[0], letter) + index->rankPrefixSums[letter]; ptrs[0] = ptrs[0] % positionsInDb; ptrs[1] = awFmGetOccupancy(index, ptrs[1], letter) + index->rankPrefixSums[letter]; ptrs[1] = ptrs[1] % positionsInDb; } } } int main (int argc, char **argv){ srand(time(NULL)); parseArgs(argc, argv); checkArgs(); uint64_t positionsInDb = dbSizeInWindows *POSITIONS_PER_FM_BLOCK; //create the "database" struct AwFmBlock *blockList = awFmAlignedAllocBlockList(dbSizeInWindows); if(blockList == NULL){ printf("could not allocate block list... maybe window count of %d was too big?\n", dbSizeInWindows); exit(-2); } //randomize the data in the blocklist for(size_t i = 0; i < (sizeof(struct AwFmBlock) * dbSizeInWindows)/ sizeof(uint32_t); i++){ ((uint32_t*)blockList)[i] = rand(); } struct AwFmIndex *index = awFmAlignedAllocAwFmIndex(); if(index == NULL){ printf("could not allocate index... wtf?\n"); exit(-2); } //set the block list in or fake index. index->blockList = blockList; for(size_t i = 0; i <= AMINO_CARDINALITY; i++){ size_t prefixSum = (positionsInDb / AMINO_CARDINALITY) * i; index->rankPrefixSums[AMINO_CARDINALITY - i] = prefixSum; } clock_t before = clock(); performDbQueries(index, positionsInDb); clock_t timeElapsed = clock() - before; double seconds = (double)timeElapsed / CLOCKS_PER_SEC; printf("completed test in %f seconds. queries: %d, numWindows: %d\n\n\n", seconds, numQueries, dbSizeInWindows); free(index->blockList); free(index); }
Java
UTF-8
1,453
2.140625
2
[]
no_license
package com.dneonline.stepdefinitions; import com.dneonline.questions.ElResultado; import com.dneonline.tasks.EnviarSuma; import cucumber.api.java.Before; import cucumber.api.java.es.Cuando; import cucumber.api.java.es.Entonces; import net.serenitybdd.screenplay.actors.OnStage; import net.serenitybdd.screenplay.actors.OnlineCast; import net.serenitybdd.screenplay.rest.abiities.CallAnApi; import org.hamcrest.Matchers; import java.util.List; import static net.serenitybdd.screenplay.GivenWhenThen.seeThat; import static net.serenitybdd.screenplay.actors.OnStage.theActorCalled; import static net.serenitybdd.screenplay.actors.OnStage.theActorInTheSpotlight; public class SumaStepDefinitions { private static final String Ella = "Ella"; @Before public void setUp() { OnStage.setTheStage(new OnlineCast()); theActorCalled(Ella).whoCan(CallAnApi.at("http://www.dneonline.com/calculator.asmx?op=Add")); } @Cuando("^envio la siguiente suma a la calculadora$") public void envioLaSiguienteSumaALaCalculadora(List <String> listaNumero) throws Exception { theActorInTheSpotlight().attemptsTo(EnviarSuma.conCuerpo(listaNumero)); } @Entonces("^deberia ver el siguiente resultado$") public void deberiaVerElSiguienteResultado(List <String> listaResultado) throws Exception { theActorInTheSpotlight().should(seeThat(ElResultado.deLaSuma("AddResult"), Matchers.equalTo(listaResultado.get(0)))); } }
C++
UTF-8
388
2.953125
3
[]
no_license
#include <stdio.h> main() { int input,i,b,count=0; printf("Enter length of array : "); scanf("%d",&input); int num[input]; for(i=1;i<=input;i++) { printf("\nEnter The number %d = ",i); scanf("%d",&num[i]); } for( i=1;i<=input;i++) { printf("\n%d is on position %d",num[i],i); count=count+1; } printf("\ntotal numbers of count are %d",count); }
Python
UTF-8
5,849
2.578125
3
[]
no_license
import sys import tensorflow as tf import numpy as np import math import inspect from models.base import Model from models.rwa_cell import RWACell from models.ran_cell import RANCell from tensorflow.contrib import rnn from tensorflow.contrib.layers import batch_norm class SwitchableDropoutWrapper(rnn.DropoutWrapper): def __init__(self, cell, is_train, input_keep_prob=1.0, output_keep_prob=1.0, seed=None): super(SwitchableDropoutWrapper, self).__init__(cell, input_keep_prob=input_keep_prob, output_keep_prob=output_keep_prob, seed=seed) self.is_train = is_train def __call__(self, inputs, state, scope=None): outputs_do, new_state_do = super(SwitchableDropoutWrapper, self).__call__(inputs, state, scope=scope) tf.get_variable_scope().reuse_variables() outputs, new_state = self._cell(inputs, state, scope) outputs = tf.cond(self.is_train, lambda: outputs_do, lambda: outputs) if isinstance(state, tuple): new_state = state.__class__(*[tf.cond(self.is_train, lambda: new_state_do_i, lambda: new_state_i) for new_state_do_i, new_state_i in zip(new_state_do, new_state)]) else: new_state = tf.cond(self.is_train, lambda: new_state_do, lambda: new_state) return outputs, new_state class CharRNN(Model): def __init__(self, vocab_size=1000, batch_size=100, rnn_size=1024, layer_depth=2, num_units=100, rnn_type="GRU", seq_length=50, keep_prob=0.9, grad_clip=5.0): Model.__init__(self) # RNN self._layer_depth = layer_depth self._keep_prob = keep_prob self._batch_size = batch_size self._num_units = num_units self._seq_length = seq_length self._rnn_size = rnn_size self._vocab_size = vocab_size self.input_data = tf.placeholder(tf.int32, [batch_size, seq_length], name="inputs") self.targets = tf.placeholder(tf.int32, [batch_size, seq_length], name="targets") self.is_training = tf.placeholder('bool', None, name="is_training") with tf.variable_scope('rnnlm'): softmax_w = tf.get_variable("softmax_w", [rnn_size, vocab_size], initializer=tf.truncated_normal_initializer(stddev=1e-4)) softmax_b = tf.get_variable("softmax_b", [vocab_size]) def create_cell(device): if rnn_type == "GRU": cell = rnn.GRUCell(rnn_size) elif rnn_type == "LSTM": if 'reuse' in inspect.signature(tf.contrib.rnn.BasicLSTMCell.__init__).parameters: cell = rnn.LayerNormBasicLSTMCell(rnn_size, forget_bias=0.0, reuse=tf.get_variable_scope().reuse) else: cell = rnn.LayerNormBasicLSTMCell(rnn_size, forget_bias=0.0) elif rnn_type == "RWA": cell = RWACell(rnn_size) elif rnn_type == "RAN": cell = RANCell(rnn_size, normalize=self.is_training) cell = SwitchableDropoutWrapper(rnn.DeviceWrapper(cell, device="/gpu:{}".format(device)), is_train=self.is_training) return cell self.cell = cell = rnn.MultiRNNCell([create_cell(i) for i in range(layer_depth)], state_is_tuple=True) with tf.device("/cpu:0"): self.embedding = tf.get_variable("embedding", [vocab_size, num_units]) inputs = tf.nn.embedding_lookup(self.embedding, self.input_data) inputs = tf.contrib.layers.dropout(inputs, keep_prob, is_training=self.is_training) with tf.variable_scope("output"): self.initial_state = cell.zero_state(batch_size, tf.float32) outputs, last_state = tf.nn.dynamic_rnn(cell, inputs, time_major=False, swap_memory=True, initial_state=self.initial_state, dtype=tf.float32) output = tf.reshape(tf.concat(outputs, 1), [-1, rnn_size]) with tf.variable_scope("loss"): self.logits = tf.matmul(output, softmax_w) + softmax_b self.probs = tf.nn.softmax(self.logits) flat_targets = tf.reshape(tf.concat(self.targets, 1), [-1]) loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.logits, labels=flat_targets) self.loss = tf.reduce_mean(loss) self.final_state = last_state self.global_step = tf.Variable(0, name="global_step", trainable=False) self.lr = tf.Variable(0.0, trainable=False) tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(self.loss, tvars), grad_clip) optimizer = tf.train.AdamOptimizer(self.lr) self.train_op = optimizer.apply_gradients(zip(grads, tvars), global_step=self.global_step) def sample(self, sess, chars, vocab, UNK_ID, num=200, prime='The '): state = sess.run(self.cell.zero_state(1, tf.float32)) for char in prime[:-1]: x = np.zeros((1, 1)) x[0, 0] = vocab.get(char, UNK_ID) feed = {self.input_data: x, self.initial_state: state, self.is_training: False} [state] = sess.run([self.final_state], feed) def weighted_pick(weights): t = np.cumsum(weights) s = np.sum(weights) return int(np.searchsorted(t, np.random.rand(1)*s)) ret = prime char = prime[-1] for _ in range(num): x = np.zeros((1, 1)) x[0, 0] = vocab[char] feed = {self.input_data: x, self.initial_state: state, self.is_training: False} [probs, state] = sess.run([self.probs, self.final_state], feed) p = probs[0] sample = weighted_pick(p) pred = chars[sample] ret += pred char = pred return ret if __name__ == "__main__": model = CharRNN()
Java
UTF-8
14,313
2.125
2
[]
no_license
package com.zamer.zamer; import java.util.ArrayList; import java.util.List; import com.zamer.parser.JSONParser; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Reedite extends Activity { TextView textView; EditText txtName; EditText txtPrice; EditText txtDesc; EditText txtMan; EditText txtMetka; EditText txtFloor; EditText txtTelz; EditText txtImena; EditText txtDen; EditText txtTim; EditText txtCompany; EditText txtOderstates; EditText txtPaystates; EditText txtIP; EditText txtUrl; Button btnSave; Button btnDelete; String pid; private ProgressDialog pDialog; JSONParser jsonParser = new JSONParser(); // url для получения одного продукта private static final String url_product_detials = "http://zamer.com.ua/api"; // url для обновления продукта private static final String url_update_product = "http://zamer.com.ua/api"; // url для удаления продукта private static final String url_delete_product = "http://zamer.com.ua/api"; // JSON параметры private static final String TAG_SUCCESS = "success"; private static final String TAG_PRODUCT = "product"; private static final String TAG_PID = "pid"; private static final String TAG_NAME = "name"; private static final String TAG_PRICE = "price"; private static final String TAG_DESCRIPTION = "description"; private static final String TAG_MAN = "man"; private static final String TAG_METKA = "metka"; private static final String TAG_FLOOR = "floor"; private static final String TAG_TELZ = "telz"; private static final String TAG_NAMER = "imena"; private static final String TAG_DEN = "den"; private static final String TAG_TIM = "tim"; private static final String TAG_COMPANY = "company"; private static final String TAG_ODERSTATES = "oderstates"; private static final String TAG_PAYSTATES = "paystates"; private static final String TAG_IP = "ip"; private static final String TAG_URL = "url"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.re_edit); btnSave = (Button) findViewById(R.id.btnSave); btnDelete = (Button) findViewById(R.id.btnDelete); // показываем форму про детальную информацию о продукте Intent i = getIntent(); // получаем id продукта (pid) с формы pid = i.getStringExtra(TAG_PID); // Получение полной информации о продукте в фоновом потоке new GetProductDetails().execute(); // обрабочик на кнопку сохранение продукта btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // запускаем выполнение задачи на обновление продукта new SaveProductDetails().execute(); } }); // обработчик на кнопку удаление продукта btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // удалем продукт в фоновом потоке new DeleteProduct().execute(); } }); } /** * Фоновая асинхронная задача для получения полной информации о продукте **/ class GetProductDetails extends AsyncTask<String, String, String> { /** * Перед началом показать в фоновом потоке прогресс диалог **/ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Reedite.this); pDialog.setMessage("Loading product details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Получение детальной информации о продукте в фоновом режиме **/ protected String doInBackground(String[] params) { // обновляем UI форму runOnUiThread(new Runnable() { public void run() { // проверяем статус success тега int success; try { // Список параметров List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("pid", pid)); // получаем продукт по HTTP запросу JSONObject json = jsonParser.makeHttpRequest(url_product_detials, "GET", params); Log.d("Single Product Details", json.toString()); success = json.getInt(TAG_SUCCESS); if (success == 1) { // Успешно получинна детальная информация о продукте JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // получаем первый обьект с JSON Array JSONObject product = productObj.getJSONObject(0); // продукт с pid найден // Edit Text txtName = (EditText) findViewById(R.id.txtName); txtImena = (EditText) findViewById(R.id.txtImena); txtDesc = (EditText) findViewById(R.id.txtDesc); txtTelz = (EditText) findViewById(R.id.txtTelz); //txtDen = (EditText) findViewById(R.id.txtDen); //txtTim = (EditText) findViewById(R.id.txtTim); txtFloor = (EditText) findViewById(R.id.txtFloor); txtMetka = (EditText) findViewById(R.id.txtMetka); // покаываем данные о продукте в EditText txtName.setText(product.getString(TAG_NAME)); txtFloor.setText(product.getString(TAG_FLOOR)); txtMetka.setText(product.getString(TAG_METKA)); txtDesc.setText(product.getString(TAG_DESCRIPTION)); txtTelz.setText(product.getString(TAG_TELZ)); txtImena.setText(product.getString(TAG_NAMER)); //txtDen.setText(product.getString(TAG_DEN)); // txtTim.setText(product.getString(TAG_TIM)); //txtMan.setText(product.getString(TAG_MAN) + " " + product.getString(TAG_COMPANY)); } else { // продукт с pid не найден } } catch (JSONException e) { e.printStackTrace(); } } }); return null; } /** * После завершения фоновой задачи закрываем диалог прогресс **/ protected void onPostExecute(String file_url) { // закрываем диалог прогресс pDialog.dismiss(); } } /** * В фоновом режиме выполняем асинхроную задачу на сохранение продукта **/ class SaveProductDetails extends AsyncTask<String, String, String> { /** * Перед началом показываем в фоновом потоке прогрксс диалог **/ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Reedite.this); pDialog.setMessage("Сохранение заявки ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Сохраняем продукт **/ protected String doInBackground(String[] args) { // получаем обновленные данные с EditTexts String name = txtName.getText().toString(); //String tim = txtTim.getText().toString(); String description = txtDesc.getText().toString(); String ime = txtImena.getText().toString(); String tel = txtTelz.getText().toString(); String floor = txtFloor.getText().toString(); //String den = txtDen.getText().toString(); String met = txtMetka.getText().toString(); // формируем параметры List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(TAG_PID, pid)); params.add(new BasicNameValuePair(TAG_NAME, name)); //params.add(new BasicNameValuePair(TAG_TIM, tim)); params.add(new BasicNameValuePair(TAG_DESCRIPTION, description)); params.add(new BasicNameValuePair(TAG_NAMER, ime)); params.add(new BasicNameValuePair(TAG_TELZ, tel)); params.add(new BasicNameValuePair(TAG_FLOOR, floor)); // params.add(new BasicNameValuePair("den", den)); params.add(new BasicNameValuePair(TAG_METKA, met)); Log.d("tag params", params.toString()); // отправляем измененные данные через http запрос JSONObject json = jsonParser.makeHttpRequest(url_update_product, "POST", params); // проверяем json success тег try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // Запускаем Activity вывода всех продуктов Intent i = new Intent(getApplicationContext(), AllProductsActivity.class); startActivity(i); finish(); } else { // продукт не обновлен } }catch(JSONException e){ e.printStackTrace(); } return null; } /** * После окончания закрываем прогресс диалог **/ protected void onPostExecute(String file_url) { // закрываем прогресс диалог pDialog.dismiss(); } } /** * Фоновая асинхронная задача на удаление продукта **/ class DeleteProduct extends AsyncTask<String, String, String> { /** * На начале показываем прогресс диалог **/ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Reedite.this); pDialog.setMessage("Удаляем заявку..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Удаление продукта **/ protected String doInBackground(String[] args) { int success; try { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("pid", pid)); // получение продукта используя HTTP запрос JSONObject json = jsonParser.makeHttpRequest(url_delete_product, "POST", params); Log.d("Delete Product", json.toString()); success = json.getInt(TAG_SUCCESS); if (success == 1) { // Продукт удачно удален Intent i = new Intent(getApplicationContext(), AllProductsActivity.class); // отправляем результирующий код 100 для уведомления об удалении продукта setResult(100, i); startActivity(i); finish(); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * После оконачния скрываем прогресс диалог **/ protected void onPostExecute(String file_url) { pDialog.dismiss(); } } }
C#
UTF-8
3,656
2.6875
3
[ "MS-PL" ]
permissive
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; using MugenMvvmToolkit.Infrastructure.Validation; using MugenMvvmToolkit.Interfaces.Validation; namespace MugenMvvmToolkit.Test.TestModels { public class SpyValidator : ManualValidator<object> { #region Constructors public SpyValidator() { ValidateProperties = new List<string>(); } #endregion #region Properties public Func<IValidatorContext, bool> CanValidate { get; set; } public int ValidateCount { get; set; } public IList<string> ValidateProperties { get; set; } public int ValidateAllCount { get; set; } public int IsValidCount { get; set; } public int ClearPropertyErrorsCount { get; set; } public int ClearAllErrorsCount { get; set; } #endregion #region Overrides of ValidatorBase /// <summary> /// Checks to see whether the validator can validate objects of the specified IValidatorContext. /// </summary> protected override bool CanValidateInternal(IValidatorContext validatorContext) { if (CanValidate == null) return base.CanValidateInternal(validatorContext); return CanValidate(validatorContext); } /// <summary> /// Determines whether the current model is valid. /// </summary> /// <returns> /// If <c>true</c> current model is valid, otherwise <c>false</c>. /// </returns> protected override bool IsValidInternal() { IsValidCount++; return base.IsValidInternal(); } /// <summary> /// Clears errors for a property. /// </summary> /// <param name="propertyName">The name of the property</param> protected override void ClearErrorsInternal(string propertyName) { base.ClearErrorsInternal(propertyName); ClearPropertyErrorsCount++; } /// <summary> /// Clears all errors. /// </summary> protected override void ClearErrorsInternal() { base.ClearErrorsInternal(); ClearAllErrorsCount++; } /// <summary> /// Updates information about errors in the specified property. /// </summary> /// <param name="propertyName">The specified property name.</param> /// <returns> /// The result of validation. /// </returns> protected override Task<IDictionary<string, IEnumerable>> ValidateInternalAsync(string propertyName) { ValidateProperties.Add(propertyName); ValidateCount++; return base.ValidateInternalAsync(propertyName); } /// <summary> /// Updates information about all errors. /// </summary> /// <returns> /// The result of validation. /// </returns> protected override Task<IDictionary<string, IEnumerable>> ValidateInternalAsync() { ValidateAllCount++; return base.ValidateInternalAsync(); } /// <summary> /// Creates a new validator that is a copy of the current instance. /// </summary> /// <returns> /// A new validator that is a copy of this instance. /// </returns> protected override IValidator CloneInternal() { return new SpyValidator(); } #endregion } }
Python
UTF-8
1,294
4.25
4
[ "MIT" ]
permissive
# 思维不清debug # 小强认识了一个新朋友叫旺财,他想让你给他取个外号,但他很不喜欢别人叫他小狗和汪汪, # 于是写了一个程序让自己避免叫他这两个外号中的一个,可是不知为什么叫他小狗程序也没有警告。 not_bad_word = True while not_bad_word: x = input('请给旺财取个外号:') if x == '小狗' and x == '汪汪': not_bad_word = False print('我生气了,不想理你了!') print('对不起,以后我不会这么叫你了') # 练习 not_bad_word = True names = ['小狗', '汪汪'] while not_bad_word: x = input('请给旺财取个外号:') if x in names: # 只要外号是两个中的一个,就会生气。 not_bad_word = False print('我生气了,不想理你了!') print('对不起,以后我不会这么叫你了') # 参考代码 not_bad_word = True while not_bad_word: x = input('请给旺财取个外号:') if x == '小狗' or x == '汪汪': # 只要外号是两个中的一个,就会生气。 not_bad_word = False print('我生气了,不想理你了!') print('对不起,以后我不会这么叫你了') # ?? 不命中判断时没有 退出程序 # ?? 什么时候你才会觉得名字可以了呢
Java
UTF-8
2,875
2.21875
2
[]
no_license
package com.amuse.frameone.common.aop; import com.amuse.frameone.common.Enum.SystemEnum; import com.amuse.frameone.common.exception.BusinessException; import com.amuse.frameone.common.model.Jwt; import com.amuse.frameone.common.util.JwtUtil; import com.amuse.frameone.common.util.ResultUtil; import io.jsonwebtoken.Claims; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.rmi.server.ExportException; /** * @ClassName MyFilter * @Description TODO * @Author 刘培振 * @Date 2018/5/29 11:30 * @Version 1.0 */ //采用bean的方式注入 //@Component //@WebFilter(urlPatterns = "/token/getResource",filterName = "MyFilter") public class MyFilter implements Filter { @Autowired private Jwt jwt; private final static Logger logger = LoggerFactory.getLogger(MyFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; logger.info("过滤器实现token请求的过滤----"); if("OPTIONS".equals(request.getMethod())){ //OPTIONS请求不处理 response.setStatus(HttpServletResponse.SC_OK); filterChain.doFilter(request,response);//执行filter }else{ final String authHeader = request.getHeader("authorization"); if(authHeader == null || !authHeader.startsWith("bearer;")){ response.sendError(response.SC_UNAUTHORIZED);//返回401错误 return; } final String token = authHeader.substring(7); //获取容器的jwt BEAN if(jwt == null){ BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); jwt = (Jwt) factory.getBean("jwt"); } final Claims claims = JwtUtil.parseJWT(token,jwt); if(null == claims){ response.sendError(response.SC_UNAUTHORIZED);//返回401错误 return; } filterChain.doFilter(request,response);//执行filter } } @Override public void destroy() { } }
TypeScript
UTF-8
812
2.75
3
[]
no_license
import baseWidget from './base.widget'; interface bufferInf { [key: string]: baseWidget; } export default class Register { private static _instance: Register = new Register(); private static buffer: bufferInf; private constructor() { if(Register._instance){ throw new Error("Error: Instantiation failed: Use Register.getInstance() instead of new."); } } static getInstance(): Register { if (!Register._instance) { Register._instance = new Register(); } return Register._instance; } static get(name: string): baseWidget { return this.buffer[name]; } static add(name: string, widgetClass: baseWidget) { this.buffer[name] = widgetClass; } static remove(name: string) { delete this.buffer[name]; } }
TypeScript
UTF-8
522
3.578125
4
[]
no_license
function add(n1: number, n2: number): number { return n1 + n2; } function printResult(num: number): void { console.log('Result: ' + num); } function addAndHandle(a: number, b: number, cb: (num: number) => void) { const result = add(a, b); cb(result); } printResult(add(5, 10)); console.log('XD'); let someValue: undefined; let combineValues: (a: number, b: number) => number; combineValues = add; // combineValues = printResult; console.log(combineValues(1, 5)); addAndHandle(10, 20, console.log);
Java
UTF-8
424
1.742188
2
[]
no_license
package com.cskaoyan.mall.mapper; import com.cskaoyan.mall.bean.AdminOrderGoods; public interface AdminOrderGoodsMapper { int deleteByPrimaryKey(Integer id); int insert(AdminOrderGoods record); int insertSelective(AdminOrderGoods record); AdminOrderGoods selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(AdminOrderGoods record); int updateByPrimaryKey(AdminOrderGoods record); }
Java
UTF-8
1,432
3.84375
4
[]
no_license
package medium; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; class InsertDeleteGetRandomO1 { class RandomizedSet { ArrayList<Integer> nums; Map<Integer, Integer> pos; Random r; /** Initialize your data structure here. */ public RandomizedSet() { nums = new ArrayList<>(); pos = new HashMap<>(); r = new Random(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(pos.containsKey(val)) return false; nums.add(val); pos.put(val, nums.size() - 1); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(!pos.containsKey(val)) return false; int i = pos.get(val); int last_num = nums.get(nums.size() - 1); nums.set(i, last_num); pos.put(last_num, i); pos.remove(val); nums.remove(nums.size() - 1); return true; } /** Get a random element from the set. */ public int getRandom() { System.out.println(nums.size()); int pick = r.nextInt(nums.size()); return nums.get(pick); } } }
C#
UTF-8
420
2.9375
3
[]
no_license
// create template matching algorithm's instance // use zero similarity to make sure algorithm will provide anything ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0); // compare two images TemplateMatch[] matchings = tm.ProcessImage(image1, image2); // check similarity level if (matchings[0].Similarity > 0.95f) { // do something with quite similar images }
TypeScript
UTF-8
1,779
2.703125
3
[ "MIT" ]
permissive
import { ipcRenderer } from "electron"; import { IRendererEventBus, RendererEvents } from "./"; import { MainEvents } from "../../main/services/enumerations"; /** * Wraps the ipcRenderer electron event emitter to provide additional functionality. */ export const RendererEventBus: IRendererEventBus = { on(event: RendererEvents, listener: Electron.IpcRendererEventListener) { ipcRenderer.on(event, listener); return RendererEventBus; }, once(event: RendererEvents, listener: Electron.IpcRendererEventListener) { ipcRenderer.once(event, listener); return RendererEventBus; }, removeListener(event: RendererEvents, listener: Electron.IpcRendererEventListener) { ipcRenderer.removeListener(event, listener); return RendererEventBus; }, removeAllListeners(event?: RendererEvents) { if (event) { ipcRenderer.removeAllListeners(event); } else { // Just remove the events that match one of the enum members for (const eventName of ipcRenderer.eventNames()) { if (typeof eventName === "string" && typeof RendererEvents[eventName] !== "undefined") { ipcRenderer.removeAllListeners(eventName); } } } return RendererEventBus; }, send(event: MainEvents, ...args: any[]) { ipcRenderer.send(event, ...args); }, sendSync(event: MainEvents, ...args: any[]): any { return ipcRenderer.sendSync(event, ...args); }, emit(event: RendererEvents, ...args: any[]) { // pass null as the first arg for the ipcRendererEvent, // this arg is only provided when sending inter-process ipcRenderer.emit(event, null, ...args); } };
Python
UTF-8
598
3.25
3
[]
no_license
class NPC: """ Basic parent class for any non player controlled characters """ def __init__(self, name, hp, damage): self.name = name self.hp = hp self.damage = damage def is_alive(self): """ Returns if NPC is alive or not """ if self.hp > 0: return True else: return False class StarvingDog(NPC): def __init__(self): super().__init__(name="Starving Dog", hp=10, damage=2) class DerangedScientist(NPC): def __init__(self): super().__init__(name="Deranged Scientist", hp=15, damage=2)
Java
UTF-8
740
2.65625
3
[]
no_license
package com.guilin.demo.boot.hello; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @RestController 等价于 @Controller和@RequestBody * Created by guilin1 on 15/12/9. */ @RestController public class SampleController { @RequestMapping("/hello") public String home() { return "Hello World!"; } /** * Spring boot默认使用的json解析框架是jackson * * @return */ @RequestMapping("/getStudent") public Student getStudent() { Student student = new Student(); student.setId(11000); student.setAge(20); student.setName("张三"); return student; } }
Python
UTF-8
1,205
2.75
3
[]
no_license
# -*- coding: utf-8 -*- from __future__ import unicode_literals from nose.tools import istest from compmake.utils import wildcard_to_regexp from . import CompmakeTest @istest class Simple(CompmakeTest): def mySetUp(self): pass def testExists1(self): key = 'not-existent' assert (not key in self.db) def testExists2(self): k = 'ciao' v = {'complex': 123} db = self.db if k in db: del db[k] self.assertFalse(k in db) db[k] = v self.assertTrue(k in db) del db[k] self.assertFalse(k in db) db[k] = v del db[k] self.assertFalse(k in db) def testSearch(self): db = self.db def search(pattern): r = wildcard_to_regexp(pattern) for k in db.keys(): if r.match(k): yield k self.assertEqual([], list(search('*'))) db['key1'] = 1 db['key2'] = 1 self.assertEqual([], list(search('ciao*'))) self.assertEqual(['key1'], list(search('key1'))) self.assertEqual(['key1'], list(search('*1'))) self.assertEqual([], list(search('d*1')))
PHP
UTF-8
601
3.671875
4
[]
no_license
<?php function addingMatrix($a, $b) { $sum = []; for ($row = 0; $row < sizeof($a); $row++) { $temp = []; for ($col = 0; $col < sizeof($a[0]); $col++) { $temp[$col] = $a[$row][$col] + $b[$row][$col]; } $sum[] = $temp; } return $sum; } function multiplyingMatrix($a, $b) { $result = []; for ($x = 0; $x < sizeof($a); $x++) { $temp = []; for ($y = 0; $y < sizeof($a); $y++) { $sum = 0; for ($z = 0; $z < sizeof($b); $z++) { $sum += $a[$x][$z] * $b[$z][$y]; } $temp[] = $sum; } $result[] = $temp; } return $result; }
C++
UTF-8
1,375
3.484375
3
[]
no_license
#ifndef BOARD_H #define BOARD_H #include <iostream> #include <ctime> #include <vector> template <class T> class Board{ private: std::vector<std::vector<T> > board; public: // Constructor Board(int size){ board.resize(size, std::vector<T>(size, 0)); } // Update board void update(std::vector<std::vector<T> > new_board){board = new_board;} // Print void wait(){ std::clock_t startTime = std::clock(); double secondsPassed; double secondsToDelay = 0.01; bool flag = true; while(flag == true) { secondsPassed = (std::clock() - startTime) / (1.0*CLOCKS_PER_SEC); if(secondsPassed >= secondsToDelay) { flag = false; } } } void clear(){ //ANSI Escape Sequence printf("\033[2J"); printf("\033[%d;%dH", 0, 0); } void print(){ wait(); clear(); for(auto iter1 = board.begin(); iter1 != board.end(); iter1++){ for(auto iter2 = iter1->begin(); iter2 != iter1->end(); iter2++){ if(*iter2 == 0){ std::cout << " "; } else std::cout << *iter2; } std::cout << "\n"; } } T at(int row, int col){ return board[row][col]; } }; #endif
TypeScript
UTF-8
1,596
2.8125
3
[]
no_license
/** * This component used to handle error messages for input field (formControl) * https://stackoverflow.com/questions/52771445/best-way-to-show-error-messages-for-angular-reactive-forms-one-formcontrol-mult */ import { Component, Input } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-form-field-errors', template: ` <div *ngIf="errors?.length > 0"> <div *ngIf="displayOnlyFirst; else showAll">{{ errors[0] }}</div> <ng-template #showAll> <div *ngFor="let error of errors"> {{ error }} </div> </ng-template> </div> `, styles: [``], }) export class FormFieldErrorsComponent { /** * The form control you want to check have errors on it. */ @Input() control: FormControl; /** * If `true`, only first error message will display. */ @Input() displayOnlyFirst = false; errorMessages: any[] = []; /** * errors with specific validator need to be defined how to display. */ messages = { required: (params) => `This field is required`, email: (params) => `This email must be a valid email address`, }; get errors(): any { if (!this.control) { return []; } if (this.control.errors) { this.errorMessages = []; Object.keys(this.control.errors).map(error => { if (this.control.touched || this.control.dirty) { this.errorMessages.push( this.messages[error](this.control.errors[error]) ); } }); return this.errorMessages; } else { return []; } } }
Python
UTF-8
467
3.84375
4
[]
no_license
#En una granja se contaron 94 patas y 35 cabezas de animales #Se sabe que hay conejos y gallinas #Cuantos animales hay de cada tipo conejos=1 total=conejos*4 indicador=True patas=94-total patasGallina= patas/2 while(indicador): patasConejos=conejos*4 gallinas=((94-patasConejos)/2) if((conejos+gallinas)!=35): conejos=conejos+1 else: indicador=False print("Hay:", conejos, "conejos y ", gallinas, "gallinas")
C#
UTF-8
2,283
3.171875
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; class NFA { char[] m_re; DirectedGraph m_g; int m_m; public NFA(string regexp) { Stack<int> ops = new Stack<int>(); m_re = regexp.ToCharArray(); m_m = m_re.Length; m_g = new DirectedGraph(m_m + 1); for (int i = 0; i < m_m; ++i ) { int lp = i; if(m_re[i] == '(' || m_re[i] == '|') { ops.Push(i); } else if (m_re[i] == ')') { int or = ops.Pop(); if(m_re[or] == '|') { lp = ops.Pop(); m_g.AddEdge(lp, or + 1); m_g.AddEdge(or, i); } else { lp = or; } } if(i < m_m - 1 && m_re[i + 1] == '*') { m_g.AddEdge(lp, i + 1); m_g.AddEdge(i + 1, lp); } if(m_re[i] == '(' || m_re[i] == '*'|| m_re[i] == ')') { m_g.AddEdge(i, i + 1); } } } public bool Recognizes(string txt) { List<int> pc = new List<int>(); DirectedDFS dfs = new DirectedDFS(m_g, 0); for (int v = 0; v < m_g.V(); v++ ) { if(dfs.Marked(v)) { pc.Add(v); } } for (int i = 0; i < txt.Length; ++i ) { List<int> match = new List<int>(); foreach(var v in pc) { if(v < m_m) { if(m_re[v] == txt[i] || m_re[v] == '.') { match.Add(v + 1); } } } pc = new List<int>(); dfs = new DirectedDFS(m_g, match); for (int v = 0; v < m_g.V(); ++v ) { if(dfs.Marked(v)) { pc.Add(v); } } } foreach(var v in pc) { if(v == m_m) { return true; } } return false; } }
Java
UTF-8
2,731
3.28125
3
[]
no_license
package com.siwoo.algo.sedgewick.collection; import com.siwoo.algo.util.AppConfig; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Random; import java.util.Scanner; /** * [algo] [mst] * spanning tree 은 순환 경로가 없으면서 모든 정점이 연결된 서브그래프이다. (tree = E = V-1 & all v is connected) * minimum spanning tree 은 이러한 그래프의 spanning tree 중 가중치의 합이 최소인 spanning tree 이다. * * problem * * (무방향) 가중 그래프 G 에서 모든 정점을 포함하는 최소 비용을 알고 싶다. * * mst 문제해결 알고리즘. * 1. prim (priority queue) * 2. kruskal (union find) * * component * 트리의 속성. tree property * 1. 트리에 간선을 하나 추가하면 "한 개의 순환" 이 만들어진다 * 2. 트리의 간선을 하나 제거하면 "두 개의 트리" 로 분리된다. * * 자르기 속성. cut property * 정점들을 두 개의 집합으로 나누어 둘 사이를 횡단하는 간선을 찾는다. * * 횡단 간선. crossing edge. * 그래프의 자르기로 나누어진 두 집합을 잇는 간선들. * * 가중 간선 그래프 G 에서, 어떤 임의의 자르기에서 최소 가중치를 가지는 횡단 간선은 그래프의 MST 에 반드시 포함된다. * */ /** * A spanning tree of G is a subgraph T that is both a tree and spanning. * MST is a sa min weight spanning tree. * @param <E> */ public interface MinimumSpanningTree<E> extends Graph<E> { /** * the mst's weight * * @return */ double weight(); default boolean isConnected(Graph<E> G) { ConnectedComponent<E> cc = new CC<>(G); return cc.count() == 1; } static void main(String[] args) throws FileNotFoundException { final String path = AppConfig.INSTANCE.getProperty("app.resources.algs4data") + "/mediumEWG.txt"; Scanner scanner = new Scanner(new BufferedReader(new FileReader(path))); Graph<Integer> G = new UnDirectedGraph<>(); int V = scanner.nextInt(), W = scanner.nextInt(); for (int i=0; i<W; i++) { int v = scanner.nextInt(), w = scanner.nextInt() ; double weight = scanner.nextDouble(); WeightedEdge<Integer> edge = new WeightedEdge<>(v, w, weight); G.addEdge(edge); } MinimumSpanningTree<Integer> mst = new Kruskal<>(G); System.out.printf("%.2f%n", mst.weight()); for (int i=0; i<100; i++) System.out.println((new Random().nextInt(90000000) + 10000000)); } }
Java
UTF-8
3,350
1.960938
2
[]
no_license
package com.ck.platform.business.weixin.service; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @desc: 微信业务接口Service * @author:lyq * @date:2014-6-5 */ @SuppressWarnings("rawtypes") public interface WeixinInteractService { /** * 获取口令 * @return */ public HashMap updateGetAccessToken(String appId,String appSecret) ; /** * 授权 请求 * @param url * @return */ public HashMap getOAuth2Authorize(String appId,String url); /** * 根据口令码获取 会员openid 及授权口令 * @param code * @return */ public HashMap getOAuth2AccessToken(String appId,String appSecret,String code); /** * 清除菜单结构 * @param accessToken * @return */ public HashMap clearMenu(String accessToken); /** * 创建菜单结构 * @param accessToken * @param jsonButton * @return */ public HashMap createMenu(String accessToken,Object jsonButton); /** * 查询菜单结构 * @param accessToken * @return */ public HashMap queryMenu(String accessToken); /** * 会员信息 * @param accessToken * @param openid * @return */ public HashMap userInfo(String accessToken,String openid); /** * 开放平台获取会员信息 * @param accessToken * @param openid 开放平台-网站openId * @return */ public HashMap openUserInfo(String accessToken,String openid); /** * 发送单文本信息 * @param accessToken * @param openid * @return */ public HashMap sendText(String accessToken,String openid,String content); /** * 发送模版消息 * @param accessToken * @param messageProperty: toUser/templateId/url/topcolor * @param data: * @return */ public HashMap sendTmpMsg(String accessToken,Map messageProperty,Map data); /** * 群发文本 * @param accessToken * @param openids 微信openid (数组或字符串) * @param content * @return */ public HashMap sendMassText(String accessToken, Object openids, String content) ; /** * 根据用户列表群发送单文本信息 "title":"Happy Day", "description":"Is Really A Happy Day", "url":"URL", "picurl":"PIC_URL" * @param accessToken * @param openid String或数组 * @return */ public HashMap sendNews(String accessToken, Object openid,List<Map> articles); /** * 根据用户列表群发媒体信息 * @param accessToken * @param openid * @return */ public HashMap sendMassMedia(String accessToken,List<String> openids,String msgType,String mediaId); /** * 上传图文信息 * @param accessToken * @param List<Map> * "thumb_media_id":"qI6_Ze_6PtV7svjolgs-rN6stStuHIjs9_DidOHaj0Q-mwvBelOXCFZiq2OsIU-p", 缩略图mediaId "author":"xxx", "title":"Happy Day", "content_source_url":"www.qq.com", "content":"content", "digest":"digest", "show_cover_pic":"1" * @return */ public HashMap uploadNews(String accessToken,List<Map> list); /** * 获取二维码生成票据 * @param accessToken * @param paramMap (expire_seconds,action_name,action_info,scene_id(scene_str)) * @return */ public HashMap createQrCodeTicket(String accessToken,Map paramMap); /** * 换取二维码 * @param ticket * @return */ public HashMap getQrCode(String ticket); }
Java
UTF-8
28,888
1.835938
2
[]
no_license
/* * Copyright Georgia Tech Research Institute * Sep 28, 2011 * * All rights reserved. */ package gov.lexs.subscribenotify; import gov.lexs.AbstractTest; import gov.ulex.searchretrieve.v20.XmlGetCapabilitiesRequestDocumentBean; import gov.ulex.searchretrieve.v20.XmlGetCapabilitiesResponseDocumentBean; import java.io.File; import java.util.ArrayList; import org.apache.xmlbeans.XmlError; import org.apache.xmlbeans.XmlOptions; import org.oasisopen.docs.wsn.b2.XmlNotifyDocumentBean; import org.oasisopen.docs.wsn.b2.XmlRenewDocumentBean; import org.oasisopen.docs.wsn.b2.XmlRenewResponseDocumentBean; import org.oasisopen.docs.wsn.b2.XmlSubscribeCreationFailedFaultDocumentBean; import org.oasisopen.docs.wsn.b2.XmlSubscribeDocumentBean; import org.oasisopen.docs.wsn.b2.XmlSubscribeResponseDocumentBean; import org.oasisopen.docs.wsn.b2.XmlUnsubscribeDocumentBean; import org.oasisopen.docs.wsn.b2.XmlUnsubscribeResponseDocumentBean; /** * * @author es130 */ public class TestSubscribeNotify extends AbstractTest{ private String SN_DIR = "src/test/resources/xml/SN-samples"; public void testNotifyDataItemRetrievalSubscriptionNotification() throws Exception{ System.out.println("Entering testNotifyDataItemRetrievalSubscriptionNotification"); String filePath = SN_DIR + "/Notify-DataItemRetrievalSubscriptionNotification-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlNotifyDocumentBean generatedBean = null; try{ generatedBean = XmlNotifyDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testNotifyDataItemRetrievalSubscriptionNotification"); } public void testNotifyDataItemSearchSubscriptionNotification() throws Exception{ System.out.println("Entering testNotifyDataItemSearchSubscriptionNotification"); String filePath = SN_DIR + "/Notify-DataItemSearchSubscriptionNotification-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlNotifyDocumentBean generatedBean = null; try{ generatedBean = XmlNotifyDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testNotifyDataItemSearchSubscriptionNotification"); } public void testNotifyIdenticalSearchSubscriptionNotification() throws Exception{ System.out.println("Entering testNotifyIdenticalSearchSubscriptionNotification"); String filePath = SN_DIR + "/Notify-IdenticalSearchSubscriptionNotification-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlNotifyDocumentBean generatedBean = null; try{ generatedBean = XmlNotifyDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testNotifyIdenticalSearchSubscriptionNotification"); } public void testNotifyMatchSubscriptionNotification() throws Exception{ System.out.println("Entering testNotifyMatchSubscriptionNotification"); String filePath = SN_DIR + "/Notify-MatchSubscriptionNotification-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlNotifyDocumentBean generatedBean = null; try{ generatedBean = XmlNotifyDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testNotifyMatchSubscriptionNotification"); } public void testNotifyTopicSubscriptionNotification() throws Exception{ System.out.println("Entering testNotifyTopicSubscriptionNotification"); String filePath = SN_DIR + "/Notify-TopicSubscriptionNotification-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlNotifyDocumentBean generatedBean = null; try{ generatedBean = XmlNotifyDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testNotifyTopicSubscriptionNotification"); } public void testRenew() throws Exception{ System.out.println("Entering testRenew"); String filePath = SN_DIR + "/Renew-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlRenewDocumentBean generatedBean = null; try{ generatedBean = XmlRenewDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testRenew"); } public void testRenewResponse() throws Exception{ System.out.println("Entering testRenewResponse"); String filePath = SN_DIR + "/RenewResponse-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlRenewResponseDocumentBean generatedBean = null; try{ generatedBean = XmlRenewResponseDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testRenewResponse"); } public void testSubscribeDataItemRetrievalSubscription() throws Exception{ System.out.println("Entering testSubscribeDataItemRetrievalSubscription"); String filePath = SN_DIR + "/Subscribe-DataItemRetrievalSubscription-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlSubscribeDocumentBean generatedBean = null; try{ generatedBean = XmlSubscribeDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testSubscribeDataItemRetrievalSubscription"); } public void testSubscribeDataItemSearchSubscription() throws Exception{ System.out.println("Entering testSubscribeDataItemSearchSubscription"); String filePath = SN_DIR + "/Subscribe-DataItemSearchSubscription-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlSubscribeDocumentBean generatedBean = null; try{ generatedBean = XmlSubscribeDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testSubscribeDataItemSearchSubscription"); } public void testSubscribeIdenticalSearchSubscription() throws Exception{ System.out.println("Entering testSubscribeIdenticalSearchSubscription"); String filePath = SN_DIR + "/Subscribe-IdenticalSearchSubscription-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlSubscribeDocumentBean generatedBean = null; try{ generatedBean = XmlSubscribeDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testSubscribeIdenticalSearchSubscription"); } public void testMatchSubscription() throws Exception{ System.out.println("Entering testMatchSubscription"); String filePath = SN_DIR + "/Subscribe-MatchSubscription-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlSubscribeDocumentBean generatedBean = null; try{ generatedBean = XmlSubscribeDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testMatchSubscription"); } public void testSimilarSearchSubscription() throws Exception{ System.out.println("Entering testSimilarSearchSubscription"); String filePath = SN_DIR + "/Subscribe-SimilarSearchSubscription-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlSubscribeDocumentBean generatedBean = null; try{ generatedBean = XmlSubscribeDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testSimilarSearchSubscription"); } public void testTopicSubscription() throws Exception{ System.out.println("Entering testSimilarSearchSubscription"); String filePath = SN_DIR + "/Subscribe-TopicSubscription-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlSubscribeDocumentBean generatedBean = null; try{ generatedBean = XmlSubscribeDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testTopicSubscription"); } public void testSubscribeResponse() throws Exception{ System.out.println("Entering testSubscribeResponse"); String filePath = SN_DIR + "/SubscribeResponse-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlSubscribeResponseDocumentBean generatedBean = null; try{ generatedBean = XmlSubscribeResponseDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testSubscribeResponse"); } public void testSubscribeResponseFault() throws Exception{ System.out.println("Entering testSubscribeResponseFault"); String filePath = SN_DIR + "/SubscribeResponseFault-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlSubscribeCreationFailedFaultDocumentBean generatedBean = null; try{ generatedBean = XmlSubscribeCreationFailedFaultDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testSubscribeResponseFault"); } public void testUnsubscribe() throws Exception{ System.out.println("Entering testUnsubscribe"); String filePath = SN_DIR + "/Unsubscribe-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlUnsubscribeDocumentBean generatedBean = null; try{ generatedBean = XmlUnsubscribeDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testUnsubscribe"); } public void testUnsubscribeResponse() throws Exception{ System.out.println("Entering testUnsubscribeResponse"); String filePath = SN_DIR + "/UnsubscribeResponse-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlUnsubscribeResponseDocumentBean generatedBean = null; try{ generatedBean = XmlUnsubscribeResponseDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testUnsubscribeResponse"); } public void testGetCapabilitiesRequest() throws Exception{ System.out.println("Entering testGetCapabilitiesRequest"); String filePath = SN_DIR + "/getCapabilitiesRequest-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlGetCapabilitiesRequestDocumentBean generatedBean = null; try{ generatedBean = XmlGetCapabilitiesRequestDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testGetCapabilitiesRequest"); } public void testGetCapabilitiesResponse() throws Exception{ System.out.println("Entering testGetCapabilitiesResponse"); String filePath = SN_DIR + "/getCapabilitiesResponse-xinclude.xml"; File file = new File( filePath ); boolean createdBean = true; XmlGetCapabilitiesResponseDocumentBean generatedBean = null; try{ generatedBean = XmlGetCapabilitiesResponseDocumentBean.Factory.parse( file ); } catch(Exception e){ e.printStackTrace(); createdBean = false; } assertTrue(createdBean); XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = generatedBean.validate(validateOptions); if( !isValid ){ for (int i = 0; i < errorList.size(); i++){ XmlError error = (XmlError)errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } assertTrue( isValid ); String fileString = getStringFromFile( filePath ); assertXMLEqual( fileString, generatedBean.xmlText() ); System.out.println("Exiting testGetCapabilitiesResponse"); } }
C++
UTF-8
1,241
3.203125
3
[]
no_license
#include "../header/myheader.h" class LT0853 { public: // D D //for (int i = 0; i < pos.size(); i++) m[-pos[i]] = (double)(target - pos[i]) / speed[i]; // 取负,保存耗时。 // vector<pair<int, int>> v; // sort(begin(v), end(v), greater<pair<int,int>>()); //Runtime: 88 ms, faster than 49.89% of C++ online submissions for Car Fleet. //Memory Usage: 23.5 MB, less than 13.56% of C++ online submissions for Car Fleet. // 计算各自需要多少小时到达目的地,如果前面有耗时比他多的,就合并 int lt0853a(int target, vector<int>& position, vector<int>& speed) { map<int, int> map2; int sz1 = speed.size(); for (int i = 0; i < sz1; i++) { map2[target - position[i]] = speed[i]; } double times = -1; int ans = 0; for (auto& p : map2) { double tms = 1.0 * p.first / p.second; if (tms > times) { ans++; times = tms; } } return ans; } }; int main() { int target = 12; vector<int> p = {10,8,0,5,3}; vector<int> s = {2,4,1,1,3}; LT0853 lt; cout<<lt.lt0853a(target, p, s)<<endl; return 0; }
C#
UTF-8
22,170
2.625
3
[]
no_license
using System.Collections.Generic; using System.Threading.Tasks; using Basket.Models; using Basket.Services; using FluentAssertions; using Models.Customers.Models; using Models.Products.Models; using Moq; using Xunit; namespace BasketTest { public class BasketServiceTests { [Fact] public async Task AddProductsToBasket_ShouldAddProductsToBasketWhenCurrentBasketIsNull() { // Arrange int customerId = 1; int productId = 1; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)).Returns<BasketWithGoods>(null); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(new Product()); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); BasketWithGoods currentBasket = new BasketWithGoods { CustomerId = customerId, ProductIds = new List<ProductsInBasket>() }; // Act await basketService.AddProductsToBasket(1, 1, 1); // Assert basketMock.Verify(x => x.AddToBasket(It.Is<BasketWithGoods>(x => x.CustomerId == currentBasket.CustomerId))); basketMock.Verify(x => x.AddToBasket(It.Is<BasketWithGoods>(x => x.ProductIds != null))); } [Theory] [InlineData(0, Status.BadRequest)] [InlineData(-1, Status.BadRequest)] public async Task AddProductsToBasket_ShouldReturnBadRequestWhenQuantityIsLessThenOrEqualZero(int quantity, Status result) { // Arrange int customerId = 1; int productId = 1; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)).Returns<BasketWithGoods>(null); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(new Product()); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act var expected = await basketService.AddProductsToBasket(customerId, productId, quantity); // Assert expected.Status.Should().Be(result); } [Fact] public async Task AddProductsToBasket_ShouldReturnNotFoundWhenCustomerIsNotFound() { // Arrange int quantity = 1; int customerId = 1; int productId = 1; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)).Returns<BasketWithGoods>(null); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(default(Customer)); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(new Product()); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act var expected = await basketService.AddProductsToBasket(customerId, productId, quantity); // Assert expected.Status.Should().Be(Status.NotFound); } [Fact] public async Task AddProductsToBasket_ShouldReturnOkWhenProductIsNull() { // Arrange int quantity = 1; int customerId = 1; int productId = 1; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)).Returns<BasketWithGoods>(null); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(default (Product)); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act var expected = await basketService.AddProductsToBasket(customerId, productId, quantity); // Assert expected.Status.Should().Be(Status.BadRequest); } [Fact] public async Task AddProductsToBasket_ShouldOnlyUpdateQuantityOfProducts() { // Arrange var customerId = 1; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)).Returns(new BasketWithGoods { CustomerId = customerId, ProductIds = new List<ProductsInBasket> { new ProductsInBasket { ProductId = 1, Quantity = 1 } } }); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(customerId)).ReturnsAsync(new Product()); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act await basketService.AddProductsToBasket(1, 1, 3); // Assert basketMock.Verify(x => x.UpdateBasket(It.Is<List<ProductsInBasket>>(x =>x[0].Quantity == 4), customerId)); } [Fact] public async Task AddProductsToBasket_ShouldReturnOk() { // Arrange int quantity = 1; int customerId = 1; int productId = 1; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)).Returns<BasketWithGoods>(null); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(new Product()); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act var expected = await basketService.AddProductsToBasket(customerId, productId, quantity); // Assert expected.Status.Should().Be(Status.Ok); } [Fact] public async Task AddProductsToBasket_ShouldUpdateProductIdAndQuantityOfProducts() { // Arrange int customerId = 1; int productId = 2; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)).Returns(new BasketWithGoods { CustomerId = customerId, ProductIds = new List<ProductsInBasket> { new ProductsInBasket { ProductId = 1, Quantity = 1 } } }); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(new Product()); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act await basketService.AddProductsToBasket(1, 2, 3); // Assert basketMock.Verify(x => x.UpdateBasket(It.Is<List<ProductsInBasket>>(x => x[1].Quantity == 3), customerId)); basketMock.Verify(x => x.UpdateBasket(It.Is<List<ProductsInBasket>>(x => x[1].ProductId == 2), customerId)); } [Fact] public async Task GetCurrentBasketProducts_ShouldReturnBasketResponse() { // Arrange var customerId = 1; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)).Returns(new BasketWithGoods { CustomerId = customerId, ProductIds = new List<ProductsInBasket> { new ProductsInBasket { ProductId = 1, Quantity = 1 } } }); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); var customer = new Customer { FirstName = "Jan", LastName = "Nowak", Age = 23, CustomerId = 1 }; customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer { FirstName = "Jan", LastName = "Nowak", Age = 23, CustomerId = 1 }); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(customerId)).ReturnsAsync(new Product { Name = "Abecadlo", Price = 200, ProductId = 1 }); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); BasketResponse basketResponse = new BasketResponse(); // Act var expected = await basketService.GetCurrentBasketProducts(customerId); // Assert expected.Value.Customer.Should().BeEquivalentTo(customer); expected.Value.Product.Should().BeEquivalentTo(new List<ProductResponse> { new ProductResponse {Quantity = 1, Details = new Product {Name = "Abecadlo", Price = 200, ProductId = 1}} }); } [Fact] public async Task GetCurrentBasketProducts_ShouldReturnStatusNotFoundWhenBasketIsNull() { // Arrange var customerId = 1; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); var customer = new Customer { FirstName = "Jan", LastName = "Nowak", Age = 23, CustomerId = 1 }; customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer { FirstName = "Jan", LastName = "Nowak", Age = 23, CustomerId = 1 }); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(customerId)).ReturnsAsync(new Product { Name = "Abecadlo", Price = 200, ProductId = 1 }); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); BasketResponse basketResponse = new BasketResponse(); // Act var expected = await basketService.GetCurrentBasketProducts(customerId); // Assert expected.Status.Should().Be(Status.NotFound); } [Theory] [InlineData(0, Status.BadRequest)] [InlineData(-1, Status.BadRequest)] public async Task UpdateQuantityOfProductsInBasket_ShouldReturnBadRequestWhenQuantityIsLessThenOrEqualZero(int quantity, Status result) { // Arrange int customerId = 1; int productId = 1; var basketWithGoods = new BasketWithGoods { CustomerId = customerId, ProductIds = new List<ProductsInBasket> { new ProductsInBasket { ProductId = 1, Quantity = 1 } } }; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)).Returns(basketWithGoods); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(new Product()); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act var expected = await basketService.UpdateQuantityOfProductsInBasket(customerId, productId, quantity); // Assert expected.Status.Should().Be(result); } [Fact] public async Task UpdateQuantityOfProductsInBasket_ShouldReturnNotFoundWhenBasketIsNull() { // Arrange int quantity = 1; int customerId = 1; int productId = 1; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(new Product()); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act var expected = await basketService.UpdateQuantityOfProductsInBasket(customerId, productId, quantity); // Assert expected.Status.Should().Be(Status.NotFound); } [Fact] public async Task UpdateQuantityOfProductsInBasket_ShouldReturnNotFoundWhenProductIsNotFound() { // Arrange int quantity = 1; int customerId = 1; int productId = 1; var basketWithGoods = new BasketWithGoods { CustomerId = customerId, ProductIds = new List<ProductsInBasket> { new ProductsInBasket { ProductId = 1, Quantity = 1 } } }; var basketMock = new Mock<IBasketRepository>(); basketMock.Setup(x => x.GetBasket(customerId)).Returns(basketWithGoods); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(default (Product)); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act var expected = await basketService.UpdateQuantityOfProductsInBasket(customerId, productId, quantity); // Assert expected.Status.Should().Be(Status.NotFound); } [Fact] public async Task UpdateQuantityOfProductsInBasket_ShouldOnlyUpdateQuantityOfProductsInBasket() { // Arrange int customerId = 1; int productId = 1; var basketMock = new Mock<IBasketRepository>(); var basketWithGoods = new BasketWithGoods { CustomerId = customerId, ProductIds = new List<ProductsInBasket> { new ProductsInBasket { ProductId = 1, Quantity = 1 } } }; basketMock.Setup(x => x.GetBasket(customerId)).Returns(basketWithGoods); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(new Product()); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act await basketService.UpdateQuantityOfProductsInBasket(1, 1, 3); // Assert basketWithGoods.ProductIds[0].Quantity.Should().Be(4); } [Fact] public async Task UpdateQuantityOfProductsInBasket_ShouldUpdateProductsAndQuantityOfProductsInBasket() { // Arrange var customerId = 1; var productId = 1; var basketMock = new Mock<IBasketRepository>(); var basketWithGoods = new BasketWithGoods { CustomerId = customerId, ProductIds = new List<ProductsInBasket> { new ProductsInBasket { ProductId = 1, Quantity = 1 } } }; basketMock.Setup(x => x.GetBasket(customerId)).Returns(basketWithGoods); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(productId)).ReturnsAsync(new Product { Name = "test", Price = 20, ProductId = 1 }); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act await basketService.UpdateQuantityOfProductsInBasket(1, 1, 4); // Assert basketWithGoods.ProductIds.Should().HaveCount(1); basketWithGoods.ProductIds[0].Quantity.Should().Be(5); basketWithGoods.ProductIds[0].ProductId.Should().Be(1); } [Theory] [InlineData(1, Status.Ok)] [InlineData(2, Status.BadRequest)] public void RemoveFromBasket_ShouldRemoveProductFromBasket(int productId, Status result) { // Arrange var customerId = 1; var basketMock = new Mock<IBasketRepository>(); var basketWithGoods = new BasketWithGoods { CustomerId = customerId, ProductIds = new List<ProductsInBasket> { new ProductsInBasket { ProductId = 1, Quantity = 1 } } }; basketMock.Setup(x => x.GetBasket(customerId)).Returns(basketWithGoods); var customerDetailsRepositoryMock = new Mock<ICustomerDetailsRepository>(); customerDetailsRepositoryMock.Setup(x => x.GetCustomer(customerId)).ReturnsAsync(new Customer()); var productDetailsRepositoryMock = new Mock<IProductDetailsRepository>(); productDetailsRepositoryMock.Setup(x => x.GetProductAsync(customerId)).ReturnsAsync(new Product()); var basketService = new BasketService(basketMock.Object, customerDetailsRepositoryMock.Object, productDetailsRepositoryMock.Object); // Act var expected = basketService.RemoveFromBasket(customerId, productId); // Assert expected.Status.Should().Be(result); } } }
JavaScript
UTF-8
485
3.453125
3
[]
no_license
function setup() { createCanvas(400, 300) background(215); //noFill(); } function draw() { for ( var i = 30; i > 0; i--) { circle(200, 150, i * 10); } } //code examples from lecture //var randColor = Math.random() * 255; //fill(randColor); //stroke(255 - (i * 15)); /*let i = 0; while(i < 5) { console.log(i); i++; document.write(i); } console.log(i); */
Java
UTF-8
4,725
2.0625
2
[]
no_license
package cn.deepcoding.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.dingtalk.api.DefaultDingTalkClient; import com.dingtalk.api.DingTalkClient; import com.dingtalk.api.request.CorpRoleSimplelistRequest; import com.dingtalk.api.request.OapiDepartmentGetRequest; import com.dingtalk.api.request.OapiUserGetRequest; import com.dingtalk.api.request.OapiUserSimplelistRequest; import com.dingtalk.api.response.CorpRoleSimplelistResponse; import com.dingtalk.api.response.OapiDepartmentGetResponse; import com.dingtalk.api.response.CorpRoleSimplelistResponse.EmpSimpleList; import com.dingtalk.api.response.OapiUserGetResponse; import com.dingtalk.api.response.OapiUserSimplelistResponse; import com.dingtalk.api.response.OapiUserSimplelistResponse.Userlist; import com.taobao.api.ApiException; public class DingtalkUserIdList { //获取角色下员工列表 // public static List<String> getDingtalkUserIdList(){ // DingTalkClient client = new DefaultDingTalkClient("https://eco.taobao.com/router/rest"); // CorpRoleSimplelistRequest req = new CorpRoleSimplelistRequest(); // req.setRoleId(328734018L); // req.setSize(20L); // req.setOffset(0L); // CorpRoleSimplelistResponse rsp = null; // try { // rsp = client.execute(req, AccessToken.getAccessToken()); // } catch (ApiException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // List<EmpSimpleList> empSimpleList = rsp.getResult().getList(); // List<String> userIdList = new ArrayList<String>(); // empSimpleList.forEach(empSimple->{ // userIdList.add(empSimple.getUserid()); // }); // return userIdList; // } //获取员工详细信息 public static Map<String,List<String>> getUser(String userID) throws ApiException{ Map<String,List<String>> map = new HashMap<String,List<String>>(); DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get"); OapiUserGetRequest request = new OapiUserGetRequest(); request.setUserid(userID); request.setHttpMethod("GET"); OapiUserGetResponse response = client.execute(request, AccessToken.getAccessToken()); List<Long> listDepartment = response.getDepartment(); List<String> list = new ArrayList<String>(); listDepartment.forEach(action->{ try { list.add(DingtalkUserIdList.getDepartmentName(action)); } catch (ApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); map.put(response.getName(),list); return map; } //获取部门名字 public static String getDepartmentName(Long id) throws ApiException{ DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/get"); OapiDepartmentGetRequest request = new OapiDepartmentGetRequest(); request.setId(id.toString()); request.setHttpMethod("GET"); OapiDepartmentGetResponse response = client.execute(request, AccessToken.getAccessToken()); return response.getName(); } // 获取部门下的用户 public static List<String> getDingtalkUserIdList(){ Long i = 1l; Long j = 100l; List<String> userIdList = new ArrayList<String>(); // 暂时 查询 1000 条数据 for(int h = 0;h<10;h++){ Map<String,String> map = new HashMap<String,String>(); DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/simplelist"); OapiUserSimplelistRequest request = new OapiUserSimplelistRequest(); // 研发部 id request.setDepartmentId(77163152L); request.setOffset(i); request.setSize(j); request.setHttpMethod("GET"); OapiUserSimplelistResponse response = null; try { response = client.execute(request, AccessToken.getAccessToken()); } catch (ApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<Userlist> userlist = response.getUserlist(); for (Userlist userlist2 : userlist) { userIdList.add(userlist2.getUserid()); } i +=j; } return userIdList; } public static void main(String[] args) throws Exception { List<String> dingtalkUserIdList = getDingtalkUserIdList(); List<String> smallUserIdList = new ArrayList<String>(); int num =0; int sum = 0; for(int i =0;i<dingtalkUserIdList.size()/8;i++){ smallUserIdList=dingtalkUserIdList.subList(num, num+8); num=num+8; sum +=1; System.out.println(smallUserIdList.get(0)+" "+sum); } System.out.println(sum); System.out.println(smallUserIdList.size()); for (String string : dingtalkUserIdList) { System.out.println(string); } } }
Python
UTF-8
5,195
2.703125
3
[]
no_license
from collections import OrderedDict from enum import Enum __all__ = ['Permission', 'preset_for_superuser', 'preset_for_author'] class Group: flags = [] name = None def __init__(self, name, flags): self.name = name self.flags = flags class Flag: value = None description = None def __init__(self, bit, description): self.value = 1 << bit self.description = description class Permission(Enum): __groups__ = OrderedDict() CONFIGURE_SYSTEM = Flag(1, '') READ_USER = Flag(4, '') CREATE_USER = Flag(5, '') MODIFY_USER = Flag(6, '') MODIFY_OTHER_USER = Flag(7, '') DELETE_USER = Flag(8, '') READ_ARTICLE = Flag(8 + 1, '') POST_ARTICLE = Flag(8 + 2, '') EDIT_ARTICLE = Flag(8 + 3, '') EDIT_OTHERS_ARTICLE = Flag(8 + 4, '') READ_CATEGORY = Flag(8 + 5, '') CREATE_CATEGORY = Flag(8 + 6, '') EDIT_CATEGORY = Flag(8 + 7, '') EDIT_OTHERS_CATEGORY = Flag(8 + 8, '') READ_COMMENT = Flag(16 + 1, '') WRITE_COMMENT = Flag(16 + 2, '') REVIEW_COMMENT = Flag(16 + 3, '') REIVEW_OTHERS_COMMENT = Flag(16 + 4, '') @classmethod def add_group(cls, name, flags): """Group flags. :param name: group name :param iterable flags: a iterable object contains :class:`FLag` """ flags_list = [] for flag in flags: flag_dict = OrderedDict() flag_dict['name'] = flag._name_ flag_dict['description'] = flag.value.description flags_list.append(flag_dict) cls.__groups__[name] = flags_list @classmethod def get_groups(cls): return cls.__groups__ @classmethod def format_permission(cls, permission_value): """Convert numberic permission value to a list of permission flags. :param int permission_value: :return: a list contains permission flags. :rtype: list """ return [ permission.name for permission in cls if permission_value & permission.value ] @classmethod def parse_permission(cls, permission_list): """Convert permission flags to a numberic permission value. The undefined permission will be ignored. :param iterable permission_list: an iterable object, contains permission flags defined in :class:``Permission`` :return: permission value :rtype: int """ permission_value = 0 for permission in permission_list: try: permission_value |= cls[permission].value except KeyError: pass return permission_value def __or__(self, flag_int): if isinstance(flag_int, Permission): return self.value.value | flag_int.value.value return self.value.value | flag_int def __xor__(self, flag_int): if isinstance(flag_int, Permission): return self.value.value ^ flag_int.value.value return self.value.value ^ flag_int def __and__(self, flag_int): if isinstance(flag_int, Permission): return self.value.value & flag_int.value.value return self.value.value & flag_int def __ror__(self, other): return other | self.value.value def __rxor__(self, other): return other ^ self.value.value def __rand__(self, other): return other & self.value.value Permission.add_group( name='System Configuration', flags=[Permission.CONFIGURE_SYSTEM] ) Permission.add_group( name='User Operation', flags=[ Permission.READ_USER, Permission.CREATE_USER, Permission.MODIFY_USER, Permission.MODIFY_OTHER_USER, Permission.DELETE_USER ] ) Permission.add_group( name='Article Operation', flags=[ Permission.READ_ARTICLE, Permission.POST_ARTICLE, Permission.EDIT_ARTICLE, Permission.EDIT_OTHERS_ARTICLE ] ) Permission.add_group( name='Category Operation', flags=[ Permission.READ_CATEGORY, Permission.CREATE_CATEGORY, Permission.EDIT_CATEGORY, Permission.EDIT_OTHERS_CATEGORY ] ) Permission.add_group( name='Comment Operation', flags=[ Permission.READ_COMMENT, Permission.WRITE_COMMENT, Permission.REVIEW_COMMENT, Permission.REIVEW_OTHERS_COMMENT ] ) """Preset permission for Superuser: All""" preset_for_superuser = int('1' * 63, 2) """Preset permission for Author: * READ_ARTICLE * POST_ARTICLE * EDIT_ARTICLE * READ_CATEGORY * POST_CATEGORY * EDIT_CATEGORY * READ_COMMENT * READ_ALL_COMMENT * WRITE_COMMENT * REVIEW_COMMENT """ preset_for_author = Permission.parse_permission([ Permission.READ_ARTICLE, Permission.POST_ARTICLE, Permission.EDIT_ARTICLE, Permission.READ_CATEGORY, Permission.CREATE_CATEGORY, Permission.EDIT_CATEGORY, Permission.READ_COMMENT, Permission.WRITE_COMMENT, Permission.REVIEW_COMMENT ]) if __name__ == '__main__': from json import dumps print(dumps(Permission.get_groups(), indent=2))
JavaScript
UTF-8
773
4.6875
5
[]
no_license
function reverseAnArrayOfNumbers(index, inputArr) { let outputArr = []; for (let i = 0; i < index; i++) { outputArr.push(inputArr[i]); } let result = outputArr.reverse().toString().replace(/[/,/]/g," "); console.log(result); } reverseAnArrayOfNumbers(3, [10, 20, 30, 40, 50]); reverseAnArrayOfNumbers(4, [-1, 20, 99, 5]); reverseAnArrayOfNumbers(2, [66, 43, 75, 89, 47]); /*⦁ Reverse an Array of Numbers Write a program which receives a number n and an array of elements. Your task is to create a new array with n numbers, reverse it and print its elements on a single line, space separated. Examples Input 3, [10, 20, 30, 40, 50] Output 30 20 10 Input 4, [-1, 20, 99, 5] Output 5 99 20 -1 Input 2, [66, 43, 75, 89, 47] Output 43 66 */
Python
UTF-8
303
4.09375
4
[]
no_license
#generator is an iterator def week(): days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] for day in days_of_week: yield day c = week() print(next(c)) print(next(c)) print(next(c)) print(next(c)) print(next(c)) print(next(c)) print(next(c))
Markdown
UTF-8
6,477
3.265625
3
[ "Apache-2.0" ]
permissive
# tkthread Easy multithreading with Tkinter on CPython 2.7/3.x and PyPy 2.7/3.x. import tkthread; tkthread.patch() # do this before importing tkinter ## Background The Tcl/Tk language that comes with Python follows a different threading model than Python itself which can raise obtuse errors when mixing Python threads with Tkinter, such as: RuntimeError: main thread is not in main loop RuntimeError: Calling Tcl from different apartment NotImplementedError: Call from another thread Tcl can have many isolated interpreters, and each are tagged to the its particular OS thread when created. Python's `_tkinter` module checks if the calling Python thread is different than the Tcl/Tk thread, and if so, [waits one second][WaitForMainloop] for the Tcl/Tk main loop to begin dispatching. If there is a timeout, a RuntimeError is raised. On PyPy, a [NotImplementedError][PyPyNotImplemented] is raised. For non-Tk calls into Tcl, Python will raise an apartment RuntimeError when calling a Tcl interpreter from a different thread. A common approach to avoid these errors involves using `.after` to set up [periodic polling][PollQueue] of a [message queue][PollRecipe] from the Tcl/Tk main loop, which can slow the responsiveness of the GUI. The initial approach used in `tkthread` is to use the Tcl/Tk `thread::send` messaging to notify the Tcl/Tk main loop of a call for execution. This interrupt-style architecture has lower latency and better CPU utilization than periodic polling. This works with CPython and PyPy. The newer approach used in `tkthread` is to use `tkthread.tkinstall()` to patch Tkinter when make calls into Tcl/Tk. This only works on CPython and it does not require the `Thread` package in Tcl. ## Usage on CPython (simplest) For CPython 2.7/3.x, `tkthread.patch()` (same as `tkthread.tkinstall()`) can be called first, and will patch Tkinter to re-route threaded calls to the Tcl interpreter using the `willdispatch` internal API call. import tkthread; tkthread.patch() import tkinter as tk root = tk.Tk() import threading def thread_run(func): threading.Thread(target=func).start() @thread_run def func(): root.wm_title(threading.current_thread()) @tkthread.main(root) @tkthread.current(root) def testfunc(): tk.Label(text=threading.current_thread()).pack() root.mainloop() ## Usage on CPython/PyPy (compatibility/legacy) The `tkthread` module provides the `TkThread` class, which can synchronously interact with the main thread. from tkthread import tk, TkThread root = tk.Tk() # create the root window tkt = TkThread(root) # make the thread-safe callable import threading, time def run(func): threading.Thread(target=func).start() run(lambda: root.wm_title('FAILURE')) run(lambda: tkt(root.wm_title,'SUCCESS')) root.update() time.sleep(2) # _tkinter.c:WaitForMainloop fails root.mainloop() The `tkt` instance is callable, and will wait for the Tcl/Tk main loop to execute and compute a result which is then passed back for return in the calling thread. A non-synchronous version also exists that does not block: tkt.nosync(root.wm_title, 'ALSO SUCCESS') There is an optional `tkt.install()` method which intercepts Python-to-Tk calls. This must be called on the default root, before the creation of child widgets. If installed, then wrapping Tk widget calls in threaded code with `tkt` is not necessary. There is, however, a slight performance penalty for Tkinter widgets that operate only on the main thread because of the thread-checking indirection. The `root` Tcl/Tk interpreter must be the primary interpreter on the main thread. If it is not, then you will receive a TclError of the form: _tkinter.TclError: invalid command name "140520536224520_call_from" For example, creating several `Tk()` instances and then using TkThread on those will cause this error. A good practice is to create a root window and then call `root.withdraw()` to keep the primary Tcl/Tk interpreter active. Future Toplevel windows use `root` as the master. ## Install pip install tkthread ## API - `tkthread.patch()` - patch Tkinter to support multi-threading. - `tkthread.tkinstall()` - same as `.patch()` - `tkthread.call(func, *args, **kw)` - call `func` on the main thread, with arguments and keyword arguments. - waits for return value (or raises error) - `tkthread.call_nosync(func, *args, **kw)` - call `func` on the main thread, with arguments and keyword arguments. - returns immediately, ignore return `func` return or error. - `@tkthread.called_on_main` - decorator to dispatch the function call on the main thread from the calling thread. - `@tkthread.main()` - decorator to call a function immediately on the main thread. - `@tkthread.current()` - decorator to call a function immediately on the current thread. - `TkThread(root)` - class to dispatch thread calls to Tk using `thread::send` ## Known (and solved) Error Messages You may receive this error when using `tkthread.TkThread(root)`: _tkinter.TclError: can't find package Thread This means that Python's Tcl/Tk libraries do not include the `Thread` package, which is needed by `TkThread`. On Debian/Ubuntu: apt install tcl-thread On Windows, you'll need to manually update your Tcl installation to include the `Thread` package. The simpler solution is to use `tkthread.patch()` instead. When using Matplotlib, you may receive a warning message that can be ignored: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail. The `demo/mpl_plot.py` script shows an example with this message. ## License Licensed under the Apache License, Version 2.0 (the "License") ## See Also These libraries offer similar functionality, using periodic polling: * https://github.com/RedFantom/mtTkinter * https://github.com/abarnert/mttkinter * https://pypi.org/project/threadsafe-tkinter [PollQueue]: http://effbot.org/zone/tkinter-threads.htm [PollRecipe]: https://www.oreilly.com/library/view/python-cookbook/0596001673/ch09s07.html [WaitForMainloop]: https://github.com/python/cpython/blob/38df97a03c5102e717a110ab69bff8e5c9ebfd08/Modules/_tkinter.c#L342 [PyPyNotImplemented]: https://bitbucket.org/pypy/pypy/src/d19ac6eec77b4e1859ab3dd8a5843989c4d4df99/lib_pypy/_tkinter/app.py?fileviewer=file-view-default#app.py-281
Shell
UTF-8
2,727
4.25
4
[]
no_license
# /bin/sh function help() { echo "This is a simple wrapper around trash-cli: https://github.com/andreafrancia/trash-cli" echo echo "Usage:" echo " trash [ACTION] [OPTIONS]... [FILE]..." echo echo "Actions available:" echo " put, list, empty, restore, uninstall, help" echo echo "Example usage:" echo " trash put FILE: move file(s) to trashcan" echo " trash FILE: shortcut for trash put FILE" echo " trash list: list files in trashcan" echo " trash empty: empty the trashcan" echo " trash restore: restore file(s) from the trashcan" echo " trash uninstall: uninstall this wrapper and use the vanilla trash-cli" echo " trash help: show this help message again" echo " trash ACTION --help: show individual help message for the above actions" } function install() { echo "trash is about to be installed following the two steps below:" echo " 1." "$t_path" "will be copied to" "$tcli_path_f" echo " 2." "$script_path" "will be copied to" "$t_path" echo read -p "Proceed? [Y/n] " -n 1 -r echo if [[ $REPLY =~ ^[Yy]$ ]] || [[ -z $REPLY ]]; then cp $t_path $tcli_path_f cp $script_path $t_path if [ $? -eq 0 ]; then echo "All set. You can start using trash now." else tput setaf 1 echo "Something went wrong." tput sgr0 fi fi } function uninstall() { echo "trash is about to be uninstalled following the two steps below:" echo " 1." "$t_path" "will be moved to trashcan" echo " 2." "$tcli_path" "will be moved $t_path" echo "You will be using the vanilla trash-cli after this operation." echo read -p "Proceed? [Y/n] " -n 1 -r echo if [[ $REPLY =~ ^[Yy]$ ]] || [[ -z $REPLY ]]; then trash-put $t_path mv $tcli_path $t_path if [ $? -eq 0 ]; then echo "All set. Farewell :-)" else tput setaf 1 echo "Something went wrong." tput sgr0 fi fi } function trash() { if [ $# -gt 0 ]; then case $1 in "list") shift trash-list $@;; "empty") tput setaf 1 read -p "Are you sure? This can not be undone. [Y/n] " -n 1 -r tput sgr0 echo if [[ $REPLY =~ ^[Yy]$ ]] || [[ -z $REPLY ]]; then shift trash-empty $@ fi;; "restore") shift trash-restore $@;; "put") shift trash-put $@;; "uninstall") uninstall;; "help") help;; *) trash-put $@ esac else trash-put fi } t_path="$(which trash)" p_path="$(dirname "$t_path")" tcli_path_f=$p_path/"trash-cli" tcli_path="$(which trash-cli)" script_dir="$( cd "$( dirname "$0" )" >/dev/null && pwd )" script_path="$script_dir/$(basename $0)" if [ -z $t_path ]; then echo "trash-cli is not installed. Please get it from https://github.com/andreafrancia/trash-cli first." exit 1 fi if [ -z $tcli_path ]; then install else trash $@ fi
C
UTF-8
1,683
3.1875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_memccpy.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rcenamor <rcenamor@student.hive.fi> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/17 14:36:16 by rcenamor #+# #+# */ /* Updated: 2020/01/21 16:02:48 by rcenamor ### ########.fr */ /* */ /* ************************************************************************** */ /* ** Replicates memccpy (string.h). ** ** Copies bytes from string src to string dst. If the character c (as ** converted to an unsigned char) occurs in the string src, the copy stops. ** Otherwise, n bytes are copied. The source and destination strings ** should not overlap, as the behavior is undefined. ** ** Returns the pointer to the byte after the copy of c in the string dst ** (if the character was found); otherwise, returns NULL. */ #include "libft.h" void *ft_memccpy(void *dst, const void *src, int c, size_t n) { unsigned char *d; const unsigned char *s; if (!dst && !src) return (NULL); d = (unsigned char *)dst; s = (const unsigned char *)src; while (n) { *d = *s; if (*d == (unsigned char)c) { d++; return ((void *)d); } d++; s++; n--; } return (NULL); }
PHP
UTF-8
561
2.59375
3
[]
no_license
<?php require_once dirname(__FILE__) . '/MySQL.php'; require_once dirname(__FILE__) . '/Job.php'; class Follower extends MySQL { public $table = 'follower'; public $schema = array( 'facebook_id' => '', 'name' => 'No name', 'power' => 0, 'money' => 0, 'pic' => '', 'job_name' => 'NEET' // 仮置き ); public function __construct() { $this->setJobAtRandom(); parent::__construct(); } public function setJobAtRandom() { $this->schema['job_name'] = Job::getJob('1234'); return $this->schema['job_name']; } }
PHP
UTF-8
2,234
2.53125
3
[]
no_license
<?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' ); class Post_model extends CI_Model { public function create($text,$image,$posttype,$link) { $data = array( 'text' => $text, 'posttype' => $posttype, 'link' => $link, 'image' => $image ); $query=$this->db->insert( 'post', $data ); $id=$this->db->insert_id(); if(!$query) return 0; else return 1; } function viewpost() { $query="SELECT `id`, `name` FROM `post`"; $query=$this->db->query($query)->result(); return $query; } public function beforeedit( $id ) { $this->db->where( 'id', $id ); $query=$this->db->get( 'post' )->row(); return $query; } public function edit($id,$text,$image,$posttype,$link) { $data = array( 'text' => $text, 'posttype' => $posttype, 'link' => $link, 'image' => $image ); $this->db->where( 'id', $id ); $query=$this->db->update( 'post', $data ); return 1; } function deletepost($id) { $query=$this->db->query("DELETE FROM `post` WHERE `id`='$id'"); } public function getpostimagebyid($id) { $query=$this->db->query("SELECT `image` FROM `post` WHERE `id`='$id'")->row(); return $query; } public function getpostdropdown() { $query=$this->db->query("SELECT * FROM `post` ORDER BY `id` ASC")->result(); $return=array( ); foreach($query as $row) { $return[$row->id]=$row->text; } return $return; } public function getposttypedropdown() { $query=$this->db->query("SELECT * FROM `posttype` ORDER BY `id` ASC")->result(); $return=array( ); foreach($query as $row) { $return[$row->id]=$row->name; } return $return; } public function viewquickpost() { $data=$this->db->query("SELECT `post`.`id` AS `id` , `post`.`text` AS `text` , `post`.`image` AS `image` ,`posttype`.`name` as `posttypename`, `post`.`posttype` AS `posttype` , `userpost`.`returnpostid` AS `returnpostid`, `post`.`link` AS `link` FROM `post` LEFT OUTER JOIN `posttype` ON `posttype`.`id`=`post`.`posttype` LEFT OUTER JOIN `userpost` ON `userpost`.`post`=`post`.`id` GROUP BY `post`.`id` ORDER BY `id` ASC, 1 LIMIT 0,10")->result(); return $data; } } ?>
C++
UTF-8
2,411
3.625
4
[ "MIT" ]
permissive
/* Yehuda Neumann 305539066 */ /* Adiel Matuf 307895268 */ #include "Player.h" Player :: Player(string name, int num_of_cards): _name(name), _num_of_cards (num_of_cards){ // create a vector of cards. for (int i = 0; i < _num_of_cards; i++) { this->_vec_of_cards.push_back(Card::generate_card()); } } Player::Player(const Player& player){ // copy name this->_name = player.get_name(); // copy cards. this->_vec_of_cards.assign(player._vec_of_cards.begin(), player._vec_of_cards.end()); } Player::~Player(){ // delete all cards from vector. _vec_of_cards.clear(); } bool Player :: play(Card& current){ // true - if player put a legal card, false - took a card int choosen_card; // choose a card. std::cin >> choosen_card; //draw a card. if(draw_card(choosen_card)) return false; // otherwise, check if legal while (!current.is_legal(_vec_of_cards.at(choosen_card-1))){ std::cout << "You can't put " << _vec_of_cards.at(choosen_card-1); std::cout << " on " << current << std::endl; // choose a card. std::cin >> choosen_card; //draw a card. if(draw_card(choosen_card)) return false; } // set choosen as a chosen card. current = _vec_of_cards.at(choosen_card-1); // remove the choosen one. _vec_of_cards.erase(_vec_of_cards.begin() + (choosen_card-1)); return true; } int const Player::get_num_of_cards() const{ return _vec_of_cards.size(); } //returns player's number of cards string const Player::get_name() const{ return _name; } //returns player's name std::ostream& operator << (std::ostream &os, const Player &p){ os << p.get_name() << ", your turn -" << std::endl; os << "Your cards:"; for (int i = 0; i < p.get_num_of_cards(); i++) { os << " (" << i+1 <<")" << p._vec_of_cards.at(i); } return os; } bool Player::draw_card(int choosen_card){ if(choosen_card < 1 || choosen_card > _vec_of_cards.size()){ _vec_of_cards.push_back(Card::generate_card()); return true; } return false; }
Java
UTF-8
3,871
2.25
2
[]
no_license
package net.cactii.target; import java.io.File; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.cactii.target.SavedGame.SavedGameState; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.graphics.Typeface; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.TextView; public class SavedGameListAdapter extends BaseAdapter { public static final String SAVEDGAME_DIR = "/data/data/net.cactii.target/"; public ArrayList<String> mGameFiles; private LayoutInflater inflater; private SavedGameList mContext; private Typeface mFace; public SavedGameListAdapter(SavedGameList context) { this.inflater = LayoutInflater.from(context); this.mContext = context; this.mGameFiles = new ArrayList<String>(); this.mFace=Typeface.createFromAsset(context.getAssets(), "fonts/font.ttf"); this.refreshFiles(); } /* public class SortSavedGames implements Comparator<String> { long save1 = 0; long save2 = 0; public int compare(String object1, String object2) { try { save1 = new SavedGame(SAVEDGAME_DIR + "/" + object1).ReadDate(); save2 = new SavedGame(SAVEDGAME_DIR + "/" + object2).ReadDate(); } catch (Exception e) { // } return (int) (save2 - save1); } } */ public void refreshFiles() { this.mGameFiles.clear(); File dir = new File(SAVEDGAME_DIR); String[] allFiles = dir.list(); for (String entryName : allFiles) if (entryName.startsWith("savedgame_")) this.mGameFiles.add(entryName); //Collections.sort((List<String>)this.mGameFiles, new SortSavedGames()); } public int getCount() { return this.mGameFiles.size() + 1; } public Object getItem(int arg0) { if (arg0 == 0) return ""; return this.mGameFiles.get(arg0-1); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { if (position == 0) { convertView = inflater.inflate(R.layout.savedgamesaveitem, null); final Button saveCurrent = (Button)convertView.findViewById(R.id.saveCurrent); saveCurrent.setOnClickListener(new OnClickListener() { public void onClick(View v) { saveCurrent.setEnabled(false); mContext.saveCurrent(); } }); if (mContext.mCurrentSaved) saveCurrent.setEnabled(false); return convertView; } convertView = inflater.inflate(R.layout.savedgameitem, null); TargetGridView grid = (TargetGridView)convertView.findViewById(R.id.savedGridView); final String saveFile = SAVEDGAME_DIR + "/" + this.mGameFiles.get(position-1); grid.mContext = this.mContext; SavedGame saver = new SavedGame(); try { TextView wordCounts = (TextView)convertView.findViewById(R.id.savedWordCounts); SavedGameState sgs = saver.RestoreGrid(saveFile); grid.setLetters(sgs.currentShuffled); wordCounts.setText("Target: " + sgs.validWords + "\n\nYou: " + sgs.playerWords); } catch (Exception e) { // Error, delete the file. new File(saveFile).delete(); return convertView; } grid.setBackgroundColor(0xFFFFFFFF); Button loadButton = (Button)convertView.findViewById(R.id.gameLoad); loadButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mContext.LoadGame(saveFile); } }); Button deleteButton = (Button)convertView.findViewById(R.id.gameDelete); deleteButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mContext.DeleteGame(saveFile); } }); return convertView; } }
Python
UTF-8
1,270
2.734375
3
[]
no_license
import numpy as np import cv2 as cv import argparse import sys cap = cv.VideoCapture(0) if (cap.isOpened()== False): print("\nUnable to read camera feed") while(cap.isOpened()): # Capture frame-by-frame ret, frame = cap.read() gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # Video capture timestamp (milliseconds) vTime = cap.get(0) # 0-based index of the frame to be decoded/captured next vFrame = cap.get(1) # Relative position of the video file: (0 to 1) vRelPos = cap.get(2) # Height and width of frame #vWid = cap.get(3) #vHi = cap.get(4) desiredWidth = 240 desiredHeight = 180 ret = cap.set(3,desiredWidth) ret = cap.set(4,desiredHeight) # Frame rate (in Hz) vFrameRate = cap.get(5) desiredFrameRate = 1/10 #vFrameRate = cap.set(5,desiredFrameRate) # 4-character code of codec (I have no idea what this is) ret, Newframe = cap.read() cv.imshow('Frame',frame) cv.imshow('Grayscale',gray) cv.imshow('Modified Frame', ret) # Press Q on keyboard to exit if cv.waitKey(1000) & 0xFF == ord('q'): print("I closed because I said Q") break # When everything done, release the video capture object cap.release() cv.destroyAllWindows()
PHP
UTF-8
1,075
2.609375
3
[]
no_license
<?php class Signup_model extends CI_Model{ function __construct() { parent::__construct (); } public function add_signup() { date_default_timezone_set('UTC'); $now = date("Y-m-d H:i:s"); $data = array( 'username' => $this->input->post('username'), 'passwd' => $this->input->post('passwd'), 'sex' => $this->input->post('sex'), 'tell' => $this->input->post('tell'), 'eamil' => $this->input->post('eamil'), 'time' => $now, ); $this->db->insert('signin', $data); echo $this->db->platform(); } public function add_sign($name) { date_default_timezone_set('UTC'); $now = date("Y-m-d H:i:s"); $arr=array( 'username' => $name, //键是数据库的字段名 ); $query=$this->db->get_where('signin',$arr);//可以根据用户的名字和密码去查询数据库 return $query->row(); //查询的结果 } }
Java
UTF-8
5,483
4.125
4
[]
no_license
package epam.fundamentals.task2; /* * Упорядочить строки (столбцы) матрицы в порядке возрастания значений элементов k-го столбца (строки) */ import java.util.Random; public class App1 { public static void sortRandomNumbers(int[][] numbers) { System.out.println("\n*Упорядочить строки (столбцы) матрицы в порядке" + " возрастания значений элементов k-го столбца (строки)*"); Random random = new Random(); int sortRandom = random.nextInt(40) - 20; int sort; if (sortRandom % 2 == 0) { // если случайное число чётное, то сортируем столбец sort = random.nextInt(numbers[0].length); // № случайного столбца sortColumn(numbers, sort, sortRandom > 0); // сортируем столбец // печатаем массив, выделив цветом отсортированый столбец printNumbersColor(numbers, -1, sort); } else { // если случайное число не четное, то сортируем строку sort = random.nextInt(numbers.length); // № случайной строки sortLine(numbers, sort, sortRandom > 0); // сортируем строку // печатаем массив, выделив цветом отсортированую строку printNumbersColor(numbers, sort, -1); } } // сортировка строки private static void sortLine(int[][] numbers, int sort, boolean flag) { // sort - номер строки, которую будем сортировать // flag - сортируем по возрастанию или по убыванию System.out.println((sort + 1) + "-я строка матрицы отсортирована по " + (flag ? "возрастанию" : "убыванию")); for (int i = 0; i < numbers[0].length - 1; i++) { for (int j = i + 1; j < numbers[0].length; j++) { if (flag) { // сортируем по возрастанию if (numbers[sort][j] < numbers[sort][i]) { int tmp = numbers[sort][i]; numbers[sort][i] = numbers[sort][j]; numbers[sort][j] = tmp; } } else { // сортируем по убыванию if (numbers[sort][j] > numbers[sort][i]) { int tmp = numbers[sort][i]; numbers[sort][i] = numbers[sort][j]; numbers[sort][j] = tmp; } } } } } // Сортировка столбца private static void sortColumn(int[][] numbers, int sort, boolean flag) { // sort - номер строки, которую будем сортировать // flag - сортируем по возрастанию или по убыванию System.out.println((sort + 1) + "-й столбец матрицы отсортирован по " + (flag ? "возрастанию" : "убыванию")); for (int i = 0; i < numbers.length - 1; i++) { for (int j = i + 1; j < numbers.length; j++) { if (flag) { // сортируем по возрастанию if (numbers[j][sort] < numbers[i][sort]) { int tmp = numbers[i][sort]; numbers[i][sort] = numbers[j][sort]; numbers[j][sort] = tmp; } } else { // сортируем по убыванию if (numbers[j][sort] > numbers[i][sort]) { int tmp = numbers[i][sort]; numbers[i][sort] = numbers[j][sort]; numbers[j][sort] = tmp; } } } } } // Печать массива с возможностью выделения цветом строки и столбца public static void printNumbersColor(int[][] numbers, int lineColor, int columnColor) { /* line - номер строки, которую нужно выделить цветом * column - номер столбца, который надо выделить цветом * Если не нужно печатать цветом, то в качестве аргументов в метод необходимо * передать числа, которые точно не соответствует индексу массива. * Это отрицательное число, например -1 */ for (int line = 0; line < numbers.length; line++) { for (int column = 0; column < numbers[0].length; column++) { if (line == lineColor || column == columnColor) { System.out.print("\033[31;1m" + numbers[line][column] + "\033[0m" + " "); } else { System.out.print(numbers[line][column] + " "); } } System.out.println(); } } }
PHP
UTF-8
1,383
2.578125
3
[]
no_license
<?php namespace rain1208\tags; use Deceitya\MiningLevel\Event\MiningLevelUpEvent; use Deceitya\MiningLevel\MiningLevelAPI; use pocketmine\event\Listener; use pocketmine\event\player\PlayerJoinEvent; use pocketmine\plugin\PluginBase; use pocketmine\utils\Config; class Main extends PluginBase implements Listener { /** * @var Config */ private $Tag; /** * @var Config */ private $shop; public function onEnable() { if (!file_exists($this->getDataFolder())) { mkdir($this->getDataFolder(), 0744,true); } $this->shop = new Config($this->getDataFolder()."shop.yml",Config::YAML); $this->Tag = new Config($this->getDataFolder()."tags.yml",Config::YAML); tagShop::loadConfig($this->shop,$this->Tag); setTag::loadTags($this->Tag); $this->getServer()->getPluginManager()->registerEvents($this,$this); $this->getServer()->getPluginManager()->registerEvents(new tagShop(),$this); } public function onJoin(PlayerJoinEvent $event) { $player = $event->getPlayer(); $level = MiningLevelAPI::getInstance()->getLevel($player); new setTag($player,$level); } public function LevelUpEvent(MiningLevelUpEvent $event) { $player = $event->getPlayer(); $level = $event->getTo(); new setTag($player,$level); } }
Python
UTF-8
16,421
2.59375
3
[]
no_license
from django.test import TestCase # Create your tests here. from catalog.models import Director from django.urls import reverse class DirectorListViewTest(TestCase): @classmethod def setUpTestData(cls): # Create directors for pagination tests number_of_directors = 13 for director_id in range(number_of_directors): Director.objects.create(first_name='Christian {0}'.format(director_id), last_name='Surname {0}'.format(director_id)) def test_view_url_exists_at_desired_location(self): response = self.client.get('/catalog/directors/') self.assertEqual(response.status_code, 200) def test_view_url_accessible_by_name(self): response = self.client.get(reverse('directors')) self.assertEqual(response.status_code, 200) def test_view_uses_correct_template(self): response = self.client.get(reverse('directors')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'catalog/director_list.html') def test_pagination_is_ten(self): response = self.client.get(reverse('directors')) self.assertEqual(response.status_code, 200) self.assertTrue('is_paginated' in response.context) self.assertTrue(response.context['is_paginated'] is True) self.assertEqual(len(response.context['author_list']), 10) def test_lists_all_directors(self): # Get second page and confirm it has (exactly) the remaining 3 items response = self.client.get(reverse('directors')+'?page=2') self.assertEqual(response.status_code, 200) self.assertTrue('is_paginated' in response.context) self.assertTrue(response.context['is_paginated'] is True) self.assertEqual(len(response.context['director_list']), 3) import datetime from django.utils import timezone from catalog.models import MovieInstance, Movie, Genre, Country from django.contrib.auth.models import User # Required to assign User as a borrower class LoanedMovieInstancesByUserListViewTest(TestCase): def setUp(self): # Create two users test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK') test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD') test_user1.save() test_user2.save() # Create a movie test_director = Director.objects.create(first_name='John', last_name='Smith') test_genre = Genre.objects.create(name='Fantasy') test_country = Language.objects.create(name='Greate Britain') test_movie = Movie.objects.create( title='Movie Title', summary='My movie summary', isbn='ABCDEFG', director=test_director, country=test_country, ) # Create genre as a post-step genre_objects_for_movie = Genre.objects.all() test_movie.genre.set(genre_objects_for_movie) test_movie.save() # Create 30 MovieInstance objects number_of_movie_copies = 30 for movie_copy in range(number_of_movie_copies): return_date = timezone.now() + datetime.timedelta(days=movie_copy % 5) if movie_copy % 2: the_borrower = test_user1 else: the_borrower = test_user2 status = 'm' MovieInstance.objects.create(movie=test_movie, imprint='Unlikely Imprint, 2021', due_back=return_date, borrower=the_borrower, status=status) def test_redirect_if_not_logged_in(self): response = self.client.get(reverse('my-borrowed')) self.assertRedirects(response, '/accounts/login/?next=/catalog/mymovies/') def test_logged_in_uses_correct_template(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('my-borrowed')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) # Check we used correct template self.assertTemplateUsed(response, 'catalog/movieinstance_list_borrowed_user.html') def test_only_borrowed_movies_in_list(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('my-borrowed')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) # Check that initially we don't have any movies in list (none on loan) self.assertTrue('movieinstance_list' in response.context) self.assertEqual(len(response.context['movieinstance_list']), 0) # Now change all movies to be on loan get_ten_movies = MovieInstance.objects.all()[:10] for copy in get_ten_movies: copy.status = 'o' copy.save() # Check that now we have borrowed movies in the list response = self.client.get(reverse('my-borrowed')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) self.assertTrue('movieinstance_list' in response.context) # Confirm all movies belong to testuser1 and are on loan for movieitem in response.context['movieinstance_list']: self.assertEqual(response.context['user'], movieitem.borrower) self.assertEqual(movieitem.status, 'o') def test_pages_paginated_to_ten(self): # Change all movies to be on loan. # This should make 15 test user ones. for copy in MovieInstance.objects.all(): copy.status = 'o' copy.save() login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('my-borrowed')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) # Confirm that only 10 items are displayed due to pagination # (if pagination not enabled, there would be 15 returned) self.assertEqual(len(response.context['movieinstance_list']), 10) def test_pages_ordered_by_due_date(self): # Change all movies to be on loan for copy in MovieInstance.objects.all(): copy.status = 'o' copy.save() login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('my-borrowed')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) # Confirm that of the items, only 10 are displayed due to pagination. self.assertEqual(len(response.context['movieinstance_list']), 10) last_date = 0 for copy in response.context['movieinstance_list']: if last_date == 0: last_date = copy.due_back else: self.assertTrue(last_date <= copy.due_back) from django.contrib.auth.models import Permission # Required to grant the permission needed to set a movie as returned. class RenewMovieInstancesViewTest(TestCase): def setUp(self): # Create a user test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK') test_user1.save() test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD') test_user2.save() permission = Permission.objects.get(name='Set movie as returned') test_user2.user_permissions.add(permission) test_user2.save() # Create a movie test_director = Director.objects.create(first_name='John', last_name='Smith') test_genre = Genre.objects.create(name='Fantasy') test_country = Country.objects.create(name='Greate Britain') test_movie = Movie.objects.create(title='Movie Title', summary='My movie summary', isbn='ABCDEFG', director=test_director, country=test_country,) # Create genre as a post-step genre_objects_for_movie = Genre.objects.all() test_movie.genre.set(genre_objects_for_movie) test_movie.save() # Create a MovieInstance object for test_user1 return_date = datetime.date.today() + datetime.timedelta(days=5) self.test_movieinstance1 = MovieInstance.objects.create(movie=test_movie, imprint='Unlikely Imprint, 2021', due_back=return_date, borrower=test_user1, status='o') # Create a MovieInstance object for test_user2 return_date = datetime.date.today() + datetime.timedelta(days=5) self.test_movieinstance2 = MovieInstance.objects.create(movie=test_movie, imprint='Unlikely Imprint, 2021', due_back=return_date, borrower=test_user2, status='o') def test_redirect_if_not_logged_in(self): response = self.client.get(reverse('renew-movie-employer', kwargs={'pk': self.test_movieinstance1.pk})) # Manually check redirect (Can't use assertRedirect, because the redirect URL is unpredictable) self.assertEqual(response.status_code, 302) self.assertTrue(response.url.startswith('/accounts/login/')) def test_forbidden_if_logged_in_but_not_correct_permission(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('renew-movie-employer', kwargs={'pk': self.test_movieinstance1.pk})) self.assertEqual(response.status_code, 403) def test_logged_in_with_permission_borrowed_movie(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('renew-movie-employer', kwargs={'pk': self.test_movieinstance2.pk})) # Check that it lets us login - this is our movie and we have the right permissions. self.assertEqual(response.status_code, 200) def test_logged_in_with_permission_another_users_borrowed_movie(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('renew-movie-employer', kwargs={'pk': self.test_movieinstance1.pk})) # Check that it lets us login. We're a employer, so we can view any users movie self.assertEqual(response.status_code, 200) def test_uses_correct_template(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('renew-movie-employer', kwargs={'pk': self.test_movieinstance1.pk})) self.assertEqual(response.status_code, 200) # Check we used correct template self.assertTemplateUsed(response, 'catalog/movie_renew_employer.html') def test_form_renewal_date_initially_has_date_three_weeks_in_future(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('renew-movie-employer', kwargs={'pk': self.test_movieinstance1.pk})) self.assertEqual(response.status_code, 200) date_3_weeks_in_future = datetime.date.today() + datetime.timedelta(weeks=3) self.assertEqual(response.context['form'].initial['renewal_date'], date_3_weeks_in_future) def test_form_invalid_renewal_date_past(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') date_in_past = datetime.date.today() - datetime.timedelta(weeks=1) response = self.client.post(reverse('renew-movie-employer', kwargs={'pk': self.test_movieinstance1.pk}), {'renewal_date': date_in_past}) self.assertEqual(response.status_code, 200) self.assertFormError(response, 'form', 'renewal_date', 'Invalid date - renewal in past') def test_form_invalid_renewal_date_future(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') invalid_date_in_future = datetime.date.today() + datetime.timedelta(weeks=5) response = self.client.post(reverse('renew-movie-employer', kwargs={'pk': self.test_movieinstance1.pk}), {'renewal_date': invalid_date_in_future}) self.assertEqual(response.status_code, 200) self.assertFormError(response, 'form', 'renewal_date', 'Invalid date - renewal more than 4 weeks ahead') def test_redirects_to_all_borrowed_movie_list_on_success(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') valid_date_in_future = datetime.date.today() + datetime.timedelta(weeks=2) response = self.client.post(reverse('renew-movie-employer', kwargs={'pk': self.test_movieinstance1.pk}), {'renewal_date': valid_date_in_future}) self.assertRedirects(response, reverse('all-borrowed')) def test_HTTP404_for_invalid_movie_if_logged_in(self): import uuid test_uid = uuid.uuid4() # unlikely UID to match our movieinstance! login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('renew-movie-employer', kwargs={'pk': test_uid})) self.assertEqual(response.status_code, 404) class DirectorCreateViewTest(TestCase): """Test case for the DirectorCreate view (Created as Challenge).""" def setUp(self): # Create a user test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK') test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD') test_user1.save() test_user2.save() permission = Permission.objects.get(name='Set disk as returned') test_user2.user_permissions.add(permission) test_user2.save() # Create a movie test_director = Director.objects.create(first_name='John', last_name='Smith') def test_redirect_if_not_logged_in(self): response = self.client.get(reverse('director-create')) self.assertRedirects(response, '/accounts/login/?next=/catalog/director/create/') def test_forbidden_if_logged_in_but_not_correct_permission(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('director-create')) self.assertEqual(response.status_code, 403) def test_logged_in_with_permission(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('director-create')) self.assertEqual(response.status_code, 200) def test_uses_correct_template(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('director-create')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'catalog/director_form.html') def test_form_date_of_death_initially_set_to_expected_date(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('author-create')) self.assertEqual(response.status_code, 200) expected_initial_date = datetime.date(2021, 5, 11) response_date = response.context['form'].initial['date_of_death'] response_date = datetime.datetime.strptime(response_date, "%d/%m/%Y").date() self.assertEqual(response_date, expected_initial_date) def test_redirects_to_detail_view_on_success(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.post(reverse('author-create'), {'first_name': 'Christian Name', 'last_name': 'Surname'})
Markdown
UTF-8
1,378
3.953125
4
[]
no_license
# 如何跳出双重循环? ``` java for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... break; // Breaks out of the inner loop } } } ``` 上面的break只能跳出第一重循环 ## Answer 你可以给循环添加一个label ``` java outLoop: for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if(i == 2 && j == 2){ break outLoop; } } } ``` ## Answer 2 上面使用label的方法是正解,但是 在实践中你应该把你的双重循环 放在一个单独的函数中,然后使用return 退出函数 ``` java public class Test { public static void main(String[] args) { loop(); System.out.println("Done"); } public static void loop() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i * j > 6) { System.out.println("Breaking"); return; } System.out.println(i + " " + j); } } } } ``` ## Answer 3 我从来不我使用label,这回让代码 难以理解 ``` java boolean finished = false; for (int i = 0; i < 5 && !finished; i++) { for (int j = 0; j < 5; j++) { if (i * j > 6) { finished = true; break; } } } ```
Java
UTF-8
470
1.726563
2
[]
no_license
package com.example.avi_pc.weatherdemo.injection.component; import com.example.avi_pc.weatherdemo.activity.home.HomeActivity; import com.example.avi_pc.weatherdemo.injection.PerActivity; import com.example.avi_pc.weatherdemo.injection.module.ActivityModule; import dagger.Component; @PerActivity @Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class) public interface ActivityComponent { void inject(HomeActivity homeActivity); }
PHP
UTF-8
1,073
3.8125
4
[]
no_license
<?php //public :公開 //private :非公開(その設計図内のみ) //protected :継承したクラスにのみ公開 //Ptoductクラスという設計図から「negima」「hatsu」という2つの実体ができた //Productクラス内で新たにProductクラスをコピーした新たなクラス「DrinkProduct」という設計図ができた class Product { public $name; public $stock; public function getStock(){ $message = $this->name . "の在庫は" . $this->stock . "個です。"; return $message; } public function __construct($name,$stock){ $this->name = $name; $this->stock = $stock; } } class DrinkProduct extends Product { public function getStock(){ $message = $this->name . "の在庫は" . $this->stock . "リットルです。"; return $message; } } $beer = new DrinkProduct("ビール",40); echo $beer->getStock(); $negima = new Product("ねぎま",22); echo $negima->getStock(); $hatsu = new Product("はつ",35); echo $hatsu->getStock(); $kawa = new Product("かわ",30); echo $kawa->getStock();
PHP
UTF-8
611
2.890625
3
[ "Apache-2.0" ]
permissive
<?php // Initialize the command line output array $speedtestcli_outputs = array(); // Initialize the returning array which will be reprsented as json $json = array(); // Execute the speedtest tool and receive output exec("speedtest-cli --list", $speedtestcli_outputs); // Remove first line... Description text of output array_shift($speedtestcli_outputs); foreach($speedtestcli_outputs as $speedtestcli_output) { $parts = explode(")", $speedtestcli_output, 2); $entry = array(); $entry["id"] = intval($parts[0]); $entry["text"] = $parts[1]; array_push($json, $entry); } print json_encode($json); ?>
JavaScript
UTF-8
2,648
3.015625
3
[]
no_license
import React, { Component } from 'react' //import firebase import firebase, {auth, provider} from '../firebase.js'; //this is a class component class UseFirebase extends Component { //initialize the state constructor(props){ super(props) this.state = { name : "", address : "", items: [] } //bind with state object this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } //this is to handle change handleChange(e) { this.setState({ [e.target.name]: e.target.value }); console.log(this.state); } //this is to handle submit handleSubmit(e) { e.preventDefault(); //create a reference to the realtime database const itemsRef = firebase.database().ref('users'); const item = { name: this.state.name, address: this.state.address, } itemsRef.push(item); //restore the state this.setState({ name : "", address : "", }); } componentDidMount() { //extract items from our firebase database const itemsRef = firebase.database().ref('users'); itemsRef.on('value', (snapshot) => { let items = snapshot.val(); let newState = []; for (let item in items) { newState.push({ id: item, name: items[item].name, address: items[item].address }); } this.setState({ items: newState }); }); } //use form here render() { return( <div> <h1>Firebase Demo</h1> <form onSubmit = {this.handleSubmit}> <input type = "text" placeholder = "Enter name" name = "name" value = {this.state.name} onChange = {this.handleChange} /> <br/> <br/> <input type = "text" placeholder = "Enter Address" name = "address" value = {this.state.address} onChange = {this.handleChange} /> <br/> <br/> <button type = "submit">Create contact</button> </form> <div> { //map over our items returned from firebase this.state.items.map((item) => { return( <div key = {item.id}> <hr/> <p>Name: {item.name}</p> <p>Address: {item.address}</p> <hr/> </div> ); }) } </div> </div> ) } } export default UseFirebase;
C
UTF-8
1,477
3.625
4
[]
no_license
#include <stdio.h> #include <math.h> #include <stdlib.h> int main() { float principal, interstRate, monthlyInterestRate; float emi, startingBalance, interest, principalPaid, endingBalance; int numOfMonths, month; float interestArr[30], principalPaidArr[30], endingBalanceArr[30]; printf("Enter amount of loan: "); scanf("%f", &principal); printf("Enter Interest rate per year: "); scanf("%f", &interstRate); printf("Enter number of payments: "); scanf("%d", &numOfMonths); monthlyInterestRate = (float)(interstRate / (12*100.0)); emi = principal * (monthlyInterestRate / (1 - pow( (1 + monthlyInterestRate) , (-numOfMonths) ))); startingBalance = principal; printf("\n Monthly Payment: $%.2f \n", emi); for(month = 1; month <= numOfMonths; month++) { interestArr[month-1] = (startingBalance * monthlyInterestRate); principalPaidArr[month-1] = emi - interestArr[month-1]; endingBalanceArr[month-1] = (startingBalance - principalPaidArr[month-1]); startingBalance = endingBalanceArr[month-1]; } printf("\n %7s %15s %14s %10s %13s \n", " # ", " Payment ", " Principal ", " Interest ", " Balance "); for (month = 1; month <= numOfMonths; month++) { printf("\n %6d \t $%-10.2f $%-10.2f $%-10.2f $%-12.2f ", month, emi, principalPaidArr[month-1], interestArr[month-1], endingBalanceArr[month-1]); } printf("\n"); return 0; }
Swift
UTF-8
3,266
2.625
3
[]
no_license
@testable import ABA_Music import DataSourceController import XCTest class SearchResultTableViewModelTests: XCTestCase { func testViewModelPublicAPI() { let artist = Artist.generateArtist(index: 5) let delegate = MockSearchResultTableDelegate() let viewModel = SearchResultTableViewModel(artist: artist, delegate: delegate) as SearchResultTableViewModelType let indexOfTrackToSelect = (0..<artist.tracks.count).randomElement()! let expectedRows = Array(artist.tracks.sorted().reversed()) let expectedName = "Mock artist number 6" XCTAssertEqual(viewModel.name, expectedName) XCTAssertEqual(viewModel.dataSource.totalRowCount, artist.tracks.count) XCTAssertNotNil((0..<artist.tracks.count).compactMap { viewModel.dataSource.modelObject(at: IndexPath(row: $0, section: 0)) } as? [Track]) XCTAssertEqual((0..<artist.tracks.count).compactMap { viewModel.dataSource.modelObject(at: IndexPath(row: $0, section: 0)) } as? [Track], expectedRows) let selectTrackExpectation = expectation(description: "didSelectTrack(_:) has been called") delegate.didSelectTrack = { track in XCTAssertEqual(track, expectedRows[indexOfTrackToSelect]) selectTrackExpectation.fulfill() } viewModel.didSelectItem(at: IndexPath(row: indexOfTrackToSelect, section: 0)) waitForExpectations(timeout: 1.0) } func testCellDataControllerConformanceWithValidModel() { let artist = Artist.generateArtist(index: 5) let delegate = MockSearchResultTableDelegate() let viewModel = SearchResultTableViewModel.populate(with: SearchResultTableCellData(artist: artist, delegate: delegate)) as? SearchResultTableViewModelType let indexOfTrackToSelect = (0..<artist.tracks.count).randomElement()! let expectedRows = Array(artist.tracks.sorted().reversed()) let expectedName = "Mock artist number 6" XCTAssertNotNil(viewModel) XCTAssertEqual(viewModel?.name, expectedName) XCTAssertEqual(viewModel?.dataSource.totalRowCount, artist.tracks.count) XCTAssertNotNil((0..<artist.tracks.count).compactMap { viewModel?.dataSource.modelObject(at: IndexPath(row: $0, section: 0)) } as? [Track]) XCTAssertEqual((0..<artist.tracks.count).compactMap { viewModel?.dataSource.modelObject(at: IndexPath(row: $0, section: 0)) } as? [Track], expectedRows) let selectTrackExpectation = expectation(description: "didSelectTrack(_:) has been called") delegate.didSelectTrack = { track in XCTAssertEqual(track, expectedRows[indexOfTrackToSelect]) selectTrackExpectation.fulfill() } viewModel?.didSelectItem(at: IndexPath(row: indexOfTrackToSelect, section: 0)) waitForExpectations(timeout: 1.0) } func testCellDataControllerConformanceWithNonValidModel() { let model = Artist.generateArtist(index: 5) let viewModel = SearchResultTableViewModel.populate(with: model) as? SearchResultTableViewModelType let expectedName = "" XCTAssertNotNil(viewModel) XCTAssertEqual(viewModel?.name, expectedName) XCTAssertEqual(viewModel?.dataSource.totalRowCount, 0) } }
Markdown
UTF-8
500
2.59375
3
[]
no_license
# Food * **Creatine** - has a number of positive effects * Is produced by body \(production is stessful\) * Contained in red meat, pork, fish * **Ketone** \(by-product of fat metabolism\) * **MCT** \(medium-chain triglyceride\) * dietary fat helping to increase amount of ketone in the blood * There are MCT oil, coconut oil, palm oil, goat's milk. breasts milk * Gene **ApoE4** - a decreased ability to glucose metabolism in the brain * at least one variant has 25% of population
C#
UTF-8
584
3.125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calculator { class Class1 { public void demoTryParse() { string val = null; int result; bool ifSuccess = int.TryParse(val, out result); // definition of TryParse Console.WriteLine(ifSuccess); string val1 = "101.11"; int result2; bool ifSuccess2 = int.TryParse(val1, out result2); Console.WriteLine(ifSuccess2); } } }
Java
UTF-8
1,545
2.671875
3
[ "MIT" ]
permissive
package jmvc.model; import java.util.HashMap; import java.util.Map; import static gblibx.Util.isNonNull; public class ColumnInfo { public ColumnInfo( Database dbase, Table table, String name, int type, int size, int position, String defaultVal, boolean isPrimaryKey) { this.dbase = dbase; this.table = table; this.name = name; this.type = type; this.size = size; this.position = position; this.defaultVal = defaultVal; this.isPrimaryKey = isPrimaryKey; add(); } public boolean hasDefaultVal() { return isNonNull(defaultVal); } public final int type; public final int size; public final int position; public final String defaultVal; public final boolean isPrimaryKey; public final Database dbase; public final Table table; public final String name; /** * Unique id across all columns, tables, databases. */ public final int id = _colInfoById.size(); /** * Fully qualified name: DATABASE.TABLE.COLUMN. * @return fully qualified name. */ public String getFQN() { return String.format("%s.%s.%s", dbase.name(), table.name, name).toUpperCase(); } private void add() { _colInfoById.put(id, this); _colInfoByName.put(getFQN(), this); } private static final Map<Integer, ColumnInfo> _colInfoById = new HashMap<>(); private static final Map<String, ColumnInfo> _colInfoByName = new HashMap<>(); }
PHP
UTF-8
6,918
2.6875
3
[]
no_license
<?php /** * * @author Bighetti * */ use \Sys\DB; use \Sys\Validation; class BlockRefused_Model extends \Sys\Model { public $id; public $excluido; public $block_id; public $client_id; public $date_refuse; public $reason; public $invoice_id; function __construct() { parent::__construct(); } function validation() { $validation = new Validation(); if (!$this->block_id > 0) { $validation->add(Validation::VALID_ERR_FIELD, 'Invalid block'); } if (!$this->client_id > 0) { $validation->add(Validation::VALID_ERR_FIELD, 'Invalid client'); } if (strlen($this->reason) == 0) { $validation->add(Validation::VALID_ERR_FIELD, 'Invalid reason'); } return $validation; } function save() { if (!$this->exists()) { return $this->insert(); } else { return $this->update(); } } function exists() { if (is_null($this->id)) { $this->id = 0; } $query = DB::query('SELECT id FROM block_refused WHERE id = ? ', array($this->id)); if (DB::has_rows($query)) { return true; } return false; } function insert() { $validation = $this->validation(); if ($validation->isValid()) { $sql = 'INSERT INTO block_refused ( block_id, client_id, date_refuse, reason ) VALUES ( ?, ?, ?, ? ) '; $dt_now = new DateTime('now'); $query = DB::exec($sql, array( // values $this->block_id, $this->client_id, $dt_now->format('Y-m-d H:i:s'), $this->reason )); $this->id = DB::last_insert_id(); if($this->invoice_id > 0){ $this->delete_from_invoice($this->invoice_id, $this->block_id); } else { $this->delete_reservation($this->block_id); } return $this->id; } return $validation; } function update() { $validation = $this->validation(); if ($validation->isValid()) { if (!$this->exists()) { $validation = new Validation(); $validation->add(Validation::VALID_ERR_NOT_EXISTS, 'Id does not exists'); } else { $sql = ' UPDATE block_refused SET block_id = ?, client_id = ?, date_refuse = ?, reason = ? WHERE id = ? '; $query = DB::exec($sql, array( // set $this->block_id, $this->client_id, $this->date_refuse, $this->reason, // where $this->id )); if($this->invoice_id > 0){ $this->delete_from_invoice($this->invoice_id, $this->block_id); } else { $this->delete_reservation($this->block_id); } return $this->id; } } return $valid; } function delete_from_invoice($invoice_id, $block_id){ $sql = "UPDATE invoice_item SET excluido = 'S' WHERE invoice_id = ? AND block_id = ? "; $query = DB::exec($sql, array($invoice_id, $block_id)); $this->delete_reservation($block_id); } function delete_reservation($block_id){ $sql = " UPDATE block SET sold = 0, sold_client_id = NULL, reserved_client_id = NULL, reserved = 0 WHERE id = " . $block_id; $query = DB::exec($sql); } function delete() { $validation = new Validation(); if (!$this->exists()) { $validation->add(Validation::VALID_ERR_NOT_EXISTS, 'Id does not exists'); } else { $sql = 'UPDATE block_refused SET excluido = ? WHERE id = ? '; $query = DB::exec($sql, array('S', $this->id)); return $this->id; } return $validation; } function populate($id) { $validation = new Validation(); if ($id) { $this->id = $id; } if (!$this->exists()) { $validation->add(Validation::VALID_ERR_NOT_EXISTS, 'Id does not exists'); } else { $query = DB::query( 'SELECT id, excluido, block_id, client_id, date_refuse, reason FROM block_refused WHERE id = ?', array($id) ); if (DB::has_rows($query)) { $this->fill($query[0]); return $this->id; } } return $validation; } function fill($row_query) { if ($row_query) { $this->id = (int)$row_query['id']; $this->excluido = (string)$row_query['excluido']; $this->block_id = (int)$row_query['block_id']; $this->client_id = (int)$row_query['client_id']; $this->date_refuse = (string)$row_query['date_refuse']; $this->reason = (string)$row_query['reason']; } } function get_list($excluido=false) { $excluido = ($excluido === true ? 'S' : 'N'); $query = DB::query('SELECT id, excluido, block_id, client_id, date_refuse, reason FROM block_refused WHERE excluido = ? ORDER BY date_refuse, block_id', array($excluido)); return $query; } }
Python
UTF-8
1,309
2.90625
3
[]
no_license
from ..message_types import * from ..datamodel.structures.utility import * class Message: """A simple class to hold data as a message. Operation is the key used by subscribers to be notified of the message. >>> m = Message("dummy_create", row=[1, 2, 3]) >>> m["row"] [1, 2, 3] """ def __init__(self, operation, **kwargs): self.operation = operation self.data = kwargs def __getitem__(self, key): return self.data[key] def __setitem__(self, key, value): self.data[key] = value def __str__(self): fmt = "{0}:{1}" return fmt.format(self.operation, str(self.data)) _actual_commands = ALL_TYPES def build_message(target, operation, data): """ Helper method for constructing messages based on param definition lists, driven by our basic syntax. >>> m = build_message("system", "create_bucket", "foo") >>> m.operation 'system_create_bucket' >>> m["name"] 'foo' >>> m = build_message("foo", "update", [1,2,3], [1,5,6]) >>> m["query_row"] [1, 2, 3] >>> m["data"] [1, 5, 6] """ op = format_op(target, operation) m = Message(op) for k,v in data.items(): m[k] = v return m if __name__ == '__main__': import doctest doctest.testmod()
Python
UTF-8
436
2.796875
3
[]
no_license
from flask import Flask,request app = Flask(__name__) # @app.route('/',methods=['GET','POST']) # def index(): # responce = 'request context \n' # responce += f"request method : {request.method}\n" # responce += f"request GET args : {request.form}\n" # return responce @app.route('/',methods=['GET','POST']) def index(): name = request.args.get('name') or request.form.get('name') return f"hello {name}\n"
PHP
UTF-8
2,621
2.71875
3
[]
no_license
<?php use Drush\Sql\SqlBase; /** * These are deprecated functions that we keep around just to ease the transition * to current Drush version. They may not work the same as they did in prior * versions. If they aren't working for you, consider upgrading your commandfile * so that it works with modern Drush. * * @deprecated */ // @deprecated function drush_sql_bootstrap_further() {} function drush_sql_get_class($db_spec = NULL) { $options = []; if ($url = drush_get_option('db-url')) { $options['db-url'] = $url; } return SqlBase::create($options); } /** * Given an alias record, overwrite its values with options * from the command line and other drush contexts as specified * by the provided prefix. For example, if the prefix is 'source-', * then any option 'source-foo' will set the value 'foo' in the * alias record. * * @deprecated */ function drush_sitealias_overlay_options($site_alias_record, $prefix) { return array_merge($site_alias_record, drush_get_merged_prefixed_options($prefix)); } /** * Retrieves a collapsed list of all options * with a specified prefix. * * @deprecated */ function drush_get_merged_prefixed_options($prefix) { $merged_options = drush_get_merged_options(); $result = array(); foreach ($merged_options as $key => $value) { if ($prefix == substr($key, 0, strlen($prefix))) { $result[substr($key, strlen($prefix))] = $value; } } return $result; } /** * Remove the trailing DIRECTORY_SEPARATOR from a path. * Will actually remove either / or \ on Windows. * * @deprecated */ function drush_trim_path($path, $os = NULL) { if (drush_is_windows($os)) { return rtrim($path, '/\\'); } else { return rtrim($path, '/'); } } /** * Makes sure the path has only path separators native for the current operating system * * @deprecated */ function drush_normalize_path($path) { if (drush_is_windows()) { $path = str_replace('/', '\\', strtolower($path)); } else { $path = str_replace('\\', '/', $path); } return drush_trim_path($path); } /** * Calculates a single md5 hash for all files a directory (incuding subdirectories) * * @deprecated */ function drush_dir_md5($dir) { $flist = drush_scan_directory($dir, '/./', array('.', '..'), 0, TRUE, 'filename', 0, TRUE); $hashes = array(); foreach ($flist as $f) { $sum = array(); exec('cksum ' . escapeshellarg($f->filename), $sum); $hashes[] = trim(str_replace(array($dir), array(''), $sum[0])); } sort($hashes); return md5(implode("\n", $hashes)); }
Swift
UTF-8
1,288
2.546875
3
[ "MIT" ]
permissive
// // CountryDetailedVC.swift // ConcurrencyLab // // Created by David Lin on 12/9/19. // Copyright © 2019 David Lin (Passion Proj). All rights reserved. // import UIKit class CountryDetailedVC: UIViewController { var countryDetails: CountryList! @IBOutlet weak var flagImage: UIImageView! @IBOutlet weak var countryName: UILabel! @IBOutlet weak var countryCapital: UILabel! @IBOutlet weak var countryPopulation: UILabel! override func viewDidLoad() { super.viewDidLoad() loadData() } func loadData() { countryName.text = countryDetails.name countryCapital.text = countryDetails.capital countryPopulation.text = countryDetails.population.description ImageClient.fetchImage(for: "https://www.countryflags.io/\(countryDetails.alpha2Code)/flat/64.png") { [unowned self](result) in switch result { case.success( let image): // UPDATE ANY UO ELEMENTS ON THE MAIN THREAD DispatchQueue.main.async { self.flagImage.image = image } case.failure( let error): (print("configueCell image error - \(error)")) } } } }
Python
UTF-8
939
4.46875
4
[]
no_license
#私有属性和方法是无法被继承的 class Animal: def __init__(self,name="动物",color="白色"): #私有属性 self.__name=name #非私有属性 self.color=color #私有方法 def __test(self): print(self.__name) print(self.color) #非私有方法,比较区别 def test(self): print(self.__name) print(self.color) class Dog(Animal): def dog_test1(self): #print(self.__name) #不能访问到父类的私有属性 print(self.color) def dog_test2(self): #self.__test() #不能访问到父类的私有方法 self.test() a=Animal() print(a.color) #print(a.__name) #程序出现异常,不能访问私有属性 #a.__test() #程序出现异常,不能访问私有方法 a.test() print("--"*30) d=Dog("柴犬","棕色") print(d.color) #print(d.__name) d.dog_test1() d.dog_test2()
C#
UTF-8
884
2.546875
3
[]
no_license
using System.Runtime.Serialization; namespace MemoryGame.MemoryGameService.DataTransferObjects { /// <summary> /// The <c>PlayerDto</c> class. /// It is used to map the information of a Player entity. /// </summary> [DataContract] public class PlayerDto { /// <summary> /// Player username. /// </summary> [DataMember] public string Username { get; set; } /// <summary> /// Player email address. /// </summary> [DataMember] public string EmailAddress { get; set; } /// <summary> /// Player password. /// </summary> [DataMember] public string Password { get; set; } /// <summary> /// Player verefication token. /// </summary> [DataMember] public string VerificationToken { get; set; } } }
JavaScript
UTF-8
182
3.484375
3
[]
no_license
let c1 = { x: 5, y: 10, }; let c2 = { x: 45, y: 235, }; function printCoordinates() { console.log(this.x + ',' + this.y); } let c1func = printCoordinates(c1); c1func();
C#
UTF-8
650
3.953125
4
[ "MIT" ]
permissive
using System; namespace _6.PathToOne { class PathToOne { static void Main() { uint n = uint.Parse(Console.ReadLine()); int steps = Divide(n); Console.WriteLine(steps); } public static int Divide(uint n, int depth = 0) { if (n == 1) { return depth; } if (n % 2 == 0) { return Divide(n / 2, depth + 1); } int d1 = Divide(n + 1, depth + 1); int d2 = Divide(n - 1, depth + 1); return Math.Min(d1, d2); } } }
Python
UTF-8
759
3.390625
3
[]
no_license
''' ----------------------------------------------- ----------------------------------------------- Author: Nishant Tewari ID: 190684430 Email: tewa4430@mylaurier.ca __updated__ = "2020-02-27" ----------------------------------------------- ''' # Imports # Constants from List_linked import List lst_link = List() lst_link.append(1) lst_link.append(2) lst_link.append(3) lst_link.append(4) lst_link.append(5) lst_link.append(6) lst_link.append(1) lst_link.append(1) print("Linked List") for i in lst_link: print(i) print() value = lst_link.peek() print("The value at the front of the list: {}".format(value)) lst_link.remove(3) print("Value 3 is removed from the list") print("List after removing a value") for j in lst_link: print(j)