repo_name
stringlengths
7
111
__id__
int64
16.6k
19,705B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
151
content_id
stringlengths
40
40
detected_licenses
sequence
license_type
stringclasses
2 values
repo_url
stringlengths
26
130
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
unknown
revision_date
unknown
committer_date
unknown
github_id
int64
14.6k
687M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
12 values
gha_fork
bool
2 classes
gha_event_created_at
unknown
gha_created_at
unknown
gha_updated_at
unknown
gha_pushed_at
unknown
gha_size
int64
0
10.2M
gha_stargazers_count
int32
0
178k
gha_forks_count
int32
0
88.9k
gha_open_issues_count
int32
0
2.72k
gha_language
stringlengths
1
16
gha_archived
bool
1 class
gha_disabled
bool
1 class
content
stringlengths
10
2.95M
src_encoding
stringclasses
5 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
10
2.95M
extension
stringclasses
19 values
num_repo_files
int64
1
202k
filename
stringlengths
4
112
num_lang_files
int64
1
202k
alphanum_fraction
float64
0.26
0.89
alpha_fraction
float64
0.2
0.89
hex_fraction
float64
0
0.09
num_lines
int32
1
93.6k
avg_line_length
float64
4.57
103
max_line_length
int64
7
931
ShaGodJi/ButterflyServer
1,279,900,302,206
2ac0dc6895b85343cb7021d984baa5f5e0d03422
b5b91fb3b4616bfccef258c68374554a5d4d72cd
/butterflyServer/views.py
19a667454a3909e545e97d7e6cdfbfb93fb844d2
[]
no_license
https://github.com/ShaGodJi/ButterflyServer
c71f24c051f022bce942b1b285eef05176dc84eb
55b6445626d250e145c98ded6e20d2bb982e6ff9
refs/heads/master
"2022-09-07T20:05:23.850223"
"2019-12-21T09:22:31"
"2019-12-21T09:22:31"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json import os from django import forms from django.http import HttpResponse from django.shortcuts import render from textblob.formats import JSON from butterflyServer.label_image import get_label from django.views.decorators.csrf import csrf_exempt class FileForm(forms.Form): username = forms.CharField() file = forms.FileField() # for creating file input def handle_uploaded_file(f, username): directory = 'static/upload/' + username + '/' if not os.path.exists(directory): os.makedirs(directory) with open(directory + f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) return directory + f.name @csrf_exempt def getFile(request): if request.method == 'POST': fileForm = FileForm(request.POST, request.FILES) if fileForm.is_valid(): file_path = handle_uploaded_file(request.FILES['file'], request.POST['username']) result_dict = get_label({ 'labels': 'butterflyServer/output_labels.txt', 'graph': 'butterflyServer/output_graph.pb', 'input_layer': 'Placeholder', 'image': file_path, 'output_layer': 'final_result' }) result_json = [] for each in result_dict: a = {} a['name'] = each a['value'] = result_dict[each] # print(a,'a') result_json.append(a) sorted_result = sorted(result_json, key = lambda i: -i['value']) print(file_path, sorted_result) if(float(sorted_result[0]['value'])<0.30): return HttpResponse('error') else: return HttpResponse(json.dumps(str(sorted_result[0]['name']))) return HttpResponse("false") else: fileForm = FileForm() return render(request, "index.html", {'form': fileForm})
UTF-8
Python
false
false
1,952
py
2
views.py
1
0.585553
0.582992
0
57
33.245614
93
el1s7/sanic-api-kit
721,554,530,655
d5a4dd08e558b8dc3b6a83bb8a912dbfaa687647
1a5e8948a3ba9df36a94489ac3f560aa960f107f
/api/middlewares/__init__.py
023b5a60064a3f85a3161775a34545611c426841
[]
no_license
https://github.com/el1s7/sanic-api-kit
7bb1729b0fc122ae18f93f99bde2cde549cd9191
55516680fcc34121df0a18ef545919b3fd444832
refs/heads/master
"2023-05-24T06:15:03.554664"
"2021-06-09T16:27:47"
"2021-06-09T16:27:47"
375,420,177
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from api.models.auth import auth def auth_verify(request): request.ctx.session = auth.verify( request.token, request.headers.get("user-agent"), request.ip )
UTF-8
Python
false
false
166
py
20
__init__.py
17
0.728916
0.728916
0
9
17.555556
36
hosseinghorbanzadeh/A-hybrid-method-of-link-prediction-in-directed-graphs
18,322,330,499,820
27c703d59b66956cb76591211835ff4f19a23d82
ef5f48eac538382f5e29cbb08a2980017cd0a177
/supervis/Method.py
9d8ae4a093242d9e4bf8fab37ac932b3192c5580
[]
no_license
https://github.com/hosseinghorbanzadeh/A-hybrid-method-of-link-prediction-in-directed-graphs
e2792447666060ca89e66511786079026a600a69
7a12f9fd458a05a2c38770e49cd0a4f8a3a3d09d
refs/heads/main
"2023-08-25T19:27:56.916190"
"2021-10-09T05:29:05"
"2021-10-09T05:29:05"
391,838,949
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon Aug 2 17:03:56 2021 @author: hossein """ import networkx as nx import pandas as pd import numpy as np import ast import matplotlib.pyplot as plt import itertools as IT import random from measure.AADirect import * from measure.CN_Hub_Auth import * from measure.RADir import * from measure.triads_motif_measure import * from measure.n2vLP import * #======================= #====================== def RandomNumber(Low,Hight,Num): L=[] i=0 while i<Num: r=random.randint(Low,Hight) if(r not in L): L.append(r) i+=1 return L def common_out_neighbors(g, i, j): return set(g.successors(i)).intersection(g.successors(j)) def common_in_neighbors(g, i, j): return set(g.predecessors(i)).intersection(g.predecessors(j)) #=============================Retuen_Miss_Link======================================================== def Retuen_Miss_Link(WholeGraph,alpha): TraningGraph=WholeGraph.copy() edges=WholeGraph.edges() Number=int(len(edges)*alpha) sample=iterSample(edges,Number) TraningGraph.remove_edges_from(sample) set1=set(WholeGraph.nodes()) set2=set(TraningGraph.nodes()) set3=set1.difference(set2) list1=list(set3) if list1!=[]: for i in range(len(list1)): TraningGraph.add_node(list1[i]) G2=nx.difference(WholeGraph,TraningGraph) missLink=list(G2.edges()) return missLink,WholeGraph,TraningGraph #======================================================================================================== def Weight_sample(WholeGraph,Nnmber_Negative): Nonedges=iterSample(nx.non_edges(WholeGraph),Nnmber_Negative) return Nonedges #=========================================================================================== def iterSample(iterable, samplesize): results = [] for i, v in enumerate(iterable): r = random.randint(0, i) if r < samplesize: if i < samplesize: results.insert(r, v) # add first samplesize items in random order else: results[r] = v # at a decreasing rate, replace random items if len(results) < samplesize: raise ValueError("Sample larger than population.") return results #Input non_edges That is iterable Output list #=========================================================================================== def Final_Result_Multi_Dataset1(WholeGraph,TraningGraph,L,Non,miss): ResultAUC_Dic={} ResultPER_Dic={} '''if(bigGraph=='no'): miss,Non,G1,G2=MissLink_and_NonExistentLink(WholeGraph_DF.values,TraningGraph_DF.values) elif(bigGraph=='yes'): miss,Non,G1,G2=MissLink_and_NonExistentLink_for_big_Graph(WholeGraph_DF.values,TraningGraph_DF.values,num_nonEdges) ''' G1=TraningGraph print('miss',len(miss)) ######################################Number Negative############################# CE=len(G1.edges())-1 NE=len(Non)-1 Nnmber_Negative=(CE/(CE+NE))*NE Number_Positive=(NE/(CE+NE))*CE list1=RandomNumber(1,NE,Nnmber_Negative) NonExistent=[] for w in list1: NonExistent.append(Non[w]) print('CE',CE) print('NonExistent',len(NonExistent)) print('miss',len(miss)) ############################################################## Class=[] for i in range(len(miss)): Class.append(1) for j in range(len(NonExistent)): Class.append(0) ################################adamic_adar_index####################################### print('#####################AADricted Graph####################################') SmissLinkAADir=list(adamic_adar_index(G1,miss,TyppeGraph='DirGhraphIn-Out')) NonExistentAAdir=list(adamic_adar_index(G1,NonExistent,TyppeGraph='DirGhraphIn-Out')) data1=pd.DataFrame(SmissLinkAADir+NonExistentAAdir,columns=['Node1','Node2','AA-in-out']) SmissLinkAADir=list(adamic_adar_index(G1,miss,TyppeGraph='DirGhraphIn')) NonExistentAAdir=list(adamic_adar_index(G1,NonExistent,TyppeGraph='DirGhraphIn')) mix=SmissLinkAADir+NonExistentAAdir CN=[k[2] for k in mix] data1['AA-in']=CN SmissLinkAADir=list(adamic_adar_index(G1,miss,TyppeGraph='DirGhraphOut')) NonExistentAAdir=list(adamic_adar_index(G1,NonExistent,TyppeGraph='DirGhraphOut')) mix=SmissLinkAADir+NonExistentAAdir CN=[k[2] for k in mix] data1['AA-Out']=CN print('#######################################') ################################adamic_adar_index####################################### #########################Common nightboar############################################### print('lin pridiction Using Common nightboar') CN_MissLink = [(e[0],e[1],len(list(common_out_neighbors(G1,e[0],e[1])))+len(list(common_in_neighbors(G1,e[0],e[1])))) for e in miss] print('common_out_neighbors') CN_nonexiteEdges=[(e[0],e[1],len(list(common_out_neighbors(G1,e[0],e[1])))+len(list(common_in_neighbors(G1,e[0],e[1])))) for e in NonExistent] mix=CN_MissLink+CN_nonexiteEdges CN=[k[2] for k in mix] data1['CN-inout']=CN CN_MissLink = [(e[0],e[1],len(list(common_out_neighbors(G1,e[0],e[1])))) for e in miss] CN_nonexiteEdges=[(e[0],e[1],len(list(common_out_neighbors(G1,e[0],e[1])))) for e in NonExistent] mix=CN_MissLink+CN_nonexiteEdges CN=[k[2] for k in mix] data1['CND-out']=CN CN_MissLink = [(e[0],e[1],len(list(common_in_neighbors(G1,e[0],e[1])))) for e in miss] CN_nonexiteEdges=[(e[0],e[1],len(list(common_in_neighbors(G1,e[0],e[1])))) for e in NonExistent] mix=CN_MissLink+CN_nonexiteEdges CN=[k[2] for k in mix] data1['CND-in']=CN #########################Common nightboar############################################### ############################## Resource Allocation############################## print('Resource Allocation') SmissLinkAADir=list(resource_allocation_index(G1,miss,TyppeGraph='DirGhraphIn-Out')) print('Len SmissLinkAADir',len(SmissLinkAADir)) NonExistentAAdir=list(resource_allocation_index(G1,NonExistent,TyppeGraph='DirGhraphIn-Out')) mix=SmissLinkAADir+NonExistentAAdir #print('RA',len(mix)) commRA=[k[2] for k in mix] data1['RA-in-out']=commRA print('Resource Allocation in') SmissLinkAADir=list(resource_allocation_index(G1,miss,TyppeGraph='DirGhraphIn')) NonExistentAAdir=list(resource_allocation_index(G1,NonExistent,TyppeGraph='DirGhraphIn')) mix=SmissLinkAADir+NonExistentAAdir commRA=[k[2] for k in mix] data1['RA-in']=commRA print('Resource Allocation out') SmissLinkAADir=list(resource_allocation_index(G1,miss,TyppeGraph='DirGhraphOut')) NonExistentAAdir=list(resource_allocation_index(G1,NonExistent,TyppeGraph='DirGhraphOut')) mix=SmissLinkAADir+NonExistentAAdir commRA=[k[2] for k in mix] data1['RA-Out']=commRA ##############################AucAndPre_co_ni_With_Pageranking######################### dic_miss,dic_NonExistent=CN_HA_AH(G1,miss,NonExistent) mix=merge_two_dicts(dic_miss,dic_NonExistent) #print('CN_HA_AH',len(mix)) CN_Hun_Auth1=[mix.get(p) for p in mix] data1['CN_HA_AH']=CN_Hun_Auth1 dic_miss,dic_NonExistent=CN_H_A(G1,miss,NonExistent) mix=merge_two_dicts(dic_miss,dic_NonExistent) CN_Hun_Auth1=[mix.get(p) for p in mix] data1['CN_H_A']=CN_Hun_Auth1 dic_miss,dic_NonExistent=CN_A_H(G1,miss,NonExistent) mix=merge_two_dicts(dic_miss,dic_NonExistent) CN_Hun_Auth1=[mix.get(p) for p in mix] data1['CN_A_H']=CN_Hun_Auth1 ##############################AucAndPre_co_ni_With_Pageranking######################### ###########################quadr_motif_measure######################################### print('################################mofit#########################') Mofit_miss=Measure_MotifsTriad(G1,miss) print('#####################') #print('Len Miss',len(miss)) #print('Len Mofit_miss',len(Mofit_miss)) Mofit_NonExistent=Measure_MotifsTriad(G1,NonExistent) mix=Mofit_miss+Mofit_NonExistent print(len(mix)) CN_MOfit=[k[2] for k in mix] data1['Motifs_triads']=CN_MOfit print('################################mofit#########################') ##############################AucAndPre_co_ni_With_Pageranking######################### ###########################n2v######################################### print('#############################N2V##############################') Miss_Scoure=n2vlp(G1,miss) Non_Scoure=n2vlp(G1,NonExistent) mix=Miss_Scoure+Non_Scoure print(len(mix)) CN_n2v=[k[2] for k in mix] data1['N2V']=CN_n2v ###########################n2v######################################### data1['Class']=Class strName="MLExcel"+" "+L+".xlsx" print(strName) print(data1) '''data1.to_excel(strName, sheet_name='MLExcel')''' return data1
UTF-8
Python
false
false
9,191
py
23
Method.py
17
0.542378
0.527037
0
224
38.986607
146
siki-aayush/Implementation-of-Advanced-Algorithms-Using-Python
10,307,921,549,522
2593164d84359b5768edadcbf82919c780743896
ebaa9207f0ce1c86c694b88045c784a5e1c687bb
/Edge_Disjoint_Path.py
c9e6c756954b3770a090043216d5edba8410e998
[]
no_license
https://github.com/siki-aayush/Implementation-of-Advanced-Algorithms-Using-Python
bd8c7b1c53cc3621ed5e621940c5f0b18c980d3b
75ddd6441bbf8ab9782145c0b009b2c2f5c8e4e9
refs/heads/master
"2021-09-22T18:04:24.436569"
"2018-09-13T07:15:36"
"2018-09-13T07:15:36"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
n = int(input("Enter the number of nodes : ")) graph = {} for i in range(0,n): j = input("Enter the edges flowing from the node : ") temp=j.split(",") graph[str(i)]=temp matrix = [[0 for x in range(n)] for y in range(n)] #print(graph) for i in graph.keys(): j = graph.get(i) for k in j: if k is not '': matrix[int(i)][int(k)]=1 print(matrix) def dfs(a,current,dest,path,f): if current==dest: path.append(current) else: path.append(current) temp=a[current] j=-1 for i in temp: j+=1 if i>0 and (j not in path) and (dest not in path): dfs(a,j,dest,path,f) f.append(current) return f source_capacity=0 sink_capacity=0 for i in range(0,n): source_capacity+=matrix[0][i] sink_capacity+=matrix[i][n-1] max_flow=min(source_capacity,sink_capacity) flow=0 disjoint_paths=[] while flow<max_flow: path=[] path=dfs(matrix,0,n-1,path,[]) if (n-1) in path: ind = path.index(n-1) path=path[ind:] path.reverse() disjoint_paths.append(path) flows=[] for i in range(0,len(path)-1): row=path[i] col=path[i+1] flows.append(matrix[row][col]) f=min(flows) flow+=f for i in range(0,len(path)-1): row=path[i] col=path[i+1] matrix[row][col]-=f matrix[col][row]+=f else: break print("Maximum number of edge-disjoint paths are :",flow) print("Disjoint Paths are : ") for i in disjoint_paths: print(i)
UTF-8
Python
false
false
1,614
py
11
Edge_Disjoint_Path.py
8
0.539653
0.526022
0
69
22.391304
62
yiclwh/Facebook-Interview-Coding
7,318,624,292,631
ea14e73556131eba674422ea954c5661e738917e
83607de1e707e955f8e7be0432fa638d709ee832
/binary search.py
1753a3dd1a699a73a14425c1e26218d8bfb80b96
[]
no_license
https://github.com/yiclwh/Facebook-Interview-Coding
b5b225f4a5bcef6286f498655a7a50b081e89e63
587238fbb66b0824b944d43a12d37c9adcdb02e7
refs/heads/master
"2021-07-11T14:43:51.803393"
"2018-12-20T00:31:58"
"2018-12-20T00:31:58"
135,938,852
0
0
null
true
"2018-06-03T20:39:29"
"2018-06-03T20:39:29"
"2018-06-03T19:43:24"
"2017-05-09T00:52:42"
85
0
0
0
null
false
null
可以找不比target小的第一个数(大于等于) 最后换成end 找比target 小的第一个数 def binarysearch(array, target): start, end = 0, len(array)-1 while start <= end: mid = start + (end-start)//2 if array[mid] < target: start = mid + 1 else: end = mid - 1 return start public static void PrintIndicesForValue(int[] numbers, int target) { if (numbers == null) return; int low = 0, high = numbers.length - 1; // get the start index of target number int startIndex = -1; while (low <= high) { int mid = (high - low) / 2 + low; if (numbers[mid] > target) { high = mid - 1; } else if (numbers[mid] == target) { startIndex = mid; high = mid - 1; } else low = mid + 1; } // get the end index of target number int endIndex = -1; low = 0; high = numbers.length - 1; while (low <= high) { int mid = (high - low) / 2 + low; if (numbers[mid] > target) { high = mid - 1; } else if (numbers[mid] == target) { endIndex = mid; low = mid + 1; } else low = mid + 1; } if (startIndex != -1 && endIndex != -1){ for(int i=0; i+startIndex<=endIndex;i++){ if(i>0) System.out.print(','); System.out.print(i+startIndex); } } }
UTF-8
Python
false
false
1,464
py
24
binary search.py
23
0.479433
0.463121
0
55
24.654545
68
insightcs/CenterNet
4,320,737,111,343
e049d9d686bc095ce7401955abcf17d59a605ead
2d0a1cc732760bbbd55f68a6483c5b65fcc5b046
/detector/utils/decode.py
415b1507bf480feb5931595ab245b415c59e5e02
[ "BSD-3-Clause", "MIT" ]
permissive
https://github.com/insightcs/CenterNet
82cb6d927e80d32849fca9b8f0705f2ee3b93676
277ab04321285023ce4f0f2e7d81ef52252d4019
refs/heads/master
"2020-06-27T04:29:26.522542"
"2019-07-31T11:57:00"
"2019-07-31T11:57:00"
199,844,651
0
1
MIT
true
"2019-07-31T11:41:18"
"2019-07-31T11:41:18"
"2019-07-31T05:43:39"
"2019-07-23T14:49:00"
6,393
0
0
0
null
false
false
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn from utils.utils import _gather_feat, _tranpose_and_gather_feat def _nms(heat, kernel=3): pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() return heat * keep def _left_aggregate(heat): ''' heat: batchsize x channels x h x w ''' shape = heat.shape heat = heat.reshape(-1, heat.shape[3]) heat = heat.transpose(1, 0).contiguous() ret = heat.clone() for i in range(1, heat.shape[0]): inds = (heat[i] >= heat[i - 1]) ret[i] += ret[i - 1] * inds.float() return (ret - heat).transpose(1, 0).reshape(shape) def _right_aggregate(heat): ''' heat: batchsize x channels x h x w ''' shape = heat.shape heat = heat.reshape(-1, heat.shape[3]) heat = heat.transpose(1, 0).contiguous() ret = heat.clone() for i in range(heat.shape[0] - 2, -1, -1): inds = (heat[i] >= heat[i +1]) ret[i] += ret[i + 1] * inds.float() return (ret - heat).transpose(1, 0).reshape(shape) def _top_aggregate(heat): ''' heat: batchsize x channels x h x w ''' heat = heat.transpose(3, 2) shape = heat.shape heat = heat.reshape(-1, heat.shape[3]) heat = heat.transpose(1, 0).contiguous() ret = heat.clone() for i in range(1, heat.shape[0]): inds = (heat[i] >= heat[i - 1]) ret[i] += ret[i - 1] * inds.float() return (ret - heat).transpose(1, 0).reshape(shape).transpose(3, 2) def _bottom_aggregate(heat): ''' heat: batchsize x channels x h x w ''' heat = heat.transpose(3, 2) shape = heat.shape heat = heat.reshape(-1, heat.shape[3]) heat = heat.transpose(1, 0).contiguous() ret = heat.clone() for i in range(heat.shape[0] - 2, -1, -1): inds = (heat[i] >= heat[i + 1]) ret[i] += ret[i + 1] * inds.float() return (ret - heat).transpose(1, 0).reshape(shape).transpose(3, 2) def _h_aggregate(heat, aggr_weight=0.1): return aggr_weight * _left_aggregate(heat) + \ aggr_weight * _right_aggregate(heat) + heat def _v_aggregate(heat, aggr_weight=0.1): return aggr_weight * _top_aggregate(heat) + \ aggr_weight * _bottom_aggregate(heat) + heat ''' # Slow for large number of categories def _topk(scores, K=40): batch, cat, height, width = scores.size() topk_scores, topk_inds = torch.topk(scores.view(batch, -1), K) topk_clses = (topk_inds / (height * width)).int() topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() return topk_scores, topk_inds, topk_clses, topk_ys, topk_xs ''' def _topk_channel(scores, K=40): batch, cat, height, width = scores.size() topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), K) topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() return topk_scores, topk_inds, topk_ys, topk_xs def _topk(scores, K=40): batch, cat, height, width = scores.size() topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), K) topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), K) topk_clses = (topk_ind / K).int() topk_inds = _gather_feat( topk_inds.view(batch, -1, 1), topk_ind).view(batch, K) topk_ys = _gather_feat(topk_ys.view(batch, -1, 1), topk_ind).view(batch, K) topk_xs = _gather_feat(topk_xs.view(batch, -1, 1), topk_ind).view(batch, K) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs def ctdet_decode(heat, wh, reg=None, cat_spec_wh=False, K=100): batch, cat, height, width = heat.size() # heat = torch.sigmoid(heat) # perform nms on heatmaps heat = _nms(heat) scores, inds, clses, ys, xs = _topk(heat, K=K) if reg is not None: reg = _tranpose_and_gather_feat(reg, inds) reg = reg.view(batch, K, 2) xs = xs.view(batch, K, 1) + reg[:, :, 0:1] ys = ys.view(batch, K, 1) + reg[:, :, 1:2] else: xs = xs.view(batch, K, 1) + 0.5 ys = ys.view(batch, K, 1) + 0.5 wh = _tranpose_and_gather_feat(wh, inds) if cat_spec_wh: wh = wh.view(batch, K, cat, 2) clses_ind = clses.view(batch, K, 1, 1).expand(batch, K, 1, 2).long() wh = wh.gather(2, clses_ind).view(batch, K, 2) else: wh = wh.view(batch, K, 2) clses = clses.view(batch, K, 1).float() scores = scores.view(batch, K, 1) bboxes = torch.cat([xs - wh[..., 0:1] / 2, ys - wh[..., 1:2] / 2, xs + wh[..., 0:1] / 2, ys + wh[..., 1:2] / 2], dim=2) detections = torch.cat([bboxes, scores, clses], dim=2) return detections
UTF-8
Python
false
false
5,168
py
9
decode.py
8
0.566176
0.543537
0
151
33.231788
79
pytsite/pytsite
7,756,710,985,013
8b0cce6b74052cb59fb7dc8423cc79e456699248
1bc7053e7582e43bdd4b943c5700677e07449d3c
/pytsite/maintenance/__init__.py
a095c4d37f4ca965860074efe8f236f8aa7a4c88
[ "MIT" ]
permissive
https://github.com/pytsite/pytsite
f92eaa041d85b245fbfcdff44224b24da5d9b73a
e4896722709607bda88b4a69400dcde4bf7e5f0a
refs/heads/master
"2021-01-18T01:06:12.357397"
"2019-08-03T02:56:48"
"2019-08-03T02:56:48"
34,899,242
12
2
null
null
null
null
null
null
null
null
null
null
null
null
null
"""PytSite Maintenance """ __author__ = 'Oleksandr Shepetko' __email__ = 'a@shepetko.com' __license__ = 'MIT' # Public API from ._api import enable, disable, is_enabled def _init(): from pytsite import console, lang from . import _console_command lang.register_package(__name__) console.register_command(_console_command.Maintenance()) _init()
UTF-8
Python
false
false
366
py
151
__init__.py
99
0.669399
0.669399
0
19
18.263158
60
dockrexter/Design-Patterns-Python
5,016,521,849,544
5313a44ebcef80b1602608e879876c208cced8cb
8b3fe40844e180d71989a7a953adfe303f3d6e24
/mvc.py
a8fb3ce604c0a26db95b138edf7c8fe8e3e51e39
[]
no_license
https://github.com/dockrexter/Design-Patterns-Python
fe24fb2bc2e3588ea2860fe63cebed022b2f7469
0b8c57b9450c9ffc2823ca9c6f0e548f5dd0c071
refs/heads/master
"2022-01-05T20:38:48.095969"
"2019-07-25T14:04:38"
"2019-07-25T14:04:38"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class model: def __init__(self,name): self.name=name def returning(self,message): if message == "name": return self.name else: return "required information not available" class view: def __init__(self,message): print (message) class controller(model,view): def __init__(self,request): information=model("ghost").returning(request) view(information) controller("name")
UTF-8
Python
false
false
461
py
13
mvc.py
6
0.596529
0.596529
0
20
22.05
56
The-Cracker-Technology/Katana
12,438,225,317,469
c72ed548d6a991c267038cc6ff63f948e5336b0f
ebe6c75ee675f45e078c4c655946c6031d9657a7
/Modes/Gmode.py
6c63cf5104af7ea428a6a835601db9d0e91082f1
[ "MIT" ]
permissive
https://github.com/The-Cracker-Technology/Katana
a8818463c167707d25d8d9cccf170c5a0f453f6d
a54a2e35927cd73505d675920d93b1d8c04a274b
refs/heads/master
"2023-03-19T12:45:04.447647"
"2021-03-14T18:13:40"
"2021-03-14T18:13:40"
347,714,228
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# @name: Katana-dorkscanner # @repo: https://github.com/adnane-X-tebbaa/Katana # @author: Adnane tebbaa (AXT) # Main Google Dorking file V2.0 """ MIT License Copyright (c) 2020 adnane tebbaa Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import requests import proxybroker from googlesearch import search import sys import sys from termcolor import colored, cprint import warnings import random from http import cookiejar class BlockAll(cookiejar.CookiePolicy): return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False netscape = True rfc2965 = hide_cookie2 = False def fxn(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(): warnings.simplefilter("ignore") fxn() def clear(): return os.system('cls' if os.name == 'nt' else 'clear') print ("") A = """ ,_._._._._._._._._|__________________________________________________________ |G|o|o|g|l|e|_|_|_|_________________________________________________________/ | Katana dork scanner (Katana-ds V1.5.3) coded by adnane-X-tebbaa Google Mode """ print ("") print(A) TLD = ["com","com.tw","co.in","be","de","co.uk","co.ma","dz","ru","ca"] s = requests.Session() s.cookies.set_policy(BlockAll()) alpha = input (colored('[>] Please set a Dork : ', 'green' )) query = alpha beta = random.choice(TLD) for gamma in search(query, tld=beta, num=10 , stop=95 , pause=2): print(colored ('[+] Found > ' ,'yellow') + (gamma) ) print(colored ('[+] Done ' ,'green')) print(colored ('[! >] delete .google-cookie file in Katana DIR ' ,'red'))
UTF-8
Python
false
false
2,706
py
3
Gmode.py
2
0.651515
0.644494
0
76
33.592105
96
aspc/mainsite
17,575,006,182,653
81a926ae23813ae67f088113ecf6fc9448d16b7d
65ec50c5bc1bd4948de96cf6a8b6fee82badacef
/aspc/files/models.py
2c537888cd5ea278613ef15da82146003ee0a07f
[ "MIT" ]
permissive
https://github.com/aspc/mainsite
eab3e75e2e701881bae1f3e1c998c5b9f76ae761
a6ccee0bb921147b7f630d65e01371e451aa3c54
refs/heads/master
"2020-04-03T10:23:24.519148"
"2018-04-02T00:49:24"
"2018-04-02T00:49:24"
3,998,083
8
20
MIT
false
"2018-08-24T07:02:02"
"2012-04-11T20:43:21"
"2018-04-02T00:50:02"
"2018-04-02T00:59:10"
26,718
10
17
2
JavaScript
false
null
from django.db import models class ImageUpload(models.Model): name = models.CharField(max_length=100) image = models.ImageField() class FileUpload(models.Model): name = models.CharField(max_length=100) _file = models.FileField() # `file` is a built-in Python function
UTF-8
Python
false
false
274
py
359
models.py
177
0.755474
0.733577
0
9
29.555556
67
csnoboa/sistemas_distribuidos_at1
9,878,424,792,999
47cfc83cb7df00e424d9b127b00bf77593db7cde
cb212d1e2ca56c6fd2c11523d98b897032a8aa18
/script_usuario.py
97b0fbf7e46884de3de3f5a2a6685a6e2775b88c
[]
no_license
https://github.com/csnoboa/sistemas_distribuidos_at1
dff41780ffe9b453895a823a5edc63cc80c83de1
e53325c3a5c848b0b53ad22ed0ec620b744096f6
refs/heads/master
"2023-08-26T05:21:28.612246"
"2021-11-07T00:05:57"
"2021-11-07T00:05:57"
424,194,220
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import Pyro5.api from cliente import Cliente import time server = Pyro5.api.Proxy("PYRONAME:server.enquete") nome = input("Digite o nome do usuario: ") cliente = Cliente(nome, server) cliente.cadastrar() while True: resp = input("Ver menu? \n1 - Sim \n2 - Não\n") if resp == "1": resp = input(""" O que deseja fazer? 0 - Atualizar ( Receber enquetes ) 1 - Criar enquete 2 - Consultar enquete """) if resp == "1": resp = input("Qual enquete pronta deseja criar? de 1 a 3\n") if resp == "1": cliente.cria_enquete("mais saches", "casa", [ { "dia": "sabado", "horario": "13:00", "votos": 0 }, { "dia": "sabado", "horario": "18:00", "votos": 0 }, { "dia": "domingo", "horario": "13:00", "votos": 0 }, ], 100) if resp == "2": cliente.cria_enquete("mais ração", "casa", [ { "dia": "sexta", "horario": "13:00", "votos": 0 }, { "dia": "sabado", "horario": "18:00", "votos": 0 }, ], 15) if resp == "3": cliente.cria_enquete("mais brinquedos", "casa", [ { "dia": "segunda", "horario": "10:00", "votos": 0 }, { "dia": "terça", "horario": "18:00", "votos": 0 }, ], 60) elif resp == "2": titulo = input("Qual o nome da enquete que quer consultar?\n") cliente.ver_enquete(titulo) else: time.sleep(15) else: time.sleep(120)
UTF-8
Python
false
false
2,274
py
7
script_usuario.py
7
0.33304
0.305727
0
81
27.024691
74
Kowenjko/Python_Homework_14_Kowenjko
3,418,794,015,392
3975a80b7c4f8f369000dd6c4d62ddade2010850
740c5c83800ab6bd54fe3a977c4af723bc354ab2
/unregisteredCustomer.py
4175ba3cc7ae8563073c1422996062baef6e70e4
[]
no_license
https://github.com/Kowenjko/Python_Homework_14_Kowenjko
1ffa41f0e96c82372e0b55591986ddfae864a7c3
5e8fc6f3488018c223bf9f978f1040efa5c8ecf3
refs/heads/master
"2023-06-22T15:09:50.751139"
"2021-07-25T07:47:19"
"2021-07-25T07:47:19"
388,225,572
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import psycopg2 from settings import * from connection import Connection class UnregisteredCuctomer(Connection): def register_self(self, login, password, data): self._register(login, password, 'customer') table = 'customer' result = self._postData(table, data) return result def get_product_info(self, category='', selector='',): """ category must be one of the item from the list: ['product_name','country_name', 'category_name'] """ categoryes = ['product_name', 'country_name', 'category_name'] table = ('product p',) fields = ( """p.id, p.product_name ,p.unit_price,c.country_name,pc.category_name """,) fieldNames = ["id", "product_name", "unit_price", "country_name", "category_name"] if category and category in categoryes and selector: where = f"""where {category} = '{selector}'""" else: where = '' selector = f""" inner join country c on c.id =p.country_id inner join product_category pc on pc.id =p.product_catagery_id {where}""" result = self._getData(table, fields, selector) changeRes = [] for item in result: cort = {} for index, element in enumerate(item): cort[fieldNames[index]] = element changeRes.append(cort) return changeRes if __name__ == '__main__': regCust = UnregisteredCuctomer() orders = regCust.get_product_info() print(orders) # ---------------------------------- # data = [{ # 'city_id': 2, # 'first_name': "Loman", # 'last_name': "Mipol" # }] # put = regCust.register_self('Petro', 'Petrow', data) # print(put)
UTF-8
Python
false
false
1,844
py
6
unregisteredCustomer.py
5
0.53308
0.531996
0
56
31.928571
101
libbyandhelen/nn_arch_search
18,717,467,478,870
63b7f96ee494f108651a37c58d893e6ce28fa8b3
2ad545b3784e523889cc8be91608b3f8fe53cf75
/NASsearch/acquisition_func.py
62ea5b7c5939e7add0c8838de381653c922c7458
[]
no_license
https://github.com/libbyandhelen/nn_arch_search
707767516140322a64f956bb79bfc74ecfc69b7c
0df1af91ff794d7017bd38bcbd758df5b3d6a091
refs/heads/master
"2020-04-12T22:44:53.618305"
"2018-12-22T09:59:11"
"2018-12-22T09:59:11"
162,797,862
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" module for acquisition function""" import numpy as np from scipy.stats import norm from Kernel_optimization.all_gp import GaussianProcess class AcquisitionFunc: """ class for acquisition function expected improvement in this case """ def __init__(self, X_train, y_train, current_optimal, mode, trade_off): """ :param mode: pi: probability of improvement, ei: expected improvement, lcb: lower confident bound :param trade_off: a parameter to control the trade off between exploiting and exploring :param model_type: gp: gaussian process, rf: random forest """ self.X_train = X_train self.y_train = y_train self.current_optimal = current_optimal self.mode = mode or "ei" self.trade_off = trade_off or 0.1 self.model = GaussianProcess(80) def compute(self, X_test, weight_file): y_means, y_vars, y_stds = self.model.fit_predict(self.X_train, X_test, self.y_train, weight_file) z = (y_means - self.current_optimal - self.trade_off) / y_stds if self.mode == "ei": result = y_stds * (z * norm.cdf(z) + norm.pdf(z)) elif self.mode == "pi": result = norm.cdf(z) elif self.mode == "ucb": result = y_means + self.trade_off * y_stds else: result = - (y_means - self.trade_off * y_stds) return result, y_means, y_stds
UTF-8
Python
false
false
1,427
py
10
acquisition_func.py
9
0.612474
0.609671
0
36
38.611111
105
milton96/practicas
12,094,627,942,210
72aabc5a22d865d0c4b8275d51be0a313b8cad7d
eb37d1ae40953bb7498e88e97e52f2c9debaae10
/Algorithms/Sorting/Bubble Sort/difference_max_min.py
2c2dc85435780b235dd9ffae6c32acd906ca814b
[]
no_license
https://github.com/milton96/practicas
141ef1c5240dbd95f122c0f670f1a0e5ed61a9a4
1c9e5b7098b9f2b665e9b3e38f8913a2784ea2d1
refs/heads/master
"2020-07-08T13:30:02.151999"
"2019-09-25T17:43:56"
"2019-09-25T17:43:56"
203,689,178
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Obtiene la diferencia entre la suma máxima y la suma mínima de un array, # usando n-m elementos para calcular cada una t = int(input()) for k in range(t): n, m = map(int, input().split()) a = list(map(int, input().split())) #Solución implementando ordenamiento con burbuja # for i in range(n-1): # for j in range(n-i-1): # if a[j] >= a[j+1]: # b = a[j] # a[j] = a[j+1] # a[j+1] = b # print(sum(a[m:n])-sum(a[0:n-m])) #Solución implementada usando el metodo de ordenación por defecto de python a.sort() i = 0 max = 0 min = 0 while i < (n-m): min += a[i] i += 1 i = 0 while i < (n-m): max += a[n-i-1] i += 1 print(max-min)
UTF-8
Python
false
false
785
py
44
difference_max_min.py
43
0.49359
0.476923
0
29
25.896552
79
ashiqur0202/Python-Projects
1,735,166,814,243
ba03002610ffd4413fcdd9510fc62f1812b6718a
21281f2124348f122894522ff8ce512c2c210568
/Heads Tails.py
0188e27a15e701d81020ec2aebf35d527daf5193
[]
no_license
https://github.com/ashiqur0202/Python-Projects
624097c93c59d4c28ecf1b919089de390141cdc9
467df5be1064dbc365e798b9e8fb52cc435f489f
refs/heads/master
"2023-02-02T16:51:11.130916"
"2021-06-04T16:29:04"
"2021-06-04T16:29:04"
319,058,235
0
0
null
false
"2021-05-31T18:27:38"
"2020-12-06T14:54:42"
"2021-05-31T17:55:17"
"2021-05-31T18:27:38"
1
0
0
0
Python
false
false
print("/// Heads and Tails ///") import random numbers = int(input("enter mumbers: \n")) random.seed(numbers) random_numbers = random.randint(0, 1) if random_numbers == 1: print("Heats") else: print("Tails")
UTF-8
Python
false
false
225
py
9
Heads Tails.py
8
0.635556
0.622222
0
10
20.7
41
Cheburashka303/edrenbaton
19,439,022,006,506
90b6883980033bfcde8b92d14c8dfa802b4c88f0
7c6adf3115e720abc0039ffafac3850abea9d2b3
/yoperniiteatr.py
5abe2a309d0613a407d94854845025c2b71e8e73
[ "MIT" ]
permissive
https://github.com/Cheburashka303/edrenbaton
2389270d9907b110ef02561743e8bbe6eefed671
55891919b6039a427991cbdb978b07b7f63a8d64
refs/heads/main
"2023-02-17T18:00:11.979975"
"2021-01-19T07:10:44"
"2021-01-19T07:10:44"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Функция кодирования в код Морзе будет называться encode_to_morse(text). Функция декодирования называется decode_from_morse(code).""" from encode import encode_to_morse from decode import decode_from_morse
UTF-8
Python
false
false
282
py
4
yoperniiteatr.py
3
0.8
0.8
0
6
34
74
markWJJ/Open_domain_QA
10,591,389,370,242
e1dee17b99b955c03f72e8b156230c27264f3bf6
f303abd351b5502138a8812f65e4ba7701faf485
/R_Net_QA/Data_r_net/Data_deal_no_array.py
55746f7197dea6f18ceb27a167a3f5ee6262183a
[]
no_license
https://github.com/markWJJ/Open_domain_QA
55b8c992de615fc00dbd8c264fd6d2f50df77df8
a06bb9511f832d6f30a67b4a420c4f2de0d7b14d
refs/heads/master
"2021-09-06T01:16:38.964566"
"2018-02-01T08:16:59"
"2018-02-01T08:16:59"
114,727,196
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import pickle import os global PATH import sys PATH=os.path.split(os.path.realpath(__file__))[0] class DataDealRNet(object): def __init__(self,train_path,dev_path,test_path,dim,batch_size,Q_len,P_len,flag): self.train_path=train_path self.dev_path=dev_path self.test_path=test_path self.dim=dim self.Q_len=Q_len self.P_len=P_len self.batch_size=batch_size if flag=="train_new": self.vocab=self.get_vocab() pickle.dump(self.vocab,open(PATH+"/vocab.p",'wb')) elif flag=="test" or flag=="train": self.vocab=pickle.load(open(PATH+"/vocab.p",'rb')) self.index=0 def get_vocab(self): ''' 构造字典 :return: ''' train_file=open(PATH+self.train_path,'r') test_file=open(PATH+self.dev_path,'r') dev_file=open(PATH+self.test_path,'r') vocab={"NONE":0} index=1 for ele in train_file: ele.replace("\n","") ele1=ele.replace("\t\t"," ") ws=ele1.split(" ") for w in ws: w=w.lower() if w not in vocab: vocab[w]=index index+=1 for ele in test_file: ele1=ele.replace(" "," ").replace("\n","") for w in ele1.split(" "): w=w.lower() if w not in vocab: vocab[w]=index index+=1 for ele in dev_file: ele1=ele.replace(" "," ").replace("\n","") for w in ele1.split(" "): w=w.lower() if w not in vocab: vocab[w]=index index+=1 train_file.close() dev_file.close() test_file.close() return vocab def sent2vec(self,sent,max_len): ''' 根据vocab将句子转换为向量 :param sent: :return: ''' sent=str(sent).replace("\n","") sent_list=[] real_len=len(sent.split(" ")) for word in sent.split(" "): word=word.lower() if word in self.vocab: sent_list.append(self.vocab[word]) else: sent_list.append(0) if len(sent_list)>=max_len: new_sent_list=sent_list[0:max_len] else: new_sent_list=sent_list ss=[0]*(max_len-len(sent_list)) new_sent_list.extend(ss) sent_vec=np.array(new_sent_list) return sent_vec,real_len def shuffle(self,Q,A,label): ''' 将矩阵X打乱 :param x: :return: ''' ss=list(range(Q.shape[0])) np.random.shuffle(ss) new_Q=np.zeros_like(Q) new_A=np.zeros_like(A) new_label=np.zeros_like(label) for i in range(Q.shape[0]): new_Q[i]=Q[ss[i]] new_A[i]=A[ss[i]] new_label[i]=label[ss[i]] return new_Q,new_A,new_label def get_ev_ans(self,sentence): ''' 获取 envience and answer_label :param sentence: :return: ''' env_list=[] ans_list=[] for e in sentence.split(" "): try: env_list.append(e.split("/")[0]) ans_list.append(self.label_dict[str(e.split("/")[1])]) except: pass return " ".join(env_list),ans_list def next_batch(self): ''' 获取训练机的下一个batch :return: ''' train_file=open(PATH+self.train_path,'r') Q_list=[] P_list=[] label_list=[] train_sentcens=train_file.readlines() file_size=len(train_sentcens) Q_len_list=[] P_len_list=[] for sentence in train_sentcens: sentence = sentence.replace("\n", "") sentences = sentence.split("\t\t") # sentences=sentence.split(" ") Q_sentence = sentences[0] P_sentence=sentences[1] label=[int(e) for e in sentences[2].split("-")] Q_array,_=self.sent2vec(Q_sentence,self.Q_len) A_array,_=self.sent2vec(P_sentence,self.P_len) Q_list.append(list(Q_array)) P_list.append(list(A_array)) if len(str(Q_sentence).split(" "))>=self.Q_len: Q_len_list.append(self.Q_len) else: Q_len_list.append(len(str(Q_sentence).split(" "))) if len(str(P_sentence).split(" ")) >= self.P_len: P_len_list.append(self.P_len) else: P_len_list.append(len(str(P_sentence).split(" "))) label_list.append(label) train_file.close() result_Q=np.array(Q_list) result_P=np.array(P_list) result_Q_len_list=np.array(Q_len_list) result_P_len_list=np.array(P_len_list) result_label=np.array(label_list) result_Q,result_A,result_label=self.shuffle(result_Q,result_P,result_label) num_iter=int(file_size/self.batch_size) if self.index<num_iter: return_Q=result_Q[self.index*self.batch_size:(self.index+1)*self.batch_size] return_P=result_P[self.index*self.batch_size:(self.index+1)*self.batch_size] return_label=result_label[self.index*self.batch_size:(self.index+1)*self.batch_size] return_Q_len=result_Q_len_list[self.index*self.batch_size:(self.index+1)*self.batch_size] return_P_len=result_P_len_list[self.index*self.batch_size:(self.index+1)*self.batch_size] self.index+=1 else: self.index=0 return_Q=result_Q[0:self.batch_size] return_P=result_P[0:self.batch_size] return_Q_len = result_Q_len_list[0:self.batch_size] return_P_len = result_P_len_list[0:self.batch_size] return_label=result_label[0:self.batch_size] return return_Q,return_P,return_label,return_Q_len,return_P_len def get_dev(self): ''' 读取验证数据集 :return: ''' dev_file = open(self.dev_path, 'r') Q_list = [] A_list = [] label_list = [] train_sentcens = dev_file.readlines() for sentence in train_sentcens: sentences=sentence.split(" ") Q_sentence=sentences[0] A_sentence=sentences[1] label=sentences[2] Q_array=self.sent2array(Q_sentence,self.Q_len) A_array=self.sent2array(A_sentence,self.P_len) Q_list.append(list(Q_array)) A_list.append(list(A_array)) label_list.append(int(label)) dev_file.close() result_Q=np.array(Q_list) result_A=np.array(A_list) result_label=np.array(label_list) return result_Q,result_A,result_label def get_test(self): ''' 读取测试数据集 :return: ''' test_file = open(self.test_path, 'r') Q_list = [] A_list = [] label_list = [] train_sentcens = test_file.readlines() for sentence in train_sentcens: sentences=sentence.split(" ") Q_sentence=sentences[0] A_sentence=sentences[1] label=sentences[2] Q_array,_=self.sent2array(Q_sentence,self.Q_len) A_array,_=self.sent2array(A_sentence,self.P_len) Q_list.append(list(Q_array)) A_list.append(list(A_array)) label_list.append(int(label)) test_file.close() result_Q=np.array(Q_list) result_A=np.array(A_list) result_label=np.array(label_list) return result_Q,result_A,result_label def get_Q_array(self,Q_sentence): ''' 根据输入问句构建Q矩阵 :param Q_sentence: :return: ''' Q_len=len(str(Q_sentence).replace("\n","").split(" ")) if Q_len>=self.Q_len: Q_len=self.Q_len Q_array,_=self.sent2vec(Q_sentence,self.Q_len) return Q_array,np.array([Q_len],dtype=np.int32) def get_A_array(self,P_sentence): ''' 根据输入的答案句子构建A矩阵 :param A_sentence: :return: ''' P_sentence, _ = self.get_ev_ans(P_sentence) P_len = len(str(P_sentence).replace("\n", "").split(" ")) if P_len>=self.P_len: P_len=self.P_len P_vec,_=self.sent2vec(P_sentence, self.P_len) return P_vec,np.array([P_len],dtype=np.int32) def get_vocab_size(self): ''' 获取词典大小 :return: ''' return len(self.vocab) if __name__ == '__main__': dd = DataDealRNet(train_path="/SQUQA_train_1.txt", test_path="/test1.txt", dev_path="/dev1.txt", dim=100, batch_size=4 ,Q_len=30, P_len=100, flag="test") print(dd.get_vocab_size()) for i in range(100): print(i) return_Q, return_P, return_label, return_Q_len, return_P_len = dd.next_batch() print(return_P) print("\n")
UTF-8
Python
false
false
9,214
py
30
Data_deal_no_array.py
22
0.511579
0.50397
0
283
31.045936
101
NTUE-Arduino-Lab/clec-inventory-backend
10,222,022,199,235
1683fb4f4c15599aa27b0fb25738c3464afc8165
fd0390330406f2d67efeca9dad978f6fef28bc1f
/app.py
02d366a197fb90d8c2e4e49cd1947116eeab538c
[]
no_license
https://github.com/NTUE-Arduino-Lab/clec-inventory-backend
825df8f5ab31271da435cf828cefe3c0f855e1a1
61e6c2697498858b414c4220b60a97272ea4dcc9
refs/heads/main
"2023-07-15T10:17:13.147852"
"2021-08-16T02:51:05"
"2021-08-16T02:51:05"
392,362,853
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import ftplib import re import sys import os import json import pymysql import socket import base64 import random import io from tenacity import * from uuid import uuid4 from flask import Flask, request, flash, redirect, url_for, send_file from werkzeug.datastructures import FileStorage from functools import wraps from flask_restful import reqparse, abort, Api, Resource from datetime import timedelta, datetime from pytz import timezone import time import logging from threading import Lock from ftplib import FTP app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() def NowTime(): return datetime.now(timezone('Asia/Taipei')).strftime("%Y-%m-%d %H:%M:%S") def after_request(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,PATCH,DELETE,POST' response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization,Referrer-Policy' return response app.after_request(after_request) app.config['PROPAGATE_EXCEPTIONS'] = True class ftpfunc(): def connect(self): ftp = FTP('gdlab-dev.local') ftp.login('GDLab','8TRcrZ') ftp.cwd('img') return ftp def upload(self, file, id): ftp = self.connect() ftp.storbinary("STOR "+id,file,1024) ftp.quit() def download(self, file, id): ftp = self.connect() try: ftp.retrbinary("RETR "+id+".jpg",file.write) except: ftp.quit() return False ftp.quit() class ConnectionManager(object): __instance = None __connection = None __lock = Lock() def __new__(cls): if ConnectionManager.__instance is None: ConnectionManager.__instance = object.__new__(cls) return ConnectionManager.__instance def __getConnection(self): if (self.__connection == None): db_settings = { "host": "gdlab-dev.local", "port": 3306, "user": "clec", "password": "jCLP4x", "db": "inventory", "charset": "utf8" } self.__connection = pymysql.connect(**db_settings) return self.__connection def __removeConnection(self): self.__connection = None @retry(stop=stop_after_attempt(3), wait=wait_fixed(10), retry=retry_if_exception_type(pymysql.Error), after=after_log(app.logger, logging.DEBUG)) def executeQueryJSON(self, procedure, payload=None): result = {} try: conn = self.__getConnection() cursor = conn.cursor() if payload: cursor.execute(f"CALL {procedure}(%s)", json.dumps(payload)) else: cursor.execute(f"CALL {procedure}()") raw = '' for r in cursor.fetchall(): for inr in r: raw = raw + inr result = json.loads(raw) print(result) except pymysql.Error as e: if isinstance(e, pymysql.ProgrammingError) or isinstance(e, pymysql.OperationalError): app.logger.error(f"{e.args[1]}") if e.args[0] == "08S01": self.__removeConnection() raise finally: conn.commit() cursor.close() self.__removeConnection() return result class Queryable(Resource): def executeQueryJson(self, verb, payload=None): entity = type(self).__name__.lower() procedure = f"web.`{verb}_{entity}`" print(procedure) result = ConnectionManager().executeQueryJSON(procedure, payload) return result @app.route('/') def index(): return "Hello" class Login(Queryable): def post(self): parser.add_argument('Account') parser.add_argument('Passwd') args = parser.parse_args() try: result = self.executeQueryJson("post", args) except: result = json.dumps({'message':'incorrect username or password'}) return result, 200 class Object(Queryable,ftpfunc): def get(self, multi): args = {} args['id'] = multi result = self.executeQueryJson("get", args) return result, 200 def post(self, multi = None): result = {} if multi == None: parser.add_argument('id') parser.add_argument('year') parser.add_argument('appellation') parser.add_argument('buydate') parser.add_argument('source') parser.add_argument('unit') parser.add_argument('keeper') parser.add_argument('note') args = parser.parse_args() args['status'] = 'in stock' if args['note'] == None: args['note'] = '' result = self.executeQueryJson("post", args) elif multi == 'multi': parser.add_argument('args',type = dict,action="append") args = parser.parse_args()['args'] result = [] for i in args: i['status'] = 'in stock' if i['note'] == None: i['note'] = '' result.append(self.executeQueryJson("post", i)) return result, 200 def delete(self): parser.add_argument('id') args = parser.parse_args() result = self.executeQueryJson("delete", args) return result, 200 def patch(self): parser.add_argument('args',type = dict) args = parser.parse_args()['args'] print(args) result = self.executeQueryJson("patch", args) return result, 200 class Borrow(Queryable): def get(self, id): args = {} args['id'] = id result = self.executeQueryJson("get", args) return result, 200 def post(self): parser.add_argument('args',type = dict,action="append") args = parser.parse_args()['args'] print(args) result = [] for i in args: result.append(self.executeQueryJson("post", i)) return result, 200 class Borrowing(Queryable): def get(self): result = self.executeQueryJson("get") return result, 200 class Return(Queryable): def get(self, id): args = {} args['id'] = id result = self.executeQueryJson("get", args) return result, 200 def post(self): parser.add_argument('args',type = dict,action="append") args = parser.parse_args()['args'] result = [] for i in args: result.append(self.executeQueryJson("post", i)) return result, 200 class Objects(Queryable): def get(self, type = None): result = {} if type == None: result = self.executeQueryJson("get") elif type == 'instock': result = self.executeQueryJson("get_instock") return result, 200 class Img(Queryable ,ftpfunc): def post(self, id): parser.add_argument('image', type=FileStorage, location='files') args = parser.parse_args() imgpath = id+'.jpg' img = args['image'].save(imgpath) del img file = open(imgpath,'rb') self.upload(file,imgpath) os.remove(imgpath) return send_file(io.BytesIO(file.read()),mimetype='image/jpeg',as_attachment=True,download_name='%s.jpg' % id) def get(self, id): file = open('file.jpg', 'wb') img = self.download(file, id) if img == False: return {"message":"no image"}, 200 else: file.close() file = open('file.jpg', 'rb') os.remove('file.jpg') return send_file(io.BytesIO(file.read()),mimetype='image/jpeg',as_attachment=True,download_name='%s.jpg' % id) class Search(Queryable): def get(self, keyword): key = keyword.split(',') print(key) result = [] for i in key: args = {} args['keyword'] = i temp = self.executeQueryJson("get", args) for t in temp: if not t in result: result.append(t) return result, 200 class History(Queryable): def get(self, id): args = {} args['id'] = id result = self.executeQueryJson("get", args) return result, 200 api.add_resource(Login, '/login') api.add_resource(Object, '/object','/object/<multi>') api.add_resource(Objects, '/objects','/objects/<type>') api.add_resource(Borrow, '/borrow', '/borrow/<id>') api.add_resource(Borrowing, '/borrowing') api.add_resource(Return, '/return') api.add_resource(Img, '/img/<id>') api.add_resource(Search, '/search/<keyword>') api.add_resource(History, '/history/<id>') if __name__ == '__main__': app.run(host='0.0.0.0', port=80)
UTF-8
Python
false
false
7,494
py
3
app.py
1
0.670003
0.660528
0
296
24.317568
146
madhavGSU/Data_Programming
8,280,696,979,711
b2c83bd0089e37970f411814ca7df593f467bf40
8f7b390fcd5fab10d7bb377512c8b912a108fc88
/Assignment_1/chapter2_21.py
9ef20b8d9fa3d90534dc0869637249f09639da51
[]
no_license
https://github.com/madhavGSU/Data_Programming
5f803f3f59a9e5c9c3e6381ce1e02a94e88bd2e2
a673ab8a2aa0d57700fd44abf10fa96280c2c904
refs/heads/master
"2021-02-22T05:57:36.797488"
"2020-03-06T09:25:15"
"2020-03-06T09:25:15"
245,370,362
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Tue Jan 14 18:37:45 2020 @author: Administrator """ import math; principal=eval(input("Give the principal amount")); intRate=0.05/12; # interest=principal*((1+(0.05)/12))**6; interest=0; total=principal; for i in range(6): total=principal+interest; interest=total*(1+intRate); # print("account value after month", i, "is:", interest); print("After the sixth month, the account value is:", round(interest, 2));
UTF-8
Python
false
false
456
py
86
chapter2_21.py
86
0.684211
0.620614
0
20
21.8
74
vincentwyshan/tap
14,035,953,154,667
4603a6ce9e042d8cd9b0b41c766200d01588b7b3
d3c126f0fe2cd531e6c5041ff3e7751035c1fb89
/tap/security.py
a3f6aae9893d514443c2c3776b352777c5c329b8
[]
no_license
https://github.com/vincentwyshan/tap
7e88e3c7042c428fa6bc008554ba134a8b856781
54a7c3bc0386db692abaf001dfa9bdfcacaab0ec
refs/heads/master
"2021-01-17T12:58:25.438682"
"2018-01-31T04:04:25"
"2018-01-31T04:04:25"
59,276,647
1
0
null
false
"2016-05-25T09:49:06"
"2016-05-20T08:13:12"
"2016-05-20T08:18:53"
"2016-05-25T09:49:05"
11,993
0
0
0
JavaScript
null
null
#coding=utf8 import datetime import os from hashlib import sha256 from hmac import HMAC from pyramid.security import Allow, Everyone, Authenticated from pyramid.security import unauthenticated_userid, authenticated_userid from pyramid.security import Allow, Deny import transaction from tap.service import exceptions from tap.models import ( DBSession, TapUser, TapPermission, TapUserPermission, TapProject, TapApi, ) def groupfinder(user_id, request): if user_id: user = bind_user(request, user_id) if user: return [user.name] raise exceptions.UserNotAvailable return [Everyone] class TempPermission(object): def __init__(self, user_permission): if not user_permission: self.a_view = False self.a_add = False self.a_edit = False self.a_delete = False else: self.a_view = user_permission.a_view self.a_add = user_permission.a_add self.a_edit = user_permission.a_edit self.a_delete = user_permission.a_delete class AuthControl(object): def __init__(self, request): self.request = request def route(self): """ 根据URL提供相应的权限查询 :return: """ need_permission = None if (self.request.path.startswith('/management/') and not self.request.path.startswith('/management/action')): need_permission = self.pages_permission(self.request.path) elif self.request.path.startswith('/management/action'): return [(Allow, Everyone, 'view'), (Allow, Everyone, 'edit'), (Allow, Everyone, 'delete'), (Allow, Everyone, 'add')] elif self.request.path == '/': need_permission = 'SYS_INDEX:view' else: raise Exception("No permission route") user_perm = self.get_userperm(need_permission) result = [] if user_perm: if user_perm.a_view: result.append((Allow, self.request.user.name, 'view')) if user_perm.a_add: result.append((Allow, self.request.user.name, 'add')) if user_perm.a_delete: result.append((Allow, self.request.user.name, 'delete')) if user_perm.a_edit: result.append((Allow, self.request.user.name, 'edit')) else: return [(Deny, Everyone, 'view'), (Deny, Everyone, 'edit'), (Deny, Everyone, 'delete'), (Deny, Everyone, 'add')] return result def get_userperm(self, perm_name): # import pdb; pdb.set_trace() with transaction.manager: need_permission, action = perm_name.split(':') permission = DBSession.query(TapPermission).filter_by( name=need_permission).first() user_perm = DBSession.query(TapUserPermission).filter_by( user_id=self.request.user.id, permission_id=permission.id).first() user_perm = TempPermission(user_perm) if not need_permission.startswith('SYS') and '.' in need_permission: # if parent-permission has the authorization, # also child-permission has it. permissions = need_permission.split('.') for i in range(len(permissions)): permission = '.'.join(permissions[:i+1]) permission = DBSession.query(TapPermission).filter_by( name=permission ).first() if not permission: continue _perm = DBSession.query(TapUserPermission).filter_by( user_id=self.request.user.id, permission_id=permission.id ).first() if _perm: user_perm.a_add = (user_perm.a_add or _perm.a_add) user_perm.a_edit = (user_perm.a_edit or _perm.a_edit) user_perm.a_delete = (user_perm.a_delete or _perm.a_delete) user_perm.a_view = (user_perm.a_view or _perm.a_view) return user_perm def project_name(self, project_id): project = DBSession.query(TapProject).get(project_id) return project.name def project_name_byapi(self, api_id): api = DBSession.query(TapApi).get(api_id) return api.project.name def api_name(self, api_id): api = DBSession.query(TapApi).get(api_id) return '%s.%s' % (api.project.name, api.name) def pages_permission(self, path): # Permission: result = None matchdict = self.request.matchdict params = self.request.params if path.startswith('/management/database'): result = 'SYS_DATABASE:view' elif path.startswith('/management/client'): result = 'SYS_CLIENT:view' elif path == '/management/user': result = 'SYS_USER:view' elif path.startswith('/management/user/edit/'): result = 'SYS_USER:edit' elif path == '/management/project': result = 'SYS_PROJECT:view' elif path.startswith('/management/project/'): result = '%s:view' % self.project_name(matchdict['project_id']) elif path.startswith('/management/api/'): result = '%s:view' % self.project_name_byapi(matchdict['api_id']) elif path.startswith('/management/api-test'): result = '%s:view' % self.project_name_byapi(params['id']) return result @property def __acl__(self): if not self.request.userid: return [(Deny, Everyone, 'view'), (Deny, Everyone, 'edit'), (Deny, Everyone, 'delete'), ] if self.request.user.is_admin: return [(Allow, self.request.user.name, 'view'), (Allow, self.request.user.name, 'edit'), (Allow, self.request.user.name, 'delete'), (Allow, self.request.user.name, 'access'), ] return self.route() class TmpContainer(object): @classmethod def load(cls, values): result = TmpContainer() for k, v in values.items(): setattr(result, k, v) return result def get_user(request): if not hasattr(request, 'inst_user'): user_id = authenticated_userid(request) if not user_id: user = unauthenticated_userid(request) request.inst_user = user else: bind_user(request, user_id) return request.inst_user def get_user_id(request): user_id = authenticated_userid(request) return user_id def bind_user(request, user_id): if hasattr(request, 'inst_user'): return request.inst_user if user_id is not None: with transaction.manager: user = DBSession.query(TapUser).get(user_id) if not user: return None user = [(k, getattr(user, k)) for k in user.__table__.columns.keys()] user = dict(user) user = TmpContainer.load(user) request.inst_user = user return request.inst_user def encrypt_password(password, salt=None): """Hash password on the fly.""" if salt is None: salt = os.urandom(8) # 64 bits. assert 8 == len(salt) assert isinstance(salt, str) if isinstance(password, unicode): password = password.encode('UTF-8') assert isinstance(password, str) result = password for i in xrange(10): result = HMAC(result, salt, sha256).digest() return salt + result def valid_password(user, password): salt = user.password[:8] return encrypt_password(password, salt) == user.password
UTF-8
Python
false
false
7,936
py
71
security.py
35
0.563811
0.561789
0
233
32.965665
82
its-sachin/LeetCode
13,683,765,826,009
1051a67ee6bf24c3f7b030af1bb5a9e4ec642376
52ece7acc902c570a8981ed8e3104cad80f4c80d
/Random/q73.py
684cb1246be534f120a83fb25ebd06f44b50e3dd
[]
no_license
https://github.com/its-sachin/LeetCode
fa1b4c30672bd82bd777001553f6e06c191ba6e3
44b79d3d55b383e74d4c9cd7a3da7d659f3f36d5
refs/heads/master
"2023-06-19T11:24:58.473110"
"2021-07-18T19:02:57"
"2021-07-18T19:02:57"
380,414,089
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Solution: def setZeroes(self, matrix): d={} for i in range(len(matrix)): for j in range(len(matrix[i])): if(matrix[i][j]==0): if(d.get(i)==None): d[i]=[j] else: d[i].append(j) done = {} for k in d: for i in range(len(matrix[k])): matrix[k][i]=0 for j in d[k]: if(done.get(j)==None): for i in range(len(matrix)): matrix[i][j]=0 done[j]=True o = Solution() matrix=[[0,1,2,0],[3,4,5,2],[1,3,1,5]] o.setZeroes(matrix) print(matrix)
UTF-8
Python
false
false
718
py
89
q73.py
88
0.376045
0.355153
0
25
27.4
48
kfconsultant/scale
12,627,203,887,421
e273b83a145ff56f86ce96288139068261a7d0b9
65306b41168a5afa6fc80904cc0fbf737939a01a
/scale/util/host.py
5c908d43ba68c7e1d9a8ec0e6b18bb843ad11a64
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
https://github.com/kfconsultant/scale
9e5df45cd36211d1bc5e946cf499a4584a2d71de
28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b
refs/heads/master
"2020-12-07T00:04:37.737556"
"2020-01-06T12:57:03"
"2020-01-06T12:57:03"
232,587,229
0
0
Apache-2.0
true
"2020-01-08T14:53:36"
"2020-01-08T14:53:35"
"2020-01-06T12:57:08"
"2020-01-06T19:10:58"
299,783
0
0
0
null
false
false
"""Defines the named tuple for host locations""" from __future__ import unicode_literals from collections import namedtuple # Named tuple represents a host location HostAddress = namedtuple('HostAddress', ['hostname', 'port', 'protocol']) def host_address_from_mesos_url(url): """Extract URL components from a Mesos Master URL Must include the protocol prefix. Ports may be omitted. :param url: The URL to parse :type url: basestring :return: Parsed URL components :rtype: :class:`util.host.HostAddress` """ from urlparse import urlparse elements = urlparse(url) # infer port from scheme if not set: port = elements.port if not port: if elements.scheme == 'https': port = 443 elif elements.scheme == 'http': port = 80 return HostAddress(elements.hostname, port, elements.scheme)
UTF-8
Python
false
false
881
py
908
host.py
755
0.671964
0.666288
0
32
26.5
73
LightSys/kardia
1,400,159,353,044
acfcb76e2ed9fca44b7fe53e85c6a242c4f87a77
f8b5d28d02800761116049df9cbe85996ada6aa1
/kardia-dev-tools/zac_python_script.py
69d0ea60bd37335553f84a44e97b2ece18104e73
[]
no_license
https://github.com/LightSys/kardia
5efee753765eb80fca36ee13fe996a278d374325
cc3b9b607dc60c23dabd7c3b950d9aad0054e562
refs/heads/master
"2023-09-04T04:29:25.330880"
"2023-07-18T21:46:52"
"2023-07-18T21:46:52"
38,851,624
6
5
null
false
"2023-08-08T23:14:39"
"2015-07-10T00:08:36"
"2023-08-03T21:35:26"
"2023-08-08T23:14:39"
66,157
5
6
2
Java
false
false
import csv from datetime import datetime counter = 0 modCount = 0 setID = set() setAmounts = set() setAmountErrorsId = [] setDatesErrorsPrev = [] setDatesErrorsNext = [] setErrorNTLOnce = [] setErrorNTLTwice = [] setErrorNTLMult = [] setErrorNTLMultBlank = [] setErrorNTLEqualFirst = [] setAmountZero = [] setIsExtraNull = [] with open('moreData.csv') as csvfile: rowReader = csv.reader(csvfile) prevRow = rowReader.__next__() for row in rowReader: firstDate = datetime.strptime(row[5], "%d %b %Y %H:%M") lastDate = datetime.strptime(row[6], "%d %b %Y %H:%M") if(row[18] == ""): setIsExtraNull.append(row[1]) setIsExtraNull.append(row[2]) setIsExtraNull.append(row[3]) if (int(row[8]) < 2): if(row[7] != ""): setErrorNTLOnce.append(row[1]) setErrorNTLOnce.append(row[2]) setErrorNTLOnce.append(row[3]) elif (int(row[8]) == 2): if(row[7] != row[5]): setErrorNTLTwice.append(row[1]) setErrorNTLTwice.append(row[2]) setErrorNTLTwice.append(row[3]) else: if(row[7] == ""): setErrorNTLMultBlank.append(row[1]) setErrorNTLMultBlank.append(row[2]) setErrorNTLMultBlank.append(row[3]) elif(row[7] == row[5]): setErrorNTLEqualFirst.append(row[1]) setErrorNTLEqualFirst.append(row[2]) setErrorNTLEqualFirst.append(row[3]) else: ntlDate = datetime.strptime(row[7], "%d %b %Y %H:%M") if(firstDate >= ntlDate or lastDate < ntlDate): setErrorNTLMult.append(row[1]) setErrorNTLMult.append(row[2]) setErrorNTLMult.append(row[3]) if(row[4][0] == "-"): setAmountZero.append(row[1]) setAmountZero.append(row[2]) setAmountZero.append(row[3]) if (row[2] == prevRow[2] and row[1] == prevRow[1]): if(row[6] != prevRow[20] and row[6] != "" and prevRow[20] != ""): setDatesErrorsPrev.append(row[1]) setDatesErrorsPrev.append(row[2]) setDatesErrorsPrev.append(row[3]) if(row[21] != prevRow[5] and row[21] != "" and row[5] != ""): setDatesErrorsNext.append(row[1]) setDatesErrorsNext.append(row[2]) setDatesErrorsNext.append(row[3]) if(row[4] == prevRow[4]): setAmountErrorsId.append(row[1]) setAmountErrorsId.append(row[2]) setAmountErrorsId.append(row[3]) prevRow = row print ("Amount Errors: ") print (setAmountErrorsId) print ("\nDate Errors Prev: ") print (setDatesErrorsPrev) print ("\nDate Errors Next: ") print (setDatesErrorsNext) print ("\n", setErrorNTLOnce) print ("\n", setErrorNTLTwice) print ("\n", setErrorNTLMult) print ("\n") f = open("thingsToEdit.txt", "w") f.write("Amount Errors: \n") f.write("Donor CostCenter Hist\n") for error in setAmountErrorsId: if(modCount % 3 == 2): f.write(error) f.write("\n") else: f.write(error) f.write("\t") modCount += 1 f.write("\nDate Errors Prev: \n") f.write("Donor CostCenter Hist\n") modCount = 0 for error in setDatesErrorsPrev: if(modCount % 3 == 2): f.write(error) f.write("\n") else: f.write(error) f.write("\t") modCount += 1 f.write("\nDate Errors Next: \n") f.write("Donor CostCenter Hist\n") modCount = 0 for error in setDatesErrorsNext: if(modCount % 3 == 2): f.write(error) f.write("\n") else: f.write(error) f.write("\t") modCount += 1 f.write("\nNTL Errors Count 1: \n") f.write("Donor CostCenter Hist\n") modCount = 0 for error in setErrorNTLOnce: if(modCount % 3 == 2): f.write(error) f.write("\n") else: f.write(error) f.write("\t") modCount += 1 f.write("\nNTL Errors Count 2: \n") f.write("Donor CostCenter Hist\n") modCount = 0 for error in setErrorNTLTwice: if(modCount % 3 == 2): f.write(error) f.write("\n") else: f.write(error) f.write("\t") modCount += 1 f.write("\nNTL Errors Count Mult: \n") f.write("Donor CostCenter Hist\n") modCount = 0 for error in setErrorNTLMult: if(modCount % 3 == 2): f.write(error) f.write("\n") else: f.write(error) f.write("\t") modCount += 1 f.write("\nNTL Errors Count Mult Blank: \n") f.write("Donor CostCenter Hist\n") modCount = 0 for error in setErrorNTLMultBlank: if(modCount % 3 == 2): f.write(error) f.write("\n") else: f.write(error) f.write("\t") modCount += 1 f.write("\nNTL Errors Count Mult Equal First: \n") f.write("Donor CostCenter Hist\n") modCount = 0 for error in setErrorNTLEqualFirst: if(modCount % 3 == 2): f.write(error) f.write("\n") else: f.write(error) f.write("\t") modCount += 1 f.write("\nSet Amounts Zero: \n") f.write("Donor CostCenter Hist\n") modCount = 0 for error in setAmountZero: if(modCount % 3 == 2): f.write(error) f.write("\n") else: f.write(error) f.write("\t") modCount += 1 f.write("\nIs Extra is Null: \n") f.write("Donor CostCenter Hist\n") modCount = 0 for error in setIsExtraNull: if(modCount % 3 == 2): f.write(error) f.write("\n") else: f.write(error) f.write("\t") modCount += 1 f.close() # for row in rowReader: # setID.add(row[1]) # setAmounts.add(row[4]) # setID.add(row[1]) # setAmounts.add(row[4]) # if(row[1] == "\"100400\""): # counter = counter + 1 # print row #print counter #print len(setID) #print "\"100400\"" in setID #print "$4.00" in setAmounts #print spamreader.next()[2] #print "\n"
UTF-8
Python
false
false
6,072
py
172
zac_python_script.py
90
0.550725
0.529315
0
219
26.730594
77
NIDHISH99444/CodingNinjas
11,450,382,820,310
73f0ebfa647db2f6933841e21301cd10b8eb1520
a1678f80efe56423d08bea6a2843633b8a81dd34
/CN_DynamicProgramming1/AlphaCode.py
689a84cac1914bf5e3da9c12e9b24eba31886089
[]
no_license
https://github.com/NIDHISH99444/CodingNinjas
af60aa93dbfcf050e727949d41201f72973b0608
b77b652cf0bf9b098ef9da4eff5eaecb7bfeaea5
refs/heads/master
"2021-05-17T03:50:45.376843"
"2020-05-03T17:25:01"
"2020-05-03T17:25:01"
250,608,228
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
def alphaCode(input,size,output): output[0]=1 output[1]=1 for i in range(2,size+1): if input[i-1]!=0: output[i]=output[i-1] if input[i-2]*10+input[i-1] <=26: output[i]+=output[i-2] return output[size] #output(i) -->checking i length ka input array ipt=int(input()) while ipt!=0: string=str(ipt) size=len(string) output=[0]*(size+1) arr=[int(string[i]) for i in range(len(string))] print(alphaCode(arr,size,output)) ipt=int(input())
UTF-8
Python
false
false
517
py
205
AlphaCode.py
201
0.576402
0.539652
0
22
22.545455
52
quanloveshui/permission
3,401,614,122,772
74ee244bdb46f91951870672370f3962d5a2c6a3
526554a69524b4e2c9233985bd901578b9445b93
/src/repository/user_type.py
c48eb70a1c07d05a8baee2494eef161545a306fe
[]
no_license
https://github.com/quanloveshui/permission
375e0b40d5dcf221f6a8776da2e4f85464c19dc9
9b8618f7ad888403f96385c738ac1d0194e694eb
refs/heads/master
"2020-06-06T22:55:16.610231"
"2019-06-20T07:31:45"
"2019-06-20T07:31:45"
192,870,029
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding:utf-8 -*- from src.utils.db_connection import DbConnection class UserTypeRepository: def __init__(self): self.db_conn = DbConnection() def add(self, caption): """ 在user_type表中添加角色 :param caption: :return: """ cursor = self.db_conn.connect() sql = """ insert into user_type(caption) values(%s) """ cursor.execute(sql, [caption,]) self.db_conn.close() def del_role(self,role): """ 在user_type表中删除角色 :param role: :return: """ cursor = self.db_conn.connect() sql = "delete from user_type WHERE caption=%s" cursor.execute(sql, role) self.db_conn.close() def get_info(self): """ 获取user_type表中所有用户角色类型 :return: """ cursor = self.db_conn.connect() sql='select * from user_type' cursor.execute(sql) result = cursor.fetchall() self.db_conn.close() return result
UTF-8
Python
false
false
1,111
py
6
user_type.py
6
0.525024
0.524079
0
46
22.021739
54
GuizaoBR/Django
5,059,471,514,171
4dbb343a34afecd5f25db08cf4b6a8551693171f
48f7e8b28b8b586e49905d78c4bf4bc19cb02293
/aplicativo2/aplicativo2/views.py
da85c459ee52b77f4662831c80feb4827a6ea2db
[]
no_license
https://github.com/GuizaoBR/Django
14d8ddef8f0d47fb4d5baa149b0a23b04c3e2ebf
c8dbbfe96d4ed0cdfb562ba7f23aeff5dd8ff07f
refs/heads/master
"2021-07-12T19:12:49.199089"
"2017-10-17T13:10:13"
"2017-10-17T13:10:13"
107,269,740
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.http import HttpResponse def ola(request): return HttpResponse("<h1>Guilherme<h1>")
UTF-8
Python
false
false
101
py
1
views.py
1
0.752475
0.732673
0
5
19.4
44
musikid/VitaPad
1,228,360,686,047
9adb28b50e9066cf94ac097215857f9d89a18056
c945d56d0d12b11b77677045ec06adeb79091a18
/client/client_test/client.py
10a7ce1777bc1822b5077bd7b242d70b41a8c2cb
[]
no_license
https://github.com/musikid/VitaPad
09d563ba26cd75d5fd9166898c12540deded56f3
576e2279935a25e2456bd3c14e7868e39086b064
refs/heads/main
"2023-08-31T23:54:04.960878"
"2023-08-16T19:07:39"
"2023-08-16T19:07:55"
135,613,021
0
0
null
true
"2023-08-16T19:05:07"
"2018-05-31T17:06:48"
"2023-07-27T19:30:47"
"2023-08-16T19:05:06"
579
0
0
1
Rust
false
false
from socket import socket, AF_INET, SOCK_STREAM, SOCK_DGRAM from time import time import flatbuffers from NetProtocol.Handshake import Handshake, Endpoint from Pad import MainPacket, Vector3 sock = socket(AF_INET, SOCK_STREAM) sock.connect(("192.168.1.24", 5000)) print("Connected") udp_sock = socket(AF_INET, SOCK_DGRAM) udp_sock.bind(("0.0.0.0", 0)) _, port = udp_sock.getsockname() builder = flatbuffers.Builder() Handshake.HandshakeStart(builder) Handshake.HandshakeAddEndpoint(builder, Endpoint.Endpoint.Client) Handshake.HandshakeAddPort(builder, port) Handshake.HandshakeAddHeartbeatFreq(builder, 0) handshake = Handshake.HandshakeEnd(builder) builder.FinishSizePrefixed(handshake) sock.sendall(builder.Output()) response = sock.recv(1024) buf, prefix = flatbuffers.util.RemoveSizePrefix(response, 0) handshake = Handshake.Handshake.GetRootAs(buf[prefix:]) delay = handshake.HeartbeatFreq() magic = bytes([0x45, 0x4e, 0x44, 0x48, 0x42, 0x54]) udp_sock.sendto(magic, ("192.168.1.24", 5000)) last_sent = int(time()) while True: if int(time()) - last_sent >= delay - (delay // 2): sock.sendall(magic) last_sent = int(time()) data, addr = udp_sock.recvfrom(1024) buf, prefix = flatbuffers.util.RemoveSizePrefix(data, 0) main = MainPacket.MainPacket.GetRootAs(buf[prefix:]) vec = Vector3.Vector3() print(main.Motion().Accelerometer(vec).X())
UTF-8
Python
false
false
1,398
py
38
client.py
27
0.734621
0.689557
0
49
27.530612
65
firanger/segundo-corte
15,582,141,388,930
2e92f69ce5c007b2629815f1b4bec4dc29ea72ca
4b361d63ac144914c59091047a4d7527f2a386b8
/meltdown-mitigation/conditionals.py
d15b8365347be1054ae811c22597e61a930bc715
[]
no_license
https://github.com/firanger/segundo-corte
b30b52715731b20945f165a6c4244c7afce73d1a
baf494a0395d15f2b77e9fdfd987316e9fda5caf
refs/heads/main
"2023-08-28T22:51:10.110069"
"2021-10-08T04:44:03"
"2021-10-08T04:44:03"
414,830,611
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def is_criticality_balanced(temperature, neutrons_emitted): return temperature < 800 and neutrons_emitted > 500 and temperature * neutrons_emitted < 500000 def reactor_efficiency(voltage, current, theoretical_max_power): efficiency = voltage * current / theoretical_max_power * 100 if efficiency >= 80: return "green" elif efficiency >= 60: return "orange" elif efficiency >= 30: return "red" else: return "black" def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) def fail_safe(temperature, neutrons_produced_per_second, threshold): volume = temperature * neutrons_produced_per_second if volume < int(threshold*0.4): return 'LOW' elif volume > int(threshold * 0.9) and volume < int(threshold * 1.1): return 'NORMAL' else: return 'DANGER'
UTF-8
Python
false
false
904
py
7
conditionals.py
6
0.651549
0.61615
0
25
35.16
99
poblouin/BudgetMe
16,595,753,659,303
05e59e48eabb0a187a0233d29a76c21f68e5c2f8
169cd04c0602735f0a648a7d44454d741fe25859
/budgetme/budgetme_api/filters.py
a4f539c7bb249f7a8b1d5c0a07818238315ef298
[ "MIT" ]
permissive
https://github.com/poblouin/BudgetMe
a1a2c939df5028018c9f7e27f8e7a20f3af70b56
b0b4b09042937e3f1d653078868bfaf3791dc03e
refs/heads/master
"2017-03-20T13:43:05.986213"
"2017-02-12T17:43:32"
"2017-02-12T17:43:32"
65,415,036
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import django_filters from django_filters import rest_framework from budgetme.budgetme_api.models import Transaction, ScheduledTransaction class TransactionFilter(django_filters.rest_framework.FilterSet): from_date = django_filters.DateTimeFilter(name='date', lookup_expr='gte') to_date = django_filters.DateTimeFilter(name='date', lookup_expr='lte') transaction_category = django_filters.CharFilter(name='transaction_category__name', lookup_expr='iexact') transaction_type = django_filters.CharFilter(name='transaction_category__transaction_type__name', label='Transaction type name', lookup_expr='iexact') account_name = django_filters.CharFilter(name='account__name', lookup_expr='iexact') account_type = django_filters.CharFilter(name='account__account_type__name', label='Account type name', lookup_expr='iexact') class Meta: model = Transaction fields = ['date', 'from_date', 'to_date', 'transaction_category', 'transaction_type', 'account_name', 'account_type'] class ScheduledTransactionFilter(django_filters.rest_framework.FilterSet): start_date = django_filters.DateTimeFilter(name='start_date', lookup_expr='gte') transaction_category = django_filters.CharFilter(name='transaction_category__name', lookup_expr='iexact') transaction_type = django_filters.CharFilter(name='transaction_category__transaction_type__name', label='Transaction type name', lookup_expr='iexact') frequency = django_filters.CharFilter(name='frequency__name', lookup_expr='iexact') class Meta: model = ScheduledTransaction fields = ['start_date', 'transaction_category', 'transaction_type', 'frequency']
UTF-8
Python
false
false
1,675
py
16
filters.py
14
0.745672
0.745672
0
28
58.821429
154
pioneers/PieCentral
1,546,188,269,297
40d131497c83471b52fe3604c6e3d0ed51d577ef
500362b86cfe4c692dd8a57a0caabe67e0efba79
/shepherd/runtimeclient.py
28f3304d72e84a98566542764c350dec1bfbc8eb
[ "Apache-2.0" ]
permissive
https://github.com/pioneers/PieCentral
e82c3c3f0ad37de2895dd15caafdad2965d9ff41
d6437d4ddfa386f44e6f70391c5211c723dde56d
refs/heads/master
"2020-09-20T19:42:19.126190"
"2020-06-05T06:47:14"
"2020-06-05T06:47:14"
67,092,938
18
9
Apache-2.0
false
"2020-06-16T01:49:33"
"2016-09-01T03:00:13"
"2020-06-05T06:47:18"
"2020-06-16T01:40:34"
62,577
13
9
74
Python
false
false
import msgpackrpc #pylint: disable=import-error class RuntimeClient: def __init__(self, host, port): self.host, self.port, self.client = host, port, None def connect(self): self.client = msgpackrpc.Client(msgpackrpc.Address(self.host, self.port)) def disconnect(self): self.client.close() self.client = None @property def connected(self): return self.client is not None def set_mode(self, mode=True): self.client.call('set_mode', mode) def set_alliance(self, alliance): self.client.call('set_alliance', alliance) def set_master(self, master): self.client.call('set_master', master) def set_starting_zone(self, zone): self.client.call('set_starting_zone', zone) def run_challenge(self, seed, timeout=1): self.client.notify('run_challenge', int(seed), timeout) def get_challenge_solution(self): return self.client.call('get_challenge_solution') class RuntimeClientManager: def __init__(self, blue_alliance, gold_alliance, b1_custom_ip=None, b2_custom_ip=None, g1_custom_ip=None, g2_custom_ip=None): custom_ips = (b1_custom_ip, b2_custom_ip, g1_custom_ip, g2_custom_ip) self.blue_alliance, self.gold_alliance = blue_alliance, gold_alliance self.clients = {} for i in range(len(self.blue_alliance+self.gold_alliance)): if custom_ips[i]: self.clients[(self.blue_alliance+self.gold_alliance)[i]] =\ (RuntimeClient(f'{custom_ips[i]}', 6020)) elif (self.blue_alliance + self.gold_alliance)[i] >= -100: self.clients[(self.blue_alliance+self.gold_alliance)[i]] =\ (RuntimeClient(f'192.168.128.{200 +(self.blue_alliance + self.gold_alliance)[i]}', 6020)) #pylint: disable=line-too-long else: self.clients[(self.blue_alliance+self.gold_alliance)[i]] = None for client in self.clients.values(): if client is not None: print(client.host) client.connect() for team in self.blue_alliance: client = self.clients[team] if client: client.set_alliance('blue') for team in self.gold_alliance: client = self.clients[team] if client: client.set_alliance('gold') def set_starting_zones(self, zones): for team, zone in zip(self.blue_alliance + self.gold_alliance, zones): if self.clients[team]: self.clients[team].set_starting_zone(zone) def set_mode(self, mode): for client in self.clients.values(): if client: print('Setting mode for client:', client.host) client.set_mode(mode) def get_challenge_solutions(self): return {team: (client.get_challenge_solution() if client else None) for team, client in self.clients.items()} def set_master_robots(self, blue_team, gold_team): """ blue_master = self.clients[blue_team] if blue_master: blue_master.set_master() gold_master = self.clients[gold_team] if gold_master: gold_master.set_master()""" """ client = RuntimeClient('192.168.128.107', 6020) client.connect() import time from Code import decode x = 1 client.run_challenge(x) time.sleep(0.2) print('Robot answer:', client.get_challenge_solution()) print('Authoritative answer:', decode(x)) """ #pylint: disable=pointless-string-statement # client = RuntimeClient('192.168.128.115', 6020) # client.connect() # client.set_mode('idle') # print('OK!') # client.set_alliance('blue') # client.set_starting_zone('left') # client.run_challenge(123) # time.sleep(0.2) # print(client.get_challenge_solution()) # time.sleep(1) # client.run_challenge(123) # print(client.get_challenge_solution())
UTF-8
Python
false
false
3,931
py
328
runtimeclient.py
172
0.614856
0.595523
0
115
33.182609
140
cyan478/MFR
12,850,542,171,275
9c9731bbc61b267ee09a3aeb03a02d063b503d77
0a4cdb328c5808dc8b4ce9b32ca9d1942a7f45e5
/textReduction.py
ce769da687f47efad4b3382d1019516002ff5e95
[]
no_license
https://github.com/cyan478/MFR
2ff029b12131541661a25bf6e224b9c9e53390db
3426ff899b3816833525c409c7088bf80e7a76b8
refs/heads/master
"2021-01-20T07:51:51.528026"
"2017-05-03T06:36:21"
"2017-05-03T06:36:21"
90,054,747
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
a = open("alice.txt", "r") text = a.read().split() a.close() words = [word.strip('()",.!*\'-') for word in text] def wordFreq(w): freq = filter(lambda a: a.lower() == w.lower(), words) return len(freq) #test print 'The frequency of the word "the" is ' + str(wordFreq('the')) print 'The frequency of the word "is" is ' + str(wordFreq('is')) print 'The frequency of the word "Alice" is ' + str(wordFreq('Alice')) def totalFreq(w): freqs = [wordFreq(x) for x in w] return reduce(lambda a, b: a + b, freqs) #test print 'The total frequency of the words "the", "is", and "Alice" is ' + str(totalFreq(['the', 'is', 'Alice'])) def mostFreq(): freqs = [[x, wordFreq(x)] for x in words] return reduce(lambda a, b: a if a[1] > b[1] else b, freqs)[0] #test -- works, but takes a long time when using list comprehensions/map/filter/reduce print 'The most frequently occurring word is ' + str(mostFreq())
UTF-8
Python
false
false
914
py
2
textReduction.py
1
0.641138
0.637856
0
28
31.678571
110
AnonymousConferences/MCF
3,375,844,321,682
ed44f4bc2aeb4e4adffbc28304b310ea0e1788cb
ddd5b79e80d5b2a43a01a92dbd8fcefbc74fbe18
/KickstarterRec/parallel_mf_posneg_embedding_user.py
cd2a6b30bdc1fc081ce98c5300c06a014d61ab6f
[]
no_license
https://github.com/AnonymousConferences/MCF
24b037dacd0ad4ee28a48dc3cde37f733dd5fd95
029a256ae91e6d8a7558385410cf6dc7e37af43f
refs/heads/master
"2021-07-14T17:38:56.938181"
"2017-10-19T19:54:55"
"2017-10-19T19:54:55"
107,186,238
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import sys import time import threading import numpy as np from numpy import linalg as LA import ParallelSolver as ps import MultiProcessParallelSolver as mpps from joblib import Parallel, delayed from sklearn.base import BaseEstimator, TransformerMixin import rec_eval class ParallelMFPositiveNegativeUserEmbedding(BaseEstimator, TransformerMixin): def __init__(self, mu_u_p = 1, mu_u_n = 1, n_components=100, max_iter=10, batch_size=1000, init_std=0.01, dtype='float32', n_jobs=8, random_state=None, save_params=False, save_dir='.', early_stopping=False, verbose=False, **kwargs): ''' Parameters --------- n_components : int Number of latent factors max_iter : int Maximal number of iterations to perform batch_size: int Batch size to perform parallel update init_std: float The latent factors will be initialized as Normal(0, init_std**2) dtype: str or type Data-type for the parameters, default 'float32' (np.float32) n_jobs: int Number of parallel jobs to update latent factors random_state : int or RandomState Pseudo random number generator used for sampling save_params: bool Whether to save parameters after each iteration save_dir: str The directory to save the parameters early_stopping: bool Whether to early stop the training by monitoring performance on validation set verbose : bool Whether to show progress during model fitting **kwargs: dict Model hyperparameters ''' self.mu_u_p = mu_u_p self.mu_u_n = mu_u_n self.n_components = n_components self.max_iter = max_iter self.batch_size = batch_size self.init_std = init_std self.dtype = dtype self.n_jobs = n_jobs self.random_state = random_state self.save_params = save_params self.save_dir = save_dir self.early_stopping = early_stopping self.verbose = verbose if type(self.random_state) is int: np.random.seed(self.random_state) elif self.random_state is not None: np.random.setstate(self.random_state) self._parse_kwargs(**kwargs) def _parse_kwargs(self, **kwargs): ''' Model hyperparameters Parameters --------- lambda_alpha, lambda_beta, lambda_gamma: float Regularization parameter for user (lambda_alpha), item factors ( lambda_beta), and context factors (lambda_gamma). c0, c1: float Confidence for 0 and 1 in Hu et al., c0 must be less than c1 ''' self.lam_alpha = float(kwargs.get('lambda_alpha', 1e-5)) self.lam_beta = float(kwargs.get('lambda_beta', 1e-5)) self.lam_theta_p = float(kwargs.get('lambda_theta_p', 1e-5)) self.lam_theta_n = float(kwargs.get('lambda_theta_n', 1e-5)) self.c0 = float(kwargs.get('c0', 0.1)) self.c1 = float(kwargs.get('c1', 2.0)) assert self.c0 < self.c1, "c0 must be smaller than c1" def _init_params(self, n_users, n_projects): ''' Initialize all the latent factors and biases ''' self.alpha = self.init_std * np.random.randn(n_users, self.n_components).astype(self.dtype) self.beta = self.init_std * np.random.randn(n_projects, self.n_components).astype(self.dtype) self.theta_p = self.init_std * np.random.randn(n_users, self.n_components).astype(self.dtype) # bias for beta and gamma self.bias_b_p = np.zeros(n_users, dtype=self.dtype) self.bias_c_p = np.zeros(n_users, dtype=self.dtype) # global bias self.global_y_p = 0.0 self.theta_n = self.init_std * np.random.randn(n_users, self.n_components).astype(self.dtype) # bias for alpha and theta self.bias_b_n = np.zeros(n_users, dtype=self.dtype) self.bias_c_n = np.zeros(n_users, dtype=self.dtype) # global bias self.global_y_n = 0.0 # intercept of second factorization for user-user # Init got equivalent res # print 'Initial alpha: \n', self.alpha # print 'Initial beta: \n', self.beta # print 'Initial gamma: \n', self.gamma # # print 'Initial bias_d: \n', self.bias_d # print 'Initial bias_e: \n', self.bias_e # print 'Initial global_x: \n', self.global_x def fit(self, M, YP = None, YN = None, FYP=None, FYN = None, vad_data=None, **kwargs): '''Fit the model to the data in M. Parameters ---------- M : scipy.sparse.csr_matrix, shape (n_users, n_projects) Training click matrix. X : scipy.sparse.csr_matrix, shape (n_projects, n_projects) Training co-occurrence matrix. F : scipy.sparse.csr_matrix, shape (n_projects, n_projects) The weight for the co-occurrence matrix. If not provided, weight by default is 1. vad_data: scipy.sparse.csr_matrix, shape (n_users, n_projects) Validation click data. **kwargs: dict Additional keywords to evaluation function call on validation data Returns ------- self: object Returns the instance itself. ''' n_users, n_projects = M.shape assert YP.shape == (n_users, n_users) assert YN.shape == (n_users, n_users) self._init_params(n_users, n_projects) self._update(M, YP, YN, FYP, FYN, vad_data, **kwargs) return self def transform(self, M): pass def _update(self, M, YP, YN, FYP, FYN, vad_data, **kwargs): '''Model training and evaluation on validation set''' MT = M.T.tocsr() # pre-compute this YPT, YNT, FYPT, FYNT = None, None, None, None if YP != None: YPT = YP.T if YN != None: YNT = YN.T if FYP != None: FYPT = FYP.T if FYN != None: FYNT = FYN.T self.vad_ndcg = -np.inf for i in xrange(self.max_iter): if self.verbose: print('ITERATION #%d' % i) self._update_factors(M, MT, YP, YPT, YN, YNT, FYP, FYPT, FYN, FYNT) self._update_biases(YP, YPT, YN, YNT, FYP, FYPT, FYN, FYNT) if vad_data is not None: vad_ndcg = self._validate(M, vad_data, **kwargs) if self.early_stopping and self.vad_ndcg > vad_ndcg: break # we will not save the parameter for this iteration self.vad_ndcg = vad_ndcg if self.save_params: self._save_params(i) #print 'alpha:\n', self.alpha # print '\n' #print 'beta:\n', self.beta # print '\n' #print 'gamma:\n', self.gamma #print 'theta:\n', self.theta pass def _update_factors(self, M, MT, YP, YPT, YN, YNT, FYP, FYPT, FYN, FYNT): if self.verbose: start_t = _writeline_and_time('\tUpdating user factors...') self.alpha = update_alpha(self.beta, self.theta_p, self.theta_n, self.bias_b_p, self.bias_c_p, self.global_y_p, self.bias_b_n, self.bias_c_n, self.global_y_n, M, YP, FYP, YN, FYN, self.c0, self.c1, self.lam_alpha, n_jobs=self.n_jobs, batch_size=self.batch_size, mu_u_p=self.mu_u_p, mu_u_n=self.mu_u_n) # print('checking user factor isnan : %d'%(np.sum(np.isnan(self.alpha)))) if self.verbose: print('\r\tUpdating user factors: time=%.2f' % (time.time() - start_t)) start_t = _writeline_and_time('\tUpdating project factors...') self.beta = update_beta(self.alpha, MT, self.c0, self.c1, self.lam_beta, self.n_jobs, batch_size=self.batch_size) # print('checking project factor isnan : %d' % (np.sum(np.isnan(self.beta)))) if self.verbose: print('\r\tUpdating user embedding factors: time=%.2f' % (time.time() - start_t)) start_t = _writeline_and_time('\tUpdating positive user embedding factors...') # here it really should be X^T and FX^T, but both are symmetric self.theta_p = update_embedding_factor(self.alpha, self.bias_b_p, self.bias_c_p, self.global_y_p, YPT, FYPT, self.lam_theta_p, self.n_jobs, batch_size=self.batch_size, mu_p=self.mu_u_p) # print('checking theta_p isnan : %d' % (np.sum(np.isnan(self.theta_p)))) if self.verbose: print('\r\tUpdating positive user factors: time=%.2f' % (time.time() - start_t)) start_t = _writeline_and_time('\tUpdating negative user embedding factors...') self.theta_n = update_embedding_factor(self.alpha, self.bias_b_n, self.bias_c_n, self.global_y_n, YNT, FYNT, self.lam_theta_n, self.n_jobs, batch_size=self.batch_size, mu_p=self.mu_u_n) # print('checking theta_n isnan : %d' % (np.sum(np.isnan(self.theta_n)))) if self.verbose: print('\r\tUpdating negative user embedding factors: time=%.2f' % (time.time() - start_t)) pass def _update_biases(self, YP, YPT, YN, YNT, FYP, FYPT, FYN, FYNT): if self.verbose: start_t = _writeline_and_time('\tUpdating bias terms...') self.bias_b_p = update_bias(self.alpha, self.theta_p, self.bias_c_p, self.global_y_p, YP, FYP, self.n_jobs, batch_size=self.batch_size, mu = self.mu_u_p) # print('checking isnan bias_b_p : %d' % (np.sum(np.isnan(self.bias_b_p)))) if np.sum(np.isnan(self.bias_b_p)) > 0 : np.argwhere(np.isnan(self.bias_b_p)) # here it really should be X^T and FX^T, but both are symmetric self.bias_c_p = update_bias(self.theta_p, self.alpha, self.bias_b_p, self.global_y_p, YP, FYP, self.n_jobs, batch_size=self.batch_size, mu=self.mu_u_p) # print('checking isnan bias_c_p: %d' % (np.sum(np.isnan(self.bias_c_p)))) if np.sum(np.isnan(self.bias_c_p)) > 0 : np.argwhere(np.isnan(self.bias_c_p)) self.global_y_p = update_global(self.alpha, self.theta_p, self.bias_b_p, self.bias_c_p, YP, FYP, self.n_jobs, batch_size=self.batch_size, mu=self.mu_u_p) # print('checking isnan global_y_p: %d' % (np.sum(np.isnan(self.global_y_p)))) if np.sum(np.isnan(self.global_y_p)) > 0 : np.argwhere(np.isnan(self.global_y_p)) self.bias_b_n = update_bias(self.alpha, self.theta_n, self.bias_c_n, self.global_y_n, YN, FYN, self.n_jobs, batch_size=self.batch_size, mu=self.mu_u_n) # print('checking isnan : %d' % (np.sum(np.isnan(self.bias_b_n)))) # here it really should be X^T and FX^T, but both are symmetric self.bias_c_n = update_bias(self.theta_n, self.alpha, self.bias_b_n, self.global_y_n, YN, FYN, self.n_jobs, batch_size=self.batch_size, mu=self.mu_u_n) # print('checking isnan : %d' % (np.sum(np.isnan(self.bias_c_n)))) self.global_y_n = update_global(self.alpha, self.theta_n, self.bias_b_n, self.bias_c_n, YN, FYN, self.n_jobs, batch_size=self.batch_size, mu=self.mu_u_n) # print('checking isnan : %d' % (np.sum(np.isnan(self.global_y_n)))) if self.verbose: print('\r\tUpdating bias terms: time=%.2f' % (time.time() - start_t)) pass def _validate(self, M, vad_data, **kwargs): vad_ndcg = rec_eval.parallel_normalized_dcg_at_k(M, vad_data, self.alpha, self.beta, **kwargs) if self.verbose: print('\tValidation NDCG@k: %.5f' % vad_ndcg) return vad_ndcg def _save_params(self, iter): '''Save the parameters''' if not os.path.exists(self.save_dir): os.makedirs(self.save_dir) filename = 'CoFacto_K%d_iter%d.npz' % (self.n_components, iter) np.savez(os.path.join(self.save_dir, filename), U=self.alpha, V=self.beta) # Utility functions # def _writeline_and_time(s): sys.stdout.write(s) sys.stdout.flush() return time.time() def get_row(Y, i): '''Given a scipy.sparse.csr_matrix Y, get the values and indices of the non-zero values in i_th row''' lo, hi = Y.indptr[i], Y.indptr[i + 1] return Y.data[lo:hi], Y.indices[lo:hi] def update_alpha(beta, theta_p, theta_n, bias_b_p, bias_c_p, global_y_p, bias_b_n, bias_c_n, global_y_n, M, YP, FYP, YN, FYN, c0, c1, lam_alpha, n_jobs = 8, batch_size=1000, mu_u_p=1, mu_u_n=1): '''Update user latent factors''' m, n = M.shape # m: number of users, n: number of items f = beta.shape[1] # f: number of factors BTB = c0 * np.dot(beta.T, beta) # precompute this BTBpR = BTB + lam_alpha * np.eye(f, dtype=beta.dtype) return mpps.UpdateUserFactorParallel( beta, theta_p=theta_p, theta_n=theta_n, bias_b_p=bias_b_p, bias_c_p=bias_c_p, global_y_p=global_y_p, bias_b_n=bias_b_n, bias_c_n=bias_c_n, global_y_n=global_y_n, M=M, YP=YP, FYP=FYP, YN=YN, FYN=FYN, BTBpR=BTBpR, c0=c0, c1=c1, f=f, mu_u_p=mu_u_p, mu_u_n=mu_u_n, n_jobs=n_jobs, mode='hybrid' ).run() def update_beta(alpha, MT, c0, c1, lam_beta, n_jobs, batch_size=1000): '''Update item latent factors/embeddings''' n, m = MT.shape # m: number of users, n: number of projects f = alpha.shape[1] assert alpha.shape[0] == m TTT = c0 * np.dot(alpha.T, alpha) # precompute this TTTpR = TTT + lam_beta * np.eye(f, dtype=alpha.dtype) return mpps.UpdateProjectFactorParallel( alpha = alpha, MT = MT, TTTpR = TTTpR, c0=c0, c1=c1, f=f, n_jobs=n_jobs, mode=None ).run() def update_embedding_factor(alpha, bias_b, bias_c, global_y, YT, FYT, lam_theta, n_jobs, batch_size=1000, mu_p = 1): '''Update context latent factors''' m, f = alpha.shape # m: number of users, f: number of factors return mpps.UpdateEmbeddingFactorParallel( main_factor = alpha, bias_main=bias_b, bias_embedding=bias_c, intercept=global_y, XT=YT, FXT=FYT, f=f, lam_embedding=lam_theta, mu=mu_p, n_jobs=n_jobs ).run() def update_bias(alpha, theta, bias_c, global_y, Y, FY, n_jobs = 8, batch_size=1000, mu = 1): return mpps.UpdateBiasParallel( main_factor=alpha, embedding_factor=theta, bias=bias_c, intercept=global_y, X=Y, FX=FY, mu=mu, n_jobs=n_jobs ).run() def update_global(alpha, theta, bias_b, bias_c, Y, FY, n_jobs = 8, batch_size=1000, mu = 1): assert alpha.shape == theta.shape assert bias_b.shape == bias_c.shape return mpps.UpdateInterceptParallel( main_factor = alpha, embedding_factor = theta, bias_main = bias_b, bias_embedding = bias_c, X = Y, FX = FY, mu=mu, n_jobs=n_jobs ).run()
UTF-8
Python
false
false
16,437
py
20
parallel_mf_posneg_embedding_user.py
18
0.536047
0.529172
0
374
42.946524
102
mtamer/spideyweb
8,538,394,985,785
ca5fc321e0df1d7eaf112cfe6f0bf577719f06b6
770277dd8ee8db9f998b7e5f9419941047fc2c5b
/spideyweb.py
9736ea1f18f13a04d588bd02d08cbd1771beb598
[]
no_license
https://github.com/mtamer/spideyweb
7c6b5a73afef60bb6eae1f144253f8e55a9bb28b
938305482480d0b05f452cad2c24ea8d9776ac18
refs/heads/master
"2020-04-29T02:38:46.285054"
"2014-10-13T14:10:36"
"2014-10-13T14:10:36"
25,057,032
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests from bs4 import BeautifulSoup #modules BeautifulSoup #WebCrawler for one page def spiderweb(max_pages): page = 25 while page <= max_pages: url = 'http://www.usedottawa.com/classifieds/all/' + str(page) + '?description=honda' source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text) for link in soup.findAll('a',{'itemprop':'name'}): href = "http://www.usedottawa.com/" + link.get('href') title = link.string print(href) print(title) get_single_item_data(href) page+=25 #Dynamic Web Crawler def get_single_item_data(item_url): source_code = requests.get(item_url) plain_text = source_code.text soup = BeautifulSoup(plain_text) for item_name in soup.findAll('div',{'class':'article'}): print(item_name.string) # for link in soup.findAll('p',{'class':'title'} ): # href = "http://www.usedottawa.com/"+link.get('href') # print(href) spiderweb(100) #of pages to crawl.
UTF-8
Python
false
false
1,055
py
2
spideyweb.py
1
0.630332
0.622749
0
33
30.939394
93
mverteuil/SIMP
13,400,298,003,621
a6be4e265deb1164cb21589dc8de0fd6e466aa92
086ec6cb1de40f1c01ecb6d14a8830d32a1eb177
/simp/inventory/urls.py
3703fa4190616eb6d9ceb95ca44c84d0094114f9
[]
no_license
https://github.com/mverteuil/SIMP
dbfd17c5b10a58c4a02b36d34446ae3feb3d1d02
cdd65f48d823b93176dc895cf5893937a9a3ad2e
refs/heads/master
"2020-05-29T12:33:20.697748"
"2013-03-31T18:22:39"
"2013-03-31T18:22:39"
7,852,994
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from bootstrap import urls as bootstrap_urls from django.conf.urls import patterns, url from .forms import (AccountForm, InventoryItemForm, PurchaserForm, TransactionForm) from .models import (InventoryItem, Purchaser) from .views import (MarkupDetailView, CreateView, ItemListView, PurchaserListView) urlpatterns = bootstrap_urls.bootstrap_patterns(AccountForm) urlpatterns += bootstrap_urls.bootstrap_pattern(InventoryItemForm, list_view=None) urlpatterns += bootstrap_urls.bootstrap_pattern(TransactionForm, create_view=None) urlpatterns += bootstrap_urls.bootstrap_pattern(PurchaserForm, list_view=None) urlpatterns += patterns( '', url( r'^inventoryitem/$', ItemListView.as_view(model=InventoryItem), name="inventoryitem_list" ), url( r'^inventoryitem/(?P<pk>\d+)/json/$', MarkupDetailView.as_view(model=InventoryItem), name='inventoryitem_json', ), url( r'^purchaser/$', PurchaserListView.as_view(model=Purchaser), name="purchaser_list" ), url( r'^transaction/add/$', CreateView.as_view(form_class=TransactionForm), name="transaction_form" ), )
UTF-8
Python
false
false
1,473
py
27
urls.py
11
0.563476
0.563476
0
47
30.340426
66
sfmajors373/city-scrapers
13,159,779,843,452
d5ae3b1b598bc43fb518f1c8994ac674689fda20
5850afa8458946781b15b8c3122f4e9b3c760b83
/city_scrapers/spiders/det_zoning_appeals.py
b9593f5598806fcc1ce6638c38db8744021e3e9e
[ "MIT" ]
permissive
https://github.com/sfmajors373/city-scrapers
8ad1b70ea5669c3b4063fbfcb90bdb928c35eca7
49ad24460bc6e7132fbace33d2ae8b10a38764d7
refs/heads/master
"2020-04-21T18:14:07.725481"
"2019-02-08T14:52:45"
"2019-02-08T14:52:45"
169,761,863
0
0
MIT
true
"2019-02-08T16:10:46"
"2019-02-08T16:10:46"
"2019-02-08T14:56:48"
"2019-02-08T14:52:46"
7,575
0
0
0
null
false
null
# -*- coding: utf-8 -*- from datetime import time from dateutil.parser import parse from city_scrapers.constants import BOARD from city_scrapers.spider import Spider class DetZoningAppealsSpider(Spider): name = 'det_zoning_appeals' agency_name = 'Detroit Zoning Division' timezone = 'America/Detroit' allowed_domains = ['www.detroitmi.gov'] start_urls = ['https://www.detroitmi.gov/Government/Boards/Board-of-Zoning-Appeals-Meeting'] def parse(self, response): """ `parse` should always `yield` a dict that follows the Event Schema <https://city-bureau.github.io/city-scrapers/06_event_schema.html>. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs. """ location = { 'name': '13th Floor in the Auditorium, Coleman A. Young Municipal Center', 'address': '2 Woodward Avenue, Detroit, MI 48226', 'neighborhood': '', } for item in response.css('.field td::text').extract(): if not item.strip(): continue start = self._parse_start(item) data = { '_type': 'event', 'name': 'Board of Zoning Appeals', 'event_description': '', 'classification': BOARD, 'start': start, 'end': { 'date': start['date'], 'time': None, 'note': '' }, 'all_day': False, 'location': location, 'documents': self._parse_documents(start['date'], response), 'sources': [{ 'url': response.url, 'note': '' }], } data['status'] = self._generate_status(data) data['id'] = self._generate_id(data) yield data def _parse_start(self, item): """ Parse start date and time. """ return { 'date': parse(item).date(), 'time': time(9, 0), 'note': '', } def _parse_documents(self, dt, response): """ Parse or generate documents. """ dt_str = '{}-{dt.day}-{dt.year}'.format(dt.strftime('%B').lower(), dt=dt) minutes_url = response.css('a[href*="{}"]::attr(href)'.format(dt_str)).extract_first() if minutes_url: return [{'url': response.urljoin(minutes_url), 'note': 'Minutes'}] return []
UTF-8
Python
false
false
2,550
py
20
det_zoning_appeals.py
14
0.502353
0.497255
0
77
32.116883
96
HYEEWON/practice_for_coding_test
14,422,500,182,744
a6302a0e8b29ece3d8f55feb135a5c1bc7e7629d
ecba61c279d1c7a729e463841382f5486e9dc7d7
/leetcode/220324_68_TextJustification_Hard.py
c8828b7996402f09d1155fd0b14bb59d8506773b
[]
no_license
https://github.com/HYEEWON/practice_for_coding_test
458479ef75f7430ace4ddafcb408f4c322492f84
d13f1b5a1cd6132ab8592c31359e3a55aa6ad7d5
refs/heads/main
"2023-04-25T00:11:36.557605"
"2022-09-24T12:36:49"
"2022-09-24T12:36:49"
326,623,683
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# Simulation class Solution: def fullJustify(self, words, maxWidth): answer = [] cnt, tmp = 0, [] # 단어 길이 합, 단어 배열 for word in words: if cnt + len(word) + len(tmp) <= maxWidth: # 단어 사이의 공백 필수 cnt += len(word) tmp.append(word) continue if len(tmp) == 1: answer.append(tmp[0]+(' '*(maxWidth-len(tmp[0])))) else: space = [(maxWidth - cnt) // (len(tmp) - 1) for i in range(len(tmp)-1)] # 공백 개수 for i in range((maxWidth-cnt) % len(space)): space[i] += 1 # 왼쪽부터 공백 개수 증가 a = '' for i in range(len(space)): a += tmp[i] + space[i]*' ' a += tmp[-1] answer.append(a) cnt, tmp = len(word), [word] answer.append(' '.join(tmp) + ' '*(maxWidth-cnt-len(tmp)+1)) # 마지막은 왼쪽 정렬 return answer s = Solution() print(s.fullJustify(["What","must","be","acknowledgment","shall","be"], 16))
UTF-8
Python
false
false
1,142
py
362
220324_68_TextJustification_Hard.py
350
0.446328
0.43597
0
31
33.290323
95
GRSEB9S/HSI_Classification-1
19,026,705,146,693
8cd2349ea7221e59892fdee4802b31223e13892f
70db19ef8603bf2209e85b865d6a1e42231a1f46
/svm/svm.py
4ee78f222a3af959b831f29d437469a4ddbb4e57
[]
no_license
https://github.com/GRSEB9S/HSI_Classification-1
1c68a8822d64348f3fb46ce6479fa906fd9ba433
35d600cc695e695d50fc97f024f4e425a8b1f2ab
refs/heads/master
"2021-09-16T21:06:30.761871"
"2018-06-25T06:13:06"
"2018-06-25T06:13:06"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*-coding=utf-8 -*- from sklearn.neighbors import KNeighborsClassifier from sklearn import svm import numpy as np import scipy.io as sio import random import matplotlib.pyplot as plt import seaborn as sn import pandas as pd import time import os from datetime import datetime PaviaU = '../data/PaviaU.mat' PaviaU_gt = '../data/PaviaU_gt.mat' Indian_pines = '../data/Indian_pines.mat' Indian_pines_gt = '../data/Indian_pines_gt.mat' Salinas = '../data/Salinas_corrected.mat' Salinas_gt = '../data/Salinas_gt.mat' for NO_data in ['Salians']: if NO_data == 'PaviaU':#use paviaU data = sio.loadmat(PaviaU) data_gt = sio.loadmat(PaviaU_gt) im = data['paviaU'] imGIS = data_gt['paviaU_gt'] elif NO_data == 'Inidan_pines':#use indian_pines data = sio.loadmat(Indian_pines) data_gt = sio.loadmat(Indian_pines_gt) im = data['indian_pines'] imGIS = data_gt['indian_pines_gt'] iG = np.zeros([imGIS.shape[0], imGIS.shape[1]], dtype=int) C = np.max(imGIS) origin_num = np.zeros(shape=[C + 1], dtype=int) for i in range(imGIS.shape[0]): for j in range(imGIS.shape[1]): for k in range(1, C + 1): if imGIS[i][j] == k: origin_num[k] += 1 index = 0 data_num = np.zeros(shape=[9], dtype=int) data_label = np.zeros(shape=[9], dtype=int) for i in range(len(origin_num)): if origin_num[i] > 400: data_num[index] = origin_num[i] data_label[index] = i index += 1 # del too few classes for i in range(imGIS.shape[0]): for j in range(imGIS.shape[1]): if imGIS[i, j] in data_label: for k in range(len(data_label)): if imGIS[i][j] == data_label[k]: iG[i, j] = k + 1 continue imGIS = iG elif NO_data == 'Salians':#use Salinas data = sio.loadmat(Salinas) data_gt = sio.loadmat(Salinas_gt) im = data['salinas_corrected'] imGIS = data_gt['salinas_gt'] im = (im - float(np.min(im))) im = im/np.max(im) sample_num = 200 deepth = im.shape[2] classes = np.max(imGIS) data_ = {} train_data = {} test_data = {} for i in range(1,classes+1): data_[i]=[] train_data[i]=[] test_data[i] = [] for i in range(imGIS.shape[0]): for j in range(imGIS.shape[1]): for k in range(1,classes+1): if imGIS[i,j]==k: data_[k].append(im[i,j]) for i in range(1,classes+1): indexies = random.sample(range(len(data_[i])),sample_num) for k in range(len(data_[i])): if k not in indexies: test_data[i].append(data_[i][k]) else: train_data[i].append(data_[i][k]) train = [] train_label = [] test = [] test_label = [] for i in range(1,len(train_data)+1): for j in range(len(train_data[i])): train.append(train_data[i][j]) train_label.append(i) for i in range(1,len(test_data)+1): for j in range(len(test_data[i])): test.append(test_data[i][j]) test_label.append(i) if not os.path.exists('result'): os.makedirs('result') time = str(datetime.now().strftime('%Y%m%d_%H%M%S')) result = open('result/result_for_NO_data_'+str(NO_data)+'_'+'_samplenum_'+'_'+str(k)+'_'+time+'.txt','w') clf = svm.SVC(gamma=1.0,C=100) clf.fit(train,train_label) C = np.max(imGIS) matrix = np.zeros((C,C)) for i in range(len(test)): r = clf.predict(test[i].reshape(-1,len(test[i]))) matrix[r-1,test_label[i]-1] += 1 print(np.int_(matrix)) print(np.sum(np.trace(matrix))) print(np.sum(np.trace(matrix)) / float(len(test_label))) result.write(str(np.int_(matrix))) result.write('\n') result.write(str(np.sum(np.trace(matrix)))) result.write('\n') result.write(str(np.sum(np.trace(matrix)) / float(len(test_label)))) result.write('\n') for i in range(len(matrix)): ac = matrix[i,i]/sum(matrix[:,i]) print('accuracy ',i+1,':',ac) result.write(str(i+1)+":"+str(ac)) result.write('\n') kk = 0 for i in range(matrix.shape[0]): kk += np.sum(matrix[i])*np.sum(matrix[:,i]) pe = kk/(np.sum(matrix)*np.sum(matrix)) pa = np.trace(matrix)/np.sum(matrix) kappa = (pa-pe)/(1-pe) print('kappa:',kappa) result.write('kappa:'+str(kappa)) result.write('\n') alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' df_cm = pd.DataFrame(matrix, index = [i for i in alphabet[:matrix.shape[0]]], columns = [i for i in alphabet[:matrix.shape[1]]]) plt1 = plt plt1.figure(figsize = (matrix.shape[0],matrix.shape[1])) sn.heatmap(df_cm, annot=True,fmt="g") plt1.savefig('result/confusion_matrix1_'+'_samplenum_'+'_'+str(k)+'_'+time+'.png', format='png') plt1.close() iG = np.zeros((imGIS.shape[0],imGIS.shape[1])) for i in range(imGIS.shape[0]): for j in range(imGIS.shape[1]): if imGIS[i,j]==0: iG[i,j]=0 else: iG[i,j] = (clf.predict(im[i,j].reshape(-1,len(im[i,j])))) plt2 = plt plt.pcolor(iG) plt.savefig('result/decode_result_'+'_sample_num_'+'_'+str(k)+'_'+str(time)+'.png', format='png') plt.close() print('end')
UTF-8
Python
false
false
5,550
py
2
svm.py
1
0.539459
0.527568
0
163
33.04908
109
eric100lin/Learn
438,086,667,126
22089c995682c6d27e954ccaae9bcd364ff374e5
b21f0a87ec5f0784f1678ccb1e5a871e05822ebc
/algorithm/Array/1169.py
9d8823fc24ed3b1f715f3f1fe41919dc74f10315
[]
no_license
https://github.com/eric100lin/Learn
b8236413e6000982861f28b8e7a7f9e6c13e2d78
317c927a06b7964af80c62487450622132974eea
refs/heads/master
"2020-08-04T20:17:08.164496"
"2019-11-29T06:47:14"
"2019-11-29T06:47:14"
212,266,993
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' 1169. Invalid Transactions https://leetcode.com/contest/weekly-contest-151/problems/invalid-transactions/ A transaction is possibly invalid if: the amount exceeds $1000, or; if it occurs within (and including) 60 minutes of another transaction with the same name in a different city. Each transaction string transactions[i] consists of comma separated values representing the name, time (in minutes), amount, and city of the transaction. Given a list of transactions, return a list of transactions that are possibly invalid. You may return the answer in any order. Example 1: Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"] Output: ["alice,20,800,mtv","alice,50,100,beijing"] Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. Example 2: Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"] Output: ["alice,50,1200,mtv"] Example 3: Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"] Output: ["bob,50,1200,mtv"] Constraints: transactions.length <= 1000 Each transactions[i] takes the form "{name},{time},{amount},{city}" Each {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10. Each {time} consist of digits, and represent an integer between 0 and 1000. Each {amount} consist of digits, and represent an integer between 0 and 2000. ''' from typing import * class Solution: def invalidTransactions(self, transactions: List[str]) -> List[str]: T = [] # parsing all transactions for tran in transactions: name, time, amount, city = tran.split(',') time, amount = int(time), int(amount) T.append((name, time, amount, city)) invalidT = [] # do comparison on all permutation for name, time, amount, city in T: invlid = amount > 1000 if not invlid: for nameX, timeX, amountX, cityX in T: if name == nameX and abs(time - timeX) <= 60 and city != cityX: invlid = True break if invlid: invalidT.append("{},{},{},{}".format(name, time, amount, city)) return invalidT class UglySolution: def invalidTransactions(self, transactions): dict = {} invalid = [] for tran in transactions: tranInfo = tran.split(',') if tranInfo[0] in dict: dict[tranInfo[0]].append((int(tranInfo[1]),tranInfo[3],int(tranInfo[2]),tran)) else: dict[tranInfo[0]] = [(int(tranInfo[1]),tranInfo[3],int(tranInfo[2]),tran)] for personTran in dict: personTranList = dict[personTran] for i in range(len(personTranList)): invalidi = False (timei,cityi,amounti,trani) = personTranList[i] if amounti > 1000: invalidi = True for j in range(i,len(personTranList)): (timej,cityj,amountj,tranj) = personTranList[j] if cityi!=cityj and abs(timei-timej)<=60: invalidi = True if amountj <= 1000 and tranj not in invalid: invalid.append(tranj) if invalidi and trani not in invalid: invalid.append(trani) return invalid import unittest class InvalidTranTest(unittest.TestCase): def testExample1(self): tran = ["alice,20,800,mtv","alice,50,100,beijing"] r = Solution().invalidTransactions(tran) self.assertEqual(r, ["alice,20,800,mtv","alice,50,100,beijing"]) def testExample2(self): tran = ["alice,20,800,mtv","alice,50,1200,mtv"] r = Solution().invalidTransactions(tran) self.assertEqual(r, ["alice,50,1200,mtv"]) def testExample3(self): tran = ["alice,20,800,mtv","bob,50,1200,mtv"] r = Solution().invalidTransactions(tran) self.assertEqual(r, ["bob,50,1200,mtv"]) def testLeetCodeTestCase1(self): tran = ["bob,689,1910,barcelona", "alex,696,122,bangkok", "bob,832,1726,barcelona", "bob,820,596,bangkok", "chalicefy,217,669,barcelona", "bob,175,221,amsterdam"] r = Solution().invalidTransactions(tran) self.assertEqual(r, ["bob,689,1910,barcelona","bob,832,1726,barcelona", "bob,820,596,bangkok"]) def testLeetCodeTestCase2(self): tran = ["bob,627,1973,amsterdam", "alex,387,885,bangkok", "alex,355,1029,barcelona", "alex,587,402,bangkok", "chalicefy,973,830,barcelona", "alex,932,86,bangkok", "bob,188,989,amsterdam"] r = Solution().invalidTransactions(tran) self.assertEqual(r, ["bob,627,1973,amsterdam","alex,387,885,bangkok", "alex,355,1029,barcelona"]) if __name__ == "__main__": unittest.main()
UTF-8
Python
false
false
5,189
py
89
1169.py
88
0.597803
0.541145
0
134
37.731343
95
sadimauro/projecteuler
9,706,626,102,311
e0c0110adb34f30ab33b8e55d285d873ad4fc96c
4b30fa26f7c5dfb413950fc4dc9e4e89129944c4
/stevepe.py
8458c20d2ac29612c42ae3cae49e0faf000d4baa
[]
no_license
https://github.com/sadimauro/projecteuler
ca6f6cc3e8eac83bdb667c88a9b892923a3df57c
a07b71ecdf7f0cc7b53fcd021c67c5a7518d8571
refs/heads/master
"2021-07-08T00:12:46.272408"
"2020-07-11T12:32:56"
"2020-07-11T12:32:56"
143,607,960
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3 import math import itertools def isPrime(a): """ >>> isPrime(1) False >>> isPrime(2) True >>> isPrime(3) True >>> isPrime(4) False >>> isPrime(25) False >>> isPrime(27) False >>> isPrime(29) True """ if a <= 0: return False # 1 is not prime if a == 1: return False # 2 is prime if a == 2: return True # all other evens are not prime if a % 2 == 0: return False # check odd divisors between 3 and sqrt(a) #for i in range(3, math.floor(math.sqrt(a))+1, 2): for i in range(3, int(math.sqrt(a))+1, 2): if a % i == 0: return False return True def isComposite(n): return not isPrime(n) def getNextOddPrime(n): """ Return next odd prime greater than n. n is expected to be odd. """ n += 2 while True: if isPrime(n): return n n += 2 def getPrimesBelow(n): """ Return a list of the primes strictly below n. >>> getPrimesBelow(-3) [] >>> getPrimesBelow(2) [] >>> getPrimesBelow(3) [2] >>> getPrimesBelow(8) [2, 3, 5, 7] >>> getPrimesBelow(13) [2, 3, 5, 7, 11] """ return getPrimesBetween(1, n) def getPrimesBetween(m, n): """ Return the list of primes strictly greater than m and strictly less than n. >>> getPrimesBetween(64, -3) [] >>> getPrimesBetween(0, 2) [] >>> getPrimesBetween(1, 3) [2] >>> getPrimesBetween(1, 8) [2, 3, 5, 7] >>> getPrimesBetween(1, 13) [2, 3, 5, 7, 11] >>> getPrimesBetween(2, 13) [3, 5, 7, 11] >>> getPrimesBetween(8, 13) [11] """ ret = list() if m >= n: return ret if n <= 2: return ret if m <= 1: ret.append(2) if n <= 3: return ret if m % 2 == 0: m = m - 1 i = getNextOddPrime(m) while i < n: ret.append(i) i = getNextOddPrime(i) return ret def getPrimesBelowBySieve(n): """ Return a list of the primes strictly below n. Calculate by using the Sieve of Eratosthenes. This is a *lot* faster than getPrimesBelow(). >>> getPrimesBelowBySieve(-3) [] >>> getPrimesBelowBySieve(2) [] >>> getPrimesBelowBySieve(3) [2] >>> getPrimesBelowBySieve(8) [2, 3, 5, 7] >>> getPrimesBelowBySieve(13) [2, 3, 5, 7, 11] """ ret = list() if n <= 2: return ret boolList = list() for i in range(n): boolList.append(True) boolList[0] = False; boolList[1] = False for i in range(2,math.floor(math.sqrt(n))+1): if boolList[i]: for j in range(i**2, n, i): boolList[j] = False for i in range(len(boolList)): if boolList[i]: ret.append(i) return ret def getPrimesBetweenBySieve(m,n): """ Return the list of primes strictly greater than m and strictly less than n. >>> getPrimesBetweenBySieve(64, -3) [] >>> getPrimesBetweenBySieve(0, 2) [] >>> getPrimesBetweenBySieve(1, 3) [2] >>> getPrimesBetweenBySieve(1, 8) [2, 3, 5, 7] >>> getPrimesBetweenBySieve(1, 13) [2, 3, 5, 7, 11] >>> getPrimesBetweenBySieve(2, 13) [3, 5, 7, 11] >>> getPrimesBetweenBySieve(8, 13) [11] """ primes = getPrimesBelowBySieve(n) i = 0 while i < len(primes): if primes[i] > m: break i += 1 if i == len(primes): return [] return primes[i:] def getFactors(n): """ Return a list containing the factors of n, including 1 and n itself. """ list2d = [[1], getPrimeFactors(n), [n]] return list(itertools.chain.from_iterable(list2d)) def getPrimeFactors(n): """ Return a list containing the factors of n, not including 1 and n itself. >>> getPrimeFactors(-3) [] >>> getPrimeFactors(0) [] >>> getPrimeFactors(1) [] >>> getPrimeFactors(2) [] >>> getPrimeFactors(4) [2, 2] >>> getPrimeFactors(7) [] >>> getPrimeFactors(18) [2, 3, 3] >>> getPrimeFactors(64) [2, 2, 2, 2, 2, 2] >>> getPrimeFactors(238202) [2, 119101] """ ret = list() if n < 4: return ret primesToTry = getPrimesBelow(n) i = 0 while i < len(primesToTry) and primesToTry[i] <= n: if n % primesToTry[i] == 0: ret.append(primesToTry[i]) n = n // primesToTry[i] else: i += 1 return ret def isStrPandigital(n): nSet = set(n) return len(nSet) == len(n) and min(nSet) == '1' and max(nSet) == str(len(n)) def isIntPandigital(n): """Return True if n is pandigital, False otherwise. We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. >>> isIntPandigital(12345) True >>> isIntPandigital(15243) True >>> isIntPandigital(1) True >>> isIntPandigital(14326) False >>> isIntPandigital(14445) False """ return isStrPandigital(str(n)) def tupleToInt(tupIn): res = 0 for i in range(len(tupIn)): res *= 10 res += int(tupIn[i]) return res def sortIntDigits(intIn): """ >>> sortIntDigits(1423) 1234 """ a = list(str(intIn)) a.sort() return tupleToInt(a) def isPentagonal(n): """ Return True is n is pentagonal, i.e. if n = k(3k-1)/2 for some value k. >>> isPentagonal(0) False >>> isPentagonal(1) True >>> isPentagonal(5) True >>> isPentagonal(117) True >>> isPentagonal(118) False >>> isPentagonal(-3) False """ if n <= 0: return False maybeNat = (math.sqrt((24*n)+1) + 1) / 6 return maybeNat == int(maybeNat) def isHexagonal(n): """ Return True is n is pentagonal, i.e. if n = k(3k-1)/2 for some value k. >>> isHexagonal(0) False >>> isHexagonal(1) True >>> isHexagonal(6) True >>> isHexagonal(231) True >>> isHexagonal(250) False >>> isHexagonal(-3) False """ if n <= 0: return False maybeNat = (math.sqrt((8*n)+1) + 1) / 4 return maybeNat == int(maybeNat) def isTriangular(n): """ Return True if n is triangular, i.e. if n = k(k+1)/2 for some integer k. >>> isTriangular(1) True >>> isTriangular(0) False >>> isTriangular(15) True >>> isTriangular(16) False >>> isTriangular(-3) False """ if n <= 0: return False maybeSq = math.sqrt((8*n) + 1) return maybeSq == int(maybeSq) def isSquare(n): """ Return n if n is a square > 0, False otherwise. """ if n < 0: return False temp = math.sqrt(n) return temp == int(temp) def getNextSquare(n): """ Return the next number greater than n that is a square. """ n += 1 while True: if isSquare(n): return n n += 1 def getIntPermutations(n): """ Return a set filled with all of the permutations of int n, including n itself. e.g. if n = 123, return is {123, 132, 213, 231, 312, 321}. >>> getIntPermutations(1) {1} >>> getIntPermutations(12) {12, 21} >>> getIntPermutations(123) {321, 132, 231, 213, 312, 123} >>> a = list(getIntPermutations(122)) >>> a.sort() >>> a [122, 212, 221] >>> getIntPermutations(144) {144, 441, 414} """ ret_list = [] ints = (int(x) for x in str(n)) iter = itertools.permutations(ints) ret_list = [tupleToInt(tup) for tup in iter] #for tup in iter: # ret.add(tupleToInt(tup)) return ret_list def getIntPermutationsDeduped(n): return set(getIntPermutations(n)) def genIntPermutations(n): """ Generate all of the permutations of int n, including n itself. e.g. if n = 123, return is {123, 132, 213, 231, 312, 321}. """ for tup in itertools.permutations(str(n)): yield tupleToInt(tup) return def getIntReverse(n): """ Return the reverse of int n. >>> getIntReverse(1234) 4321 >>> getIntReverse(0) 0 >>> getIntReverse(-7575) -5757 """ neg = False if n < 0: neg = True n *= -1 n_str = str(n) n_str_rev = '' for i in range(len(n_str)): n_str_rev += n_str[len(n_str)-i-1] if neg: n_str_rev = '-' + n_str_rev return int(n_str_rev) def isIntPalindrome(n): """ Return True if n is a palindrome. >>> isIntPalindrome(1234) False >>> isIntPalindrome(12321) True """ return getIntReverse(n) == n def getDigitalSum(n): """ Return the sum of the digits in n. >>> getDigitalSum(1234) 10 """ tot = 0 while n > 0: tot += n % 10 n = n // 10 return tot def numberOfDigits(n): """ Return the number of digits in n. >>> numberOfDigits(123) 3 >>> numberOfDigits(-4567) 4 >>> numberOfDigits(0) 1 """ if n == 0: return 1 count = 0 n = abs(n) while n > 0: count += 1 n = n // 10 return count if __name__ == "__main__": import doctest doctest.testmod()
UTF-8
Python
false
false
9,468
py
84
stevepe.py
79
0.529045
0.482256
0
533
16.763602
80
carlosescorche/pythoneando
10,917,806,875,137
2a319a8cd54f9cb01ed54cac7c5cc13099c0b985
b9611ff290c88a4907020b2a2026d5ad4d713fc4
/teoria/12_excepciones/03.py
040133be04ff099ec643d72cc873a02e2490ed22
[]
no_license
https://github.com/carlosescorche/pythoneando
fddd70a1e5b27e2d37fa6512fbfef5a63e89ed81
7e4a430d8a0a076dfb655f82b089f3c58efce21d
refs/heads/master
"2020-03-23T15:34:16.174446"
"2018-09-05T21:04:07"
"2018-09-05T21:04:07"
141,757,926
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python #coding=utf-8 #Por último es posible utilizar un bloque finally que se ejecute al final del código, ocurra o no ocurra un error: while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{}={}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") else: print("Todo ha funcionado correctamente") break #Importante romper la iteración si todo ha salido bien finally: print("Fin de la iteración") # Siempre se ejecuta
UTF-8
Python
false
false
559
py
23
03.py
21
0.63472
0.631103
0
16
33.5625
114
wongmi21/uoft-mail-merge
10,050,223,516,880
21764df53c0640faa721f0113d6e3e56947dcb65
e5e472c4e838788ace767ddbab3594fc47d619f2
/Step 1-scrape.py
f50e4abe09fafbdd12bc87863fdbf0163929977c
[]
no_license
https://github.com/wongmi21/uoft-mail-merge
aa9f5a763ab06210c91b0033fbc0d61aefd85e62
c5c8bfa8f3b27b1b4af55581e43173e9f8c9121d
refs/heads/master
"2020-04-16T08:43:31.073222"
"2013-08-09T23:27:55"
"2013-08-09T23:27:55"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Thu Jul 25 02:21:06 2013 @author: mike """ from bs4 import BeautifulSoup import requests import csv from titlecase import titlecase url = raw_input("Enter a website to extract the URL's from: ") while url != 'done': jobid = url.index('JOB_ID=') + 7 endjobid = url.index('&abPage=') tr = url.index('tr=') + 3 endtr = url.index('&K1=') printurl = 'http://www.careers.utoronto.ca/st/jobview.aspx?print=Y&JOB_ID=' + url[jobid:endjobid] + '&tr=' + url[tr:endtr] print printurl r = requests.get(url) data = r.text soup = BeautifulSoup(data) try: email = soup.find('span', {'id' :'ctl00_MainContent_ctl03_lbl_apply'}) email = unicode(email)[unicode(email).index(u'<strong>Email:</strong>\u00a0') + len(u'<strong>Email:</strong>\u00a0'):] email = email[:email.index('<br')] print email except: email = 'email' print 'no email' try: employer = soup.find('span', {'id' :'ctl00_MainContent_ctl03_lbl_contact'}).text print employer except: employer = 'Hiring Manager' print 'no employer' try: company = titlecase(soup.find('span', {'id' :'ctl00_MainContent_ctl03_lbl_org'}).text) print company except: company = '' print 'no company' try: companyaddress = soup.find('span', {'id' :'ctl00_MainContent_ctl03_lbl_address'}) companyaddress = unicode(companyaddress) companyaddress = companyaddress[companyaddress.index('ctl03_lbl_address">') + len('ctl03_lbl_address">'):companyaddress.index('<br/></span>')] companyaddress = companyaddress.replace('<br/>', r'\\') print companyaddress except: companyaddress = '' print 'no companyaddress' try: position = soup.find('span', {'id' :'ctl00_MainContent_ctl03_lbl_position_title'}).text print position except: position = '' print 'no position' try: actuarial = soup.find('span', {'id' :'ctl00_MainContent_ctl03_lbl_discipline'}).text actuarial = actuarial[actuarial.index('Actuarial Science'):] actuarial = '1' print actuarial except: actuarial = '0' print 'no actuarial' try: industry = soup.find('span', {'id' :'ctl00_MainContent_ctl03_lbl_industry'}).text print industry except: industry = 'Finance/Insurance and Big Data' print 'industry' source = "University of Toronto's career website" resultFile = open("jobs.csv",'a') index = sum(1 for row in csv.reader(open("jobs.csv",'r'))) newrow = [str(index),employer,company,companyaddress,position,industry,source,actuarial,url,email] newentry = ','.join('"' + item.replace(unichr(160), " ").strip() + '"' for item in newrow) + '\n' resultFile.write(newentry) resultFile.close url = raw_input("Enter a website to extract the URL's from: ")
UTF-8
Python
false
false
3,014
py
2
Step 1-scrape.py
2
0.604512
0.584273
0
86
34.05814
150
peteowe/geo
12,335,146,110,311
87d88ee2d0c75b8efe3a56e0eeacf9c5ff1aa609
efe8529bd4ceb2092531137db14f8953e7e96a9a
/app/command/DownloadCommand.py
21807944b89356f1a7e4ac1b3b234c6ca7d47aaf
[]
no_license
https://github.com/peteowe/geo
1badfd3f60297c5715b943772b82cfbe7c2e098e
c75fcd8d5dc5110f607d4dc98708172cf50def61
refs/heads/master
"2020-07-28T18:01:02.938033"
"2019-09-19T07:16:03"
"2019-09-19T07:16:03"
209,462,084
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from app.command.Command import Command class DownloadCommand(Command): downloader = None def __init__(self, downloader): self.downloader = downloader def execute(self, args): if len(args) != 3: raise Exception("Must provide a filename and url to continue") self.downloader.download(args[2],args[1])
UTF-8
Python
false
false
325
py
34
DownloadCommand.py
23
0.707692
0.698462
0
10
31.5
68
marflodin/adventofcode-2020
14,886,356,661,625
005d9a0769aead3b73e39433a3adaa1bde4d1707
36297b58bedf27422e149e9eb10a39e3f29c0014
/src/day_4_part_1.py
b64e89ee43fb3d72aa50efb71f42237b2a6079a1
[]
no_license
https://github.com/marflodin/adventofcode-2020
fa4711c9ab7010bdc10be58a6c8a4407371b589f
e825a41398ea2f0a527e673c004bcc0b09486aaf
refs/heads/main
"2023-01-24T17:30:48.340870"
"2020-12-09T10:12:55"
"2020-12-09T10:12:55"
318,784,884
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
with open('../resources/input_day_4.txt', 'r') as input_file: entries = [] entry = {} for line in input_file.readlines(): if line in ['\n', '\r\n']: entries.append(entry) entry = {} else: properties = line.split(' ') for prop in properties: entry[prop.split(':')[0].strip()] = prop.split(':')[1].strip() entries.append(entry) required_keys = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] def is_valid_passport(item) -> bool: for key in required_keys: if item.get(key, None) is None: return False return True if __name__ == "__main__": valid_passports = 0 for entry in entries: if is_valid_passport(entry): valid_passports += 1 print(f"Valid passports {valid_passports}") print(f"passports {len(entries)}")
UTF-8
Python
false
false
874
py
15
day_4_part_1.py
14
0.536613
0.530892
0
29
29.137931
78
aaronpmishkin/normalizing_flows
17,265,768,548,922
b05647d00cf0b6916dca2e94939e7b289526c60e
0fa7b9328e04d2ff5a2b607d9ec6962b7ee97532
/vi_lib/lib/torchutils/code_examples/indgrad.py
c58716b3486982b86f013804d4d48028c6367b9c
[]
no_license
https://github.com/aaronpmishkin/normalizing_flows
4b12bcbe85f400bb27d21e93d8a3c35d9e5df90c
249f0d99fee6d07783a2a3a595cfeb439af8c599
refs/heads/master
"2020-04-09T01:09:40.906963"
"2018-12-14T07:47:08"
"2018-12-14T07:47:08"
159,893,931
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
r""" Utility functions to handle parralel computation of individual gradients """ import torch from torch.optim import Optimizer from torchutils.models import MLP __all__ = [ ] class MLPIndGrad(MLP): r"""MultiLayer Perceptron with support for individual gradient computation """ def __init__(self, input_size, hidden_sizes=[], output_size=1, act_func=torch.tanh): r"""See ``torchutils.models.MLP`` """ super(MLP, self).__init__(input_size, hidden_sizes, output_size, act_func) def forward(self, x): r""" """ activation = x activations = [activation] linearCombs = [] for layer in self.hidden_layers: linearComb = layer(activation) activation = self.act(linearComb) linearComb.retain_grad() linearComb.requires_grad_(True) linearCombs.append(linearComb) activations.append(activation) output = self.output_layer(activation) output.retain_grad() output.requires_grad_(True) linearComb.append(output) return (output, activations, linearCombs) def goodfellow_grad(G, X) def goodfellow_backprop(activations, linearCombs, backprop_func, n_out): outs = tuple([[] for i in range(n_out)]) for i in range(len(linearCombs)): out = backprop_func(linearCombs[i], activations[i]) for j in range(n_out): outs[j].append(out[j]) return *outs
UTF-8
Python
false
false
1,361
py
95
indgrad.py
66
0.676708
0.675974
0
60
21.683333
85
rc-luo/FedML
3,676,492,005,766
3a0984a46165ae2295d5e5163a96e27c5bc40c3f
4145e7d391cf4296f92ec692d02d6daca25f3bfb
/fedml_api/standalone/decentralized/client_dsgd_toy.py
ebe05dd869ba1f33c32751c2d3ee28b10a7caf25
[ "Apache-2.0" ]
permissive
https://github.com/rc-luo/FedML
0ec31b59b8e60f1b884eaef66103aea3890047bd
2a7cacbf0b74307f9adedcceb3b0fb6f92c41067
refs/heads/master
"2023-06-17T05:04:00.349345"
"2021-07-10T10:07:39"
"2021-07-10T10:07:39"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import random import torch from fedml_api.standalone.decentralized.client_dsgd import ClientDSGD class ClientDSGD_Toy(ClientDSGD): def __init__(self, model, model_cache, client_id, streaming_data, iteration_number, learning_rate, batch_size, weight_decay, latency, b_symmetric): # logging.info("streaming_data = %s" % streaming_data) # Since we use logistic regression, the model size is small. # Thus, independent model is created each client. self.model = model() self.b_symmetric = b_symmetric self.id = client_id # integer self.streaming_data = streaming_data self.topology = [] # print(self.topology) self.optimizer = torch.optim.SGD(self.model.parameters(), lr=learning_rate, weight_decay=weight_decay) self.criterion = torch.nn.BCELoss() self.learning_rate = learning_rate self.iteration_number = iteration_number # TODO: self.latency = random.uniform(0, latency) self.batch_size = batch_size self.loss_in_each_iteration = [] # the default weight of the model is z_t, while the x weight is another weight used as temporary value self.model_x = model_cache() # neighbors_weight_dict self.neighbors_weight_dict = dict() self.neighbors_topo_weight_dict = dict() def examine_loss(self, model, exam_samples=5): selected_samples = random.sample(range(len(self.streaming_data)), k=exam_samples) loss = [] for _id in selected_samples: train_x = torch.from_numpy(self.streaming_data[_id]['x']).float() # print(train_x) train_y = torch.FloatTensor([self.streaming_data[_id]['y']]) outputs = model(train_x) # print(train_y) loss.append(self.criterion(outputs, train_y)) return sum(loss)
UTF-8
Python
false
false
1,901
py
9
client_dsgd_toy.py
7
0.62809
0.627038
0
52
35.576923
110
peteWT/cec_apl
10,754,598,146,526
123a4c05ad38fd12a7ec54d9106c33c81e35cdc2
85a5f0601d22f587bd93d4877d264eb95acd5107
/Allocation model/Transmodel_v1.py
cf6a6041d16c3a89a54fb2ba911cd16ad222b387
[ "MIT" ]
permissive
https://github.com/peteWT/cec_apl
72630abbae0e952b4b2f9bfab040ca77b1c4a08f
388e0a41178876caae2a52e49c656b3c93adc4d2
refs/heads/master
"2021-01-16T23:28:28.857446"
"2017-02-19T21:55:52"
"2017-02-19T21:55:52"
47,349,609
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # Deployment model for distributed gasifiers # Jose Daniel Lara # Import from __future__ import division from pyomo.environ import * import googlemaps import datetime from pprint import pprint # Replace the API key below with a valid API key. gmaps = googlemaps.Client(key='AIzaSyAh2PIcLDrPecSSR36z2UNubqphdHwIw7M') # Creation of a Concrete Model model = ConcreteModel() # Load the data from files sources_file = open('sources.dat', 'r') destinations_file = open('destinations.dat', 'r') substation_list = destinations_file.read().splitlines() exception_list = zip(substation_list, substation_list) biomass_list = sources_file.read().splitlines() sources_file.close() destinations_file.close() # Components: # SETS_ALL_CAPS # VarsCamelCase # params_lower_case_with_underscores # Constraints_Words_Capitalized_With_Underscores # SET_time_system # Define sets from the data read## model.SOURCES = Set(initialize=biomass_list, doc='Location of Biomass sources') model.SUBS = Set(initialize=substation_list, doc='Location of Substations') model.EXCEPTION_LIST = Set(initialize=exception_list, doc='Temp Set') model.ROUTES = Set(dimen=2, doc='Allows routes from sources to sinks', initialize=lambda mdl: ((mdl.SOURCES | mdl.SUBS) * mdl.SUBS) - mdl.EXCEPTION_LIST) model.TIME_n = Set(initialize=range(1, 25), doc='Time set') # Define Parameters # Cost related parameters model.installation_cost_var = Param(initialize=15, doc='Variable installation cost per kW') model.installation_cost_fix = Param(initialize=500, doc='Fixed cost of installing in the site') model.om_cost_fix = Param(initialize=1, doc='Fixed cost of operation per installed kW') model.om_cost_var = Param(initialize=0.04, doc='Variable cost of operation per installed kW') model.biomass_cost = Param(model.SOURCES, initialize={'Seattle, WA, USA': 28, 'San Diego, CA, USA': 28}, doc='Cost of biomass per ton') model.transport_cost = Param(initialize=90, doc='Freight in dollars per ton per km') model.fit_tariff = Param(model.SUBS, initialize={'New York, NY, USA': 12, 'Chicago, IL, USA': 14, 'Topeka, KY, USA': 12}, doc='Payment FIT $/kWh') # Limits related parameters model.source_biomass_max = Param(model.SOURCES, initialize={'Seattle, WA, USA': 2350, 'San Diego, CA, USA': 2600}, doc='Capacity of supply in tons') model.installation_cost_var = Param(initialize=150, doc='Cost of installing units per kW') model.installation_cost_fix = Param(initialize=5000, doc='Fixed cost of installing the unit') model.om_cost_fix = Param(initialize=1, doc='Fixed cost of operation per kW') model.om_cost_var = Param(initialize=0.04, doc='Fixed operation cost per kW') model.biomass_cost = Param(model.SOURCES, initialize={'seattle': 28, 'san-diego': 28}, doc='Cost of biomass per ton') model.transport_cost = Param(initialize=90, doc='Freight in dollars per case-thousand-miles') model.fit_tariff = Param(model.SUBS, initialize={'new-york': 12, 'chicago': 14, 'topeka': 12}, doc='Payment FIT $/kWh') model.max_power = Param(initialize=1000, doc='Max installation per site kW') model.min_power = Param(initialize=100, doc='Min installation per site kW') model.capacity_factor = Param(initialize=0.85, doc='Gasifier capacity factor') # Operational parameters model.heat_rate = Param(initialize=0.8333, doc='Heat rate kWh/Kg') model.delta_t = Param(initialize=1, doc='Time step of analysis') model.total_time = Param(initialize=24, doc='Max timeframe for analysis') # Distances from googleAPI, matrx_distance is a dictionary, first it extends # the biomass list to include the substations for the distance calculations biomass_list.extend(substation_list) matrx_distance = gmaps.distance_matrix(biomass_list, substation_list, mode="driving") # This loop goes over the results from the google API to extract the distances # the n and k indexes are used to iterate over the contents of the biomass_list # kk is the same as nn but saving the index in the list. distance_table = {} for n in biomass_list: k = biomass_list.index(n) for nn in substation_list: kk = substation_list.index(nn) if n != nn: distance_table[biomass_list[k], substation_list[kk]] = ( matrx_distance['rows'][k]['elements'][kk]['distance']['value']) model.distances = Param(model.SOURCES, model.SUBS, initialize=distance_table, doc='Distance in meters') # Define variables # Generator Variables model.CapInstalled = Var(model.SUBS, within=NonNegativeReals, doc='Installed Capacity kW') model.InstallorNot = Var(model.SUBS, within=Binary, doc='Decision to install or not') model.S_b = Var(model.SOURCES, within=NonNegativeReals, doc='Total Biomass supplied from source') model.flow_biomass = Var(model.SOURCES, model.SUBS, within=NonNegativeReals, doc='Biomass shipment quantities in tons') ## Define contraints ## def balance(model): return sum(model.P_s[s,t]*model.delta_t for s in model.SUBS for t in model.TIME_n) == sum(model.heat_rate*model.S_b[b] for b in model.SOURCES) model.e_balance = Constraint(rule=balance, doc='Energy Balance in the system') def flow_rule(mdl, k): inFlow = sum(mdl.flow[i, j] for (i, j) in mdl.routes if j == k) outFlow = sum(mdl.flow[i, j] for (i, j) in mdl.routes if i == k) return inFlow+mdl.supply[k] == outFlow+mdl.demand[k] model.flowconstraint = Constraint(model.nodes, rule=flow_rule) def capacity_factor_limit(model, substations): return sum(model.P_s[s,t]*model.delta_t for s in model.SUBS for t in model.TIME_n) <= sum(model.capacity_factor*model.P_s_max[s] for s in model.SUBS) model.cap_factor_limit = Constraint(model.SUBS, rule=capacity_factor_limit, doc='Capacity factor limitation') def minimum_power(model, s, t): return model.min_power*model.U_s[s] <= model.P_s[s,t] model.minm_power=Constraint(model.SUBS, model.TIME_n, rule=minimum_power, doc='Minimum Power constraint') def maximum_power(model, s, t): return model.P_s[s,t] <= model.P_s_max[s] model.maxm_power=Constraint(model.SUBS, model.TIME_n, rule=maximum_power, doc='Max Power constraint') def maximum_power_limit(model, s): return model.P_s_max[s] <= model.U_s[s]*model.max_power model.maxm_power_limit = Constraint(model.SUBS, rule=maximum_power_limit, doc='Limit to Max Power') def maximum_biomass(mdl, b): return mdl.S_b[b] <= mdl.source_biomass_max[b] # model.maxm_biomass = Constraint(model.SOURCES, rule=maximum_biomass, doc='Max biomass in source') model.maxm_biomass = Constraint(model.SOURCES, doc='Max biomass in source', rule=lambda mdl, b: mdl.S_b[b] <= mdl.source_biomass_max[b]) ======= model.maxm_power_limit=Constraint(model.SUBS, rule=maximum_power_limit, doc='Limit to Max Power') def maximum_biomass(model, b): return model.S_b[b] <= model.source_biomass_max[b] model.maxm_biomass=Constraint(model.SOURCES, rule=maximum_biomass, doc='Max biomass in source') def demand_rule(model, b): return sum(model.flow_biomass[b,s] for s in model.SUBS) == model.S_b[b] model.demand = Constraint(model.SOURCES, rule=demand_rule, doc='Calculate total supply from biomass source') ## Define Objective and solve ## def objective_rule(model): return ( sum(model.installation_cost_var*model.P_s_max[s] for s in model.SUBS) + sum(model.installation_cost_fix*model.U_s[s] for s in model.SUBS) + sum(model.OM_cost_fix*model.P_s_max[s] for s in model.SUBS) + sum(model.OM_cost_var*model.P_s[s,t]*model.delta_t for s in model.SUBS for t in model.TIME_n) + sum(model.matrix_transport_cost[b,s]*model.flow_biomass[b,s] for b in model.SOURCES for s in model.SUBS) - sum(model.biomass_cost[b]*model.S_b[b] for b in model.SOURCES) - sum(model.FIT_tariff[s]*model.P_s[s,t]*model.delta_t for s in model.SUBS for t in model.TIME_n) ) model.objective = Objective(rule=objective_rule, sense=minimize, doc='Define objective function') ## Display of the output ## # Display x.l, x.m ; def pyomo_postprocess(options=None, instance=None, results=None): model.P_s_max.display() model.P_s.display() model.U_s.display() model.S_b.display() model.flow_biomass.display() # This is an optional code path that allows the script to be run outside of # pyomo command-line. For example: python transport.py if __name__ == '__main__': # This emulates what the pyomo command-line tools does from pyomo.opt import SolverFactory import pyomo.environ opt = SolverFactory("gurobi") results = opt.solve(model) #sends results to stdout results.write() print("\nDisplaying Solution\n" + '-'*60) pyomo_postprocess(None, None, results)
UTF-8
Python
false
false
9,499
py
55
Transmodel_v1.py
33
0.658385
0.649753
0
208
44.668269
151
sainttobs/learning_python
3,917,010,211,402
f875601de44f366bcc2852cd2923fb8d7919d314
cb63c72a398c26be68f4c206d24fb4c923e9ba8d
/variables.py
6d05055ff4b60135689a330e1b80359eb3c80242
[]
no_license
https://github.com/sainttobs/learning_python
c7891bc5c910d96d8d790d5cf1fbe74bacdc6e2a
406ab06ef36001ea1a6dbbd62787c519fab5d651
refs/heads/master
"2020-04-17T02:18:54.300075"
"2019-03-13T00:40:20"
"2019-03-13T00:40:20"
166,128,480
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# simple python tutorial learning how to assign values to variables. firstName = "Adeyefa" lastName = "Oluwatoba Adegoke" age = 19 print (firstName) print (lastName) print (age)
UTF-8
Python
false
false
178
py
25
variables.py
24
0.764045
0.752809
0
8
21.375
68
truonghoanghuy/handwritten-text-recognition
2,388,001,832,775
57fda2e9bc2048cdc361988e3acdaf58b98499ca
9701b8b6d8ef262e4909e37ce452467b82349da9
/lf/lf_loss_function.py
15cd57f850e03fdb02df00dfb365e8ff6c5eff5d
[]
no_license
https://github.com/truonghoanghuy/handwritten-text-recognition
61f826fdfd21b2b9ef5f3ce1ba8112c0e8988b65
d6ff66aee01744a36bd8de13e84870814b698d26
refs/heads/master
"2022-11-16T17:37:20.181799"
"2020-07-12T08:39:27"
"2020-07-12T08:39:27"
173,250,718
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from typing import List, Optional, Dict import torch from torch.nn import Module from lf import lf_loss from utils import string_utils, error_rates def calculate(lf_model: Module, input, dtype: torch.dtype, device: torch.device, train=True, hw: Optional[Module] = None, idx_to_char: Optional[Dict] = None): input = input[0] # Only single batch for now lf_xyrs = input['lf_xyrs'] # type: List[torch.Tensor] lf_xyxy = input['lf_xyxy'] # type: List[torch.Tensor] img = input['img'] # type: torch.Tensor x_i: torch.Tensor positions = [x_i.to(device, dtype).unsqueeze_(0) for x_i in lf_xyrs] xy_positions = [x_i.to(device, dtype).unsqueeze_(0) for x_i in lf_xyxy] img = img.to(device, dtype).unsqueeze_(0) # There might be a way to handle this case later, but for now we will skip it if len(xy_positions) <= 1: raise UserWarning('Skipped 1 sample') if train: grid_line, _, _, xy_output = lf_model(img, positions[0], steps=len(positions), skip_grid=True, all_positions=positions, reset_interval=4, randomize=True) loss = lf_loss.point_loss(xy_output, xy_positions) else: skip_hw = hw is None or idx_to_char is None grid_line, _, _, xy_output = lf_model(img, positions[0], steps=len(positions), skip_grid=skip_hw) if skip_hw: loss = lf_loss.point_loss(xy_output, xy_positions) else: # noinspection PyArgumentList line = torch.nn.functional.grid_sample(img.transpose(2, 3), grid_line, align_corners=True) line = line.transpose(2, 3) predictions = hw(line) out = predictions.permute(1, 0, 2).data.cpu().numpy() gt_line = input['gt'] pred, raw_pred = string_utils.naive_decode(out[0]) pred_str = string_utils.label2str_single(pred, idx_to_char, False) loss = error_rates.cer(gt_line, pred_str) return loss
UTF-8
Python
false
false
1,994
py
94
lf_loss_function.py
84
0.615346
0.606319
0
44
44.318182
105
thisismyrobot/twitter-ebook
15,247,133,913,725
a0a42b21bebfe9f9174ec61d667f9a7de739c9cb
cba0aef9e65e7e59d002de3bba369b81baf59974
/tools.py
92589c353a5881bc2fa9529d724384e0c7a74d94
[ "Unlicense" ]
permissive
https://github.com/thisismyrobot/twitter-ebook
aa3dc8636f57ecaadcde6f050799d4b48e3aa73a
dbbb94f999abd3affda0b84afabe6be8318bcd24
refs/heads/master
"2021-01-21T13:11:10.036089"
"2016-05-16T07:56:40"
"2016-05-16T08:11:10"
48,943,008
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Twitter/tweet tools.""" import HTMLParser import itertools import re import string def normalise(word): """Normalise a word for frequency lookups.""" # Remove anything except a-z and &. word = re.sub(r'[^\w&]', '', word) return word.lower() def tidy(tweet): """Tidy a tweet.""" # Ensure it's unicode tweet = unicode(tweet) # Convert HTML characters to unicode. tweet = HTMLParser.HTMLParser().unescape(tweet) # Remove unicode characters - original or from HTML. tweet = tweet.encode('ascii', 'ignore') # Strip basic characters tweet = re.sub(r'[*"()\n\r\t]', '', tweet) # Filter certain words tweet = ' '.join([word for word in tweet.split(' ') if not(word.startswith('http') or word.startswith('#') or word.startswith('.@') or word.startswith('@') or normalise(word) == '')]) # Remaining characters to strip tweet = re.sub(r'[#@]', '', tweet) # Re-apply uniform spacing return ' '.join(filter(None, map(string.strip, tweet.split(' ')))) def sentences(tweet): """Splits a tweet up into one of more sentences.""" return filter(None, map(string.strip, re.split('[.?!]', tweet))) def sentence_corpus(corpus): """Converts a corpus of tweets to a corpus of sentences.""" return list(itertools.chain(*map(sentences, corpus)))
UTF-8
Python
false
false
1,511
py
10
tools.py
6
0.561218
0.561218
0
53
27.509434
70
mk200789/pascal_compiler
19,292,993,097,763
72605445622f42fe300d6d1f0d8737ccad273306
dd95ff24e5aee2a621b13e448854c96ff039f114
/compiler/simulator.py
b4ba6df832f1c86b1c74d40a6d993a28a81da169
[]
no_license
https://github.com/mk200789/pascal_compiler
115812d4cd8eb364161ae141ca3613a1543cb021
7c9030bf897dfe15e7d2576e589901d70d6716c5
refs/heads/master
"2020-12-24T15:05:19.652205"
"2014-12-31T04:53:13"
"2014-12-31T04:53:13"
24,251,422
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#code for simulator will be placed here import sys class Simulator(object): def __init__(self, symtable, d_nodes, stack = [], ip=0): self.symtable = symtable self.d_nodes = d_nodes self.stack = stack self.ip = ip def simulate(self): while(1): print str(self.ip) + ": [" + str(self.d_nodes[self.ip]['instruction']) + " : " +str(self.d_nodes[self.ip]['value']) + "]" if self.d_nodes[self.ip]['instruction'] == 'push': if self.d_nodes[self.ip]['type'] == 'TK_IDENTIFIER': self.pushi(self.d_nodes[self.ip]['value']) else: #push value to stack self.push(self.d_nodes[self.ip]['value']) elif self.d_nodes[self.ip]['instruction'] == 'pop': self.pop(self.d_nodes[self.ip]['value']) elif self.d_nodes[self.ip]['instruction'] == 'add': self.add() elif self.d_nodes[self.ip]['instruction'] == 'minus': self.minus() elif self.d_nodes[self.ip]['instruction'] == 'mult': self.mult() elif self.d_nodes[self.ip]['instruction'] == 'div': self.div() elif self.d_nodes[self.ip]['instruction'] == 'less': self.less() elif self.d_nodes[self.ip]['instruction'] == 'greater': self.greater() elif self.d_nodes[self.ip]['instruction'] == 'equals': self.equals() elif self.d_nodes[self.ip]['instruction'] == 'mod': self.mod() elif self.d_nodes[self.ip]['instruction'] == 'halt': self.halt() elif self.d_nodes[self.ip]['instruction'] == 'jmp': self.jmp(self.d_nodes[self.ip]['value']) elif self.d_nodes[self.ip]['instruction'] == 'jFalse': self.jFalse(self.d_nodes[self.ip]['value']) elif self.d_nodes[self.ip]['instruction'] == 'jTrue': self.jTrue(self.d_nodes[self.ip]['value']) elif self.d_nodes[self.ip]['instruction'] == 'writeln': print self.d_nodes[self.ip+1] self.writeln() self.ip += 1 print "stack: "+str(self.stack) print self.stack def jmp(self, value): self.ip = value - 1 return def jFalse(self, value): value1 = self.stack.pop() if value1 == False: self.ip = value - 1 return def jTrue(self, value): value1 = self.stack.pop() if value1 == True: self.ip = value -1 return def push(self, value): self.stack.insert(0,value) return def pushi(self, value): for v in self.symtable: if value == v['NAME']: self.stack.insert(0,v['VALUE']) return def pop(self, value): #print "pop" value1 = self.stack.pop() for v in self.symtable: if value == v['NAME']: v['VALUE'] = value1 print self.symtable return def add(self): #print "add" value1 = self.stack.pop() value2 = self.stack.pop() #if (type(value1) == type(value2)): # print str(self.symtable) + " HELOWORLD" # for v in self.symtable: # if v['NAME'] == self.d_nodes[self.ip+1]['value']: # tempTotal = v['TYPE'] # if v['VALUE'] == value1: # tempValue1 = v['TYPE'] # if tempValue1 == tempTotal: t = int(value1) + int(value2) self.push(t) return def minus(self): value1 = self.stack.pop() value2 = self.stack.pop() t = int(value1) - int(value2) self.push(t) return def mult(self): value1 = self.stack.pop() value2 = self.stack.pop() t = int(value1) * int(value2) self.push(t) return def div(self): value1 = self.stack.pop() value2 = self.stack.pop() t = int(value1)/int(value2) self.push(t) return def mod(self): value1 = self.stack.pop() value2 = self.stack.pop() t = int(value1)%int(value2) self.push(t) return def less(self): value1 = self.stack.pop() value2 = self.stack.pop() t = int(value1) < int(value2) self.push(t) return def greater(self): value1 = self.stack.pop() value2 = self.stack.pop() t = int(value1) > int(value2) self.push(t) return def equals(self): value1 = self.stack.pop() value2 = self.stack.pop() print type(value1) if type(value1) is int: t = (int(value1) == int(value2)) if type(value1) is str: t = value1 == value2 self.push(t) return def halt(self): print "END" self.printer() sys.exit(0) def printer(self): print "-------------------------------------------" print "%0s %8s %8s %10s %10s %0s" %('|','TOKEN|', 'VALUE|', 'TYPE|', 'ADDRESS', '|') print "-------------------------------------------" for n in self.symtable: print "%0s %8s %8s %10s %10s %0s" %('|', str(n['NAME'])+"|", str(n['VALUE'])+"|", str(n['TYPE'])+"|", n['ADDRESS'], '|') print "-------------------------------------------" return def writeln(self): value1 = self.stack.pop() return
UTF-8
Python
false
false
4,498
py
11
simulator.py
4
0.588039
0.571143
0
175
24.697143
125
akshay-sharma1995/CMU_DeepRL_course
5,531,917,917,288
c2ce80788e01bb85fc37f3697a0bde1cfc52c5d3
466c687ad90a356e1b7811bc337328fcb00f0247
/hw2/hw2-VI-PI-DQN/Q3-3-DQN/codes/DQN_Implementation.py
9d46496067461a6f6fd8170b023476acef1c95a2
[]
no_license
https://github.com/akshay-sharma1995/CMU_DeepRL_course
a0088a8da229a1c4a380abf0a6e4b125b13660cd
bb973312216531a9916568c84e05bb0a685ed547
refs/heads/master
"2022-03-26T19:40:47.172671"
"2019-12-28T13:18:40"
"2019-12-28T13:18:40"
211,947,146
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import numpy as np import gym import sys import copy import os import random import pdb import torch import torch.nn as nn import torch.nn.functional as F from tensorboardX import SummaryWriter from utils import Replay_Memory DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") class DQN_Agent(): # In this class, we will implement functions to do the following. # (1) Create an instance of the Q Network class. # (2) Create a function that constructs a policy from the Q values predicted by the Q Network. # (a) Epsilon Greedy Policy. # (b) Greedy Policy. # (3) Create a function to train the Q Network, by interacting with the environment. # (4) Create a function to test the Q Network's performance on the environment. # (5) Create a function for Experience Replay. def __init__(self, environment_name, Q_model, render=False, learning_rate=1e-5, gamma=0.99, replay_size=100000, burn_in=20000, save_weights_path=None, replay_mem=None): # Create an instance of the network itself, as well as the memory. # Here is also a good place to set environmental parameters, # as well as training parameters - number of episodes / iterations, etc. self.environment_name = environment_name # env for generating and storing transistions self.env = gym.make(self.environment_name) # test env self.test_env = gym.make(self.environment_name) self.obs_space = self.env.observation_space self.action_space = self.env.action_space self.nb_actions = self.action_space.n # creating the Q network self.Q_net = Q_model self.replay_buffer = Replay_Memory(memory_size=replay_size,burn_in=burn_in) if(replay_mem): self.replay_buffer.replay_deque = replay_mem else: self.burn_in_memory(burn_in) self.gamma = gamma self.batch_size = 256 def epsilon_greedy_policy(self, q_values, epsilon): # Creating epsilon greedy probabilities to sample from. # go_greedy = np.random.choice(2,size=1,p=[epsilon,1-epsilon])[0] if(random.random() > epsilon): action = np.argmax(q_values) else: action = np.random.choice(q_values.shape[1],size=1)[0] return action def greedy_policy(self, q_values): # Creating greedy policy for test time. action = np.argmax(q_values) return action def action_to_one_hot(env, action): action_vec = np.zeros(env.action_space.n) action_vec[action] = 1 return action_vec def custom_mse_loss(self, Y_pred, Y_target, actions): loss = 0 for i in range(len(actions)): loss += torch.pow(Y_pred[i,actions[i]] - Y_target[actions[i]], 2) loss /= len(actions) # loss = torch.tensor([Y_pred[i,actions[i]] - Y_target[i,actions[i]] for i in range(0,len(actions))]) # loss = torch.mean(torch.pow(loss,2)) return loss def create_action_mask(self,actions): action_mask = np.zeros((actions.shape[0],self.nb_actions)) for id, mask in enumerate(action_mask): mask[actions[id]] = 1 return action_mask def train(self,epsilon): # In this function, we will train our network. # If training without experience replay_memory, then you will interact with the environment # in this function, while also updating your network parameters. # When use replay memory, you should interact with environment here, and store these # transitions to memory, while also updating your model. curr_state = self.env.reset() ## getting the first state done = False while not(done): with torch.no_grad(): q_values = self.Q_net(torch.unsqueeze(torch.from_numpy(curr_state),dim=0)) action = self.epsilon_greedy_policy(q_values.cpu().numpy(), epsilon) next_state, reward, done, info = self.env.step(action) self.replay_buffer.append((curr_state,action,reward,next_state,done)) curr_state = next_state.copy() ## sample a minibatch of random transitions from the replay buffer sampled_transitions = self.replay_buffer.sample_batch(batch_size=self.batch_size) pdb.set_trace() X_train = np.array([transition[0] for transition in sampled_transitions]) transition_actions = np.array([transition[1] for transition in sampled_transitions]) action_mask = torch.tensor(self.create_action_mask(transition_actions),dtype=torch.bool).to(device=DEVICE) exp_rewards = torch.tensor([transition[2] for transition in sampled_transitions]).float().to(device=DEVICE) sampled_nxt_states = np.array([transition[3] for transition in sampled_transitions]) dones = np.array([int(transition[4]) for transition in sampled_transitions]) with torch.no_grad(): q_max_nxt_state,_ = torch.max(self.Q_net(torch.from_numpy(sampled_nxt_states)),axis=1) q_values_target = exp_rewards + self.gamma * q_max_nxt_state * torch.tensor(1-dones).float().to(device=DEVICE) Y_pred_all_actions = self.Q_net(torch.from_numpy(X_train)) Y_pred = torch.masked_select(Y_pred_all_actions,action_mask) batch_loss = F.mse_loss(Y_pred,q_values_target) self.Q_net.optimizer.zero_grad() batch_loss.backward() self.Q_net.optimizer.step() #print("train_loss: {}".format(batch_loss.item())) return batch_loss.item() def test(self, test_num_episodes=100): # Evaluate the performance of your agent over 100 episodes, by calculating cummulative rewards for the 100 episodes. # Here you need to interact with the environment, irrespective of whether you are using a memory. # load the model weights if provided with a saved model self.Q_net.eval() done = False episodic_test_rewards = [] for episode in range(test_num_episodes): episode_reward = 0 state_t = self.env.reset() done = False while not done: with torch.no_grad(): q_values = self.Q_net(torch.unsqueeze(torch.from_numpy(state_t),dim=0)) action = self.greedy_policy(q_values.cpu().numpy()) state_t_1, reward, done, info = self.env.step(action) episode_reward += reward state_t = state_t_1.copy() episodic_test_rewards.append(episode_reward) self.Q_net.train() return np.mean(episodic_test_rewards), np.std(episodic_test_rewards) def burn_in_memory(self,burn_in): # Initialize your replay memory with a burn_in number of episodes / transitions. print("burn_in_start") nb_actions = self.action_space.n for i in range(burn_in): curr_state = self.env.reset() done = False while not done: action = np.random.randint(0,nb_actions) next_state,reward,done,info = self.env.step(action) self.replay_buffer.append((curr_state,action,reward,next_state,done)) curr_state = next_state.copy() print("burn_in_over") pass
UTF-8
Python
false
false
8,153
py
26
DQN_Implementation.py
13
0.572182
0.564823
0
198
40.171717
128
podgef/euler
2,113,123,951,596
f05d730fceacf3de4d884381c8ace39659df20e9
96ae3fef2fe458d17b0ca8442c85cf175cfc4a0b
/35.py
1699e38a497336b730fbea7ed69e75c040fe8d52
[]
no_license
https://github.com/podgef/euler
c8b0fe613a821b24eb9d914c1804079ece05a742
2add8d31d1cc2557d74904acc7d91b2f1085c4e2
refs/heads/master
"2016-09-08T03:24:22.250602"
"2014-07-20T20:49:47"
"2014-07-20T20:49:47"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python #Padraic Flood <podge.pi@gmail.com> from prime import get_primes from prime import is_prime primes = get_primes(1000000) cirs = 0 prev_circ = [] for prime in primes: s = str(prime) for i in range(1, len(s)): if not is_prime(int(s[i:] + s[:i])): break else: cirs += 1 print cirs
UTF-8
Python
false
false
346
py
59
35.py
59
0.595376
0.566474
0
21
15.47619
44
pixelink-support/pixelinkPythonWrapper
14,645,838,517,184
73f0f676741460badae10662107ce146a069779c
b381ae027aff7ac7d3c32993072e7a029b036150
/samples/Windows/eventCallback.py
1c65e1e09634cc498a15802defc3107323552e37
[ "MIT" ]
permissive
https://github.com/pixelink-support/pixelinkPythonWrapper
f0040fb4c89aff33efba03da7a95253a276c30d8
3f5d4f28c8730debe4e774ceedbbd31c75f85c1d
refs/heads/master
"2022-10-11T10:19:02.191089"
"2022-09-09T18:51:46"
"2022-09-09T18:51:46"
254,446,479
13
3
null
null
null
null
null
null
null
null
null
null
null
null
null
""" eventCallback.py Demonstrates how to use event callbacks """ from pixelinkWrapper import* import time import msvcrt STALL_TIME = 20 # 20 seconds EXIT_SUCCESS = 0 EXIT_FAILURE = 1 """ Callback function called by the API with each event (of interest) reported by the camera. N.B. This is called by the API on a thread created in the API. """ @PxLApi._eventProcessFunction def event_callback_func( hCamera, \ eventId, \ eventTimestamp, \ numDataBytes, \ data, \ userData): # Copy event specific data, if it is provided eventData = data.contents if bool(data) == True else 0 print("EventCallbackFunction: hCamera=%s, eventId=%d" % (hex(hCamera), eventId)) print(" eventTimestamp=%f, numDataBytes=%d" % (eventTimestamp, numDataBytes)) print(" eventData=%s, userData=%d (%s)\n" % (hex(eventData), userData, hex(userData))) return PxLApi.ReturnCode.ApiSuccess def main(): print("This sample application will use the GPI line to demostrate events, OK to proceed Y/N?") userChar = kbHit() if 'y' != userChar and 'Y' != userChar: return EXIT_SUCCESS ret = PxLApi.initialize(0) if not PxLApi.apiSuccess(ret[0]): print("ERROR on PxLApi.initialize: %d" % ret[0]) return EXIT_FAILURE hCamera = ret[1] print("\nMain thread, stalling for %d seconds awaiting events. Toggle the GPI line...\n" % STALL_TIME) userData = 1526647550 # hex(0x5AFECAFE) # Note: We can specify a specific event, or all of them ret = PxLApi.setEventCallback( hCamera, \ PxLApi.EventId.ANY, \ userData, \ event_callback_func) if not PxLApi.apiSuccess(ret[0]): retErr = PxLApi.getErrorReport(hCamera) err = retErr[1] print("ERROR setting event callback function: %d (%s)" % (ret[0], str(err.strReturnCode, encoding='utf-8'))) PxLApi.uninitialize(hCamera) return EXIT_FAILURE time.sleep(STALL_TIME) PxLApi.setEventCallback(hCamera, PxLApi.EventId.ANY, userData, 0) # Cancel the callback PxLApi.uninitialize(hCamera) return EXIT_SUCCESS """ Unbuffered keyboard input on command line. Keyboard input will be passed to the application without the user pressing the enter key. Note: IDLE does not support this functionality. """ def kbHit(): keyPressed = msvcrt.getch() if b'\xe0' == keyPressed: return str(keyPressed) return str(keyPressed, "utf-8") if __name__ == "__main__": main()
UTF-8
Python
false
false
2,675
py
41
eventCallback.py
40
0.622056
0.610841
0.000374
89
28.05618
116
Amiao-miao/all-codes
14,654,428,444,828
4a053dd714c7f41115f35889e0125630cf715bd7
568d7d17d09adeeffe54a1864cd896b13988960c
/project_blog/day02/ddblog/topic/urls.py
d5009b12714fda48ede011e6f70361f66e5b5282
[ "Apache-2.0" ]
permissive
https://github.com/Amiao-miao/all-codes
e2d1971dfd4cecaaa291ddf710999f2fc4d8995f
ec50036d42d40086cac5fddf6baf4de18ac91e55
refs/heads/main
"2023-02-24T10:36:27.414153"
"2021-02-01T10:51:55"
"2021-02-01T10:51:55"
334,908,634
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.urls import path from . import views urlpatterns = [ path('<str:author_id>',views.TopicView.as_view()), ]
UTF-8
Python
false
false
122
py
284
urls.py
274
0.696721
0.696721
0
6
19.5
54
AngaKoko/py_test
3,126,736,214,494
831da0fbaaca22215fdd6de6de4ace8b89efac0f
d2946fdac3b4508788926b09598e29be7d3262e8
/test_nearest.py
e1dcff9f59d335f3bae9a73f618735dfea31db1d
[]
no_license
https://github.com/AngaKoko/py_test
8d22420c90160e9a67901d2535d0aca580579c89
5ab748976652fed20de7580814af6ad296d8d8ca
refs/heads/master
"2022-10-08T18:08:44.118690"
"2020-06-08T09:49:33"
"2020-06-08T09:49:33"
270,612,146
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from nearest import nearest_square def test_nerest_square_5(): assert(nearest_square(5)) == 4 def test_nearest_squaare_12(): assert(nearest_square(-12) == 0)
UTF-8
Python
false
false
167
py
2
test_nearest.py
2
0.694611
0.646707
0
7
23
36
giladsc19-meet/C-Users-schur-PycharmProjects-Gp--version-2
3,856,880,647,344
3d96f2e70816a4f227178c38183b1dba9dffb196
490fe81f02faa1f340420a5ae09b6e16822f5eb9
/server.py
a7e4ce4886e67b14cee6d047e8d59e9128f56ee0
[]
no_license
https://github.com/giladsc19-meet/C-Users-schur-PycharmProjects-Gp--version-2
20960626134e45510b4a5283f17c9264920152cc
f59add075d0a8673334cacecdcd85ea884cba4d0
refs/heads/master
"2022-08-25T16:32:54.728443"
"2020-05-26T12:33:30"
"2020-05-26T12:33:30"
267,037,472
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from database import * from socket import socket from select import select from ssl import create_default_context, Purpose # the 'server.py' directory responsible for getting data from other sockets and send them data in exchange. it # cooperates with the 'analyze.py' directory that contains all the function that analyze the data. # a list that contains all the messages that were;nt sent yet. messages_to_send = [] # lists that record the open clients that exist in chat. open_client_sockets = [] # from the moment a client logs in with his user, the following list records his socket with his username. socket_username = [] def new_connection(server_socket, context): (new_socket, address) = server_socket.accept() new_socket = context.wrap_socket(new_socket, server_side=True) open_client_sockets.append(new_socket) def find_type(data): t = data[0:2] data = data[2:] return types_dictionary[t], data # sends waiting message to everyone. def send_waiting_messages(writable): for message in messages_to_send: (client_socket, data) = message for user in writable: if user is not client_socket: print(data) user.write(data.encode()) messages_to_send.remove(message) # the 'process_income_messages' responsible for directing each message according to it's content to a specific function # that will take care of it. def process_income_messages(readable, context, server_socket): for current_socket in readable: # the next if checks if the current_socket is a new connection. if yes, it applies it, and append it to the open # client socket list so he can contact him later if needed. if current_socket is server_socket: new_connection(current_socket, context) # if the message just arrived belongs to a known socket already, the function starts analyze the data. else: try: data = current_socket.recv(1024).decode() if data == EMPTY: pass else: function_name, data = find_type(data) answer, message = eval(function_name)(data) except: pass # the main function creates the server socket and makes him listen in th port of '1025' to check if a client wants to # connect to him. def main(): # adding an ssl layer that encode the messages passing from the clients to the server, and from the server to the # client. context = create_default_context(Purpose.CLIENT_AUTH) context.load_cert_chain(certfile=CERT) # creating the server socket. server_socket = socket() server_socket.bind((EMPTY, 1025)) server_socket.listen(5) # receiving an sending messages. connected = True while connected: readable, writable, exceptional = select([server_socket] + open_client_sockets, open_client_sockets, []) process_income_messages(readable, context, server_socket) send_waiting_messages(writable) if __name__ == '__main__': main()
UTF-8
Python
false
false
3,181
py
9
server.py
8
0.655769
0.650739
0
81
37.271605
120
SaberShip/clustering_fun
8,443,905,733,571
a02ebed7ec5c298c3ad34e267620db5bec6e8914
bbdfcc0c81c858401839754e2eb161fafa03a2ad
/kmeans.py
53a12aa5eafbf5b6179e44781eab0e76964274f4
[]
no_license
https://github.com/SaberShip/clustering_fun
3076475b260c10f0355dafd4d42bfebd08d0eca1
4004d16dd4bee708a63a909fd3dba879bf626179
refs/heads/master
"2023-03-30T14:28:07.694421"
"2021-04-12T03:23:21"
"2021-04-12T03:23:21"
357,042,983
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 import sys import csv import random import math import location import numpy as np import matplotlib.pyplot as plt from operator import itemgetter from haversine import haversine, Unit class KMeans(): def __init__(self, data, k, verbose, dist_limit=None): self.data = data self.k = k self.verbose = verbose self.distance_limit = dist_limit def classify(self, start_centers): print(f"\nClassifying with k={self.k}:") centers = start_centers iteration = 0 not_converged = True while (not_converged): self._iterate_classify(centers) means = self._find_means(centers) iter_variance = self._sum_variance() if self.verbose: print(f"Converging iteration {iteration}, variance = {iter_variance} km") iteration += 1 not_converged = self._means_differ(means, centers) centers = means if self.verbose: print(f"\nConverged after {iteration} iterations") print(f"Total classification variance = {iter_variance} km") return centers, self.data def init_centers(self): centers = np.array([random.sample(self.data, len(self.data))[0].point]) while len(centers) < self.k: dist_sq = self._get_distance_from_centers(centers) centers = np.append(centers, [self._choose_next_center(centers, dist_sq)], axis=0) return centers, sum(self._get_distance_from_centers(centers)) def _choose_next_center(self, centers, dist_sq): probs = dist_sq / dist_sq.sum() sum_probs = probs.cumsum() r = random.random() idx = np.where(sum_probs >= r)[0][0] return self.data[idx].point def _get_distance_from_centers(self, centers): return np.array([min([haversine(d.point, c) for c in centers]) for d in self.data]) def _iterate_classify(self, centers): for d in self.data: distances = np.array([haversine(d.point, c) for c in centers]) # Minimum in the enumerated list (value is item index 1) idx, dist = min(enumerate(distances), key=itemgetter(1)) if self.distance_limit is not None and dist > self.distance_limit: d.classification = None d.class_distance = None else: d.classification = idx d.class_distance = dist def _find_means(self, centers): means = np.array([ [ np.mean([l.point[0] for l in self.data if l.classification == classification]), np.degrees(np.arctan2( np.mean([np.sin(np.radians(l.point[1])) for l in self.data if l.classification == classification]), np.mean([np.cos(np.radians(l.point[1])) for l in self.data if l.classification == classification]) )) ] for (classification, center) in enumerate(centers)]) return means def _means_differ(self, means, points): for mean, point in zip(means, points): if not np.array_equal(mean, point): return True return False def _sum_variance(self): return sum([d.class_distance for d in self.data if d.class_distance is not None])
UTF-8
Python
false
false
3,401
py
4
kmeans.py
3
0.583064
0.579241
0
105
31.4
119
jack-virus/mrjack-v
11,458,972,763,606
9dfeb1e3984b8c4c598e18adfb0e77b3672096a0
19a34f53faa1eeea9d31dda75fe68eb6a0289714
/mrjack.py
70dcbb53de4c51d75c69dd55bdf7926008c2e319
[]
no_license
https://github.com/jack-virus/mrjack-v
5e5977d292d939e0cae400d4682f3a3ee29937f7
8af0576b17508102258750fadefbaf61624cc50a
refs/heads/master
"2020-06-01T20:16:47.629769"
"2019-06-08T17:36:14"
"2019-06-08T17:36:14"
190,914,651
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
print("ډٱډ جُـ‘ـُٱكُـ‘ـُ ٱبُـ‘ـُنُـ‘ـُ رٱيسُـ‘ـُنُـ‘ـُډ") print("choose frome the list") print("1)android 2)micro 3)iphone 4)contact") x = int(input("Please enter an integer: ")) if x == 1: print("https://mega.nz/#F!nboHVaAC!GE-zyldXCcfCTuN_HxY-mA") elif x == 2: print("https://mega.nz/#F!yPAwUQ7A!GIcegjdTV2aCytOeDhs20A") elif x == 3: print("https://mega.nz/#F!efAAxAbT!kThDdTZ5cqu3fp7yipKMQg") elif x == 4: print("https://mega.nz/#F!vLZBCAzY!0MN3WfZf6i4B8qPZKjdsTw")
UTF-8
Python
false
false
551
py
2
mrjack.py
1
0.65
0.61
0
13
36.461538
63
Aasthaengg/IBMdataset
8,126,078,125,805
2603a173bbfd6513f647405af4f3ac1b14afd79b
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03409/s269074863.py
7d95b406b1861f3126d8296b990895ec0464ab6b
[]
no_license
https://github.com/Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
"2023-04-22T10:22:44.763102"
"2021-05-13T17:27:22"
"2021-05-13T17:27:22"
367,112,348
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
N = int(input()) P = [[0, 0, 0]for _ in range(2*N)] for i in range(N): x, y = map(int, input().split()) P[i] = [0, x, y] for i in range(N): x, y = map(int, input().split()) P[N+i] = [1, x, y] P.sort(key=lambda x: x[1]) cnt = 0 for i in range(2*N): if P[i][0] == 0: continue else: if i == 0: continue else: M = [-1, -1] for j in range(i): if P[j][0] == 0: if P[j][2] > M[1] and P[j][2] < P[i][2]: M = [j, P[j][2]] if M[0] != -1: cnt += 1 P[M[0]][0] = 2 print(cnt)
UTF-8
Python
false
false
651
py
202,060
s269074863.py
202,055
0.35023
0.308756
0
26
24.038462
60
minisaki/riskid_rest_framework
13,116,830,164,788
3c5d4f5203f701604d70a800802208e89f92d909
8b9e781dca36ea5080c51e31e739ad9f9fbbe231
/webapp/migrations/0007_customerorder_customuser_id.py
9a903abb42c2003d626ac5c19567c4ac623f902b
[]
no_license
https://github.com/minisaki/riskid_rest_framework
9e9005aee2a8bcee0a165a9a44f61ba9acb15b0e
8d4216b557d50d8cef025bbb2be77e653d8a4333
refs/heads/master
"2023-05-13T15:09:40.251904"
"2021-06-09T15:51:34"
"2021-06-09T15:51:34"
366,133,299
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 3.2 on 2021-04-25 15:31 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('webapp', '0006_auto_20210425_2224'), ] operations = [ migrations.AddField( model_name='customerorder', name='customuser_id', field=models.ForeignKey(default=12, on_delete=django.db.models.deletion.CASCADE, to='webapp.customuser'), preserve_default=False, ), ]
UTF-8
Python
false
false
531
py
19
0007_customerorder_customuser_id.py
19
0.634652
0.574388
0
20
25.55
117
biocore/american-gut-web
10,368,051,065,082
979837d889cd33a57d24aa491bf694cd367266de
9763f5afff394c50221bda2cfad7938acdb5abac
/amgut/lib/startup_tests.py
5b50db3b7c712c18900389b320388b92570b6334
[ "BSD-3-Clause" ]
permissive
https://github.com/biocore/american-gut-web
501336883bc0213287edb26e300864d984c06d5d
0edf4fd621b04d1de8768ed154864825904d0638
refs/heads/master
"2023-06-07T20:52:34.593532"
"2019-11-19T22:42:43"
"2019-11-19T22:42:43"
22,621,149
5
16
BSD-3-Clause
false
"2023-05-25T17:08:42"
"2014-08-04T21:47:22"
"2021-01-15T16:19:00"
"2023-05-25T17:08:42"
227,574
5
24
56
Python
false
false
from amgut.lib.data_access.sql_connection import TRN from os import listdir from os.path import join, dirname, abspath def startup_tests(): """Wrapper function for calling all tests needed before startup""" patch_number() barcodes_correct() def patch_number(): # Make sure the system is using the latest patch before starting up. with TRN: TRN.add('SELECT current_patch FROM ag.settings') system = TRN.execute_fetchlast() patches_dir = join(dirname(abspath(__file__)), '../db/patches') latest = sorted(listdir(patches_dir)).pop() if latest != system: raise EnvironmentError(("Not running latest patch. System: %s " "Latest: %s") % (system, latest)) def barcodes_correct(): # For patch 0011 & 0012 # Needed because barcodes are added as last barcode in system + 1 # and system testing was using these larger barcodes. Now use 0-1000 range with TRN: sql = """SELECT barcode FROM barcodes.barcode WHERE barcode::integer >= 800000000""" TRN.add(sql) bcs = TRN.execute_fetchindex() if bcs: joined_bcs = ", ".join([x[0] for x in bcs]) raise EnvironmentError("Invalid barcodes found: %s" % joined_bcs)
UTF-8
Python
false
false
1,315
py
161
startup_tests.py
116
0.615209
0.596958
0
36
35.527778
78
eridanvilas/Projeto_Django_1
3,693,671,893,914
623ec962ab62358e54a1064b3ff8ffd3d3948417
2446551f72dd6ce86807ce8702d3d4b6e196f975
/cestabasica/Cestabasica/__init__.py
ed26ab74f059ee60c1e8cdde263202ade6f35837
[]
no_license
https://github.com/eridanvilas/Projeto_Django_1
955705a982b77febb5c1dcc4e8046abfd1fbd158
676e820300db366ccca6dbfdc9df2b51f5d01b1a
refs/heads/master
"2023-01-05T20:55:48.106528"
"2021-09-22T03:23:48"
"2021-09-22T03:23:48"
240,088,379
1
0
null
false
"2022-12-27T15:37:10"
"2020-02-12T18:45:34"
"2021-09-22T03:23:51"
"2022-12-27T15:37:09"
953
1
0
3
JavaScript
false
false
""" Package for Cestabasica. """
UTF-8
Python
false
false
34
py
20
__init__.py
8
0.617647
0.617647
0
3
10
24
FweiGao/VascularGraph
15,977,278,380,788
925455e76b57b24508e0627b51bef5e0c8cb91dd
3194fef7e32993b2383fa4e556bec5865c835c96
/VascGraph/Extra/graphsVal.py
721bb1ae4228102e68047854d7a2f0848a9431af
[ "MIT" ]
permissive
https://github.com/FweiGao/VascularGraph
35719ec5b344a3187806c17d7f48338e8214651c
9843c2ce1ef1e3d707061c4b14032bd060d7295a
refs/heads/master
"2023-08-28T09:16:49.262366"
"2020-12-04T02:46:52"
"2020-12-04T02:46:52"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Oct 31 15:27:18 2018 @author: rdamseh """ from util_validation import * import scipy as sc import seaborn as sns sns.set_style('darkgrid') def setC(s='full'): if s=='full': e=mlab.get_engine() c=e.current_scene c.scene.camera.position = [1508.0806790757697, -75.76570871449209, -246.80378086524414] c.scene.camera.focal_point = [275.9113889043341, 290.74905627194926, 310.09149593802437] c.scene.camera.view_angle = 30.0 c.scene.camera.view_up = [-0.39322212027637654, 0.07091714343590497, -0.9167044904942061] c.scene.camera.clipping_range = [586.1793691504713, 2399.2338745098964] c.scene.camera.compute_view_plane_normal() c.scene.render() if s=='mag': e=mlab.get_engine() c=e.current_scene c.scene.camera.position = [228.2594962041794, 245.50442377609815, 193.67886145992924] c.scene.camera.focal_point = [228.2594962041794, 245.50442377609815, 248.55941772460938] c.scene.camera.view_angle = 30.0 c.scene.camera.view_up = [0.0, 1.0, 0.0] c.scene.camera.clipping_range = [0.5371343542211496, 537.1343542211496] c.scene.camera.compute_view_plane_normal() c.scene.render() def pltDistance(d1, d2, linestyle='-', figure=True, tag='', savepath=None): if figure: plt.figure(figsize=(8.3,5.5)) sns.kdeplot(d1, label=r'$\mathbf{J}_{r}$ $\rightarrow$ $\mathbf{J}_{e}$ ('+tag+')', cut=0, linestyle=linestyle, markevery=0.05, linewidth=2, color=(0,.4,.6)) sns.kdeplot(d2, label=r'$\mathbf{J}_{e}$ $\rightarrow$ $\mathbf{J}_{r}$ ('+tag+')', cut=0, linestyle=linestyle, markevery=0.05, linewidth=2, color=(.5,.5,0)) plt.legend(fontsize=22) plt.ylabel('Probability', fontsize=20); plt.xlabel('$D$', fontsize=20) plt.xlim(xmin=0 , xmax=60) plt.xticks(fontsize = 16) plt.yticks(fontsize = 16) if savepath: plt.savefig(savepath+'dist.eps', format='eps', dpi=1000, transparent=True) if __name__=='__main__': path='graphs/' names1=['gr1', 'gr2', 'gr3', 'gr4', 'gr5', 'gr6'] names2=['g1', 'g2', 'g3', 'g4', 'g5', 'g6'] names3=['gbasic1', 'gbasic2', 'gbasic3', 'gbasic4', 'gbasic5', 'gbasic6'] graphs1=[rescaleG(readPAJEK(path+i+'.pajek')) for i in names1] graphs2=[rescaleG(readPAJEK(path+i+'.pajek')) for i in names2] #graphs2=[getFullyConnected(i) for i in graphs2 ] graphs33=[rescaleG(readPAJEK(path+i+'.pajek')) for i in names3] #graphs3=[getFullyConnected(i) for i in graphs33 ] graphs3=[adjustGraph(i, flip=[0,1,0]) for i in graphs3] savepath='graphs/figures/' ########## ### vis distance matching (for geaometric validation) ########## orig_nodes=[i.number_of_nodes() for i in graphs33] nodes=[i.number_of_nodes() for i in graphs3] jnodes=[len(findNodes(i, j_only=True)[0]) for i in graphs3] percent=[float(i)/j for i , j in zip(nodes, orig_nodes)] # create validation objects + get score valsbasic=[validate(i, j, sigma=[60], rescale=True, middle=64) for i, j in zip(graphs1, graphs3)] sbasic=[i.scores() for i in valsbasic] sbasic=np.array(sbasic) valsmesh=[validate(i, j, sigma=[60], rescale=True, middle=64) for i, j in zip(graphs1, graphs2)] smesh=[i.scores() for i in valsmesh] smesh=np.array(smesh) # average scores avmesh=np.mean(smesh, axis=0) avbasic=np.mean(sbasic, axis=0) varmesh=np.var(smesh, axis=0) varbasic=np.var(sbasic, axis=0) # get and plot matching d=5 d1basic = [i.d1 for i in valsbasic] d2basic = [i.d2 for i in valsbasic] d1mesh = [i.d1 for i in valsmesh] d2mesh = [i.d2 for i in valsmesh] d1b=[] [d1b.extend(i) for i in d1basic] d2b=[] [d2b.extend(i) for i in d2basic] d1m=[] [d1m.extend(i) for i in d1mesh ] d2m=[] [d2m.extend(i) for i in d2mesh ] #pltDistance(d1=d1basic[d], d2=d2basic[d], linestyle='--', tag='3D thining') #pltDistance(d1=d1mesh[d], d2=d2mesh[d], figure=False, tag='Proposed') pltDistance(d1=d1b, d2=d2b, linestyle='--', tag='3D thining') pltDistance(d1=d1m, d2=d2m, figure=False, tag='Proposed', savepath=savepath)
UTF-8
Python
false
false
4,494
py
87
graphsVal.py
80
0.598353
0.490654
0
136
31.830882
97
redystum/Spam-Bot
627,065,244,336
77ddc0a1338c4caa1721e5b64dbe94941ce54da9
e7a000a1f887e41d7d84be9599041f74308a0df3
/spam_bot.py
262d0e65dbebcf8f63b6a461de507f74886c1ddf
[]
no_license
https://github.com/redystum/Spam-Bot
016c071e4733652e76a58477f9316ca5d9435b3b
af11780e627c17e2fe7258905d93a14ecf75fb3e
refs/heads/main
"2023-07-25T00:43:19.774417"
"2021-08-30T17:07:54"
"2021-08-30T17:07:54"
396,119,160
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from tkinter import * import time import pyautogui import pyperclip root = Tk() root.geometry("600x750") root.resizable(0, 0) root.title("Spammer") root.configure(bg='#2e2e2e',cursor="dot") def starting(): num = x.get() try: int(num) except ValueError: Label(root, text="Enter a valid number!", bg='#2e2e2e', fg="white").pack() return timer_font = ("Consolas", 26, "normal") start_font = ("Consolas", 16, "normal") timer = Label(root, text="Start", font=timer_font, bg='#2e2e2e', fg="white") timer.pack(pady = 30) Label(root, text="If you need to stop, close this window!", font=start_font, bg='#2e2e2e', fg="white").pack() time.sleep(3) spam() def spam(): count = 0 text = txt.get("1.0", END) num = int(x.get()) pyperclip.copy(text) for count in range(0, num): pyautogui.hotkey("ctrl", "v") if __name__ == "__main__": font_title = ("Calibri", 40, "normal") font = ("Consolas", 12, "normal") Label(root, text="Spam Bot", font=font_title, bg='#2e2e2e', fg="white").pack() Label(root, text="Type the text do you want to spam", fg="white",bg='#2e2e2e').pack(pady = 20) global txt txt = Text(root, bg='#0f0f0f', fg="white", font=font, width=100, height=10,insertbackground="white") txt.pack(padx = 10) Label(root, text="number of times :", fg="white",bg='#2e2e2e').pack() global x x = Entry(root, fg="white", font=font,bg='#0f0f0f',insertbackground="white") x.pack() Label(root, fg="white",bg='#2e2e2e').pack() aviso = "When you click on the button you have 3s to place the cursor where you want to spam..." Label(root, text=aviso, fg="white",bg='#2e2e2e').pack(pady=5) Button(root, text="Start",width=50, bg='#2e2e2e', fg="white",command=starting).pack() root.mainloop()
UTF-8
Python
false
false
1,919
py
2
spam_bot.py
1
0.587285
0.549766
0
70
25.442857
113
mikudehuane/FedLaAvg
13,194,139,552,534
d10f7a92f17883a188e7fcdac30453c86935c71d
9e58b1f380eae12907db9be7a68c7e07a19e259c
/common.py
f9f1bc2ce06584bb8fc0f397b4873415268e00ad
[]
no_license
https://github.com/mikudehuane/FedLaAvg
4e298dc2846472489ce3f59f46260c24e266fa24
7ffc5668bec340f16952ed374e1fd717c2810752
refs/heads/main
"2023-05-23T11:58:40.948642"
"2023-05-09T12:49:55"
"2023-05-09T12:49:55"
306,807,969
8
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os.path as osp import os import torch from config import project_dir, use_cuda cifar10_classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') raw_data_dir = osp.join(project_dir, 'raw_data') data_cache_dir = osp.join(project_dir, 'data') cache_fd = osp.join(project_dir, 'cache') sentiment140_fd = osp.join(raw_data_dir, 'Sentiment140') sentiment140_fn = 'training.1600000.processed.noemoticon.csv' sentiment140_pyobj_fn = 'training.1600000.processed.noemoticon.pkl' alibaba_fd = osp.join(raw_data_dir, 'taobao_data_process', 'central_taobao_data') alibaba_fp = osp.join(alibaba_fd, 'taobao-jointed-new') alibaba_new_fp = osp.join(alibaba_fd, 'FedLaAvg_taobao-jointed-new_sorted.pkl') alibaba_new_fp_csv = osp.join(alibaba_fd, 'FedLaAvg_taobao-jointed-new_remap.csv') alibaba_uid_map_fp = osp.join(alibaba_fd, 'taobao_uid_voc.pkl') alibaba_gid_map_fp = osp.join(alibaba_fd, 'taobao_mid_voc.pkl') alibaba_cid_map_fp = osp.join(alibaba_fd, 'taobao_cat_voc.pkl') alibaba_meta_fp = osp.join(alibaba_fd, 'taobao-item-info') lr_configure_fd = osp.join(project_dir, 'train', 'lr_configures') tb_slink_fd = osp.join(project_dir, 'log', "tensorboard") record_fd = osp.join('log', "runs") log_fd = "log" checkpoint_fd = "checkpoint" tensorboard_fd = "tensorboard" figure_fd = osp.join(project_dir, "figure") os.makedirs(figure_fd, exist_ok=True) NUM_CIFAR10_CLASSES = 10 NUM_CIFAR10_TRAIN = 50000 NUM_CIFAR10_TEST = 10000 NUM_MNIST_CLASSES = 10 NUM_MNIST_TRAIN = 60000 NUM_MNIST_TEST = 10000 device = torch.device('cuda') if use_cuda else torch.device('cpu') seed_for_train_test_partition = 1 seed_for_client_sampling = 1 seed_for_drop = 1 other_seed = 1 nlp_embedding_fd = osp.join(project_dir, 'models', 'glove')
UTF-8
Python
false
false
1,762
py
21
common.py
17
0.719637
0.684449
0
53
32.245283
98
davikawasaki/password-manager-security-class
4,827,543,281,053
b87702f3748f9c467bb355764316a3850646f69f
7bde08eeed0e6132958b56f60fb0a73c493e8b1a
/python/app/controllers/CommonClass.py
9574e78f2e2f67bce4c9949f15a485ade9583d0e
[ "MIT" ]
permissive
https://github.com/davikawasaki/password-manager-security-class
20dbb894f1dada87eb5c16a36a32efa24f85eba9
b150906e6c8bf4bc94502c37912e4b7042fc8934
refs/heads/master
"2021-07-25T23:17:43.376747"
"2021-07-18T11:19:20"
"2021-07-18T11:19:20"
103,836,007
7
0
MIT
false
"2021-07-18T11:14:06"
"2017-09-17T14:39:58"
"2021-07-18T11:13:48"
"2021-07-18T11:14:05"
1,302
5
0
1
Python
false
false
import htmlPy import datetime import time import os from Crypto.Protocol import KDF from Crypto.Cipher import AES import hashlib KEY_LENGTH = 32 class Common(htmlPy.Object): """ Common service class with cryptography methods. The class Common can be used to implement any common methods between controllers. """ def __init__(self, app): super(Common, self).__init__() self.app = app def checkAuth(self, fileType, pw, user): if(not user or not pw): return False else: try: path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/data/security/hash_' + fileType + '_' + user + '.txt' hf = open(path, 'r').read() hash = hashlib.sha256(pw).hexdigest() if(hash == hf): return True else: return False except IOError: return False def pad(self, s, bs): return s + (bs - len(s) % bs) * chr(bs - len(s) % bs) def unpad(self, s): return s[0:-ord(s[-1])] def ts2str(self, ts): ts = float(ts) return datetime.datetime.utcfromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") def genTimestamp(self): return time.mktime(datetime.datetime.now().timetuple()) def genRandom(self): return os.urandom(KEY_LENGTH) def genSalt(self, fileType, user): # Randomly generate a fileType salt path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/data/security/salt_' + fileType + '_' + str(KEY_LENGTH) + '_' + user + '.txt' sf = open(path, 'w') salt = os.urandom(KEY_LENGTH) sf.write(salt) sf.close() return salt def genIV(self, fileType, user): # Randomly generate a fileType iv path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/data/security/iv_' + fileType + '_' + str(KEY_LENGTH/2) + '_' + user + '.txt' ivf = open(path, 'w') iv = os.urandom(KEY_LENGTH/2) ivf.write(iv) ivf.close() return iv def decKey(self, fileType, pw, user): # Read password salt and iv path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/data/security/iv_' + fileType + '_' + str(KEY_LENGTH/2) + '_' + user + '.txt' iv = open(path, 'r').read() path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/data/security/salt_' + fileType + '_' + str(KEY_LENGTH) + '_' + user + '.txt' salt = open(path, 'r').read() # Read encrypted intermediary key path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/data/security/aes_' + fileType + '_enc_' + str(KEY_LENGTH) + '_' + user + '.key' enc = open(path, 'r').read() # Generate KDF secret key pk = KDF.PBKDF2(pw, salt, KEY_LENGTH, 1000, None) # Create the cipher object and decrypt intermediary key with KDF secret key cipher = AES.AESCipher(pk, AES.MODE_CBC, iv) key = self.unpad(cipher.decrypt(enc[len(pk)/2:])) # print 'deckey ' + fileType + ': ' + key.encode('base-64') return key def encKey(self, pw, key, salt, iv, fileType, user): # Generate KDF secret key pk = KDF.PBKDF2(pw, salt, KEY_LENGTH, 1000, None) # Pad intermediary key with pk length key_padded = self.pad(key, len(pk)) # Create the cipher object and encrypt intermediary key with KDF secret key cipher = AES.AESCipher(pk, AES.MODE_CBC, iv) encKey = iv + cipher.encrypt(key_padded) # print 'enckey ' + fileType + ': ' + encKey.encode('base-64') self.storeEncKey(encKey, fileType, user) key = None key_padded = None def storeEncKey(self, encKey, fileType, user): path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/data/security/aes_' + fileType + '_enc_' + str(KEY_LENGTH) + '_' + user + '.key' kf = open(path, 'w') kf.write(encKey) kf.close() def genRecCode(self): return os.urandom(KEY_LENGTH/4) def genHash(self, pw, fileType, user): path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/data/security/hash_' + fileType + '_' + user + '.txt' hf = open(path, 'w') hf.write(hashlib.sha256(pw).hexdigest()) hf.close()
UTF-8
Python
false
false
4,448
py
34
CommonClass.py
16
0.566996
0.560252
0
122
35.467213
159
JLoppert/HackerRank
9,431,748,198,791
90470c7a400f298360aadea740b0e9327ad0878c
eb0a035dc3c725127fcc63d5e8cfad782381684e
/Algorithms/Warmup/manasa-and-stones.py
e0e60780334eeef7ec97b883586ba409f1226c6b
[]
no_license
https://github.com/JLoppert/HackerRank
0a310eaaa34beb9a420c5bdb10fbf78ce6270a5e
77ef52942512a1f4f50bce11a09052c453bedbe9
refs/heads/master
"2016-09-10T15:36:51.446328"
"2014-08-25T03:31:31"
"2014-08-25T03:31:31"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import math; cases = int(input()); for case in range(cases): stones = int(input()); a = int(input()); b = int(input()); s = set([0]); for index in range(stones-1): temp = set(); for elm in range(len(s)): curr = s.pop(); temp.add(curr+a); temp.add(curr+b); s = temp; l = list(s); l.sort(); for elm in l: if elm != l[-1]: print(str(elm) + ' ', end=''); else: print(elm);
UTF-8
Python
false
false
505
py
38
manasa-and-stones.py
37
0.425743
0.419802
0
26
18.461538
42
MadhavPruthi/SCC-Website
11,312,943,878,857
829f05c488b52513e49e9103428ac64e42e5137f
d6a07545ca3350fe060b1274b7205c0ff7f52c66
/appointment/admin.py
6405fe1a293328a53ca8770959439bb26b152678
[]
no_license
https://github.com/MadhavPruthi/SCC-Website
0865e03975fe31cf5c6f3c6148754799f5dab2fa
f728a681e4e0ab9f7b358b0e7c181189d26d22bd
refs/heads/master
"2022-12-12T22:38:12.557753"
"2020-02-13T10:28:39"
"2020-02-13T10:28:39"
226,687,464
0
0
null
false
"2022-12-08T03:18:10"
"2019-12-08T15:20:07"
"2020-02-13T10:28:49"
"2022-12-08T03:18:10"
11,567
0
0
3
CSS
false
false
from django.contrib import admin from appointment.models import Appointment admin.site.register(Appointment)
UTF-8
Python
false
false
111
py
33
admin.py
17
0.846847
0.846847
0
5
21.2
42
omkar-javadwar/CodeWars
17,669,495,461,737
3ff6867f834a6d468bc3e10ea10f2417a7057bf5
9302b8d21b93bf7ee7d9bcf8d44ba963bf7a4240
/katas/kyu_7/Sum_of_the_first_nth_term_of_Series.py
2b6e3c45ba6b770415c633569d4db61f4b185b09
[ "MIT" ]
permissive
https://github.com/omkar-javadwar/CodeWars
ec15643dadcf409cba2af608b374642f9826bacb
83540dc963b151163ba81d886ab6b3ccbe6442b6
refs/heads/master
"2023-09-01T22:04:49.931940"
"2021-10-30T15:51:17"
"2021-10-30T15:51:17"
258,919,537
0
1
MIT
false
"2021-10-30T15:51:17"
"2020-04-26T02:21:09"
"2021-10-30T15:42:26"
"2021-10-30T15:51:17"
228
0
1
0
Python
false
false
# https://www.codewars.com/kata/555eded1ad94b00403000071/train/python ''' Instructions: Task: Your task is to write a function which returns the sum of following series upto nth term(parameter). Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +... Rules: You need to round the answer to 2 decimal places and return it as String. If the given value is 0 then it should return 0.00 You will only be given Natural Numbers as arguments. Examples: SeriesSum(1) => 1 = "1.00" SeriesSum(2) => 1 + 1/4 = "1.25" SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57" NOTE: In PHP the function is called series_sum(). ''' def series_sum(n): return '{:.2f}'.format(sum(1.0/(3 * i + 1) for i in range(n)))
UTF-8
Python
false
false
699
py
138
Sum_of_the_first_nth_term_of_Series.py
137
0.666667
0.569385
0
26
25.884615
100
taltil/Sudoku
4,320,737,123,345
15a7405606718c38e0456e96944cf21fb4bc9fee
6b74561adbb55d99977669eb000820538c3d86ad
/main.py
a4eab13c85a2b8be2d021d290548f05f3bb57033
[]
no_license
https://github.com/taltil/Sudoku
02ffa1a0bb894005b7830b11d060f92e75413b6a
b8ea0d1f1e0b8fe28fabe4a0008a938d11c8e859
refs/heads/master
"2021-09-14T12:04:11.474671"
"2018-05-13T10:28:11"
"2018-05-13T10:28:11"
124,799,529
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from SudokuUI import * root = Tk() app = SudokuUI(root, 'board.txt') root.title('Sudoku Game') root.mainloop()
UTF-8
Python
false
false
112
py
6
main.py
5
0.696429
0.696429
0
6
17.666667
33
isysc1/django_project
18,305,150,624,658
caa62458ec7fcb784f285a2f1a4a8648f647ca8e
f04c5d67300b77137ca96789fb135cb315d671be
/utils/__init__.py
85f795019e589f67b2585359f7bbb288e37b9a67
[]
no_license
https://github.com/isysc1/django_project
6e8dc510ebc068ee6213ceb7d7fefbae1544882d
64aae255136f0077566a0de87b636eb6a0e4571d
refs/heads/master
"2020-06-08T15:16:11.209624"
"2019-06-27T12:45:06"
"2019-06-27T12:45:06"
193,249,691
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Created by Young on 2019/6/25 16:43 """
UTF-8
Python
false
false
47
py
17
__init__.py
14
0.574468
0.340426
0
3
13.666667
35
MarcelArthur/leetcode_collection
17,128,329,611,498
a186dcb74d0a7f018ccc3c0574c4f6829bc45e4a
6b43695ca4a86d8f1a57268a7f8cb7c138ef5771
/984_String_Without_AAA_or_BBB.py
9ed13b428ff5b28846763be52d92fb41b1c45f31
[]
no_license
https://github.com/MarcelArthur/leetcode_collection
bd3a8a23f3095fbea79831e6a6ea4c515bddfd7c
a39280ab6bbbf3b688a024a71ef952be5010d98e
refs/heads/master
"2021-11-23T15:40:21.874639"
"2021-11-20T16:15:17"
"2021-11-20T16:15:17"
110,528,906
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!python3 """ Given two integers A and B, return any string S such that: S has length A + B and contains exactly A 'a' letters, and exactly B 'b' letters; The substring 'aaa' does not occur in S; The substring 'bbb' does not occur in S. Example 1: Input: A = 1, B = 2 Output: "abb" Explanation: "abb", "bab" and "bba" are all correct answers. Example 2: Input: A = 4, B = 1 Output: "aabaa" Note: 0 <= A <= 100 0 <= B <= 100 It is guaranteed such an S exists for the given A and B. """ class Solution: """ Solution explain: 观察规律: 1. 当A和B都数量都小于等于2时,返回任意组合都字符串都可以 2. 通常当A大于B时, 默认最大字符串数量m为A的数量, 否则为B的数量 3. 初始位置为2, 每次改变一对ab(即两个b一个a,或者两个a一个b) 时间复杂度: 最多字符串长度为m+n, 故时间复杂度为O(m + n) 空间复杂度: 原因同上,O(m + n) """ def strWithout3a3b(self, A: int, B: int) -> str: if A < 3 and B < 3: return A * 'a' + B * 'b' m, n = 'a', 'b' flag = B if A < B: m, n = 'b', 'a' flag = A start = 2 tmp = [m] * (A + B) while flag: for i in range(start, A + B, 3): if i > -1: flag -= 1 tmp[i] = n if flag == 0: break start -= 1 return "".join(tmp)
UTF-8
Python
false
false
1,528
py
259
984_String_Without_AAA_or_BBB.py
258
0.487062
0.464231
0
58
21.62069
81
WillyWilsen/KU1102-Praktikum-Pengenalan-Komputasi
1,821,066,137,884
2cb850764cd2834d37bcc248ef74fb74e3121e62
3af1c386c2d6bd42d66973de33a3fe0c64998abb
/src/Tugas Praktikum/P04_16520145_02.py
8831182d7574bfe3bde1c3ebcf2d0564cc0e7f72
[]
no_license
https://github.com/WillyWilsen/KU1102-Praktikum-Pengenalan-Komputasi
c98bf23d07a18c1a55bb9cc31ed4ae139b924081
249354c03f1f7b8a041a61ac07d63bf49cb7c955
refs/heads/main
"2023-08-11T14:09:14.360825"
"2021-10-10T18:52:08"
"2021-10-10T18:52:08"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Nama : Willy Wilsen # NIM : 16520145 # Tanggal : 2 Desember 2020 # Deskripsi : Membuat program mengeluarkan matriks yang berisi angka-angka # KAMUS # A : int # B : int # T : matriks # ALGORITMA A = int(input("Masukkan jumlah baris matriks: ")) # input A B = int(input("Masukkan jumlah kolom matriks: ")) # input B T = [["*" for j in range(B)] for i in range(A)] # membuat matriks a = 0 # inisiasi a for i in range(A): for j in range(B): T[i][j] = str(input("Masukkan elemen baris "+str(i+1)+" kolom "+str(j+1)+": ")) # input isi matriks for i in range(A): for j in range(B): if T[i][j] == "*": # saat matriks berupa * T[i][j] = "#" elif T[i][j] == ".": # saat tidak * # conditional if i != 0 and j != 0 and i != A-1 and j != B-1: a = 0 for k in range(i-1,i+2): for l in range(j-1,j+2): if T[k][l] == "*" or T[k][l] == "#": a += 1 elif i == 0 and j == 0: a = 0 for k in range(i,i+2): for l in range(j,j+2): if T[k][l] == "*" or T[k][l] == "#": a += 1 elif i == 0 and j == B - 1: a = 0 for k in range(i,i+2): for l in range(j-1,j+1): if T[k][l] == "*" or T[k][l] == "#": a += 1 elif i == A - 1 and j == B - 1: a = 0 for k in range(i-1,i+1): for l in range(j-1,j+1): if T[k][l] == "*" or T[k][l] == "#": a += 1 elif i == A - 1 and j == 0: a = 0 for k in range(i-1,i+1): for l in range(j,j+2): if T[k][l] == "*" or T[k][l] == "#": a += 1 elif i == 0 and j != B - 1 and j != 0: a = 0 for k in range(i,i+2): for l in range(j-1,j+2): if T[k][l] == "*" or T[k][l] == "#": a += 1 elif i == A - 1 and j != B - 1 and j != 0: a = 0 for k in range(i-1,i+1): for l in range(j-1,j+2): if T[k][l] == "*" or T[k][l] == "#": a += 1 elif j == 0 and i != A - 1 and i != 0: a = 0 for k in range(i-1,i+2): for l in range(j,j+2): if T[k][l] == "*" or T[k][l] == "#": a += 1 elif j == B - 1 and i != A - 1 and i != 0: a = 0 for k in range(i-1,i+2): for l in range(j-1,j+1): if T[k][l] == "*" or T[k][l] == "#": a += 1 T[i][j] = a print("Matriks angka:") for i in range(A): # print matriks for j in range(B): print(T[i][j], end = "") print()
UTF-8
Python
false
false
3,173
py
31
P04_16520145_02.py
24
0.325244
0.29751
0
87
35.471264
107
sahaia1/python
11,166,914,993,952
d0713073039f5df3404a063640d7aa0f80b9f6bd
77041bd6b1225c01ad123ac6eeab11f635dd9560
/gcd.py
efac33ed6bf992bc8eb05baf7246eaaf345e0b0c
[]
no_license
https://github.com/sahaia1/python
8434aeec41b8461f29bcc37916108b584b7aa89c
0563d6d432c4a89c876258e40b7c4c80669ee4c3
refs/heads/master
"2020-12-31T07:55:36.572446"
"2015-12-23T06:12:52"
"2015-12-23T06:12:52"
47,989,397
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys def gcd(m, n): if m > n: larger = m smaller = n else: smaller = m larger = n while True: if larger % smaller == 0: return smaller else: r = larger % smaller larger = smaller smaller = r def euclid_gcd(a, b): if a > b: m = a n = b else: m = b n = a if n == 0: return m else: return euclid_gcd(n, m % n) def diff_gcd(a, b): r = abs(a-b) if r == 0: return a else: a = min(a, b) b = r print "a - {} \t b - {}".format(a, b) return diff_gcd(a, b) def euclid_extended(m, n, a=0, b=1, a_prime=1, b_prime=0): c = m d = n r = c % d q = c / d if r == 0: print "a = {} and b = {} and d = {}".format(a, b, d) return else: print "a_prime = {} and b_prime = {} and c = {}".format(a_prime, b_prime, c) c = d d = r t = a_prime a_prime = a a = t - q * a t = b_prime b_prime = b b = t - q * b return euclid_extended(c, d, a=a, b=b, a_prime=a_prime, b_prime=b_prime) if __name__ == "__main__": # print gcd(int(sys.argv[1]), int(sys.argv[2])) # print euclid_gcd(int(sys.argv[1]), int(sys.argv[2])) # print diff_gcd(float(sys.argv[1]), float(sys.argv[2])) euclid_extended(int(sys.argv[1]), int(sys.argv[2]))
UTF-8
Python
false
false
1,282
py
26
gcd.py
26
0.49454
0.482059
0
67
18.134328
80
desgyz/MultiMonit
7,722,351,204,453
9714a843abe463fc3814cee2b81938832270ad54
fc41d1b7949301b31556acfefcdd2c52fd895a4e
/controllers/base.py
55f0802b94aad2229af614a2861c146f546f534a
[]
no_license
https://github.com/desgyz/MultiMonit
21182b9c2f67398ee626420f35eb8baa6f5bd69f
ebc64a932f9e87b045a565fdf3300f7b6e23b412
refs/heads/master
"2021-05-04T11:27:56.162524"
"2016-02-28T12:22:52"
"2016-02-28T12:22:52"
51,357,985
4
2
null
null
null
null
null
null
null
null
null
null
null
null
null
import inspect import cherrypy from jinja2 import Environment, FileSystemLoader, TemplateNotFound from controllers.jinjahelper import JinjaHelper from models.loghelper import Logger class BaseController: def render_template(self, path, template_vars=None): template_vars = template_vars if template_vars else {} try: session = cherrypy.session # set variables in the page so you know whether or not a user is logged in. I # use this because I have different menus defined in the layout, and a user # will see a different menu when they're logged in. This code is optional; # remove it if you have different code for handling sessions. template_vars['logged_in'] = '0' template_vars['isUserLoggedIn'] = False if session: if 'logged_in_user' in session and session['logged_in_user'] is not None: template_vars['isUserLoggedIn'] = True template_vars['logged_in'] = '1' template_vars['logged_in_user'] = session['logged_in_user'] template_vars['logged_in_username'] = session['logged_in_username'] # set our base path for loading templates, and load the template view file jh = JinjaHelper(cherrypy.site['base_path']) tpl = jh.get_template(path) if not tpl: Logger.error('Error rendering template: ' + path, None, True) return tpl.render(template_vars) except Exception as ex: Logger.error('Error rendering template', ex, True)
UTF-8
Python
false
false
1,638
py
16
base.py
10
0.622711
0.620879
0
36
44.5
89
Aasthaengg/IBMdataset
4,681,514,367,553
8817ce3f77c84e692a0f4a46c6d52bb9005a5d7c
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02628/s362193022.py
e87e9fcbd77032044050c2062ff678d78bac50f8
[]
no_license
https://github.com/Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
"2023-04-22T10:22:44.763102"
"2021-05-13T17:27:22"
"2021-05-13T17:27:22"
367,112,348
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
N, K = map(int, input().split()) a = input().split() a = list(map(int,a)) a.sort() b = sum(a[:K]) print(b)
UTF-8
Python
false
false
112
py
202,060
s362193022.py
202,055
0.517857
0.517857
0
10
10.1
32
tsunammis/software-craftsmanship
15,487,652,096,836
cc70dad88e08282db1bf21174558f7504912afda
a3f1f4f558d9d6340865e9c08f301bc627c961e2
/development/python.py
32bd7e64e3dca2f6531e45852be514e1a72aca0c
[ "MIT" ]
permissive
https://github.com/tsunammis/software-craftsmanship
0793641fcf0e53ecf71295b2fcb7513630289585
e5631ac431fbe13d6814aa2c2c18b602e564da0f
refs/heads/master
"2020-12-24T16:34:01.294869"
"2018-06-15T13:00:48"
"2018-06-15T13:00:48"
35,549,841
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" High quality resources - https://github.com/vinta/awesome-python - Manage CLI -> http://plumbum.readthedocs.org/en/latest/ - Create tasks -> http://www.pyinvoke.org/ - https://automatetheboringstuff.com/ PEP 8 is the de-facto code style guide for Python. pip install pep8 $ pep8 optparse.py optparse.py:69:11: E401 multiple imports on one line optparse.py:77:1: E302 expected 2 blank lines, found 1 optparse.py:88:5: E301 expected 1 blank line, found 0 optparse.py:222:34: W602 deprecated form of raising exception optparse.py:347:31: E211 whitespace before '(' The program autopep8 can be used to automatically reformat code in the PEP 8 style. $ pip install autopep8 Use it to format a file in-place with: $ autopep8 --in-place optparse.py With pyvenv pyvenv myenv source myenv/bin/activate python With virtualenv & virtualenvwrapper http://www.marinamele.com/2014/07/install-python3-on-mac-os-x-and-use-virtualenv-and-virtualenvwrapper.html mkvirtualenv --python=/usr/local/bin/python3 myenv deactivate workon myenv Magic Methods (source: http://www.rafekettler.com/magicmethods.html) Comparison magic methods Python has a whole slew of magic methods designed to implement intuitive comparisons between objects using operators, not awkward method calls. They also provide a way to override the default Python behavior for comparisons of objects (by reference). Here's the list of those methods and what they do: __cmp__(self, other) __cmp__ is the most basic of the comparison magic methods. It actually implements behavior for all of the comparison operators (<, ==, !=, etc.), but it might not do it the way you want (for example, if whether one instance was equal to another were determined by one criterion and and whether an instance is greater than another were determined by something else). __cmp__ should return a negative integer if self < other, zero if self == other, and positive if self > other. It's usually best to define each comparison you need rather than define them all at once, but __cmp__ can be a good way to save repetition and improve clarity when you need all comparisons implemented with similar criteria. __eq__(self, other) Defines behavior for the equality operator, ==. __ne__(self, other) Defines behavior for the inequality operator, !=. __lt__(self, other) Defines behavior for the less-than operator, <. __gt__(self, other) Defines behavior for the greater-than operator, >. __le__(self, other) Defines behavior for the less-than-or-equal-to operator, <=. __ge__(self, other) Defines behavior for the greater-than-or-equal-to operator, >=. Numeric magic methods Just like you can create ways for instances of your class to be compared with comparison operators, you can define behavior for numeric operators. Buckle your seat belts, folks, there's a lot of these. For organization's sake, I've split the numeric magic methods into 5 categories: unary operators, normal arithmetic operators, reflected arithmetic operators (more on this later), augmented assignment, and type conversions. Unary operators and functions Unary operators and functions only have one operand, e.g. negation, absolute value, etc. __pos__(self) Implements behavior for unary positive (e.g. +some_object) __neg__(self) Implements behavior for negation (e.g. -some_object) __abs__(self) Implements behavior for the built in abs() function. __invert__(self) Implements behavior for inversion using the ~ operator. For an explanation on what this does, see the Wikipedia article on bitwise operations. __round__(self, n) Implements behavior for the built in round() function. n is the number of decimal places to round to. __floor__(self) Implements behavior for math.floor(), i.e., rounding down to the nearest integer. __ceil__(self) Implements behavior for math.ceil(), i.e., rounding up to the nearest integer. __trunc__(self) Implements behavior for math.trunc(), i.e., truncating to an integral. Normal arithmetic operators Now, we cover the typical binary operators (and a function or two): +, -, * and the like. These are, for the most part, pretty self-explanatory. __add__(self, other) Implements addition. __sub__(self, other) Implements subtraction. __mul__(self, other) Implements multiplication. __floordiv__(self, other) Implements integer division using the // operator. __div__(self, other) Implements division using the / operator. __truediv__(self, other) Implements true division. Note that this only works when from __future__ import division is in effect. __mod__(self, other) Implements modulo using the % operator. __divmod__(self, other) Implements behavior for long division using the divmod() built in function. __pow__ Implements behavior for exponents using the ** operator. __lshift__(self, other) Implements left bitwise shift using the << operator. __rshift__(self, other) Implements right bitwise shift using the >> operator. __and__(self, other) Implements bitwise and using the & operator. __or__(self, other) Implements bitwise or using the | operator. __xor__(self, other) Implements bitwise xor using the ^ operator. Augmented assignment Python also has a wide variety of magic methods to allow custom behavior to be defined for augmented assignment. You're probably already familiar with augmented assignment, it combines "normal" operators with assignment. If you still don't know what I'm talking about, here's an example: x = 5 x += 1 # in other words x = x + 1 Each of these methods should return the value that the variable on the left hand side should be assigned to (for instance, for a += b, __iadd__ might return a + b, which would be assigned to a). Here's the list: __iadd__(self, other) Implements addition with assignment. __isub__(self, other) Implements subtraction with assignment. __imul__(self, other) Implements multiplication with assignment. __ifloordiv__(self, other) Implements integer division with assignment using the //= operator. __idiv__(self, other) Implements division with assignment using the /= operator. __itruediv__(self, other) Implements true division with assignment. Note that this only works when from __future__ import division is in effect. __imod__(self, other) Implements modulo with assignment using the %= operator. __ipow__ Implements behavior for exponents with assignment using the **= operator. __ilshift__(self, other) Implements left bitwise shift with assignment using the <<= operator. __irshift__(self, other) Implements right bitwise shift with assignment using the >>= operator. __iand__(self, other) Implements bitwise and with assignment using the &= operator. __ior__(self, other) Implements bitwise or with assignment using the |= operator. __ixor__(self, other) Implements bitwise xor with assignment using the ^= operator. Type conversion magic methods Python also has an array of magic methods designed to implement behavior for built in type conversion functions like float(). Here they are: __int__(self) Implements type conversion to int. __long__(self) Implements type conversion to long. __float__(self) Implements type conversion to float. __complex__(self) Implements type conversion to complex. __oct__(self) Implements type conversion to octal. __hex__(self) Implements type conversion to hexadecimal. __index__(self) Implements type conversion to an int when the object is used in a slice expression. If you define a custom numeric type that might be used in slicing, you should define __index__. __trunc__(self) Called when math.trunc(self) is called. __trunc__ should return the value of `self truncated to an integral type (usually a long). __coerce__(self, other) Method to implement mixed mode arithmetic. __coerce__ should return None if type conversion is impossible. Otherwise, it should return a pair (2-tuple) of self and other, manipulated to have the same type. Representing your Classes It's often useful to have a string representation of a class. In Python, there's a few methods that you can implement in your class definition to customize how built in functions that return representations of your class behave. __str__(self) Defines behavior for when str() is called on an instance of your class. __repr__(self) Defines behavior for when repr() is called on an instance of your class. The major difference between str() and repr() is intended audience. repr() is intended to produce output that is mostly machine-readable (in many cases, it could be valid Python code even), whereas str() is intended to be human-readable. __unicode__(self) Defines behavior for when unicode() is called on an instance of your class. unicode() is like str(), but it returns a unicode string. Be wary: if a client calls str() on an instance of your class and you've only defined __unicode__(), it won't work. You should always try to define __str__() as well in case someone doesn't have the luxury of using unicode. __format__(self, formatstr) Defines behavior for when an instance of your class is used in new-style string formatting. For instance, "Hello, {0:abc}!".format(a) would lead to the call a.__format__("abc"). This can be useful for defining your own numerical or string types that you might like to give special formatting options. __hash__(self) Defines behavior for when hash() is called on an instance of your class. It has to return an integer, and its result is used for quick key comparison in dictionaries. Note that this usually entails implementing __eq__ as well. Live by the following rule: a == b implies hash(a) == hash(b). __nonzero__(self) Defines behavior for when bool() is called on an instance of your class. Should return True or False, depending on whether you would want to consider the instance to be True or False. __dir__(self) Defines behavior for when dir() is called on an instance of your class. This method should return a list of attributes for the user. Typically, implementing __dir__ is unnecessary, but it can be vitally important for interactive use of your classes if you redefine __getattr__ or __getattribute__ (which you will see in the next section) or are otherwise dynamically generating attributes. __sizeof__(self) Defines behavior for when sys.getsizeof() is called on an instance of your class. This should return the size of your object, in bytes. This is generally more useful for Python classes implemented in C extensions, but it helps to be aware of it. """
UTF-8
Python
false
false
11,728
py
25
python.py
21
0.675136
0.67002
0
249
46.100402
150
luizolima/estudo-python
7,765,300,889,493
da2345bd7df2645c24bc00fd4cb6f7b15472e93c
6022301811e6900b44062341943e6edc2cf13052
/66-seek_e_cursors.py
1d091c6ad1d60a373d305420e314a3298c07d4b5
[]
no_license
https://github.com/luizolima/estudo-python
780b7c94da9afa4e9b1f3599edf1667ce0d7da04
fec2fec1114c23aef273007fcb6a0d66e3bcfed3
refs/heads/main
"2023-06-08T11:12:13.816088"
"2021-06-28T02:43:38"
"2021-06-28T02:43:38"
361,577,869
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Seek e Cursors seek() -> Utilizada para movimentar o cursor pelo arquivo. arquivo = open('texto.txt', encoding='UTF-8') print(arquivo.read()) # A função seek() é utilizada para movimentação do cursor pelo arquivo. Ela recebe um # parâmetro que indica onde queremos colocar o cursor. # Movimentando o cursor pelo arquivo com a função seek() -> Procurar arquivo.seek(0) print(arquivo.read()) arquivo.seek(22) print(arquivo.read()) # readline() -> função que lê o arquivo linha a linha print(arquivo.readline()) # Primeira linha print(arquivo.readline()) # Segunda linha print(arquivo.readline()) # Terceira linha print(arquivo.readline()) # Quarta linha print(arquivo.readline()) # Quinta linha print(arquivo.readline()) # Sexta linha print(arquivo.readline()) # Sétima linha # readline() -> função que lê o arquivo linha a linha ret = arquivo.readline() print(type(ret)) print(ret) print(ret.split(' ')) # readlines() -> transforma cada linha em um elemento de uma lista linhas = arquivo.readlines() print(len(linhas)) # OBS: Quando abrimos um arquivo com a função open() é criada uma conexão entre o arquivo no disco do computador e o nosso programa. Essa conexão é chamada de streaming. Ao finalizar os trabalhos com o arquivo devemos fechar essa conexão. Para isso utilizamos a função close() Passos para se trabalhar com um arquivo 1- Abrir o arquivo 2 - Trabalhar o arquivo 3 - Fechar o arquivo # 1 - Abrir o arquivo arquivo = open('texto.txt', encoding='UTF-8') # 2 - Trabalhar o arquivo print(arquivo.read()) print(arquivo.closed) # False Verifica se o arquivo estã aberto ou fechado # 3 - Fechar o arquivo arquivo.close() print(arquivo.closed) # True Verifica se o arquivo estã aberto ou fechado print(arquivo.read()) # OBS: Se tentarmos manipular o arquivo apõs seu fechamento, teremos um ValueError """ arquivo = open('texto.txt', encoding='UTF-8') print(arquivo.read(50))
UTF-8
Python
false
false
1,956
py
33
66-seek_e_cursors.py
25
0.733541
0.726283
0
82
22.52439
93
iufl/Geo_Classifier
2,611,340,144,510
ecf5080f500c9c21b868b3e659f03a18eb70eba0
c98097efa0d4fde7a5521044e4b06928e6e7f077
/Predefined Labels - Biologic Process.py
9a7358566451178965be8b42d314c9489198de3b
[]
no_license
https://github.com/iufl/Geo_Classifier
99f7ce3c0b2a31c4c4a1654ad87c406f76c1e9dd
12d08fd5875feed1fb5441f8f63b8856e9fb1b8b
refs/heads/master
"2020-07-31T15:00:26.232417"
"2020-03-31T06:46:55"
"2020-03-31T06:46:55"
210,644,449
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # coding: utf-8 # In[1]: cellular_process_info = ['cell', 'adhesion', 'communication', 'signal_transduction', 'extracellular_stimulus', 'hormone_secretion', 'intracellular_signaling_cascade', 'enzyme_linked', 'receptor_protein', 'small_GTPase-mediated_signal_transduction', 'transmembrane', 'signaling_pathway', 'protein_kinase', 'notch_pathway', 'NF-kB', 'VEGF', 'regulation', 'activity'] development_info = ['morphogenesis', 'organ_development', 'tissue', 'cell_differentiation', 'epithelial', 'epidermal', 'epidermis', 'keratinization', 'mesenchymal_differentiation_transition','ectoderm', 'mesoderm', 'anglogenesis', 'vasculature', 'blood_vessel', 'morphogenesis', 'cellular', 'projection', 'organization', 'biogenesis', 'pseudopodium', 'formation', 'filopodium', 'microvilius_biogenesis', 'epithelium', 'epihtelial'] physiological_process_info = ['cellular_physiological_process', 'cell', 'motility', 'death', 'organization', 'biogenesis', 'cycle', 'cellular_morphogenesis', 'cycle', 'substrate_junction_assembly', 'cytoskeleton_organization_biogenesis', 'actin_cytoskeleton', 'intermediate_filament', 'organization_biogenesis', 'proliferation', 'regulation'] domains = ['cellular_process', 'development', 'physiologic_process'] themes = ['biologic_process']
UTF-8
Python
false
false
1,469
py
23
Predefined Labels - Biologic Process.py
1
0.651464
0.650102
0
22
65.5
157
Akilan10/Python-bootcamp
5,033,701,679,478
13518335657f152d7e6c3949757fc63c3f500150
282c56aafeb96c7c306aa69e038d2a69c14c273a
/Day-14 task.py
1673c3926bcc0bd2f2e3e2bd41ff56946daef738
[]
no_license
https://github.com/Akilan10/Python-bootcamp
1e12f3ef5fb545ff7e68a3743ca1e43c1c3678ab
ccd29b55849e92ec9519371352a79e5dd0c84136
refs/heads/main
"2023-06-16T08:05:41.348161"
"2021-07-16T05:27:58"
"2021-07-16T05:27:58"
376,889,048
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# 1 # Name error list=12 print(list1) # Type error a='123' a+=123 # Syntax error for i range(1,10): print(i) # index error l=[1,2,3,4,5,56,6,7] for i in range(len(l)): print(l[i+1]) # Module not found error import numpys # Key error dict1=dict() dict1={1:12,11:12,13:14} print(dict1[23]) # Import error from math import x # Value error int("abc") # Zero Division Error 100/0 # 2 def calculate(): try: print('+', '-', '*', '/', '%', '**') op = input("Select an operator : ") print("Enter two numbers : ") num_1 = int(input()) num_2 = int(input()) if op == '+': print(num_1 + num_2) elif op == '-': print(num_1 - num_2) elif op == '*': print(num_1 * num_2) elif op == '/': print(num_1 / num_2) elif op == '%': print(num_1 % num_2) elif op == '**': print(num_1 ** num_2) else: print('Invalid Input') except Exception as e: print(e) print(calculate()) # 3 try: print(d) except NameError: print("Variable x is not defined") except: print("Something else went wrong") # 5 try: x = int(input('enter a number : ')) except: print("Invalid value !!") finally: print("You entered is : ", x)
UTF-8
Python
false
false
1,394
py
23
Day-14 task.py
23
0.480631
0.43759
0
76
16.368421
44
pesfahanian/ML_API
8,899,172,248,547
aa63af4115e85b9332df60519aef9610d1714c6d
f2e151cd8e7e927941ab90e56015258744fe2bfc
/API/dashboard/routers.py
7f313fa447bbb4d0a7b5a3eec37f625800e6537a
[]
no_license
https://github.com/pesfahanian/ML_API
10adfd135ec061ef5c140a63bfd474f515a742c3
e17daa214f4bc8394e9bc096aca6a04b0fba04e9
refs/heads/master
"2023-05-26T04:10:37.102786"
"2021-06-02T15:25:12"
"2021-06-02T15:25:12"
306,056,646
6
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import logging from datetime import datetime from fastapi import APIRouter, HTTPException from .urls import DASHBOARD_ENDPOINT from authentication.decorator import authentication from database.usersdb import users_database, users from utils.security import make_hash from utils.misc import user_credentials logger = logging.getLogger(__name__) router = APIRouter(prefix=DASHBOARD_ENDPOINT, tags=["Dashboard"], responses={404: { "description": "Not found" }}) @router.get("/query/", status_code=200) @authentication.admin_required async def query_all_users(): """ [Query all user records in the users database.] """ logger.info('Querying all user records.') query = users.select() return await users_database.fetch_all(query) @router.post("/query/", status_code=200) @authentication.admin_required async def query_user(username: str): """ [Query one user record in the users database.] Args: username (str): [Username of user to be queried.] Raises: HTTPException: [User does not exist.] Returns: [type]: [User record.] """ logger.info(f'Querying record for user {username}.') query = users.select().where(users.c.username == username) result = await users_database.fetch_one(query) if result: logger.info(f'Record found for user {username}.') return result else: logger.warning(f'User {username} does not exist.') raise HTTPException(status_code=404, detail=f"User {username} does not exist.") @router.post("/register/", status_code=200) @authentication.admin_required async def register_user(username: str, password: str, passwordConfirm: str): """ [Register a new user by adding one record to the users database.] Args: username (str): [Username of user.] password (str): [Password of user.] passwordConfirm (str): [Password confirmation.] Raises: HTTPException: [User already exists.] HTTPException: [Passwords do not match.] Returns: [type]: [Record of registered user.] """ logger.info(f'Registering user {username}.') if (password == passwordConfirm): ID, now, salt = user_credentials() hash_pasword = make_hash(password + salt) query = users.insert().values(id=ID, registerDate=now, updateDate=now, username=username, salt=salt, password=hash_pasword, active=True) try: await users_database.execute(query) logger.info(f'User {username} created at {now} with ID {ID}.') except Exception: logger.warning(f'User {username} already exists.') raise HTTPException(status_code=409, detail=f"User {username} already exists.") response = { "id": ID, "registerDate": now, "username": username, "active": True } return response else: raise HTTPException(status_code=400, detail="Password confirmation doesn't match.") @router.patch("/change/", status_code=200) @authentication.admin_required async def change_password(username: str, password: str, passwordConfirm: str): """ [Change an existing user's password by updating the user's record in the users database.] Args: username (str): [Username of user.] password (str): [New password.] passwordConfirm (str): [Password confirmation.] Raises: HTTPException: [User already exists.] HTTPException: [Passwords do not match.] Returns: [type]: [Confirmation message.] """ logger.info(f'Changing password for user {username}.') if (password == passwordConfirm): exist = users.select().where(users.c.username == username) exist_result = await users_database.fetch_one(exist) if exist_result: salt = exist_result['salt'] new_password = make_hash(password + salt) now = datetime.now() query = users.update().values( updateDate=now, password=new_password).where(users.c.username == username) await users_database.execute(query) logger.info(f'Password changed for user {username} at {now}.') return { "Message": f'Password changed for user {username} at {now}.' } else: logger.warning(f'User {username} does not exist.') raise HTTPException(status_code=404, detail=f"User {username} does not exist.") else: logger.warning('Password confirmation does not match.') raise HTTPException(status_code=400, detail="Password confirmation does not match.") @router.patch("/activate/", status_code=200) @authentication.admin_required async def activate_user(username: str): """ [Set the active status of an existing user to 'True' in the users database.] Args: username (str): [Username of user.] Raises: HTTPException: [User does not exist.] Returns: [type]: [Confirmation message.] """ exist = users.select().where(users.c.username == username) exist_result = await users_database.fetch_one(exist) if exist_result: now = datetime.now() query = users.update().values( updateDate=now, active=True).where(users.c.username == username) await users_database.execute(query) logger.info(f'User {username} activated at {now}.') return {"Message": f'User {username} activated at {now}.'} else: logger.warning(f'User {username} does not exist.') raise HTTPException(status_code=404, detail=f"User {username} does not exist.") @router.patch("/deactivate/", status_code=200) @authentication.admin_required async def deactivate_user(username: str): """ [Set the active status of an existing user to 'False' in the users database.] Args: username (str): [Username of user.] Raises: HTTPException: [User does not exist.] Returns: [type]: [Confirmation message.] """ exist = users.select().where(users.c.username == username) exist_result = await users_database.fetch_one(exist) if exist_result: now = datetime.now() query = users.update().values( updateDate=now, active=False).where(users.c.username == username) await users_database.execute(query) logger.info(f'User {username} deactivated at {now}.') return {"Message": f'User {username} deactivated at {now}.'} else: logger.warning(f'User {username} does not exist.') raise HTTPException(status_code=404, detail=f"User {username} does not exist.") @router.delete("/delete/", status_code=200) @authentication.admin_required async def delete_user(username: str): """ [Delete an existing user by removing its record from the users database.] Args: username (str): [Username of user.] Raises: HTTPException: [User does not exist.] Returns: [type]: [Confirmation message.] """ exist = users.select().where(users.c.username == username) exist_result = await users_database.fetch_one(exist) if exist_result: query = users.delete().where(users.c.username == username) await users_database.execute(query) now = datetime.now() logger.info(f'User {username} deleted at {now}.') return {"Message": f'User {username} deleted at {now}.'} else: logger.warning(f'User {username} does not exist.') raise HTTPException(status_code=404, detail=f"User {username} does not exist.")
UTF-8
Python
false
false
8,175
py
36
routers.py
28
0.599388
0.593517
0
241
32.921162
81
xiawy/common_summary
1,752,346,662,048
9ef54acd8a735abf95046b44a76704c0584d5968
f7be5f0acf23bff29992fa0a383558a01aa76ee4
/algorithm/search_algorithm.py
0426acec70ac4f589805ac3a705c417b8fd5cfa6
[]
no_license
https://github.com/xiawy/common_summary
ecd3997a72b4900ac24a1a439aab1f47a6ae48ba
7fae5f7912a47cfc5f51b52d9dfe2879ec0ba886
refs/heads/master
"2020-05-23T11:50:13.787415"
"2019-05-30T11:58:36"
"2019-05-30T11:58:36"
186,745,121
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -------------------------- 顺序查找 --------------------------- # 描述:从第一个元素开始逐个与查找的元素进行比较,当元素相同时返回对应元素的下标,如果到 # 最后都没有找到,则返回-1 # 缺点:当N很大时,平均查找查找长度较大、效率低 # 优点:对表中数据元素的存储没有要求。对于线性链表,只能进行顺序查找 def sequential_search(array, key): length = len(array) for i in range(length): if array[i] == key: return i return False # ------------------------- 二分查找(折半) ------------------------------ # 描述:一种在有序数组中查找某一特定元素的查找算法。查找过程从数组中间元素开始每次范围缩小一半 # 优点:查找速度较快,每次搜索区域减少一半,时间复杂度为O(logn), # 缺点:数组必须是有顺序的 def binary_search(array, key): low, high, time = 0, len(array) - 1, 0 while low < high: mid = int((low + high) / 2) if key < array[mid]: high = mid - 1 elif key > array[mid]: low = mid + 1 else: return mid return False # ------------------------ 插值查找 ------------------------------------- # 描述:基于二分查找算法,将查找点的选择改进为自适应选择,一定程度上提高查找效率 # 优点:对于数据较大,且分布均匀时插值查找算法的平均性能要优于折半查找,O(log log n) < 时间复杂度 <O(n) # 缺点:插值查找也是有序查找 # 比较:差值查找是根据要查找的关键字key与查找表中最大最小记录的关键字比较后的查找方法,其核心就在于 # 插值的计算公示(key-a[low])/(a[high]-a[low])*(high-low) def interpolation_search(array, key): low, high, time = 0, len(array) - 1, 0 while low < high: mid = low + int((high-low) * (key-array[low])/(array[high]-array[low])) if key < array[mid]: high = mid - 1 elif key > array[mid]: low = mid + 1 else: return mid return False # -------------------------- 斐波那契数列 ----------------------------------- # 描述:斐波那契查找就是在二分查找的基础上根据斐波那契数列进行分割 def fib_search(array, key): if key < array[0] or key > array[-1]: return -1 def fib_func(n): prev, curr = 0, 1 while n > 0: n -= 1 yield curr prev, curr = curr, prev + curr fib_list = [i for i in fib_func(len(array))] # 获取array长度在fib_list中的位置 k, n = 0, len(array) while n > fib_list[k]: k += 1 # 数组长度不会刚好等于fib的数据,须填充 for i in range(n, fib_list[k]): array.append(array[-1]) low, high = 0, fib_list[k] while low <= high: mid = low + fib_list[k-1] # fib_search[k] == array[-1] if key < array[mid]: high = mid - 1 k -= 1 elif key > array[mid]: low = mid + 1 k -= 2 else: return mid return -1
UTF-8
Python
false
false
3,226
py
9
search_algorithm.py
6
0.492462
0.479899
0
85
27.070588
79
gerlindee/UBB-Artificial-Intelligence
15,719,580,319,609
478c0068c6faeb2e3f749458893d2afe46c429fe
3c48adcc837314986344d7db6f9a66ab7ddbfea8
/laborator_1/UI.py
aeb9af5441ec23115936426f9253a3681769e2e3
[]
no_license
https://github.com/gerlindee/UBB-Artificial-Intelligence
cde83e9bc5275d18d3f47da787ee76a9f49e9a97
60b5dc5d938a1e8623253e12af7b488935266254
refs/heads/master
"2020-04-28T22:43:40.841422"
"2020-03-03T08:58:12"
"2020-03-03T08:58:12"
175,628,499
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from SudokuBoard import SudokuBoard from Problem import Problem from Controller import Controller class UI: def __init__(self, controller): self._controller = controller @staticmethod def mainMenu(): print("0. exit;") print("1. select game board;") print("2. solve using an uninformed search method (bfs);") print("\t" + "2.5. display the step-by-step solution;") print("3. solve using an informed search method (gbfs);") print("\t" + "3.5. display the step-by-step solution;") def run(self): running = True selected_board = SudokuBoard("data/board-3x3-1.txt") while running: self.mainMenu() command = input(">> ") if command == "0": running = False elif command == "1": msg_size = "\t" + "- 3x3" + "\n" msg_size = msg_size + "\t" + "- 4x4;" + "\n" msg_size = msg_size + "\t" + "- 9x9;" + "\n" size = input("board size: " + "\n" + msg_size) msg_diff = "\t" + "- very easy;" + "\n" msg_diff = msg_diff + "\t" + "- easy;" + "\n" msg_diff = msg_diff + "\t" + "- medium;" + "\n" msg_diff = msg_diff + "\t" + "- hard;" + "\n" difficulty = input("difficulty: " + "\n" + msg_diff) if size == "3" or size == "3x3": if difficulty == "easy" or difficulty == "very easy": selected_board = SudokuBoard("data/board-3x3-1.txt") elif difficulty == "medium": selected_board = SudokuBoard("data/board-3x3-2.txt") elif difficulty == "hard": selected_board = SudokuBoard("data/board-3x3-3.txt") elif size == "4" or size == "4x4": if difficulty == "very easy": selected_board = SudokuBoard("data/board-4x4-1.txt") elif difficulty == "easy": selected_board = SudokuBoard("data/board-4x4-2.txt") elif difficulty == "medium": selected_board = SudokuBoard("data/board-4x4-3.txt") elif difficulty == "hard": selected_board = SudokuBoard("data/board-4x4-4.txt") else: print("Invalid input!") elif size == "9" or size == "9x9": if difficulty == "very easy": selected_board = SudokuBoard("data/board-9x9-1.txt") elif difficulty == "easy": selected_board = SudokuBoard("data/board-9x9-2.txt") elif difficulty == "medium": selected_board = SudokuBoard("data/board-9x9-3.txt") elif difficulty == "hard": selected_board = SudokuBoard("data/board-9x9-4.txt") else: print("Invalid input!") else: print("Invalid input!") print("You have selected: ") print(selected_board) elif command == "2": prbl = Problem(selected_board) self._controller.set_problem(prbl) result = self._controller.bfs() if result is None: print("There is no solution for this Sudoku game!") else: print(result[-1]) elif command == "2.5": prbl = Problem(selected_board) self._controller.set_problem(prbl) result = self._controller.bfs() if result is None: print("There is no solution for this Sudoku game!") else: for step in result: print(step) elif command == "3": prbl = Problem(selected_board) self._controller.set_problem(prbl) result = self._controller.gbfs() if result is None: print("There is no solution for this Sudoku game!") else: print(result) else: print("Invalid command!") ctrl = Controller() ui = UI(ctrl) ui.run()
UTF-8
Python
false
false
4,416
py
36
UI.py
26
0.456975
0.442029
0
104
41.461538
76
navidbahadoran/echo-server
2,405,181,730,867
a15a22ae78cca3198fcbf3422cb020ae321a493d
347a6b676e66d89a55b6b85ef30a654f70d33c2a
/echo_client.py
e1f22dcc17dd96d31057f970c6cee643c2c275e5
[]
no_license
https://github.com/navidbahadoran/echo-server
ac922c2b4540fb82db672d7138c4fb28708583ee
523c08258df03ffb36e0d5e73a672bb70abbc238
refs/heads/master
"2020-06-11T02:15:28.761204"
"2019-07-06T03:18:05"
"2019-07-06T03:18:05"
193,823,829
0
0
null
true
"2019-06-26T03:35:11"
"2019-06-26T03:35:11"
"2019-03-31T18:22:11"
"2019-03-31T18:22:09"
142
0
0
0
null
false
false
import socket import sys import traceback def client(message, log_buffer=sys.stderr): server_address = ('localhost', 10000) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) # print('connecting to {0} port {1}'.format(*server_address), file=log_buffer) sock.connect(server_address) received_message = '' sent_message = '' try: # print('sending "{0}"'.format(message), file=log_buffer) message = message.encode() while True: if len(message) < 16: chunk_sent = message sock.send(chunk_sent) # print('sending "{0}"'.format(chunk_sent.decode())) sent_message += chunk_sent.decode('utf8') chunk_rcv = sock.recv(16) # print('receiving "{0}"'.format(chunk_rcv.decode())) received_message += chunk_rcv.decode('utf8') message = b'' if not message: sock.send(b'') break chunk_sent = message[:16] message = message[16:] sock.send(chunk_sent) # print('sending "{0}"'.format(chunk_sent.decode())) sent_message += chunk_sent.decode('utf8') chunk_rcv = sock.recv(16) # print('receiving "{0}"'.format(chunk_rcv.decode())) received_message += chunk_rcv.decode('utf8') # print('received "{0}"'.format(received_message), file=log_buffer) except Exception as e: traceback.print_exc() sys.exit(1) finally: # print('closing socket', file=log_buffer) sock.close() return received_message if __name__ == '__main__': if len(sys.argv) != 2: usage = '\nusage: python echo_client.py "this is my message"\n' print(usage, file=sys.stderr) sys.exit(1) msg = sys.argv[1] client(msg)
UTF-8
Python
false
false
1,908
py
1
echo_client.py
1
0.546646
0.530398
0
55
33.690909
82
peeyush-tm/pyobjc
8,950,711,851,169
6d34660eba43bc8d5428fc459c8eb6f0a06d384f
4b89a7de426fb53b999b5f3834404215a90817df
/pyobjc-framework-AVFoundation/PyObjCTest/test_avplayer.py
cc42405e4b998866800b7c0408a9505a88cc437f
[]
no_license
https://github.com/peeyush-tm/pyobjc
a1f3ec167482566ddc7c895cfa2aca436109cf66
da488946f6cc67a83dcc26c04484ca4f10fabc82
refs/heads/master
"2021-01-20T19:26:06.015044"
"2016-05-22T14:53:37"
"2016-05-22T14:53:37"
60,502,688
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from PyObjCTools.TestSupport import * import AVFoundation class TestAVPlayer (TestCase): @min_os_level('10.7') def testConstants(self): self.assertEqual(AVFoundation.AVPlayerStatusUnknown, 0) self.assertEqual(AVFoundation.AVPlayerStatusReadyToPlay, 1) self.assertEqual(AVFoundation.AVPlayerStatusFailed, 2) self.assertEqual(AVFoundation.AVPlayerActionAtItemEndAdvance, 0) self.assertEqual(AVFoundation.AVPlayerActionAtItemEndPause, 1) self.assertEqual(AVFoundation.AVPlayerActionAtItemEndNone, 2) @min_os_level('10.7') def testMethods(self): self.assertArgIsBlock(AVFoundation.AVPlayer.seekToDate_completionHandler_, 1, b'vZ') self.assertArgIsBlock(AVFoundation.AVPlayer.seekToTime_completionHandler_, 1, b'vZ') self.assertArgIsBlock(AVFoundation.AVPlayer.seekToTime_toleranceBefore_toleranceAfter_completionHandler_, 3, b'vZ') self.assertArgIsBlock(AVFoundation.AVPlayer.prerollAtRate_completionHandler_, 1, b'vZ') self.assertArgIsBlock(AVFoundation.AVPlayer.addPeriodicTimeObserverForInterval_queue_usingBlock_, 2, b'v{_CMTime=qiIq}') self.assertArgIsBlock(AVFoundation.AVPlayer.addBoundaryTimeObserverForTimes_queue_usingBlock_, 2, b'v') self.assertResultIsBOOL(AVFoundation.AVPlayer.isMuted) self.assertArgIsBOOL(AVFoundation.AVPlayer.setMuted_, 0) self.assertResultIsBOOL(AVFoundation.AVPlayer.isClosedCaptionDisplayEnabled) self.assertArgIsBOOL(AVFoundation.AVPlayer.setClosedCaptionDisplayEnabled_, 0) self.assertResultIsBOOL(AVFoundation.AVQueuePlayer.canInsertItem_afterItem_) @min_os_level('10.9') def testMethods10_9(self): self.assertResultIsBOOL(AVFoundation.AVPlayer.appliesMediaSelectionCriteriaAutomatically) self.assertArgIsBOOL(AVFoundation.AVPlayer.setAppliesMediaSelectionCriteriaAutomatically_, 0) @min_os_level('10.11') def testMethods10_11(self): self.assertResultIsBOOL(AVFoundation.AVPlayer.allowsExternalPlayback) self.assertArgIsBOOL(AVFoundation.AVPlayer.setAllowsExternalPlayback_, 0) self.assertResultIsBOOL(AVFoundation.AVPlayer.isExternalPlaybackActive) if __name__ == "__main__": main()
UTF-8
Python
false
false
2,242
py
77
test_avplayer.py
48
0.767172
0.751115
0
45
48.822222
128
leonw774/rnnstuck
9,534,827,444,629
f20cf8bef1ea5308ce12a1151e396cc0d987e0fb
6aa637069704152f8f62aad1dbd911b7078b97b1
/ganstuck.py
6532330ffd947cdeaa2fb2136fe66792e02b7315
[]
no_license
https://github.com/leonw774/rnnstuck
eddc3155cbf6c575ce29f0cc40c8a691f126d228
65c3f7ee37e751979573f70f1580261afe726947
refs/heads/master
"2021-12-14T23:45:49.604510"
"2020-10-01T07:35:27"
"2020-10-01T07:35:27"
135,281,943
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import re import sys import numpy as np import math import h5py import datetime from configure import * from train_w2v import * from gensim.models import word2vec from keras import activations, optimizers from keras import backend as K from keras.models import Model, load_model from keras.callbacks import Callback, LearningRateScheduler, EarlyStopping from keras.layers import Activation, Bidirectional, Concatenate, ConvLSTM2D, CuDNNLSTM, Dense, Dropout, Embedding, Flatten, GRU, Input, Lambda, LSTM, Masking, multiply, BatchNormalization, Permute, RepeatVector, Reshape, SimpleRNN, TimeDistributed #os.environ["CUDA_VISIBLE_DEVICES"] = '1' # -1 : Use CPU; 0 or 1 : Use GPU print("\nW2V_BY_VOCAB: ", W2V_BY_VOCAB, "\nPAGE_LENGTH_MAX", PAGE_LENGTH_MAX, "\nPAGE_LENGTH_MIN", PAGE_LENGTH_MIN) if MAX_TIMESTEP : if MAX_TIMESTEP > PAGE_LENGTH_MIN : print("Error: PAGE_LENGTH_MIN must bigger than MAX_TIMESTEP") exit() ### PREPARE TRAINING DATA ### page_list, total_word_count = get_train_data(page_length_min = PAGE_LENGTH_MIN, page_length_max = PAGE_LENGTH_MAX, line_length_min = LINE_LENGTH_MIN, line_length_max = LINE_LENGTH_MAX) np.random.shuffle(page_list) ### LOAD WORD MODEL ### word_model_name = "myword2vec_by_word.model" if W2V_BY_VOCAB else "myword2vec_by_char.model" try : word_model = word2vec.Word2Vec.load(word_model_name) except : print("couldn't find wordvec model file", word_model_name, "exiting program...") exit() word_vector = word_model.wv VOCAB_SIZE = word_vector.syn0.shape[0] del word_model print("total_word_count: ", total_word_count) print("vector size: ", WV_SIZE, "\nvocab size: ", VOCAB_SIZE) #print("\n貓:", word_vector.most_similar("貓", topn = 10)) #for i in range(0, 10) : print(page_list[i]) ### PREPARE TRAINING DATA ### def make_input_matrix(word_list, sentence_length_limit = None) : dim = WV_SIZE if sentence_length_limit : input_matrix = np.zeros([1, sentence_length_limit, dim]) else : input_matrix = np.zeros([1, len(word_list), dim]) if sentence_length_limit : word_list = word_list[ -sentence_length_limit : ] # only keep last few words if has sentence_length_limit for i, word in enumerate(word_list) : try : input_matrix[0, i] = word_vector[word] # add one because zero is masked except KeyError : for c in word : try : input_matrix[0, i] = word_vector[word] except KeyError : continue return input_matrix def make_label_matrix(word_list) : label_matrix = np.zeros([1, len(word_list), 1], dtype = int) word_list = word_list[1 : ] # delete start mark for i, word in enumerate(word_list) : try : label_matrix[0, i, 0] = word_vector.vocab[word].index # because sparse_categorical except KeyError : for c in word : try : label_matrix[0, i, 0] = word_vector.vocab[word].index except KeyError : continue # don't want last element in label_matrix be zero vecter, so make it to be ending mark label_matrix[0, -1, 0] = word_vector.vocab[ENDING_MARK].index return label_matrix train_data_list = [] label_data_list = [] for page in page_list : train_data_list.append(make_input_matrix(page)) label_data_list.append(make_label_matrix(page)) # make batch training data def generate_train_data(max_timestep, batch_size, zero_offset = False) : train_in_len = len(train_data_list) n = 0 #print(train_data_list[0].shape, label_data_list[0].shape) while 1 : if max_timestep : post_length = max_timestep else : max_post_length = min([train_data_list[(n + b) % train_in_len].shape[1] for b in range(batch_size)]) batch_post_length = np.random.randint(1, max_post_length) x = np.zeros((batch_size, batch_post_length, WV_SIZE)) y = np.zeros((batch_size, 1), dtype = int) for b in range(batch_size) : post_num = (n + b) % train_in_len post_length = np.random.randint(1, batch_post_length + 1) if zero_offset : answer = post_length - 1 else : answer = np.random.randint(post_length, train_data_list[post_num].shape[1]) x[b, : post_length] = train_data_list[post_num][:, answer - (post_length - 1) : answer + 1] y[b] = label_data_list[post_num][:, answer] yield x, y n = (n + batch_size) % train_in_len ### CALLBACK FUNCTIONS ### def sample(prediction, temperature = 1.0) : prediction = np.asarray(prediction).astype('float64') prediction = np.log(prediction) / temperature exp_preds = np.exp(prediction) prediction = exp_preds / np.sum(exp_preds) return np.random.multinomial(1, prediction, 1) def predict_output_sentence(predict_model, temperature, max_output_length, initial_input_sentence = None) : output_sentence = [] if initial_input_sentence : output_sentence += initial_input_sentence for n in range(max_output_length) : input_array = make_input_matrix(output_sentence, sentence_length_limit = MAX_TIMESTEP) y_test = predict_model.predict(input_array) y_test = sample(y_test[0], temperature) next_word = word_vector.wv.index2word[np.argmax(y_test[0])] output_sentence.append(next_word) if next_word == ENDING_MARK : break output_sentence.append("\n") return output_sentence def output_to_file(filename, output_number, max_output_length) : outfile = open(filename, "w+", encoding = "utf-8-sig") predict_model = Gmodel for _ in range(output_number) : output_sentence = predict_output_sentence(predict_model, 0.9, max_output_length, np.random.choice(page_list)[0 : 2]) output_string = "" for word in output_sentence : output_string += word outfile.write(output_string) outfile.write(">>>>>>>>\n") outfile.close() sgd = optimizers.SGD(lr = LEARNING_RATE, momentum = 0.9, nesterov = True, decay = 0.0) d_adam = optimizers.Adam(lr = LEARNING_RATE * 0.1, decay = 0.0) am_adam = optimizers.Adam(lr = LEARNING_RATE, decay = 0.0) if MAX_TIMESTEP : STEPS_PER_EPOCH = int((total_word_count // BATCH_SIZE) * STEP_EPOCH_RATE) else : STEPS_PER_EPOCH = int(len(page_list) * STEP_EPOCH_RATE) print("\nUSE_SAVED_MODEL:", USE_SAVED_MODEL) print("max time step:", MAX_TIMESTEP, "\nrnn units:", RNN_UNIT, "\nbatch size:", BATCH_SIZE, "\nvalidation number:", VALIDATION_NUMBER, "\noutput number:", OUTPUT_NUMBER) print("step per epoch:", STEPS_PER_EPOCH, "\nlearning_rate:", LEARNING_RATE) ### GENERATIVE MODEL ### def get_gen_model() : input_layer = Input([MAX_TIMESTEP, WV_SIZE]) if MAX_TIMESTEP : rnn_layer = Masking(mask_value = 0.)(input_layer) else : rnn_layer = input_layer for i, v in enumerate(RNN_UNIT) : is_return_seq = (i != len(RNN_UNIT) - 1) or USE_ATTENTION or MAX_TIMESTEP == None if MAX_TIMESTEP == None : rnn_layer = CuDNNLSTM(v, return_sequences = is_return_seq, stateful = False)(rnn_layer) else : rnn_layer = LSTM(v, return_sequences = is_return_seq, stateful = False)(rnn_layer) rnn_layer = Dropout(0.2)(rnn_layer) if USE_ATTENTION : print(rnn_layer.shape) attention = Dense(1, activation = "softmax")(rnn_layer) print(attention.shape) postproc_layer = multiply([attention, rnn_layer]) postproc_layer = Lambda(lambda x: K.sum(x, axis = 1))(postproc_layer) postproc_layer = Dropout(0.2)(postproc_layer) else : postproc_layer = rnn_layer guess_next = Dense(VOCAB_SIZE, activation = "softmax")(postproc_layer) return Model(input_layer, guess_next) ### END GENERATIVE MODEL ### ### DESCRIMINATIVE MODEL ### def get_dis_model() : input_layer_sentence = Input([MAX_TIMESTEP, WV_SIZE]) input_layer_next_word = Input([VOCAB_SIZE]) _, rnn_state = SimpleRNN(RNN_UNIT[0], return_state = True)(input_layer_sentence) conc_layer = Concatenate()([rnn_state, input_layer_next_word]) guess_layer = Dense(1, activation = "sigmoid")(conc_layer) Dmodel = Model([input_layer_sentence, input_layer_next_word], guess_layer) return Dmodel def noised_binary_accuracy(y_true, y_pred): return K.mean(K.equal(K.round(y_true), K.round(y_pred)), axis=-1) Dmodel = get_dis_model() Dmodel.compile(optimizer = d_adam, loss = ['mse'], metrics = [noised_binary_accuracy]) Dmodel.summary() ### END DESCRIMINATIVE MODEL ### ### MAKE ADVERSARIAL MODEL ### Gmodel = get_gen_model() Dmodel.trainable = False X = Input([MAX_TIMESTEP, WV_SIZE]) Pred_Y = Gmodel(X) Guess = Dmodel([X, Pred_Y]) Amodel = Model(X, [Guess, Pred_Y]) Amodel.compile(optimizer = am_adam, loss = ["mse", "sparse_categorical_crossentropy"]) Amodel.summary() ### END ADVERSARIAL MODEL ### def softmax(x) : return np.exp(x) / np.sum(np.exp(x), axis = 0) GMODEL_TRAIN_RATIO = 8 start_time = datetime.datetime.now() d_acc_unbalanced = 0 for e in range(EPOCHS * STEPS_PER_EPOCH) : x, y_true = next(generate_train_data) y_true = np.squeeze(y_true) #print(x.shape, y_true.shape) # use Gmodel to make training data D_y_pred = Gmodel.predict(x) D_y_true = np.random.random(size = [BATCH_SIZE, VOCAB_SIZE]) for b in range(BATCH_SIZE) : D_y_true[b, y_true[b]] *= 100.0 D_y_true = softmax(D_y_true) #print(D_y_true, D_y_pred) # train on Dmodel d_ans_true = np.full((BATCH_SIZE, 1), 1.0) d_ans_false = np.full((BATCH_SIZE, 1), 0.0) d_loss_t, d_acc_t = Dmodel.train_on_batch([x, D_y_true], d_ans_true) d_loss_f, d_acc_f = Dmodel.train_on_batch([x, D_y_pred], d_ans_false) d_loss = 0.5 * d_loss_f + 0.5 * d_loss_t d_acc = 0.5 * d_acc_f + 0.5 * d_acc_t # Emergency stop: if d_acc >= 0.66 or d_acc <= 0.33 : d_acc_unbalanced += 1 elif d_acc_unbalanced > 0 : d_acc_unbalanced = 0 if d_acc_unbalanced >= 20 : print("break: d_acc_unbalanced!") break # train on Gmodel amg_loss = 0 for _ in range(GMODEL_TRAIN_RATIO) : x, y_true = next(generate_train_data) amg_loss = Amodel.train_on_batch(x, [d_ans_true, y_true])[1] amg_loss /= GMODEL_TRAIN_RATIO if e % 100 == 0 : output_to_file("output.txt", 4, OUTPUT_TIME_STEP) # output loss to file and screen if e % 10 == 0 : end_time = datetime.datetime.now() - start_time print("%d/%d, dloss: %.3f, dacc: %.3f, amg_loss: %.3f, t: %s" % (e, EPOCHS, d_loss, d_acc, amg_loss, end_time)) output_to_file("output.txt", 4, OUTPUT_TIME_STEP) Gmodel.save(SAVE_MODEL_NAME)
UTF-8
Python
false
false
10,808
py
8
ganstuck.py
7
0.63495
0.622917
0
271
38.867159
247
noootown/algorithm
17,892,833,755,762
0134de666c96fc1c543b066a1da003bf8c32d289
02eef3d6f2bd05ffd64ff5df63bf4bfb0721a31a
/leetcode/string/345.py
8bcfab540cabb712d1d2f262949e734464921122
[]
no_license
https://github.com/noootown/algorithm
7e06a35071f8ff9cb2dbd56be8575168a44618ab
84132372485ec4b1fbb3c0ab87362c1b0b37aa1c
refs/heads/master
"2021-09-27T03:10:12.763215"
"2018-11-05T19:32:52"
"2018-11-05T19:32:52"
117,585,824
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# https://leetcode.com/problems/reverse-vowels-of-a-string/ # http://bit.ly/2H7sjLs import re class Solution: def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = re.findall('(?i)[aeiou]', s) return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s) assert Solution().reverseVowels('hello') == 'holle' assert Solution().reverseVowels('hEllo') == 'hollE'
UTF-8
Python
false
false
398
py
135
345.py
131
0.628141
0.623116
0
16
23.875
59
Jothapunkt/tournament-network
3,289,944,969,713
fb9eb2355e387d2826ed1f93531c425e9411133c
083163376119755d26ca3ff9aab18700244f590e
/tournament_organizer.py
71d48b0c225092a5b9c242de55a03d618eebd955
[]
no_license
https://github.com/Jothapunkt/tournament-network
818f07904b7eb3d3e04fb41567831bf49b258a7e
e8dcc717b01a981ed1a91d4ca8a13866217f68e8
refs/heads/master
"2022-01-08T17:00:15.920947"
"2019-02-27T20:38:31"
"2019-02-27T20:38:31"
167,858,728
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import math from random import * from player import RemotePlayer from mutator import Mutator import copy from gamesim import GameSim from game_data import * from ball import * class Tournament(object): def __init__(self): self.mutator = Mutator() self.data = GameData() #Game Data is stored in singleton self.players = [] self.total_players = 0 self.matches_played = 0 self.data = GameData() self.game = GameSim() def mutate_player(self, p): new_p = copy.deepcopy(p) new_p.controller = self.mutator.mutate(new_p.controller) return new_p #Creates a tournament of completely randomized players def random_tournament(self,rounds): #rounds is the number of KO rounds played. There are 2^rounds random players in total, e.g. 15 self.players = [] self.total_players = 2 ** rounds self.matches_played = 0 print("-- Random Tournament --") print("Total players: " + str(self.total_players)) for i in range(self.total_players): p = RemotePlayer() self.players.append(p) return self.play_tournament() #Creates a tournament of the player imported from disk and mutations of that player def import_tournament(self,filename,rounds): self.players = [] self.total_players = 2 ** rounds self.matches_played = 0 print("-- Import Tournament --") print("Total players: " + str(self.total_players)) p = RemotePlayer() p.import_player(filename) self.players.append(p) while(len(self.players) < self.total_players): self.players.append(self.mutate_player(p)) return self.play_tournament() #Creates a tournament of the base player passed and mutations of that player def continue_tournament(self, base_player, rounds): self.players = [] self.total_players = 2 ** rounds self.matches_played = 0 print("-- Continue Tournament -- ") print("Total players: " + str(self.total_players)) self.players.append(base_player) while(len(self.players) < self.total_players): self.players.append(self.mutate_player(base_player)) return self.play_tournament() def play_tournament(self): for pl in self.players: pl.score += self.total_players #Non-final rounds while (len(self.players) > 2): i = 0 new_players = [] while(i < len(self.players) - 1): self.data.set("playerLeft", self.players[i]) self.data.set("playerRight", self.players[i+1]) if (self.game.play_match() == "left"): new_players.append(self.players[i]) else: new_players.append(self.players[i+1]) self.matches_played += 1 i += 2 if (self.matches_played % 20 == 0): print("Matches played: " + str(self.matches_played) + "/" + str(self.total_players - 1)) self.players = new_players #Final round if (len(self.players) != 2): print("There are not exactly 2 players for final match: " + str(len(self.players)) + " players left") return None else: print("-- Finale --") self.data.set("playerLeft", self.players[0]) self.data.set("playerRight", self.players[1]) winner = self.players[1] second = self.players[0] second.score -= 1 if (self.game.play_match(record=True) == "left"): winner = self.players[0] second = self.players[1] print("Sieger: #" + str(winner.id)) print("Stolzer Zweiter: #" + str(second.id)) print("Endstand: " + str(self.data.get("scoreLeft")) + " - " + str(self.data.get("scoreRight")) + ". " + str(self.data.get("numberParries",0)) + " mal pariert") winner.export_player() second.export_player() return winner
UTF-8
Python
false
false
3,551
py
35
tournament_organizer.py
24
0.663757
0.654745
0
120
28.533333
163
zymrytekabashi/python_fundamentals
2,774,548,905,853
4d6b82de45772d8190d11927a24ca9cd83bab008
0142aa7bca656c66d59be3e90a0bd8d2a2bf1133
/insertion-sort.py
0b50b470d1456f7aa9840731b95daac4f7860f7a
[]
no_license
https://github.com/zymrytekabashi/python_fundamentals
6ce5b5ff7ba125648d55276e43460c1632b974de
eaa634ceef0e9958caf32d0bf724c401c7f15693
refs/heads/master
"2022-12-02T03:14:24.759910"
"2020-08-21T13:31:22"
"2020-08-21T13:31:22"
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#insertion sort def insertion_sort(my_list): for i in range(len(my_list)-1): for j in range(i, len(my_list)-1): while j>0 and my_list[j-1]<my_list[j]: j-=1 my_list[i], my_list[i-1]=my_list[i-1], my_list[i] my_list=[7,1,4,3,2] insertion_sort(my_list) print(my_list) my_arr = [9,3,78,12,76,0,-2] for idx in range(1, len(my_arr)): temp = my_arr[idx] prev_idx = idx-1 while prev_idx >= 0 and temp < my_arr[prev_idx]: my_arr[prev_idx + 1] = my_arr[prev_idx] prev_idx -= 1 my_arr[prev_idx + 1] = temp print(my_arr)
UTF-8
Python
false
false
636
py
18
insertion-sort.py
18
0.515723
0.471698
0
24
25.5
61
bayneri/fake-commit-bot
377,957,144,026
f94802281d0d9a66c2f82745664ba14c9672a4b9
b9a9204e417e492236c08a15af4f41ae04ac4d7a
/bot.py
5b395411d75b5b3df54b08e82ff4c6bba6b4750f
[]
no_license
https://github.com/bayneri/fake-commit-bot
ebfd593769c279e720ec41ca0272e834386167ad
89ac86daf832ef8f9ea0778763589839235ee7b9
refs/heads/master
"2021-09-05T14:28:31.163614"
"2018-01-28T21:25:00"
"2018-01-28T21:25:00"
119,252,910
1
3
null
null
null
null
null
null
null
null
null
null
null
null
null
import subprocess import random rand = random.randint(0,10) if rand >= 5: # my little tiny miny fake github activity subprocess.Popen(["bash", "/Users/halil/Desktop/funfunfun/fake-commit-bot/git.sh"]) else: print('unlucky')
UTF-8
Python
false
false
238
py
4
bot.py
2
0.705882
0.689076
0
10
22.8
87
LARS-robotics/lars-ros
11,690,900,987,463
a6f2326c587f1b6a1155048c9e5b8d4fae04232f
2a79e87928f4b17575171e029b54f9fe7f00046e
/src/connectivity_controller/cfg/ConnectivityVariables.cfg
3e7bc7201a9d60fc1cf393eeaa59e76338b358e8
[ "Apache-2.0" ]
permissive
https://github.com/LARS-robotics/lars-ros
4303c6e2c1b351484a428dcd9f1c55b8e93c00c2
83b0161e1339b39f638276dcbc29f5c71a9c3d06
refs/heads/master
"2016-09-06T08:48:59.616170"
"2015-07-07T19:56:41"
"2015-07-07T19:56:41"
37,946,032
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python PACKAGE = "connectivity_controller" #import roslib;roslib.load_manifest(PACKAGE) from dynamic_reconfigure.parameter_generator_catkin import * gen = ParameterGenerator() gen.add("r_min", double_t, 0, "Radius min", .4, 0.0, 1.5) gen.add("r_max", double_t, 0, "Radius max", .7, 0.0, 1.5) exit(gen.generate(PACKAGE, "connectivity_controller", "ConnectivityVariables"))
UTF-8
Python
false
false
392
cfg
252
ConnectivityVariables.cfg
57
0.721939
0.691327
0
13
29.153846
79
priyanshu3666/Iedaas-python-bootcamp
12,180,527,270,503
80f5ca17f2a0f47f0957b3cfd2dc0b79cbfaffe3
54909b9c7b0d033b371643dbdf9a4b03bc85552b
/day4/student.py
63472651da8131d3b8d9e3c219ad6bc9d5b72287
[]
no_license
https://github.com/priyanshu3666/Iedaas-python-bootcamp
2e710eaa4d6978c4ca4be015b49a537007fc9aa5
853f31452d98bfa1a33dfcf750493edf44d9a3cd
refs/heads/main
"2023-08-05T10:00:12.099226"
"2021-09-18T05:37:27"
"2021-09-18T05:37:27"
404,589,347
0
0
null
false
"2021-09-18T05:37:28"
"2021-09-09T04:50:28"
"2021-09-16T05:58:28"
"2021-09-18T05:37:27"
13,948
0
0
0
Python
false
false
class Student(): def __init__(self,name,roll): self.name = name self.roll= roll def display(self): print(self.name) print(self.roll) def setAge(self,age): self.age=age def setMarks(self,marks): self.marks = marks stuu =Student("priyanshu",50) stuu.display()
UTF-8
Python
false
false
290
py
104
student.py
85
0.648276
0.641379
0
14
19.785714
31
rafelafrance/traiter_brazil
6,158,983,151,451
b651827a7dc258d93023aeb1dfed1c727de2a49b
88b40052d6c36bdc136a97827209dcdfe7026c87
/tests/matchers/test_surface.py
9be8f758288e7a40fc266a94a7cd426c12bf4707
[ "MIT" ]
permissive
https://github.com/rafelafrance/traiter_brazil
d4e4303adced0873cca9603925ec5798422cc9ff
b3ce904a48c368a66c30edd2e7b70bd7c2166d8a
refs/heads/master
"2023-02-25T22:46:04.095548"
"2021-01-31T22:01:13"
"2021-01-31T22:01:13"
324,609,565
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Test plant surface trait matcher.""" # pylint: disable=missing-function-docstring, too-many-public-methods import unittest from tests.setup import test class TestSurface(unittest.TestCase): """Test plant surface trait matcher.""" def test_surface_01(self): self.assertEqual( test('indumentum of the leaflet villose on the surface abaxial;'), [{'surface': 'villose', 'location': 'abaxial', 'part': 'leaflet', 'subpart': 'indumentum', 'trait': 'surface', 'start': 0, 'end': 56}] ) def test_surface_02(self): self.assertEqual( test(""" Flower: indumentum of the calyx present; indumentum of the corolla absent. """), [{'part': 'flower', 'trait': 'part', 'start': 0, 'end': 7}, {'part': 'calyx', 'subpart': 'indumentum', 'present': True, 'trait': 'surface', 'start': 8, 'end': 39}, {'part': 'corolla', 'subpart': 'indumentum', 'present': False, 'trait': 'surface', 'start': 41, 'end': 73} ] ) def test_surface_03(self): self.assertEqual( test('indumentum of the calyx absent/present;'), [{'part': 'calyx', 'subpart': 'indumentum', 'present': [False, True], 'trait': 'surface', 'start': 0, 'end': 38} ] ) def test_surface_04(self): self.assertEqual( test('indumentum of the leaflet puberulent on the surface abaxial;'), [{'surface': 'puberulent', 'part': 'leaflet', 'subpart': 'indumentum', 'location': 'abaxial', 'trait': 'surface', 'start': 0, 'end': 59}] ) def test_surface_05(self): self.assertEqual( test('indumentum of the leaflet glabrous;'), [{'surface': 'glabrous', 'part': 'leaflet', 'subpart': 'indumentum', 'trait': 'surface', 'start': 0, 'end': 34}] ) def test_surface_06(self): self.assertEqual( test(""" indumentum of the leaflet glabrous/puberulent on the surface abaxial; """), [{'surface': ['glabrous', 'puberulent'], 'part': 'leaflet', 'subpart': 'indumentum', 'location': 'abaxial', 'trait': 'surface', 'start': 0, 'end': 68}] )
UTF-8
Python
false
false
2,427
py
35
test_surface.py
28
0.509683
0.49485
0
68
34.691176
86
AbdElRahmanFarhan/Autonomous_Serial_Manipulators_for_Industry
644,245,100,613
a3d6aeb9a019e62a1998b8bd926b90766c0ff23d
6560bbe097cb01b5a6d0297df6b6a00c8091b4c1
/Autonomous_Serial_Manipulators_for_Industry/attrobot/scripts/target_pose.py
1ba55fa62e009701b2675689b238b18d486585b9
[]
no_license
https://github.com/AbdElRahmanFarhan/Autonomous_Serial_Manipulators_for_Industry
c35dde2f826886622be34d9730c8b8d60de089eb
9eb70062d56b1fb4550aecde64ca0c7fcb453310
refs/heads/master
"2022-11-07T03:33:19.642671"
"2022-10-30T14:57:34"
"2022-10-30T14:57:34"
196,573,878
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python import sys import rospy from moveit_commander import RobotCommander, MoveGroupCommander, PlanningSceneInterface, roscpp_initializer from trajectory_msgs.msg import JointTrajectory from geometry_msgs.msg import Pose from moveit_msgs.msg import RobotState from sensor_msgs.msg import JointState from std_msgs.msg import Header from math import pi roscpp_initializer.roscpp_initialize(sys.argv) rospy.init_node('user_interface', anonymous=True) pose_pub = rospy.Publisher("/robot_target_pose", Pose, queue_size=5) joint_pub = rospy.Publisher("/robot_target_joint", JointState, queue_size=5) pose_1_pub = rospy.Publisher("/robot_target_pose_1", Pose, queue_size=5) pose_2_pub = rospy.Publisher("/robot_target_pose_2", Pose, queue_size=5) # rospy.sleep(1) target_pose = Pose() target_pose.position.x = 0.5 target_pose.position.y = 0.1 target_pose.position.z = 0.5 target_pose.orientation.x = 0 target_pose.orientation.y = 0 target_pose.orientation.z = 0 target_pose.orientation.w = 1 raw_input() pose_1_pub.publish(target_pose) # target_pose = Pose() # target_pose.position.x = 0.4 # target_pose.position.y = 0.1 # target_pose.position.z = 0.6 # target_pose.orientation.x = 0 # target_pose.orientation.y = 0 # target_pose.orientation.z = 0 # target_pose.orientation.w = 1 # raw_input() # pose_2_pub.publish(target_pose) # joint_goal = JointState() # joint_goal.header = Header() # joint_goal.header.frame_id = "base_link" # joint_goal.header.stamp = rospy.Time.now() # joint_goal.name = ["joint_1", "joint_2", "joint_3", "joint_4", "joint_5", "joint_6"] # joint_goal.position = [-90*(pi/180), -40*(pi/180), 0*(pi/180), 0*(pi/180), 0*(pi/180), 0*(pi/180)] # joint_pub.publish(joint_goal) rospy.loginfo("processing start time")
UTF-8
Python
false
false
1,753
py
41
target_pose.py
32
0.728465
0.692527
0
54
31.462963
107
denis-shamray/shopbox
14,061,722,973,404
8fd981f7449bff9f1e73f1822bdd6fb0af70ae14
e05e417880a13996b139553cab2d35c77ec037cf
/main/migrations/0004_auto_20160422_1137.py
04d6abdd18c060d44292139da7ef4b0134daa2d0
[]
no_license
https://github.com/denis-shamray/shopbox
201d8b5aebc2730dc22eb2933398ab0975a6485e
b3d2adb7157e08fc375d5e4332b03e7268641d33
refs/heads/master
"2021-01-21T04:41:32.996495"
"2016-07-17T11:31:48"
"2016-07-17T11:31:48"
55,285,921
0
1
null
false
"2016-05-13T15:26:40"
"2016-04-02T08:50:52"
"2016-04-19T19:25:41"
"2016-05-13T15:26:39"
36,692
0
0
0
CSS
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-22 11:37 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20160415_1151'), ] operations = [ migrations.AlterModelOptions( name='good', options={'ordering': ['pk']}, ), migrations.AlterModelOptions( name='picture', options={'ordering': ['pk']}, ), ]
UTF-8
Python
false
false
521
py
30
0004_auto_20160422_1137.py
11
0.554702
0.493282
0
23
21.652174
47
minqiang/ProjectEuler
5,394,478,973,339
2bb66725d91b4c00e3fe4487834366c1281fafff
41961531401b6cb1ff753a3f2b1600a857bc2abf
/Python_Code/010_summation_of_primes.py
dff8a980ec52445c1bd6c6d97d087f322f29516d
[]
no_license
https://github.com/minqiang/ProjectEuler
d0c2212299e57fbf5fdf64f1a502274bb596af20
97df621b7fac00154226ce4cc9be7bb5ab1e86e3
refs/heads/master
"2021-01-20T00:29:26.035304"
"2015-07-27T01:58:53"
"2015-07-27T01:58:53"
18,692,702
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#=============================================================================== # Problem 10: # # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # # Find the sum of all the primes below two million. #=============================================================================== # Author: Minqiang Li (any comments welcome at myfirstname.mylastname@gmail.com! # https://github.com/minqiang/ProjectEuler #=============================================================================== # This problem is related to Problem 7. # In fact, code change is extremely minimal. # Any idea of speeding up code is welcome. #=============================================================================== from math import sqrt # given number num, check whether divisible by any number in plist def not_divisible(num, plist): m = long(sqrt(num)) for j in plist: if j>m: return True if num%j == 0: return False return True plist = [2,3] sum_prime = 5 i = plist[-1] limit = 2000000 while i < limit: i += 2 if not_divisible(i, plist): plist.append(i) sum_prime += i print(sum_prime)
UTF-8
Python
false
false
1,171
py
21
010_summation_of_primes.py
14
0.457728
0.437233
0
42
26.690476
80
purelledhand/fat32_carving
953,482,763,437
29076d8ef3ea91951c31d9782896e7c5eaf106d0
57969afdd8e3c1b273e92c125b76f4b3f2267b03
/fat32/fat32parser/models.py
616b02519e08f61d7989f012302b5302cf15b9bd
[]
no_license
https://github.com/purelledhand/fat32_carving
3e2ec15b8a0adcbe165c74235decaee7ddfcd982
760350262793aef2cacee93181fd3642eb540901
refs/heads/master
"2021-04-28T13:55:48.368907"
"2018-02-18T13:29:06"
"2018-02-18T13:29:06"
121,953,480
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.utils import timezone # Create your models here. class Carving(models.Model): bytes_per_sector = models.IntegerField() sectors_per_cluster = models.IntegerField() reserved = models.IntegerField() fat32_size = models.IntegerField() cluster_size = models.IntegerField() FAT1 = models.IntegerField() FAT2 = models.IntegerField() Root_Directory = models.IntegerField() """ def cluster_size(self): return bytes_per_sector*sectors_per_cluster def FAT1(self): return reserved def FAT2(self): return FAT1()+fat32_size def Root_Directory(self): return FAT2()+fat32_size """
UTF-8
Python
false
false
629
py
7
models.py
5
0.745628
0.72655
0
26
23.230769
45
mushahiroyuki/beginning-python
18,184,891,540,917
a1c4e781411d51b91a49f313e1b39baf58413216
1a24def8879972f21d846ffb3813632070e1cf12
/Chapter10/1007-webbrowser.py
9a7ade3b6da6b6d104c6bd13a90c5451b65fadd6
[]
no_license
https://github.com/mushahiroyuki/beginning-python
03bb78c8d3f678ce39662a44046a308c99f29916
4d761d165203dbbe3604173c404f70a3eb791fd8
refs/heads/master
"2023-08-16T12:44:01.336731"
"2023-07-26T03:41:22"
"2023-07-26T03:41:22"
238,684,870
5
4
null
false
"2023-09-06T18:34:01"
"2020-02-06T12:33:26"
"2023-07-25T09:42:56"
"2023-09-06T18:33:58"
23,447
5
2
2
Python
false
false
#ファイル名 Chapter10/1007-webbrowser.py import webbrowser webbrowser.open('http://www.python.org')
UTF-8
Python
false
false
105
py
209
1007-webbrowser.py
185
0.8
0.736842
0
3
30.666667
40
hiroaster/syslog-monitor
6,184,752,944,043
df2f18927ba828efb3e9778d5c05b23fc425c4a0
ffdb900645e7b9f070a9a898e4dbf1d07bc8f861
/dbconn.py
bf26d26b6b3a3596e04ca5d0c17b646e867abc3a
[]
no_license
https://github.com/hiroaster/syslog-monitor
a21589f05d176af82dc3a10799333578545a6760
8bbf873ac2dfa251bfce4f37757f4657c8a2f57d
refs/heads/master
"2021-01-24T12:04:13.475565"
"2017-10-17T10:41:46"
"2017-10-17T10:41:46"
55,965,469
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python #edit: wenyang # # -*- coding: utf-8 -*- # encoding: utf-8 #!/usr/bin/python import MySQLdb import time ISOTIMEFORMAT='%Y-%m-%d' today = time.strftime(ISOTIMEFORMAT,time.localtime()) def rule_exist(hostname,itemname,db_ip,db_user,db_pass): db = MySQLdb.connect(db_ip,db_user,db_pass,"enigma" ) cursor = db.cursor() sql = "select Alertoff from alert_rule where Hostname='"+hostname+"' and Itemname='"+itemname+"'" # sql=sql_base+sql_body try: #results = cursor.execute(sql) cursor.execute(sql) results = cursor.fetchall() if results: return results else: return False except: print "Error: unable to fecth data" db.close() def get_desc(hostname,itemname,db_ip,db_user,db_pass): db = MySQLdb.connect(db_ip,db_user,db_pass,"enigma" ) cursor = db.cursor() sql = "select Portdesc from alert_rule where Hostname='"+hostname+"' and Itemname='"+itemname+"'" # sql=sql_base+sql_body try: #results = cursor.execute(sql) cursor.execute(sql) results = cursor.fetchall() if results: return results[0][0] else: return False except: print "Error: unable to fecth data" db.close()
UTF-8
Python
false
false
1,298
py
5
dbconn.py
5
0.607088
0.604006
0
53
23.490566
102
grapin3/django-annuaire-alumni
2,284,922,606,588
e2951c3adcfbfab98c1de7d5f97196bb7d95d09e
d9049630f6307285f69d1a4c808be1e749f31c67
/apps/annuaire/migrations/0001_initial.py
3060b1d3ea3ea52ad5049d7b4d471d5ba0fe7881
[]
no_license
https://github.com/grapin3/django-annuaire-alumni
c577a8c0262a0900704bb4d3ff538a624c6a1205
21dbd90800253500053d6f2baba60f015614f8cb
refs/heads/master
"2020-03-21T08:20:24.511700"
"2018-08-28T15:26:49"
"2018-08-28T15:26:49"
138,336,923
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 2.0.6 on 2018-08-17 15:52 import apps.annuaire.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Member', fields=[ ('memberid', models.AutoField(primary_key=True, serialize=False)), ('firstname', models.CharField(max_length=30, verbose_name='prénom')), ('lastname', models.CharField(max_length=30, verbose_name='nom')), ('registration_date', models.DateField(default=django.utils.timezone.now, verbose_name="date d'inscription")), ('expiration_date', models.DateField(default=apps.annuaire.models.one_year_delta, verbose_name="date d'expiration")), ], options={ 'verbose_name': 'membre', 'ordering': ('lastname', 'firstname'), }, ), migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('gender', models.IntegerField(blank=True, choices=[(0, 'Homme'), (1, 'Femme')], null=True, verbose_name='sexe')), ('photo', models.ImageField(blank=True, null=True, upload_to=apps.annuaire.models.avatar_directory_path)), ('city', models.CharField(blank=True, max_length=500, null=True, verbose_name='ville')), ('region', models.CharField(blank=True, max_length=500, null=True, verbose_name='region')), ('country', models.CharField(blank=True, max_length=500, null=True, verbose_name='pays')), ('bio', models.TextField(blank=True, max_length=500, null=True, verbose_name='biographie')), ('promo', models.IntegerField(blank=True, null=True, verbose_name='promotion')), ('gap_year', models.BooleanField(default=False, verbose_name='césure')), ('miscellaneous', models.TextField(blank=True, max_length=500, verbose_name='divers')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='member', name='profile', field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='annuaire.Profile'), ), ]
UTF-8
Python
false
false
2,701
py
33
0001_initial.py
12
0.608003
0.594665
0
54
48.981481
133