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
list
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
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
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
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
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
14malbright/music-utils
14,611,478,786,129
e99098280a8059e7982bd1525538a973faec6d3d
795c7200bc283b9fee80dba1b6499d5104e40984
/music_tools/utils.py
6cbdc487f57a743ca7667ff5e2e6a17cb3f8babf
[]
no_license
https://github.com/14malbright/music-utils
8dc1f63f2280d8847c5d452c22db9a03f524c440
097975cfbbd07df4ef5bd09967572d565f4ca450
refs/heads/master
2022-02-17T19:33:52.305064
2022-02-15T02:30:32
2022-02-15T02:30:32
180,013,121
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from functools import wraps import requests def no_timeout(func): @wraps(func) def wrapped(*args, **kwargs): while True: try: return func(*args, **kwargs) except requests.ConnectionError: print(f"ConnectionError on {func.__name__}. Retrying...") continue except requests.ReadTimeout: print(f"ReadTimout on {func.__name__}. Retrying...") continue return wrapped def take_x_at_a_time(items, x): sequence = list(items) quotient, remainder = divmod(len(sequence), x) for i in range(quotient + bool(remainder)): yield sequence[i * x : (i + 1) * x]
UTF-8
Python
false
false
729
py
27
utils.py
21
0.554184
0.55144
0
27
26
73
kdheepak89/pypdevs
7,868,380,096,290
67db3e6854bcc87a53114c9fce7b0cdd345047f6
823909fb73fb3b721385e59b22f021be4183198b
/performance/benchmarks/PHOLD.py
ebbc9128b2bc79eb23e9d11171f53908cdef070d
[ "Apache-2.0" ]
permissive
https://github.com/kdheepak89/pypdevs
302c69757b8eca443ca5993af287543f190185d9
979d708a184d342313cc7c2b6bd24225e475af3b
refs/heads/master
2021-05-24T06:52:42.774852
2015-06-18T21:33:57
2015-06-18T21:33:57
37,686,146
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os.path import random import pypdevs from pypdevs.DEVS import AtomicDEVS, CoupledDEVS class PHOLDModelState(object): def __init__(self): self.event = [] def copy(self): a = PHOLDModelState() a.event = [list(b) for b in self.event] return a def __eq__(self, other): return other.event == self.event def getProcTime(event): random.seed(event) return random.random() def getNextDestination(event, nodenum, local, remote, percentageremotes): random.seed(event) if random.random() > percentageremotes or len(remote) == 0: return local[int(random.uniform(0, len(local)))] else: return remote[int(random.uniform(0, len(remote)))] def getRand(event): # For determinism with a global random number generator # This only works because each node runs its own Python interpreter random.seed(event) return int(random.uniform(0, 60000)) class HeavyPHOLDProcessor(AtomicDEVS): def __init__(self, name, iterations, totalAtomics, modelnumber, local, remote, percentageremotes): AtomicDEVS.__init__(self, name) self.inport = self.addInPort("inport") self.percentageremotes = percentageremotes self.outports = [] self.totalAtomics = totalAtomics self.modelnumber = modelnumber for i in xrange(totalAtomics): self.outports.append(self.addOutPort("outport_" + str(i))) self.state = PHOLDModelState() ev = modelnumber self.state.event = [[ev, getProcTime(ev)]] self.iterations = iterations self.local = local self.remote = remote def timeAdvance(self): if len(self.state.event) > 0: return self.state.event[0][1] else: return float('inf') def confTransition(self, inputs): if len(self.state.event) > 1: self.state.event = self.state.event[1:] else: self.state.event = [] for i in inputs[self.inport]: self.state.event.append([i, getProcTime(i)]) for _ in xrange(self.iterations): pass return self.state def intTransition(self): self.state.event = self.state.event[1:] return self.state def extTransition(self, inputs): if len(self.state.event) > 0: self.state.event[0][1] -= self.elapsed for i in inputs[self.inport]: self.state.event.append([i, getProcTime(i)]) # Just keep ourself busy for some time for _ in xrange(self.iterations): pass return self.state def outputFnc(self): if len(self.state.event) > 0: i = self.state.event[0] return {self.outports[getNextDestination(i[0], self.modelnumber, self.local, self.remote, self.percentageremotes)]: [getRand(i[0])]} else: return {} class PHOLD(CoupledDEVS): def __init__(self, nodes, atomicsPerNode, iterations, percentageremotes): CoupledDEVS.__init__(self, "PHOLD") self.processors = [] have = 0 destinations = [] cntr = 0 totalAtomics = nodes * atomicsPerNode procs = [] for node in range(nodes): procs.append([]) for i in range(atomicsPerNode): procs[-1].append(atomicsPerNode*node+i) cntr = 0 global distributed for e, i in enumerate(procs): allnoi = [] for e2, j in enumerate(procs): if e2 != e: allnoi.extend(j) for j in i: inoj = list(i) inoj.remove(j) self.processors.append(self.addSubModel(HeavyPHOLDProcessor("Processor_%d" % cntr, iterations, totalAtomics, cntr, inoj, allnoi, percentageremotes), e if distributed else 0)) cntr += 1 # All nodes created, now create all connections for i in range(len(self.processors)): for j in range(len(self.processors)): if i == j: continue self.connectPorts(self.processors[i].OPorts[j], self.processors[j].inport) try: from mpi4py import MPI distributed = MPI.COMM_WORLD.Get_size() > 1 except: distributed = False
UTF-8
Python
false
false
5,030
py
17
PHOLD.py
9
0.612326
0.604374
0
144
33.930556
190
syurskyi/Python_Topics
18,167,711,666,390
680ddb6e52c93299793252fa5b7f5a0d9a3e0180
e23a4f57ce5474d468258e5e63b9e23fb6011188
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/BinarySearch/34_SearchForRange.py
0e5cb506f050a5583b6d6c9fe898279cdd9dabb2
[]
no_license
https://github.com/syurskyi/Python_Topics
52851ecce000cb751a3b986408efe32f0b4c0835
be331826b490b73f0a176e6abed86ef68ff2dd2b
refs/heads/master
2023-06-08T19:29:16.214395
2023-05-29T17:09:11
2023-05-29T17:09:11
220,583,118
3
2
null
false
2023-02-16T03:08:10
2019-11-09T02:58:47
2022-11-03T01:22:28
2023-02-16T03:08:09
198,671
2
2
33
Python
false
false
#! /usr/bin/env python # -*- coding: utf-8 -*- c.. Solution o.. # log(n) here. ___ firstAppear nums, target left, right = 0, l..(nums) - 1 _____ left <= right: mid = (left + right) / 2 __ target __ nums[mid] a.. mid - 1 >= left a.. target __ nums[mid - 1]: right = mid - 1 ____ target __ nums[mid]: r_ mid ____ target > nums[mid]: left = mid + 1 ____ right = mid - 1 r_ -1 # log(n) again. ___ lastAppear(s.., nums, target left, right = 0, l..(nums) - 1 _____ left <= right: mid = (left + right) / 2 __ target __ nums[mid] a.. mid + 1 <= right a.. target __ nums[mid + 1]: left = mid + 1 ____ target __ nums[mid]: r_ mid ____ target > nums[mid]: left = mid + 1 ____ right = mid - 1 r_ -1 ___ searchRange nums, target r_ (self.firstAppear(nums, target), self.lastAppear(nums, target)) """ [] 0 [1,1,1,1] 1 [1,2,3,4,5] 3 [1,2,3,4,5] 6 """
UTF-8
Python
false
false
1,167
py
15,362
34_SearchForRange.py
14,734
0.384747
0.353042
0
48
23.3125
84
wzx120606/TensorFlowTest
13,486,197,312,993
17ff1bf8d15b4074f90373efbc5a3331a8273712
9805e2a9a6a2b5c4545adf7ef266d94a15850cd5
/TensorFlow/查看模型训练动态图2.py
bb6ebb683d3e3d89d8b22cb0d1c761cde1088819
[]
no_license
https://github.com/wzx120606/TensorFlowTest
46a1552c067bf3866ddc195219b2da071e319294
f54a9df2648f1e5c9b6d415e7b8743e6222d1c78
refs/heads/master
2022-01-12T10:18:59.242898
2019-06-27T02:57:56
2019-06-27T02:57:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from tensorflow.contrib.tensorboard.plugins import projector # 载入数据集,如果没有则会将mnist数据下载到对应路径下 mnist = input_data.read_data_sets("MNIST_data",one_hot=True) # number of cycles max_steps = 1001 # number of pictures image_num = 3000 # file directory DIR = "C:/Users/admin/PycharmProjects/TensorFlowTestNew/TensorFlow/" # define session sess = tf.Session() # load pictures embedding = tf.Variable(tf.stack(mnist.test.images[:image_num]), trainable=False, name='embedding') # 命名空间 with tf.name_scope('base_values'): # 批次大小 batch_size = 100 # 批次数 n_batch = mnist.train.num_examples // batch_size keep_prob=tf.placeholder(tf.float32) lr = tf.Variable(0.001,dtype=tf.float32)#步长 # 命名空间 with tf.name_scope('input'): x=tf.placeholder(tf.float32,[None,784],name='x-input') y=tf.placeholder(tf.float32,[None,10],name='y-input') # show images 在tensorboard中显示 with tf.name_scope('input_reshape'): image_shaped_input = tf.reshape(x, [-1, 28, 28, 1]) tf.summary.image('input', image_shaped_input, 10) with tf.name_scope('first_layer'): # 使用tf.truncated_normal初始化很多时候会比使用tf.zeros好很多 # tf.truncated_normal(shape, mean, stddev) :shape表示生成张量的维度,mean是均值,stddev是标准差。 # 这个函数产生正太分布,均值和标准差自己设定。这是一个截断的产生正太分布的函数,就是说产生正太分布的值如果与均值的差值大于两倍的标准差,那就重新生成。 # 和一般的正太分布的产生随机数据比起来,这个函数产生的随机数与均值的差距不会超过两倍的标准差,但是一般的别的函数是可能的。 w1 = tf.Variable(tf.truncated_normal(shape=[784,500],stddev=0.1),name="w1") b1 = tf.Variable(tf.zeros([500])+0.1,name="b1") L1 = tf.nn.tanh(tf.matmul(x,w1)+b1,name="L1") L1_drop=tf.nn.dropout(L1,keep_prob)#相当于下一层的特征输入 with tf.name_scope('second_layer'): w2 = tf.Variable(tf.truncated_normal(shape=[500,300],stddev=0.1),name="w2") b2 = tf.Variable(tf.zeros([300])+0.1,name="b2") L2 = tf.nn.tanh(tf.matmul(L1_drop,w2)+b2,name="L2") L2_drop=tf.nn.dropout(L2,keep_prob,name="L2_drop")#相当于下一层的特征输入 with tf.name_scope('output_layer'): w3 = tf.Variable(tf.truncated_normal(shape=[300,10],stddev=0.1),name="w3") b3 = tf.Variable(tf.zeros([10])+0.1,name="b3") prediction = tf.nn.softmax(tf.matmul(L2_drop,w3)+b3,name="prediction") with tf.name_scope('train'): with tf.name_scope('loss'): # loss = tf.reduce_mean(tf.square(y-prediction))#二次代价函数 loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))#对数似然代价函数()或者说叫做用于softmax的交叉熵代价函数 with tf.name_scope('train_step'): # train_step = tf.train.GradientDescentOptimizer(.1).minimize(loss)#梯度下降训练 # train_step = tf.train.AdadeltaOptimizer(1e-3).minimize(loss)#Adadelta算法优化器训练 train_step = tf.train.AdamOptimizer(lr).minimize(loss)#Adam算法优化器训练 with tf.name_scope('accuracy'): # 结果存放布尔列表中 correct_predition = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) # 准确率 accuracy = tf.reduce_mean(tf.cast(correct_predition,tf.float32)) with tf.name_scope('init_value'): inti = tf.global_variables_initializer() # create metadata file if tf.gfile.Exists(DIR + 'projector/projector/metadata.tsv'): tf.gfile.DeleteRecursively(DIR + 'projector/projector') tf.gfile.MkDir(DIR + 'projector/projector') with open(DIR + 'projector/projector/metadata.tsv', 'w') as f: labels = sess.run(tf.argmax(mnist.test.labels[:], 1)) for i in range(image_num): f.write(str(labels[i]) + '\n') # combine all summaries merged = tf.summary.merge_all() projector_writer = tf.summary.FileWriter(DIR + 'projector/projector', sess.graph) saver = tf.train.Saver() config = projector.ProjectorConfig() embed = config.embeddings.add() embed.tensor_name = embedding.name embed.metadata_path = DIR + 'projector/projector/metadata.tsv'#测试集中对应的前image_num的label值 embed.sprite.image_path = DIR + 'projector/data/numbers.jpg'#这张图片顺序对应测试集的样本(测试集也是10000个样本) # embed.sprite.image_path = DIR + 'projector/data/numberschild.jpg' embed.sprite.single_image_dim.extend([28, 28]) projector.visualize_embeddings(projector_writer, config) with tf.Session() as sess: sess.run(inti) tf.summary.FileWriter('logs/',sess.graph)#在terminal视图运行命令:tensorboard --logdir=C:\Users\admin\PycharmProjects\TensorFlowTestNew\TensorFlow\logs for epoch in range(1): sess.run(tf.assign(lr,lr*0.95)) for batch in range(n_batch): batch_xs,batch_ys = mnist.train.next_batch(batch_size) run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_ys,keep_prob:1.0}, options=run_options,run_metadata=run_metadata) l_r = sess.run(lr); acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0}) print("epoch:",epoch," acc:",acc,"l_r:",l_r) saver.save(sess, DIR + 'projector/projector/a_model.ckpt', global_step=max_steps) projector_writer.close
UTF-8
Python
false
false
5,621
py
38
查看模型训练动态图2.py
35
0.706942
0.681239
0
112
43.125
147
jcafiero/Courses
4,690,104,324,787
45c8658784dff7f0988340eb7bc631687669a7d6
4f9e30387653a61cdc7c02fa1731c02aaea8aa59
/CS115/Homework/hw6.py
de60b9ed8d1434571401d8c55973265c5ce984bb
[]
no_license
https://github.com/jcafiero/Courses
03a09e9f32e156b37de6da2a0b052ded99ca4d07
c82bc4bbc5657643dabc3a01fadfd961c33ebf5e
refs/heads/master
2022-02-17T14:40:27.073191
2019-10-06T23:58:23
2019-10-06T23:58:23
103,605,315
1
1
null
false
2019-10-07T00:05:39
2017-09-15T02:36:30
2019-10-06T23:58:26
2019-10-07T00:05:29
26,596
0
2
3
JavaScript
false
false
''' Created on March 9, 2015 @author: Jennifer Cafiero, Ayse Akin Pledge: I pledge my honor that I have abided by the Stevens Honor System. CS115 - Hw 6 ''' # Number of bits for data in the run-length encoding format. # The assignment refers to this as k. COMPRESSED_BLOCK_SIZE = 5 # Number of bits for data in the original format. MAX_RUN_LENGTH = 2 ** COMPRESSED_BLOCK_SIZE - 1 # Do not change the variables above. # Write your functions here. You may use those variables in your code. def numToBinary(s): '''Converts a decimal number to binary''' if s == 0: return "" return numToBinary(s/2) + str(s % 2) def numBits(s, k): '''Utilizes the numToBinary function to create binary strings that are k number of bits''' if len(numToBinary(s)) < k: return '0' * (k - len(numToBinary(s))) + numToBinary(s) return numToBinary(s) def compress(s): '''Takes a binary string of length 64 and returns a run-length encoding of the input string.''' def compressHelper(s, curr, count): if s == "": return '' if count == 31: return numToBinary(count) + compressHelper(s, str(1-int(curr)), 0) if s[0] != curr: return numToBinary(count) + compressHelper(s, str(1-int(curr)), 0) return compressHelper(s, curr, count+1) return compressHelper(s,'0', 0) print compress('10'*32)
UTF-8
Python
false
false
1,603
py
287
hw6.py
138
0.562695
0.542732
0
58
25.482759
99
phongluudn1997/leet_code
11,802,570,146,311
f178f1d7a021341180cf409f506d440d0be39c5a
c583fbc131307c4f868c14c08525efec0f325bef
/magic_index.py
28e73a06306f0da59c1feb3770dfbe595d7f722c
[]
no_license
https://github.com/phongluudn1997/leet_code
8c7ccc8597c754c3ce0f794667777c3acea50fa2
c0fc0a53f44967b66afb101daaf6be05dedec24d
refs/heads/master
2021-03-28T11:56:02.646965
2021-03-13T10:57:09
2021-03-13T10:57:09
247,861,580
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def magic_index(array): if not len(array): return "No magic index found." middle_index = len(array) // 2 if array[middle_index] == middle_index: return middle_index if array[middle_index] > middle_index: return magic_index(array[:middle_index]) else: return magic_index(array[middle_index:]) print(magic_index([-1, 1, 2, 4]))
UTF-8
Python
false
false
379
py
74
magic_index.py
74
0.622691
0.609499
0
13
28.230769
48
ndkmbsr/L2
14,620,068,726,073
86e3de44dd62da5d29d28148cc1c9c7fa6c86b4c
adb773515e226668e086c77a4d2ff2e4c65838d8
/goruntu_isleme/MNIST_HOG_SVM.py
fc5139376a08f51ead9bac281b82dfd600db7a87
[]
no_license
https://github.com/ndkmbsr/L2
d455e5ece503c25963d0e35dd70982d4a697250d
2c9bcfa1ba860e3c475b877cfdef7abd913c169a
refs/heads/master
2020-04-11T16:23:45.796337
2018-12-15T17:15:09
2018-12-15T17:15:09
161,922,660
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from skimage.feature import hog from sklearn import svm import numpy as np from sklearn.metrics import confusion_matrix from datetime import datetime import warnings warnings.filterwarnings('ignore') ''''Main Function''' start_time=datetime.now() train_images=np.load('train_images.npy') test_images=np.load('test_images.npy') train_labels=np.load('train_labels.npy') test_labels=np.load('test_labels.npy') n=1152; hog_feature_train=np.zeros([len(train_images),n]); hog_feature_test=np.zeros([len(test_images),n]); for i in range(len(train_images)): hog_values = hog(train_images[i,:,:], orientations=8, pixels_per_cell=(4,4),cells_per_block=(2,2)) hog_feature_train[i]=hog_values for i in range(len(test_images)): hog_values = hog(test_images[i,:,:], orientations=8, pixels_per_cell=(4,4),cells_per_block=(2,2)) hog_feature_test[i]=hog_values model = svm.SVC(decision_function_shape='ovo') #model = svm.SVC() model.fit(hog_feature_train,train_labels) label_estimate=model.predict(hog_feature_test) conf_matrix=confusion_matrix(test_labels,label_estimate) accuracy_rate=(sum(np.diag(conf_matrix)))/np.sum(conf_matrix)*100; print("Accuracy Rate: " ,accuracy_rate) 'stop time' stop_time=datetime.now() elapsed_time=stop_time-start_time print("Elapsed Time: " +str(elapsed_time))
UTF-8
Python
false
false
1,324
py
39
MNIST_HOG_SVM.py
3
0.72432
0.71148
0
44
29.090909
105
ponyatov/metaLold
12,902,081,787,796
2ab2b717db41f7774a514546fb316f5f3e289faa
a20a1bb293c18897133e6f4e6dde75f803654c94
/book/prolog/yield00.py
6731898851d3f8c33826af69e5d5fdd2d72c3d09
[]
no_license
https://github.com/ponyatov/metaLold
e7c0fe94002251e982f003d167a64a5fee2e2fed
e2f0680c945cf4fe44747d0102647740b6b1f740
refs/heads/master
2023-04-10T07:30:20.818855
2020-10-01T11:12:55
2020-10-01T11:12:55
173,776,238
0
2
null
false
2021-04-20T18:33:06
2019-03-04T16:00:23
2020-10-01T11:12:59
2021-04-20T18:33:06
19,202
5
2
4
TeX
false
false
def person(): yield "Chelsea" yield "Hillary" yield "Bill" def main(): for p in person(): print(p) main()
UTF-8
Python
false
false
130
py
283
yield00.py
93
0.546154
0.546154
0
9
13.555556
22
FidelAlberto/Jarvis
8,452,495,676,054
0b48fd2ec120a332be882d50d2be8f70e7cb64b4
857e986c54550246006b3b5c120e285ff6604680
/Program_Files/nlp/lemmatizer.py
f84553100653998e9ab27c79550bff760c11fac1
[]
no_license
https://github.com/FidelAlberto/Jarvis
f8166c264a162b4aec15f4bb83d77c855938fa7b
6218809f15bef844647f745e623e5e61dd725315
refs/heads/master
2022-04-07T23:26:26.075591
2020-02-26T20:16:18
2020-02-26T20:16:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() my_tokens = ["leaves","calves","books","surprising","data mining","girls","goes","puppies"] for word in my_tokens: print(lemmatizer.lemmatize(word))
UTF-8
Python
false
false
226
py
15
lemmatizer.py
14
0.743363
0.743363
0
5
44.2
91
iut-ibk/PowerVIBe
3,221,225,510,993
1705adedee64755654e2da502b4582969becad03
58a167111cd91f21715b2ab0810833781ff77fb9
/scripts/PowerVIBe/importDAE.py
b44c53a00467dea6a8e8ffe76763382c58158188
[]
no_license
https://github.com/iut-ibk/PowerVIBe
33fd68bd219925e7a704d8833b8ab3463a257bcb
fb820fe77a6311fe20bf286943ebb82a8da5f48b
refs/heads/master
2016-09-03T07:26:44.500093
2014-04-10T14:53:07
2014-04-10T14:53:07
5,998,512
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Thu Nov 15 10:00:56 2012 @author: christianurich """ import collada from pydynamind import * class ImportDAE(Module): def __init__(self): Module.__init__(self) self.createParameter("FileName", FILENAME, "filename") self.FileName = "" self.dummy = View("dummy", SUBSYSTEM, MODIFY) self.object = View("Objects", COMPONENT, WRITE) self.geometry = View("Geometry", FACE, WRITE) self.datastream = [] self.datastream.append(self.object) self.datastream.append(self.geometry) self.datastream.append(self.dummy) self.createParameter("OffsetX", DOUBLE, "offsetx") self.OffsetX = 0.0 self.createParameter("OffsetY", DOUBLE, "offsety") self.OffsetY = 0.0 self.createParameter("ScaleX", DOUBLE, "scalesetx") self.ScaleX = 1.0 self.createParameter("ScaleY", DOUBLE, "scalesety") self.ScaleY = 1.0 self.createParameter("ScaleZ", DOUBLE, "scalesetz") self.ScaleZ = 1.0 self.addData("sys", self.datastream) def run(self): sys = self.getData("sys") cmp = Component() cmp = sys.addComponent(cmp, self.object) print self.FileName col = collada.Collada(self.FileName, ignore=[collada.DaeUnsupportedError, collada.DaeBrokenRefError]) for geom in col.geometries: for triset in geom.primitives: trilist = list(triset) elements = len(trilist) for i in range(elements): nl = nodevector() for j in range(3): node = triset.vertex[triset.vertex_index][i][j] n = sys.addNode(float(node[0]* self.ScaleX + self.OffsetX), float(node[1]* self.ScaleY+self.OffsetY), float(node[2])* self.ScaleZ) nl.append(n) nl.append(nl[0]) f = sys.addFace(nl, self.geometry) cmp.getAttribute("Geometry").setLink("Geometry", f.getUUID())
UTF-8
Python
false
false
2,297
py
83
importDAE.py
73
0.522421
0.510231
0
57
38.22807
154
UwePabst91052/Exercises
10,204,842,343,394
638cf943746a1595d727f8d9a30098346ff7adc4
3e6fbf27b5b4dac9a26589343981230c3214c5c8
/TeeUhr.py
7b269ebf28a0d02121f220a63b127618dc45eb57
[]
no_license
https://github.com/UwePabst91052/Exercises
9c08c6a6ee83e5be77eebcc579fef6cea8750cc1
9ea430599d63b4da53ddc2c103d2adeae9c105e5
refs/heads/master
2023-05-26T13:20:11.493249
2023-05-10T14:31:01
2023-05-10T14:31:01
264,718,193
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\pabst\PycharmProjects\Übungen\TeeUhr.ui' # # Created by: PyQt5 UI code generator 5.14.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(235, 217) MainWindow.setWindowTitle("Tee Uhr") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(50, 10, 131, 61)) font = QtGui.QFont() font.setFamily("Impact") font.setPointSize(30) font.setItalic(False) font.setKerning(True) self.label.setFont(font) self.label.setLayoutDirection(QtCore.Qt.LeftToRight) self.label.setFrameShape(QtWidgets.QFrame.WinPanel) self.label.setFrameShadow(QtWidgets.QFrame.Sunken) self.label.setLineWidth(3) self.label.setMidLineWidth(0) self.label.setText("00:00") self.label.setScaledContents(False) self.label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label.setObjectName("label") self.pb_inc_seconds = QtWidgets.QPushButton(self.centralwidget) self.pb_inc_seconds.setGeometry(QtCore.QRect(180, 10, 21, 23)) self.pb_inc_seconds.setObjectName("pb_inc_seconds") self.pb_dec_seconds = QtWidgets.QPushButton(self.centralwidget) self.pb_dec_seconds.setGeometry(QtCore.QRect(180, 50, 21, 23)) self.pb_dec_seconds.setObjectName("pb_dec_seconds") self.pb_inc_minute = QtWidgets.QPushButton(self.centralwidget) self.pb_inc_minute.setGeometry(QtCore.QRect(30, 10, 21, 23)) self.pb_inc_minute.setObjectName("pb_inc_minute") self.pb_dec_minute = QtWidgets.QPushButton(self.centralwidget) self.pb_dec_minute.setGeometry(QtCore.QRect(30, 50, 21, 23)) self.pb_dec_minute.setObjectName("pb_dec_minute") self.pb_start_timer = QtWidgets.QPushButton(self.centralwidget) self.pb_start_timer.setGeometry(QtCore.QRect(70, 150, 75, 23)) self.pb_start_timer.setObjectName("pb_start_timer") self.pb_seven = QtWidgets.QPushButton(self.centralwidget) self.pb_seven.setGeometry(QtCore.QRect(20, 90, 75, 23)) self.pb_seven.setObjectName("pb_seven") self.pb_three = QtWidgets.QPushButton(self.centralwidget) self.pb_three.setGeometry(QtCore.QRect(130, 90, 75, 23)) self.pb_three.setObjectName("pb_three") self.pb_five = QtWidgets.QPushButton(self.centralwidget) self.pb_five.setGeometry(QtCore.QRect(20, 120, 75, 23)) self.pb_five.setObjectName("pb_five") self.pb_six_30 = QtWidgets.QPushButton(self.centralwidget) self.pb_six_30.setGeometry(QtCore.QRect(130, 120, 75, 23)) self.pb_six_30.setObjectName("pb_six_30") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 235, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.pb_inc_minute.clicked.connect(MainWindow.increment_minutes) self.pb_dec_minute.clicked.connect(MainWindow.decrement_minutes) self.pb_inc_seconds.clicked.connect(MainWindow.increment_seconds) self.pb_dec_seconds.clicked.connect(MainWindow.decrement_seconds) self.pb_start_timer.clicked.connect(MainWindow.start_timer) self.pb_seven.clicked.connect(MainWindow.start_seven_minutes) self.pb_three.clicked.connect(MainWindow.start_three_minutes) self.pb_five.clicked.connect(MainWindow.start_five_minutes) self.pb_six_30.clicked.connect(MainWindow.start_six_thirty_minutes) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate self.pb_inc_seconds.setText(_translate("MainWindow", "+")) self.pb_dec_seconds.setText(_translate("MainWindow", "-")) self.pb_inc_minute.setText(_translate("MainWindow", "+")) self.pb_dec_minute.setText(_translate("MainWindow", "-")) self.pb_start_timer.setText(_translate("MainWindow", "Start")) self.pb_seven.setText(_translate("MainWindow", "7 min")) self.pb_three.setText(_translate("MainWindow", "3 min")) self.pb_five.setText(_translate("MainWindow", "5 min")) self.pb_six_30.setText(_translate("MainWindow", "6:30 min")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
UTF-8
Python
false
false
5,179
py
26
TeeUhr.py
16
0.688104
0.662225
0
105
48.314286
103
bregnery/UFDiMuonsAnalyzer
16,664,473,119,817
08232cbb4433e6dfa6554306a3393c0a9f9c906e
6c53d1eefbcddd4d2fbc3caca02616af14dae5d9
/UFDiMuonsAnalyzer/test/UFDiMuonAnalyzer.py
72802a0c0a3f3d6d4e41324ab0a285713d65730b
[]
no_license
https://github.com/bregnery/UFDiMuonsAnalyzer
691950774bf7496980cca5ca709b8c51ebc7bc32
91813ccc4f309b9be46f1ee0d3a59121c66ec949
refs/heads/master
2020-12-12T06:49:39.015086
2016-03-11T23:20:53
2016-03-11T23:20:53
40,377,298
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import FWCore.ParameterSet.Config as cms process = cms.Process("UFDiMuonAnalyzer") thisIsData = False if thisIsData: print 'Running over data sample' else: print 'Running over MC sample' process.load("FWCore.MessageService.MessageLogger_cfi") #process.MessageLogger.cerr.FwkReport.reportEvery = 1000 ##process.MessageLogger.destinations.append("detailedInfo") ##process.MessageLogger.detailedInfo = cms.untracked.PSet( ## threshold = cms.untracked.string("INFO"), ## categories = cms.untracked.vstring("UFHLTTests") ##) process.load("Configuration.StandardSequences.MagneticField_38T_cff") ## Geometry and Detector Conditions (needed for a few patTuple production steps) process.load("Configuration.Geometry.GeometryIdeal_cff") process.load('Configuration.EventContent.EventContent_cff') process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") from Configuration.AlCa.autoCond import autoCond # Get a sample from our collection of samples from Samples_v3 import ggToHToMuMu_PU40bx50 as s # global tag, should get this automatically from the sample data structure globalTag = "PLS170_V6AN2" print 'Loading Global Tag: '+globalTag process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") process.GlobalTag.globaltag = globalTag+"::All" # ------------ PoolSource ------------- readFiles = cms.untracked.vstring(); # Get list of files from the sample we loaded readFiles.extend(s.files); process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) ) process.source = cms.Source("PoolSource",fileNames = readFiles) process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(False) ) process.source.lumisToProcess = cms.untracked.VLuminosityBlockRange() # use a JSON file locally #import FWCore.PythonUtilities.LumiList as LumiList #process.source.lumisToProcess = LumiList.LumiList(filename = 'goodList.json').getVLuminosityBlockRange() # -------- PoolSource END ------------- #=============================================================================== # Clean the Jets from good muons, apply loose jet Id ccMuPreSel = "pt > 15. && isGlobalMuon " ccMuPreSel += " && globalTrack().normalizedChi2 < 10 " ccMuPreSel += " && isPFMuon " ccMuPreSel += " && innerTrack().hitPattern().trackerLayersWithMeasurement > 5 " ccMuPreSel += " && innerTrack().hitPattern().numberOfValidPixelHits > 0 " ccMuPreSel += " && globalTrack().hitPattern().numberOfValidMuonHits > 0 " ccMuPreSel += " && numberOfMatchedStations > 1 && dB < 0.2 && abs(eta) < 2.4 " ccMuPreSel += " && ( chargedHadronIso + max(0.,neutralHadronIso + photonIso - 0.5*puChargedHadronIso) ) < 0.12 * pt" jetSelection = 'neutralEmEnergy/energy < 0.99 ' jetSelection += ' && neutralHadronEnergy/energy < 0.99 ' jetSelection += ' && (chargedMultiplicity + neutralMultiplicity) > 1 ' jetSelection += ' && ((abs(eta)>2.4) || (chargedMultiplicity > 0 ' jetSelection += ' && chargedHadronEnergy/energy > 0.0' jetSelection += ' && chargedEmEnergy/energy < 0.99))' process.cleanJets = cms.EDProducer("PATJetCleaner", src = cms.InputTag("slimmedJets"), preselection = cms.string(jetSelection), checkOverlaps = cms.PSet( muons = cms.PSet( src = cms.InputTag("slimmedMuons"), algorithm = cms.string("byDeltaR"), preselection = cms.string(ccMuPreSel), deltaR = cms.double(0.5), checkRecoComponents = cms.bool(False), pairCut = cms.string(""), requireNoOverlaps = cms.bool(True), ), #electrons = cms.PSet( # src = cms.InputTag("slimmedElectrons"), # algorithm = cms.string("byDeltaR"), # preselection = cms.string(ccElePreSel), # deltaR = cms.double(0.5), # checkRecoComponents = cms.bool(False), # pairCut = cms.string(""), # requireNoOverlaps = cms.bool(True), #), ), finalCut = cms.string('') ) process.TFileService = cms.Service("TFileService", fileName = cms.string("stage_1_"+s.name+".root") ) #=============================================================================== # UFDiMuonAnalyzer if thisIsData: process.load("UfHMuMuCode.UFDiMuonsAnalyzer.UFDiMuonAnalyzer_cff") else: process.load("UfHMuMuCode.UFDiMuonsAnalyzer.UFDiMuonAnalyzer_MC_cff") process.dimuons = process.DiMuons.clone() process.dimuons.pfJetsTag = cms.InputTag("cleanJets") #=============================================================================== process.p = cms.Path(# process.cleanJets* process.dimuons ) #process.outpath = cms.EndPath() ## #Test to dump file content ## process.output = cms.OutputModule("PoolOutputModule", ## outputCommands = cms.untracked.vstring("keep *"), ## fileName = cms.untracked.string('dump.root') ## ) ## ## process.out_step = cms.EndPath(process.output) #=============================================================================== #process.source.fileNames.extend( #[ ##'file:/data/0b/digiovan/code/higgs/dev/addEle/CMSSW_5_3_3_patch3/src/UserArea/test/DYJetsToLL.root' ##"file:/data/uftrig01b/jhugon/hmumu/devNtupler/testFiles/VBFHToMM_M125_8TeV-powheg-pythia6-tauola-RECO_1.root" ##"file:/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_3_patch3/testPriVtxConstr/TTJetsSkims/TTJets_10_1_crI.root" ##"file:/home/jhugon/scratchRaid7/hmumu/recoData/VBFHToMM_M125_8TeV-powheg-pythia6-tauola-RECO_1.root" #] #) #process.out.outputCommands = cms.untracked.vstring("keep *") #process.outpath = cms.EndPath(process.out) #process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(20) )
UTF-8
Python
false
false
5,924
py
2
UFDiMuonAnalyzer.py
2
0.6342
0.618501
0
145
39.841379
116
ShayLn/py-fighter
17,944,373,399,712
e9ae4aaf3ae4d097e2d66a903ae07922421af2b2
52a8ba52146c6943e00b34b8f5823b21f2622fe3
/pyfighter.py
f03166b36baa6fdfa97506d30d43369b33911b6c
[ "MIT" ]
permissive
https://github.com/ShayLn/py-fighter
718db5d6f889abd2f078b2c11ad0ffd9d219cd24
01ace29afb066e6d5965d1fd460c5939c8b8c81b
refs/heads/master
2023-03-29T12:11:56.412382
2021-01-05T10:42:12
2021-01-05T10:42:12
327,468,085
0
0
MIT
true
2021-01-07T14:18:40
2021-01-07T01:09:33
2021-01-07T01:09:34
2021-01-05T10:42:16
106,958
0
0
1
null
false
false
''' Pyfighter (working title) A long time ago in a galaxy far, far away there existed in person tuition. But in the year 2020, COVID struck. All semester modules have been 100% online and you haven't seen your professors. So do they exist? Are they just a figment of your imagination? To cut costs, the university created AI professors to deliver your lectures and set your coursework. Exam season approaches and the evil Darth Virus has hacked your professors, multiplying them and making your exams harder. Only you can save your degree... Pyfighter is an 8-bit side scrolling, infinite level platform game, produced in python using PyGame as part on an MSc by R. Soane, R. Danevicius, and S. Mistry. Inspired by super street fighter, super smash bros and Mario, they created a customisable and addictive game that gets progressively harder. This file forms a start menu for the game. When selected, the game function is loaded as a new instance of pygame within the same window. Implemented in this way so that whenever the player quits the game, it goes back to the menu. ''' ### Library Imports import os import webbrowser import json import pygame from screens.game import pyfighterGame from screens.settings import SettingsMenu from classes.generalfunctions import quitGame from classes.menu import Menu from classes.menu import Button from classes.text import Text ### Important Game Variables from JSON with open('json/config.JSON') as config_file: config = json.load(config_file) # Colour tuples and font sizesd colour = config['colour'] font_size = config['font_size'] # Important screen variables screen_width = config['screen_dims'][0] screen_height = config['screen_dims'][1] max_fps = config['max_fps'] game_name = config['game_name'] ### Setting up Screen and clock menu_screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption(game_name) clock = pygame.time.Clock() ### Setting Icon logo_image = pygame.image.load(config['logo_location']) pygame.display.set_icon(logo_image) menu_background = config['start_menu_background'] menu_background_path = config['menu_music'] ### Setting up Menu # Menu Functions - These functions are passed into each menu button def playGame(): pyfighterGame() playMusic(menu_background_path) def playMusic(music_path): ### Setting up game music # - Music code inspired by code here: # https://riptutorial.com/pygame/example/24563/example-to-add-musi # c-in-pygame # - Found detail on setting volume on pygame docs pygame.mixer.init() pygame.mixer.music.load(music_path) pygame.mixer.music.play(-1) def loadAbout(): webbrowser.open('https://www.pyfighter.xyz/', new=2) def runSettings(): return 'settings' # String names menu_title = game_name play_text = 'Play' about_text = 'About' settings_text = 'Settings' quit_text = 'Quit' # Title position title_x = screen_width // 2 title_y = screen_height // 9 # Calculating (x,y) coords of buttons width_unit = screen_width // 6 height_unit = screen_height // 2 major_button_dims = (192, 64) offset = 20 about_position = (screen_width - 64 - offset, 32 + offset) # Creating pygame string objects title_obj = Text(menu_screen, (title_x, title_y), font_size['title'], menu_title, 'purple') play_button = Button(menu_screen, play_text, (1 * width_unit, height_unit), playGame, 35, major_button_dims) settings_button = Button(menu_screen, settings_text,(3 * width_unit, height_unit), runSettings, 30, major_button_dims) about_button = Button(menu_screen, about_text, about_position, loadAbout, 30) quit_button = Button(menu_screen, quit_text, (5 * width_unit, height_unit), quitGame, 35, major_button_dims) # Initialising StartMenu class start_menu = Menu(menu_screen, title_obj, menu_background, play_button, settings_button, about_button, quit_button) # Start Music playMusic(menu_background_path) # Found on pygame docs # https://www.pygame.org/docs/ref/cursors.html # Believe it makes the cursor look nicer in the game pygame.mouse.set_cursor(*pygame.cursors.tri_left) ### Main Game Loop while start_menu.playing: # Limit frame rate clock.tick(max_fps) # Get/action events for event in pygame.event.get(): # Send each event to the start menu button_out = start_menu.do(event) if button_out == 'settings': SettingsMenu(menu_screen, max_fps) # Refresh screen menu_screen.fill(colour['black']) ### Code to re-display items on screen will go here start_menu.display() # Display everything on screen pygame.display.flip() quitGame()
UTF-8
Python
false
false
4,821
py
35
pyfighter.py
20
0.702136
0.693217
0
159
29.308176
118
131131yhx/rchol
3,607,772,552,183
ee8e0cb1cae095068d05b5416d0569e64d179e82
498b99130944b81809627ffcf9bf3ae95eaa2660
/python/ex_reuse_partition.py
3fe180882beca002f447c93b3b221a22e0951e55
[ "BSD-3-Clause" ]
permissive
https://github.com/131131yhx/rchol
f5759b3ae04ed77eabfbf9be06437626bcc905b3
100c6264958beba9d7d87e93d1f8808a6cc6df34
refs/heads/master
2023-04-28T12:13:13.980643
2021-04-24T19:34:55
2021-04-24T19:34:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys sys.path.append('rchol/') import numpy as np from scipy.sparse import identity from numpy.linalg import norm from rchol import * from util import * # Initial problem: 3D-Poisson n = 20 A = laplace_3d(n) # see ./rchol/util.py # random RHS N = A.shape[0] b = np.random.rand(N) print("Initial problem:") # compute preconditioner after reordering (multi thread) nthreads = 2 G, perm, part = rchol(A, nthreads) Aperm = A[perm[:, None], perm] print('fill-in ratio: {:.2}'.format(2*G.nnz/A.nnz)) # solve with PCG tol = 1e-6 maxit = 200 x, relres, itr = pcg(Aperm, b[perm], tol, maxit, G, G.transpose().tocsr()) print('# CG iterations: {}'.format(itr)) print('Relative residual: {:.2e}\n'.format(relres)) # perturb the original matrix B = A + 1e-3*identity(N) print('New problem (same sparsity) ...') # compute preconditioner with existing permutation/partition L = rchol(B, nthreads, perm, part)[0] print('fill-in ratio: {:.2}'.format(2*L.nnz/A.nnz)) # solve the new problem Bperm = B[perm[:, None], perm] x, relres, itr = pcg(Bperm, b[perm], tol, maxit, L, L.transpose().tocsr()) print('# CG iterations: {}'.format(itr)) print('Relative residual: {:.2e}\n'.format(relres))
UTF-8
Python
false
false
1,190
py
48
ex_reuse_partition.py
25
0.679832
0.663025
0
44
25.977273
74
qwertyuu/old-code-backup
644,245,107,622
d418f6a30acd2535a28407674eb42201a24bfbea
af396ad814ec4bf1849908c7f83b402ae191fab2
/2k16/QualityContent/QualityContent/QualityContent.py
c1024dbcb08871672c54a221d0ce3ace14469ac7
[]
no_license
https://github.com/qwertyuu/old-code-backup
bab805dda171814bf72aa9b3693827667819f56c
6a47b8d9f18e01a90be2de9267d955851e413f9a
refs/heads/main
2023-02-20T04:52:28.362866
2021-01-22T08:36:54
2021-01-22T08:36:54
331,884,338
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests import json import pprint def login(username, password, header): """logs into reddit, saves cookie""" print 'begin log in' #username and password UP = {'user': username, 'passwd': password, 'api_type': 'json',} #POST with user/pwd client = requests.session() client.headers.update(header) r = client.post('http://www.reddit.com/api/login', data=UP) #print r.text #print r.cookies #gets and saves the modhash print r.text j = json.loads(r.text) client.modhash = j['json']['data']['modhash'] print '{USER}\'s modhash is: {mh}'.format(USER=username, mh=client.modhash) client.user = username def name(): return '{}\'s client'.format(username) #pp2(j) return client header={'user-agent' : 'qualitybot/2.0',} chose = login('Quality_Posts', 'qw3rtyui0p', header) r = chose.post('http://www.reddit.com/api/comment', data={'api_type': 'json', 'text' : '\>/r/DotA2\n\n\>Quality Content\n\nPick one.', 'thing_id' : 't3_2817zd', 'uh' : chose.modhash, }) print json.loads(r.text) raw_input()
UTF-8
Python
false
false
1,099
py
409
QualityContent.py
33
0.631483
0.621474
0
40
26.45
185
ufomysis/cartbot
8,667,244,019,518
8673d830589b49d954e94a57c883a13254edd9da
401900b0ed64dc00775ef4bb39ff9d37fc7566b4
/remove_invalid.py
200d361ad489f4d5b756a2929c918836a57ff21a
[]
no_license
https://github.com/ufomysis/cartbot
9e6c6809008c1b3b9565949b8dcd4fdf0ff3e4dc
14b8544b7586df22025674a7dfa0d4b38cfcaca4
refs/heads/master
2021-01-23T20:12:12.574211
2013-04-13T14:37:54
2013-04-13T14:37:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys,json import os.path file_in = open(sys.argv[1], 'r') obj = json.load(file_in) for x in list(obj.keys()): if not os.path.exists(obj[x][0]): del(obj[x]) file_out = open(sys.argv[2], 'w') json.dump(obj,file_out)
UTF-8
Python
false
false
235
py
8
remove_invalid.py
6
0.617021
0.604255
0
12
18.583333
37
sajanraj/Optical-Character-Recognition
13,589,276,565,562
4d8acbb045c482a90fc7a67577b9fed8ce3139ba
474e4059af0858ddcafaa61f61eeecb2626888df
/pancheck.py
a7e014f5b811b13ebf3db931e47099708147f10e
[ "MIT" ]
permissive
https://github.com/sajanraj/Optical-Character-Recognition
258416fa3a5ab97623fad2e4cdc904ccaf96dbef
a21064457322089a1ddeaedd49ffe4bc619000a5
refs/heads/master
2023-03-20T07:17:47.326224
2021-02-28T05:04:36
2021-02-28T05:04:36
213,962,684
1
0
null
false
2021-02-28T05:04:36
2019-10-09T16:02:02
2020-05-07T12:59:12
2021-02-28T05:04:36
3,123
0
0
0
Python
false
false
# -*- coding: utf-8 -*- # import the necessary packages # construct the argument parse and parse the arguments def ocr(imgdata,pan,preprs): print('path1=',imgdata) from PIL import Image import pytesseract import cv2 import os path=os.getcwd() print('pathos=',str(path)) from pdf2image import convert_from_path # load the example image and convert it to grayscale if imgdata.lower().endswith(('.pdf')): filename = "{}.jpg".format(os.getpid()) pages = convert_from_path(imgdata, 200) for page in pages: page.save(filename, 'JPEG') image = cv2.imread(filename) else: image = cv2.imread(imgdata) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # check to see if we should apply thresholding to preprocess the # image if preprs == "thresh": gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] # make a check to see if median blurring should be done to remove # noise elif argspreprs == "blur": gray = cv2.medianBlur(gray, 3) # write the grayscale image to disk as a temporary file so we can # apply OCR to it filename = "{}.png".format(os.getpid()) cv2.imwrite(filename, gray) # load the image as a PIL/Pillow image, apply OCR, and then delete # the temporary file text = pytesseract.image_to_string(Image.open(filename)) os.remove(filename) flagis=0 text = text.lower() print(text) word = text.find(pan.lower()) if (word > 0): flagis=1 print(flagis) return text,flagis #Return url # show the output images #cv2.imshow("Image", image) #cv2.imshow("Output", gray) #cv2.waitKey(0)
UTF-8
Python
false
false
1,804
py
4
pancheck.py
3
0.609202
0.592572
0
61
27.540984
70
abeljim/SSDK
19,327,352,840,960
5a9417108f96f7dc42392b87f93f004e41a65202
6effe32673d1dcb7d86a81991ea3a35e82ed4533
/SA_cap_figures.py
4b208b81b46504d767828151cd941ad5d807688b
[]
no_license
https://github.com/abeljim/SSDK
406eb903a8349a11cf3aedddcd45444e9ce9d8f3
84edc24e27a6b0b69831f1eae7b8ad668ae217e4
refs/heads/master
2020-09-10T20:04:32.910237
2019-11-15T16:35:11
2019-11-15T16:35:11
221,822,185
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np from zipfile import ZipFile import matplotlib.pyplot as plt import scipy from scipy import signal import mdat def plothot(i, run, steps, cvmin, cvmax, plotmin, plotmax, plot, alpha=1): sweeprate = steps[i] # Create a dummy array onto which we can append data buffer = [run[s] for s in run.keys() if i in s][0][0:1] # In the dictionary Run01, there are steps that are named (Step01, etc) # similarly to the step that was identified as having a sweep rate of 5 # take these arrays and process them in the following loop for iv in [run[s] for s in run.keys() if i in s]: # iv[:,2] = iv[:,2] * 1000 # Convert A to mA iv = iv[np.where(iv[:,1] > plotmin)] iv = iv[np.where(iv[:,1] < plotmax)] buffer = np.concatenate((buffer, iv)) plot.plot(iv[:,1], scipy.signal.savgol_filter(iv[:,2], 7, 2)*1000, mdat.colors1[steps[i]], alpha=alpha) iv = iv[:,1:3] iv = iv[np.where(iv[:,0] > cvmin)] iv = iv[np.where(iv[:,0] < cvmax)] # if len(buffer) >= 2: buffer = buffer[1:] buffer = buffer[np.where(buffer[:,1] > cvmin)] buffer = buffer[np.where(buffer[:,1] < cvmax)] potmax = np.nan try: if buffer[0,1] > buffer[-1,1]: # A 'true' here indicates sweep down potmax = buffer[np.where(buffer[:,2] == np.amin(buffer[:,2]))][0][1] imax = np.mean(buffer[np.where(np.abs(buffer[:,1]-potmax) <= 0.005)][:,2]) return potmax, imax*1000, sweeprate elif buffer[0,1] < buffer[-1,1]: # A 'true' here indicates sweep up potmax = buffer[np.where(buffer[:,2] == np.amax(buffer[:,2]))][0][1] imax = np.mean(buffer[np.where(np.abs(buffer[:,1]-potmax) <= 0.005)][:,2]) return potmax, imax*1000, sweeprate except: return buffer #### #### #### #### #### #### Set variables for the program here wdir = "C:/Users/MummLab/Sierra/CV/" file_names = [ '6-21-18_ME.mdat', '7-26-18_planar_pellet_CV.mdat', '7-16-18_P_powder_CV.mdat', '8-14-18_bijel#10_CV.zip', '7-26-18_planar_bijels_CV.zip' ] #### #### #### #### #### #### Start the program figure, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 3)) ax1.set_yticklabels([]) ax2.set_yticklabels([]) ax3.set_yticklabels([]) plotmin, plotmax = -0.5, 0.8 # Set the limits for the plot here results = np.asarray([['data'], [5],[-5],[10],[-10],[25],[-25],[50],[-50],[100],[-100],[250],[-250]]) """ """ file_path= str(wdir + file_names[0]) run, runlist = mdat.importdata(file_path) steps = {} # make a dictionary with steps and sweep rates for line in runlist: if line.startswith(b'Potentiodynamic'): steps[str(line)[str(line).find("Step"):str(line).find("Step")+6]] = str(line)[str(line).find(",", str(line).find("mV/S")-5, str(line).find("mV/S"))+1:str(line).find("mV/S")] try: del steps['Step02'] # remove the first (Step02) wchich is technically potentiodynamic but not the CV section except: print('No Step02!') sweeps = [] if 'ME' in file_names[0]: cvmin, cvmax = 0.2, 0.4 # Set the limits for the duck curve here elif 'MicroElec' in file_names[0]: cvmin, cvmax = 0.2, 0.4 # Set the limits for the duck curve here elif '#' in file_names[0]: cvmin, cvmax = -0.2, 0.55 # Set the limits for the duck curve here elif 'powder' in file_names[0]: cvmin, cvmax = -0.2, 0.8 # Set the limits for the duck curve here elif 'med' in file_names[0]: cvmin, cvmax = 0.2, 0.6 # Set the limits for the duck curve here elif 'planar' in file_names[0]: cvmin, cvmax = 0.2, 0.6 # Set the limits for the duck curve here # For every named step in the steps dictionary (Step01, Step02, etc) for i in steps.keys(): #print(i) """ Cathodic peaks are simple to find, but the anodic peaks can be convoluted by gas evolution. Use these peaks for SA with caution! Because of this convolution, the peaks must be selected by finding either where the first derivative makes a minima, or where the second derivative crosses the x axis """ sweep = run[i + '_Rp01'][:,1:3] # first derivative sweep = np.concatenate((run[i + '_Rp01'][:,1:3], np.zeros((len(sweep),1))), axis=1) sweep[:,1] = scipy.signal.savgol_filter(sweep[:,1], 71, 2) for i_n in np.arange(5,len(sweep)-5): sweep[i_n, 2] = (sweep[i_n+5,1] - sweep[i_n-5,1]) / (sweep[i_n+5,0] - sweep[i_n-5,0]) sweep = sweep[10:-10] sweep[:,2] = scipy.signal.savgol_filter(sweep[:,2], 71, 2) # second derivative sweep = np.concatenate((sweep, np.zeros((len(sweep),1))), axis=1) for i_n in np.arange(1,len(sweep)-1): sweep[i_n, 3] = (sweep[i_n+1,2] - sweep[i_n-1,2]) / (sweep[i_n+1,0] - sweep[i_n-1,0]) sweep = sweep[1:-1] sweep[:,3] = scipy.signal.savgol_filter(sweep[:,3], 51, 3) sweep = sweep[np.where(sweep[:,0] >= 0.4)] if sweep[0,0] <= sweep[-1,0]: n = len(sweep) - 1 if sweep[np.where(sweep[:,1] == np.amin(sweep[:,1])),0][0][0] >= cvmax: cvmax1 = sweep[np.where(sweep[:,1] == np.amin(sweep[:,1])),0][0][0] elif sweep[np.where(sweep[:,2] == np.amin(sweep[:,2])),0][0][0] >= 0.4: cvmax1 = sweep[np.where(sweep[:,2] == np.amin(sweep[:,2])),0][0][0] else: cvmax1 = sweep[np.where(((np.roll(np.sign(sweep[:,3]), 1) - np.sign(sweep[:,3])) != 0).astype(int) == 1)[0][-1]][0] cvmin1 = cvmin else: cvmin1, cvmax1 = cvmin, cvmax point = plothot(i, run, steps, cvmin1, cvmax1, plotmin, plotmax, ax1, mdat.alpha) try: ax1.scatter(point[0], point[1], s=150, c=mdat.colors3[point[2]], zorder=4) point = np.asarray(point) sweeps.append(point) point[2] = float(point[2]) #ax1.ylabel('Current (mA)', fontproperties=mdat.font) ax1.xlabel('Potential (V) vs Ag/AgCl (1M KCl)', fontproperties=mdat.font) except: print(' No peak for ' + i) dlayer_cap = np.asarray(sweeps, dtype=float) dlayer_cap[np.where(dlayer_cap[:,1] < 0)[0]][:,2] = dlayer_cap[np.where(dlayer_cap[:,1] < 0)[0]][:,2] * -1 cathodic = np.asarray([point for point in dlayer_cap if float(point[1]) <= 0]) anodic = np.asarray([point for point in dlayer_cap if float(point[1]) >= 0]) ax1.set_ylim([1.1 * cathodic[-1,1], 1.1 * anodic[-1,1]]) """ """ file_path= str(wdir + file_names[1]) run, runlist = mdat.importdata(file_path) steps = {} # make a dictionary with steps and sweep rates for line in runlist: if line.startswith(b'Potentiodynamic'): steps[str(line)[str(line).find("Step"):str(line).find("Step")+6]] = str(line)[str(line).find(",", str(line).find("mV/S")-5, str(line).find("mV/S"))+1:str(line).find("mV/S")] try: del steps['Step02'] # remove the first (Step02) wchich is technically potentiodynamic but not the CV section except: print('No Step02!') sweeps = [] if 'ME' in file_names[1]: cvmin, cvmax = 0.2, 0.4 # Set the limits for the duck curve here elif 'MicroElec' in file_names[1]: cvmin, cvmax = 0.2, 0.4 # Set the limits for the duck curve here elif '#' in file_names[1]: cvmin, cvmax = -0.2, 0.55 # Set the limits for the duck curve here elif 'powder' in file_names[1]: cvmin, cvmax = -0.2, 0.8 # Set the limits for the duck curve here elif 'med' in file_names[1]: cvmin, cvmax = 0.2, 0.6 # Set the limits for the duck curve here elif 'planar' in file_names[1]: cvmin, cvmax = 0.2, 0.6 # Set the limits for the duck curve here # For every named step in the steps dictionary (Step01, Step02, etc) for i in steps.keys(): #print(i) """ Cathodic peaks are simple to find, but the anodic peaks can be convoluted by gas evolution. Use these peaks for SA with caution! Because of this convolution, the peaks must be selected by finding either where the first derivative makes a minima, or where the second derivative crosses the x axis """ sweep = run[i + '_Rp01'][:,1:3] # first derivative sweep = np.concatenate((run[i + '_Rp01'][:,1:3], np.zeros((len(sweep),1))), axis=1) sweep[:,1] = scipy.signal.savgol_filter(sweep[:,1], 71, 2) for i_n in np.arange(5,len(sweep)-5): sweep[i_n, 2] = (sweep[i_n+5,1] - sweep[i_n-5,1]) / (sweep[i_n+5,0] - sweep[i_n-5,0]) sweep = sweep[10:-10] sweep[:,2] = scipy.signal.savgol_filter(sweep[:,2], 71, 2) # second derivative sweep = np.concatenate((sweep, np.zeros((len(sweep),1))), axis=1) for i_n in np.arange(1,len(sweep)-1): sweep[i_n, 3] = (sweep[i_n+1,2] - sweep[i_n-1,2]) / (sweep[i_n+1,0] - sweep[i_n-1,0]) sweep = sweep[1:-1] sweep[:,3] = scipy.signal.savgol_filter(sweep[:,3], 51, 3) sweep = sweep[np.where(sweep[:,0] >= 0.4)] if sweep[0,0] <= sweep[-1,0]: n = len(sweep) - 1 if sweep[np.where(sweep[:,1] == np.amin(sweep[:,1])),0][0][0] >= cvmax: cvmax1 = sweep[np.where(sweep[:,1] == np.amin(sweep[:,1])),0][0][0] elif sweep[np.where(sweep[:,2] == np.amin(sweep[:,2])),0][0][0] >= 0.4: cvmax1 = sweep[np.where(sweep[:,2] == np.amin(sweep[:,2])),0][0][0] else: cvmax1 = sweep[np.where(((np.roll(np.sign(sweep[:,3]), 1) - np.sign(sweep[:,3])) != 0).astype(int) == 1)[0][-1]][0] cvmin1 = cvmin else: cvmin1, cvmax1 = cvmin, cvmax point = plothot(i, run, steps, cvmin1, cvmax1, plotmin, plotmax, ax2, mdat.alpha) try: ax2.scatter(point[0], point[1], s=150, c=mdat.colors3[point[2]], zorder=4) point = np.asarray(point) sweeps.append(point) point[2] = float(point[2]) #ax1.ylabel('Current (mA)', fontproperties=mdat.font) ax2.xlabel('Potential (V) vs Ag/AgCl (1M KCl)', fontproperties=mdat.font) except: print(' No peak for ' + i) dlayer_cap = np.asarray(sweeps, dtype=float) dlayer_cap[np.where(dlayer_cap[:,1] < 0)[0]][:,2] = dlayer_cap[np.where(dlayer_cap[:,1] < 0)[0]][:,2] * -1 cathodic = np.asarray([point for point in dlayer_cap if float(point[1]) <= 0]) anodic = np.asarray([point for point in dlayer_cap if float(point[1]) >= 0]) ax2.set_xlim(plotmin, plotmax) ax2.set_ylim([1.1 * cathodic[-1,1], 1.1 * anodic[-1,1]]) """ """ file_path= str(wdir + file_names[2]) run, runlist = mdat.importdata(file_path) steps = {} # make a dictionary with steps and sweep rates for line in runlist: if line.startswith(b'Potentiodynamic'): steps[str(line)[str(line).find("Step"):str(line).find("Step")+6]] = str(line)[str(line).find(",", str(line).find("mV/S")-5, str(line).find("mV/S"))+1:str(line).find("mV/S")] try: del steps['Step02'] # remove the first (Step02) wchich is technically potentiodynamic but not the CV section except: print('No Step02!') sweeps = [] if 'ME' in file_names[2]: cvmin, cvmax = 0.2, 0.4 # Set the limits for the duck curve here elif 'MicroElec' in file_names[2]: cvmin, cvmax = 0.2, 0.4 # Set the limits for the duck curve here elif '#' in file_names[2]: cvmin, cvmax = -0.2, 0.55 # Set the limits for the duck curve here elif 'powder' in file_names[2]: cvmin, cvmax = -0.2, 0.8 # Set the limits for the duck curve here elif 'med' in file_names[2]: cvmin, cvmax = 0.2, 0.6 # Set the limits for the duck curve here elif 'planar' in file_names[2]: cvmin, cvmax = 0.2, 0.6 # Set the limits for the duck curve here # For every named step in the steps dictionary (Step01, Step02, etc) for i in steps.keys(): #print(i) """ Cathodic peaks are simple to find, but the anodic peaks can be convoluted by gas evolution. Use these peaks for SA with caution! Because of this convolution, the peaks must be selected by finding either where the first derivative makes a minima, or where the second derivative crosses the x axis """ sweep = run[i + '_Rp01'][:,1:3] # first derivative sweep = np.concatenate((run[i + '_Rp01'][:,1:3], np.zeros((len(sweep),1))), axis=1) sweep[:,1] = scipy.signal.savgol_filter(sweep[:,1], 71, 2) for i_n in np.arange(5,len(sweep)-5): sweep[i_n, 2] = (sweep[i_n+5,1] - sweep[i_n-5,1]) / (sweep[i_n+5,0] - sweep[i_n-5,0]) sweep = sweep[10:-10] sweep[:,2] = scipy.signal.savgol_filter(sweep[:,2], 71, 2) # second derivative sweep = np.concatenate((sweep, np.zeros((len(sweep),1))), axis=1) for i_n in np.arange(1,len(sweep)-1): sweep[i_n, 3] = (sweep[i_n+1,2] - sweep[i_n-1,2]) / (sweep[i_n+1,0] - sweep[i_n-1,0]) sweep = sweep[1:-1] sweep[:,3] = scipy.signal.savgol_filter(sweep[:,3], 51, 3) sweep = sweep[np.where(sweep[:,0] >= 0.4)] if sweep[0,0] <= sweep[-1,0]: n = len(sweep) - 1 if sweep[np.where(sweep[:,1] == np.amin(sweep[:,1])),0][0][0] >= cvmax: cvmax1 = sweep[np.where(sweep[:,1] == np.amin(sweep[:,1])),0][0][0] elif sweep[np.where(sweep[:,2] == np.amin(sweep[:,2])),0][0][0] >= 0.4: cvmax1 = sweep[np.where(sweep[:,2] == np.amin(sweep[:,2])),0][0][0] else: cvmax1 = sweep[np.where(((np.roll(np.sign(sweep[:,3]), 1) - np.sign(sweep[:,3])) != 0).astype(int) == 1)[0][-1]][0] cvmin1 = cvmin else: cvmin1, cvmax1 = cvmin, cvmax point = plothot(i, run, steps, cvmin1, cvmax1, plotmin, plotmax, ax3, mdat.alpha) try: ax3.scatter(point[0], point[1], s=150, c=mdat.colors3[point[2]], zorder=4) point = np.asarray(point) sweeps.append(point) point[2] = float(point[2]) #ax1.ylabel('Current (mA)', fontproperties=mdat.font) ax3.xlabel('Potential (V) vs Ag/AgCl (1M KCl)', fontproperties=mdat.font) except: print(' No peak for ' + i) dlayer_cap = np.asarray(sweeps, dtype=float) dlayer_cap[np.where(dlayer_cap[:,1] < 0)[0]][:,2] = dlayer_cap[np.where(dlayer_cap[:,1] < 0)[0]][:,2] * -1 cathodic = np.asarray([point for point in dlayer_cap if float(point[1]) <= 0]) anodic = np.asarray([point for point in dlayer_cap if float(point[1]) >= 0]) ax3.set_ylim([1.1 * cathodic[-1,1], 1.1 * anodic[-1,1]])
UTF-8
Python
false
false
14,569
py
44
SA_cap_figures.py
40
0.576086
0.528863
0
354
40.155367
185
dunsmoorlab/fearcon
15,015,205,699,726
35941350cfb0f33adaa76efd1a956291043ad957
51a8770d852af6d01158a1dba6ca37ea96eb7ed8
/estimate_bs.py
9308ea7620cb88e947e74c8c882f272939c3f45e
[]
no_license
https://github.com/dunsmoorlab/fearcon
4c322db3f3634a1c4f98918b9157725421786f48
78282c4f9b987d302b68d3dc4d78c05778fe5b14
refs/heads/master
2022-12-12T11:31:51.810749
2020-09-18T20:47:44
2020-09-18T20:47:44
102,023,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from glob import glob import os from fc_config import * from glm_timing import * from preprocess_library import meta from shutil import copytree, move from argparse import ArgumentParser, RawTextHelpFormatter from mvpa2.misc.fsl.base import FslGLMDesign, read_fsl_design from mvpa2.datasets.mri import fmri_dataset, map2nifti import numpy as np import scipy.stats from scipy.stats.mstats import zscore def group_beta(phases=None, subs=None): #ptsd or controls if subs == 'p': subs = p_sub_args elif subs == 'c': subs = sub_args elif subs == 'no107': subs = no107 elif subs == 'all': subs = all_sub_args for phase in phases: print(phase) #set the number of trials n_trials = beta_n_trials[phase] print(n_trials) for sub in subs: print(sub) subj = meta(sub) #check to make sure all the timing files are there onsets = glob('%s/%s/model/GLM/onsets/%s/betaseries/trial**.txt'%(data_dir, subj.fsub, py_run_key[phase])) if len(onsets) != n_trials * len(subs): pop_beta_timing(phase=phase, subs=[sub]) #check to make sure all of the fsf design files are there fsfs = glob('%s/%s/bold/%s/fsl_betas/%s_beta.fsf'%(data_dir, subj.fsub, phase2rundir[phase], py_run_key[phase])) if len(fsfs) != len(subs): populate_beta_fsf(phase=phase, subs=[sub]) #now were ready to estimate the betas! estimate_betaseries(sub=sub,n_trials=n_trials,phase=phase,mask=None,no_zscore=True) def pop_beta_timing(phase=None, subs=None): print('Populating beta timing files') if isinstance(phase, str): phase = [phase] for sub in subs: for run in phase: # if 'localizer' in run: glm_timing(sub, run).loc_blocks(beta=True) # if 'extinction_recall' in run: glm_timing(sub, run).betaseries(er_start=True) glm_timing(sub, run).betaseries() def populate_beta_fsf(phase=None, subs=None): print('Populating beta design files') template = os.path.join(data_dir,'beta_templates',py_run_key[phase] + '_template.fsf') for sub in subs: subj = meta(sub) outdir = os.path.join(subj.bold_dir,phase2rundir[phase],'fsl_betas') if not os.path.exists(outdir): os.mkdir(outdir) outfile = os.path.join(outdir, py_run_key[phase] + '_beta.fsf') replacements = {'SUBJID':subj.fsub, 'RUNID':py_run_key[phase]} with open(template) as temp: with open(outfile,'w') as out: for line in temp: for src, target in replacements.items(): line = line.replace(src, target) out.write(line) def estimate_betaseries(sub=0,n_trials=0,phase=None,mask=None,no_zscore=True): subj = meta(sub) # find FSF files for this subject model_dir = os.path.join(subj.bold_dir,phase2rundir[phase],'fsl_betas') if not os.path.exists(model_dir): os.mkdir(model_dir) ''' pattern = os.path.join(model_dir, 'fsf', '{}_{}*.fsf'.format(args.model, args.subject)) fsf_files = glob(pattern) if not fsf_files: raise IOError('No FSF files found matching: {}'.format(pattern)) fsf_files.sort() log.start() ''' fsf_files = [os.path.join(model_dir,'%s_beta.fsf'%(py_run_key[phase]))] # temporary subject directory for individual beta images ''' out_dir = os.path.join(model_dir, 'beta', args.subject) log.run('mkdir -p {}'.format(out_dir)) ''' out_dir = model_dir beta_files = [] for f in fsf_files: # use a feat utility to create the design matrix (base, ext) = os.path.splitext(f) name = os.path.basename(base) os.system('feat_model {}'.format(base)) design = read_fsl_design(f) bold = design['feat_files'] if not bold.endswith('.nii.gz'): bold += '.nii.gz' if not os.path.exists(bold): raise IOError('BOLD file not found: {}'.format(bold)) # obtain individual trial estimates betaseries(base=base, out_dir=out_dir, n_trials=n_trials, mask=mask, no_zscore=no_zscore) # # get one file with estimates for each trial/stimulus beta_file = os.path.join(out_dir, name + '.nii.gz') ev_files = [] for i in range(n_trials): ev_files.append(os.path.join(out_dir, 'ev{:03d}.nii.gz'.format(i))) os.system('fslmerge -t {} {}'.format(beta_file, ' '.join(ev_files))) beta_files.append(beta_file) # remove temp files os.system('rm {}'.format(' '.join(ev_files))) os.system('rm {}*.{{con,png,ppm,frf,mat,min,trg}}'.format(base)) def betaseries(base=None,out_dir=None,n_trials=0,mask=None,no_zscore=True): s = """Estimate betaseries using LS-S regression. See Mumford et al. 2014 for details. Specify the base for a design generated by FEAT. For example, if you have a .fsf file in mydesign.fsf, specify mydesign as the modelbase. The trial regressors are assumed to be in your original EVs (as opposed to the real EVs, which include for example temporal derivatives of the original EVs). The trials to model are assumed to be the first ones listed. For example, if 30 orig EVs are included in the model, and ntrials is set to 20, then the last 10 EVs are assumed to be modeling things other than the individual trials. The exception are temporal derivatives of the trial EVs, which are assumed to be interleaved with the original trial EVs. If derivatives are included in the model, they will be included as additional regressors. If --sep-derivs is included as an option, then the current trial derivative and other trial derivatives will be estimated separately. For unknown reasons, each trial image is z-scored over voxels. This means that the value o f a voxel in a given trial image will depend on things like the size of the mask and values at other voxels. For legacy purposes, for now that is still the default. To write raw betaseries estimates, use the --no-zscore flag. You may also specify confound regressors (defined in the fsf file under 'confoundev_files'), which will be included as regressors of no interest. """ # parser = ArgumentParser(description="Estimate betaseries using LS-S regression (Mumford et al. 2014).") # parser.add_argument('modelbase', type=str, # help="path to model files, without file extension") # parser.add_argument('betadir', type=str, # help="path to directory in which to save betaseries image") # parser.add_argument('ntrials', type=int, # help="number of trials to be estimated") # parser.add_argument('-m', '--mask', type=str, # help="(optional) path to mask image, indicating included voxels") # parser.add_argument('-n', '--no-zscore', action="store_true", # help="do not z-score trial images over voxels") # parser.add_argument('-s', '--sep-derivs', action="store_true", # help="use separate trial and other derivative regressors") # args = parser.parse_args() fsffile = base + '.fsf' matfile = base + '.mat' betadir = out_dir n_trial = n_trials print("Loading design...") design = read_fsl_design(fsffile) desmat = FslGLMDesign(matfile) n_tp, n_evs = desmat.mat.shape # number of original regressors and all regressors including # derivatives n_orig = design['fmri(evs_orig)'] # check which trial regressors have temporal derivatives isderiv = np.zeros(n_orig, dtype=bool) for i in range(n_orig): f = 'fmri(deriv_yn{:d})'.format(i+1) isderiv[i] = design[f] # check if derivatives are included for all trials n_trial_deriv = np.sum(isderiv) if n_trial_deriv == n_trial: deriv = True elif n_trial_deriv == 0: deriv = False else: raise ValueError('Must either include derivatives for all trials or none.') if deriv: # temporal derivatives are included. FEAT interleaves them with # the original ones, starting with the first original regressor n_trial_evs = n_trial * 2 trial_evs = range(0, n_trial_evs, 2) deriv_evs = range(1, n_trial_evs, 2) print("Using derivatives of trial regressors.") else: # trial regressors are just the first N regressors n_trial_evs = n_trial trial_evs = range(0, n_trial) deriv_evs = [] # find input bold data print("Loading data...") bold = design['feat_files'] if not bold.endswith('.nii.gz'): bold += '.nii.gz' if not os.path.exists(bold): raise IOError('BOLD file not found: {}'.format(bold)) #if args.mask is not None: if mask is not None: # user specified a mask if not mask.endswith('.nii.gz'): mask += '.nii.gz' if not os.path.exists(mask): raise IOError('Mask file not found: {}'.format(mask)) data = fmri_dataset(bold, mask=mask) else: # load all voxels data = fmri_dataset(bold) # everything after the trial EVs is regressors of no interest dm_extra = desmat.mat[:,n_trial_evs:] # additional confound regressors if 'confoundev_files' in design: conf_file = design['confoundev_files'] print("Loading confound file {}...".format(conf_file)) dm_nuisance = np.loadtxt(conf_file) else: print("No confound file indicated. Including no confound regressors...") dm_nuisance = None # create a beta-forming vector for each trial print("Creating design matrices...") beta_maker = np.zeros((n_trial, n_tp)) sep_derivs = False for i, ev in enumerate(trial_evs): # this trial if deriv and sep_derivs: # if using separate derivatives, include a dedicated regressor # for this trial dm_trial = np.hstack((desmat.mat[:,ev,np.newaxis], desmat.mat[:,deriv_evs[i],np.newaxis])) else: # just the one regressor for this trial dm_trial = desmat.mat[:,ev,np.newaxis] # other trials, summed together other_trial_evs = [x for x in trial_evs if x != ev] if deriv: if args.sep_derivs: # only include derivatives except for this trial other_deriv_evs = [x for x in deriv_evs if x != deriv_evs[i]] dm_otherevs = np.hstack(( np.sum(desmat.mat[:,other_trial_evs,np.newaxis],1), np.sum(desmat.mat[:,other_deriv_evs,np.newaxis],1))) else: # put all derivatives in one regressor dm_otherevs = np.hstack(( np.sum(desmat.mat[:,other_trial_evs,np.newaxis],1), np.sum(desmat.mat[:,deriv_evs,np.newaxis],1))) else: # just one regressor for all other trials dm_otherevs = np.sum(desmat.mat[:,other_trial_evs,np.newaxis],1) # put together the design matrix if dm_nuisance is not None: dm_full = np.hstack((dm_trial, dm_otherevs, dm_nuisance, dm_extra)) else: dm_full = np.hstack((dm_trial, dm_otherevs, dm_extra)) s = dm_full.shape dm_full = dm_full - np.kron(np.ones(s), np.mean(dm_full,0))[:s[0],:s[1]] dm_full = np.hstack((dm_full, np.ones((n_tp,1)))) # calculate beta-forming vector beta_maker_loop = np.linalg.pinv(dm_full) beta_maker[i,:] = beta_maker_loop[0,:] print("Estimating model...") # this uses Jeanette's trick of extracting the beta-forming vector for each # trial and putting them together, which allows estimation for all trials # at once glm_res_full = np.dot(beta_maker, data.samples) # map the data into images and save to betaseries directory for i in range(len(glm_res_full)): if no_zscore: ni = map2nifti(data, glm_res_full[i]) else: outdata = zscore(glm_res_full[i]) ni = map2nifti(data, data=outdata) ni.to_filename(os.path.join(betadir, 'ev{:03d}.nii.gz'.format(i))) def clean_old_betas(p=False): if p: subs = working_subs else: subs = sub_args for sub in subs: subj = meta(sub) for phase in ['localizer_1','localizer_2']: rundir = subj.bold_dir + phase2rundir[phase] target = os.path.join(rundir,'old_betas') os.mkdir(target) move(os.path.join(rundir,'ls-s_betas'),target) move(os.path.join(rundir,'new_ls-s_betas'),target)
UTF-8
Python
false
false
11,385
py
341
estimate_bs.py
122
0.691085
0.686166
0
350
31.531429
115
fylein/fyle-qbo-api
15,229,954,032,034
cdf4434dcd92938adf008bcb777003f69c17c518
a5564fbf541b4fb602f5ad47aa5d06441bcf9f0a
/apps/tasks/migrations/0005_tasklog_qbo_expense.py
5a7e3bb569647b23f62149a6a4aeabcd48a35872
[ "MIT" ]
permissive
https://github.com/fylein/fyle-qbo-api
1fc222501276ebf0f316f43bb278a6adcc0e08ce
b4c464cc6442ead91ceb3b2840103b27af3e029c
refs/heads/master
2023-08-31T06:26:07.296341
2023-08-24T15:45:55
2023-08-24T15:45:55
243,419,752
1
3
MIT
false
2023-09-07T13:31:53
2020-02-27T03:15:01
2023-07-25T14:33:19
2023-09-07T13:31:52
9,991
1
3
3
Python
false
false
# Generated by Django 3.0.3 on 2021-05-04 19:13 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [('quickbooks_online', '0010_qboexpense_qboexpenselineitem'), ('tasks', '0004_tasklog_bill_payment')] operations = [migrations.AddField(model_name='tasklog', name='qbo_expense', field=models.ForeignKey(help_text='Reference to QBO Expense', null=True, on_delete=django.db.models.deletion.PROTECT, to='quickbooks_online.QBOExpense'))]
UTF-8
Python
false
false
522
py
279
0005_tasklog_qbo_expense.py
242
0.760536
0.716475
0
11
46.454545
234
IgorFedchenko/TicketSystem
9,062,380,994,598
ee9ac034d58d2cb77e7a54b73052eca5c169d45d
a94409c79b9ca3ecbbe5fe82971470c58aa3e57f
/TicketSystem/urls.py
5d163447865edb0c4a875adf828c1058c3e6ec3b
[]
no_license
https://github.com/IgorFedchenko/TicketSystem
d26e57774ba20a07ec9926b32f14e2a583d231a7
3038c62e4fb205b1b9687022c512256b256c3391
refs/heads/master
2016-09-02T04:35:21.934804
2015-06-26T11:26:20
2015-06-26T11:26:20
27,052,482
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, include, url from django.contrib import admin from tickets import views from tickets import api urlpatterns = patterns('', # Examples: # url(r'^$', 'TicketSystem.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', views.tickets_list), url(r'^api/$', api.ExternalApi.as_view()), url(r'^admin/', include(admin.site.urls)), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'tickets/login.html'}), url(r'^password_change/$', 'django.contrib.auth.views.password_change', {'post_change_redirect':'/tickets/'}, name='password_change'), url(r'^password_change_done/$', 'django.contrib.auth.views.password_change_done', name='password_change_done'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/login/'}, name='logout'), url(r'^create/$', views.create_ticket, name='create_ticket'), url(r'^tickets/$', views.tickets_list, name='tickets_list'), url(r'^tickets/(?P<pk>[\d]+)/$', views.TicketDetailView.as_view(), name = 'ticket_detail'), url(r'^download/(?P<pk>[\d]+)/$', views.downloader, name='downloader'), url(r'^close/(?P<pk>[\d]+)/$', views.close_ticket, name = 'close_ticket'), url(r'^statistics/(?P<pref>.{2})/(?P<num>[\d]+)/', views.statistics, name='statistics'), url(r'^to_excel/$', views.to_excel, name='to_excel'), url(r'^docs/$', views.docs, name='docs'), )
UTF-8
Python
false
false
1,447
py
17
urls.py
7
0.63718
0.636489
0
27
52.592593
138
mohiitaa/synthesis-and-optimisation-of-digital-circuits
3,642,132,305,626
d1e9e200e285359d843018203668319bbe176df4
083af5989edd689b34d75f6cbe45c352a8eeeccc
/Operations_URP/Cofactor/Cofactor/op_notor.py
95b5bf88d9fb683e28b3cfa557e9ccd6a4015aae
[]
no_license
https://github.com/mohiitaa/synthesis-and-optimisation-of-digital-circuits
3382c66a98ee97edff62e2598caf9a5c36c5a8be
ff9d8da4ce306227c437ed42c39af463cf098ca2
refs/heads/master
2022-04-10T06:38:58.068952
2020-03-13T17:48:02
2020-03-13T17:48:02
116,579,416
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' # Simple OR operation between a and c. # Constraint:Neither a nor c can be null("00") # c is complemented in the begining (b=c') .Then we proceed # ahead by following these simple steps: # # i) If a and b are equal, the result is equal to one of them # ii) If a="11" the result is "11" # iii) If b="00", the result is a # iii)Otherwise the result is "11" ''' def op_notor(a,c): if a=="00" or c=="00": print "ERROR! 00 not a valid input" return if c=="11": b="00" elif c=="01": b="10" else: b="01" if a=="11": s="11" elif a==b: s=a elif b=="00": s=a else: s="11" return s
UTF-8
Python
false
false
739
py
21
op_notor.py
13
0.491204
0.445196
0
35
19.114286
62
BenDoan/playground
12,859,132,131,464
f39a6e9220018de7cd840b6823edb4b9bdef9c04
4945fef321f2823683378d71b49b3d2fae222d0d
/python/email-transaction-to-budget/email_transaction_to_budget.py
09dbc91c8c207ddd9df0671b59348b9b4014c9ff
[ "MIT" ]
permissive
https://github.com/BenDoan/playground
0c1fc4cfca81be68dfafde6974f95a6564366948
28fd14f08090023a6cb2cbcf98c16b4f041e2050
refs/heads/master
2023-05-26T07:26:28.374004
2023-04-30T16:14:07
2023-04-30T16:14:07
29,168,104
1
0
MIT
false
2023-02-22T21:14:19
2015-01-13T02:11:46
2021-12-16T05:51:33
2023-02-22T21:14:17
2,879
1
0
66
Jupyter Notebook
false
false
#!/usr/bin/env python import argparse from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import configparser import datetime import imaplib import json import os.path import pickle import re import traceback import enum from bs4 import BeautifulSoup import time HAVE_READ_MIDS_FILE = "have-processed-mids.json" HAVE_READ_TRANSACTIONS_FILE = "have-processed-transactions.json" # If modifying these scopes, delete the file token.pickle. SCOPES = ["https://www.googleapis.com/auth/spreadsheets"] # The ID and range of a sample spreadsheet. SPREADSHEET_ID = "1h-GBpn__5CG-jlG1LuQbooNaOm_rLQmBmz6OS1GdaeM" TEMPLATE_SHEET_ID = "740803055" BudgetCategory = enum.Enum("BudgetCategory", "food shopping recurring") FOOD_RANGE = "B6:C" SHOPPING_RANGE = "E6:F" RECURRING_RANGE = "" # keep lowercase food_vendors = ["hy-vee", "doordash", "chipotle", "jimmy johns"] def main(dry_run, proc_all): config = configparser.ConfigParser() config.read("imap-creds.ini") username = config.get("creds", "username") password = config.get("creds", "password") hostname = config.get("server", "hostname") have_processed_mids = {} have_processed_transactions = {} try: if not proc_all: have_processed_mids = json.load(open(HAVE_READ_MIDS_FILE)) have_processed_transactions = json.load(open(HAVE_READ_TRANSACTIONS_FILE)) except: pass service = get_sheets_service() with imaplib.IMAP4_SSL(hostname) as M: M.login(username, password) M.select("Transactions", readonly=True) now = datetime.datetime.now() month_ago = datetime.timedelta(days=-7) + now formatted_date = month_ago.strftime("%d-%b-%Y") message_ids_from_chase = M.search( "NONE", "FROM", '"chase.com"', "SINCE", formatted_date )[1][0].split() print(f"Found {len(message_ids_from_chase)} messages") entries = [] for mid in message_ids_from_chase: d_mid = mid.decode("utf-8") if d_mid not in have_processed_mids: try: message = M.fetch(d_mid, "(BODY.PEEK[TEXT])")[1][0][1] decoded_message = message.decode("UTF-8") scrubbed_message = decoded_message.replace("=", "").replace( "\n", "" ) if "credit card statement is ready" in scrubbed_message: have_processed_mids[d_mid] = True continue soup = BeautifulSoup(scrubbed_message, "html.parser") tables = soup.findAll("table") merchant = None amount = None datestr = None for table in tables: tds = table.findAll("td") if len(tds) < 2: continue text1 = tds[0].text text2 = tds[1].text if text1 == "Merchant": merchant = clean(text2) if text1 == "Amount": amount = clean(text2) if text1 == "Date": datestr = clean(text2) ident = f"{merchant}-{amount}-{datestr}" if amount is None or merchant is None: print("failed to process") print(soup.prettify()) merchant = "ERROR" have_processed_mids[d_mid] = True if ident in have_processed_transactions: continue entries.append([merchant, amount]) have_processed_transactions[ident] = True print(d_mid, amount, merchant, datestr) except Exception as e: print("Couldn't process: {}".format(decoded_message)) traceback.print_exc() if not dry_run: add_to_spreadsheet(service, entries) if not dry_run: with open(HAVE_READ_MIDS_FILE, "w+") as f: json.dump(have_processed_mids, f) with open(HAVE_READ_TRANSACTIONS_FILE, "w+") as f: json.dump(have_processed_transactions, f) def clean(s): t = s.replace("\r", "") t = re.sub(r"</?\w+>", "", t) t = t.strip() return t def get_sheets_service(): creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists("token.pickle"): with open("token.pickle", "rb") as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open("token.pickle", "wb") as token: pickle.dump(creds, token) service = build("sheets", "v4", credentials=creds) return service def get_curr_month_str(): return datetime.datetime.now().strftime("%Y-%m") def get_current_month_sheet(service): resp = service.spreadsheets().get(spreadsheetId=SPREADSHEET_ID).execute() sheets = resp.get("sheets", []) curr_month_str = get_curr_month_str() for sheet in sheets: if sheet.get("properties", {}).get("title") == curr_month_str: return sheet return None def add_to_spreadsheet(service, entries): curr_month_sheet = get_current_month_sheet(service) if not curr_month_sheet: copy_sheet(service, TEMPLATE_SHEET_ID) curr_month_str = get_curr_month_str() for entry in entries: cat = classify(entry[0], entry[1]) if cat == BudgetCategory.food: RANGE_NAME = f"{curr_month_str}!{FOOD_RANGE}" else: RANGE_NAME = f"{curr_month_str}!{SHOPPING_RANGE}" body = { "range": RANGE_NAME, "majorDimension": "ROWS", "values": [entry], } result = ( service.spreadsheets() .values() .append( spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME, valueInputOption="USER_ENTERED", body=body, ) .execute() ) def copy_sheet(service, old_sheet_id): resp = ( service.spreadsheets() .sheets() .copyTo( spreadsheetId=SPREADSHEET_ID, sheetId=old_sheet_id, body={"destinationSpreadsheetId": SPREADSHEET_ID}, ) .execute() ) sheet_id = resp["sheetId"] change_tab_index(service, sheet_id, 0) change_tab_title(service, sheet_id, get_curr_month_str()) return sheet_id def change_tab_index(service, sheet_id, index): resp = ( service.spreadsheets() .batchUpdate( spreadsheetId=SPREADSHEET_ID, body={ "requests": [ { "updateSheetProperties": { "properties": { "sheetId": sheet_id, "index": 0, }, "fields": "index", } } ] }, ) .execute() ) def change_tab_title(service, sheet_id, title): resp = ( service.spreadsheets() .batchUpdate( spreadsheetId=SPREADSHEET_ID, body={ "requests": [ { "updateSheetProperties": { "properties": { "sheetId": sheet_id, "title": title, }, "fields": "title", } } ] }, ) .execute() ) """ TODO - auto create tab for new month - add transactions to category for cur month - scrape recurring list from spreadsheet - stretch: decorate amazon transactions """ def classify(merchant, amount): merchant_l = merchant.lower() if merchant.startswith("TST*"): return BudgetCategory.food for food_vendor in food_vendors: if food_vendor in merchant_l: return BudgetCategory.food if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-d", "--dry-run", action="store_true") parser.add_argument("-a", "--all", action="store_true") args = parser.parse_args() main(dry_run=args.dry_run, proc_all=args.all)
UTF-8
Python
false
false
9,170
py
123
email_transaction_to_budget.py
52
0.529662
0.524973
0
301
29.465116
88
ritheshbhat/flask-restful
5,531,917,899,142
073c04e7163b1921f24e02a762f4d50aabb13bb6
92dfdc573ddb703306b0ba05a5bbcbefd8647a11
/setup.py
97563642b1c4abfe73ca6b8a32832637d34da9ca
[]
no_license
https://github.com/ritheshbhat/flask-restful
35a136eb57477b9e3e005e05081c409f59c176b6
af3d420b043edcb7ddb4c135e0ce5352b2792ae4
refs/heads/main
2023-06-17T07:01:47.291384
2021-07-11T10:41:09
2021-07-11T10:41:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import print_function from os import path from setuptools import find_namespace_packages, setup here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() with open(path.join(here, 'src/wisecoder/version.txt'), encoding='utf-8') as f: version = f.read() with open('requirements.txt') as f: required = f.read().splitlines() setup( name = 'wisecoder', version = version, description = long_description, python_requires = '>=3.6, <4', package_dir = {"": "src"}, packages = find_namespace_packages(where = "src"), install_requires = required )
UTF-8
Python
false
false
679
py
8
setup.py
5
0.662739
0.655376
0
25
26.16
79
rodrigowerberich/TaskAllocation
19,172,734,037,700
c7e54a379149a21b01c693f893d04f205da98ce8
c1f28fa6e77dd9acba75cf6c5aa65168ebbe479c
/task.py
5b9a9aff89c7349f4fe3e96816fdd8b03dd93ee8
[]
no_license
https://github.com/rodrigowerberich/TaskAllocation
163067076cd48d9b76b3407f8fe291844dfa8de0
408add66320ef496c542566ea0d83afda732ea72
refs/heads/master
2020-04-24T06:45:04.085279
2019-02-27T17:31:21
2019-02-27T17:31:21
171,775,818
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from functools import reduce class Task: def __init__(self, name, mu_tasks, priority, deadline): self.name = name self.mu_tasks = mu_tasks self.priority = priority self.deadline = deadline def __str__(self): return 'T'+str(self.name) def __repr__(self): return str(self)
UTF-8
Python
false
false
333
py
28
task.py
25
0.582583
0.582583
0
14
22.857143
59
duplodemo/demoservice
4,904,852,669,637
73eb3c0be52e9ced86baf5a4a52dfbc1c8e733d0
2750060dc44575bf2a324ad6cd5e0bfc38716e6a
/mysite/mysite/s3_utils.py2.7.py
23c8f6e22a6e54b2fdfc63d48c63e450eba40bcb
[]
no_license
https://github.com/duplodemo/demoservice
179325b6f5c32284127cd0b0b99134b26b9bdd54
9b32551c31bb62eddd93c43a6d194f66dbf60161
refs/heads/master
2023-04-14T09:37:20.307891
2023-04-04T08:51:42
2023-04-04T08:51:42
70,591,728
0
8
null
false
2023-04-04T12:43:38
2016-10-11T12:38:14
2021-11-02T16:34:21
2023-04-04T12:43:37
189
0
7
25
Python
false
false
# import boto # import sys, os # from boto.s3.key import Key # from boto.exception import S3ResponseError # from django.conf import settings # # class S3Utils: # # ############ s3 file list ####### # def get_s3_list_default(self): # s3_bucket = settings.S3_BUCKET_DEMO # if s3_bucket is None or s3_bucket=="": # return ["ERROR: 'S3_BUCKET_DEMO' setting is missing"] # return self.get_s3_list(s3_bucket) # # def get_s3_list(self, s3_bucket): # conn = boto.connect_s3() # bucket = conn.get_bucket(s3_bucket) # bucket_list = bucket.list() # results = [] # for file in bucket_list: # key_string = str(file.key) # results.append(key_string) # print(file) # # return results # # ############ s3 file ####### # def get_s3_file_default(self): # s3_bucket = settings.S3_BUCKET_DEMO # s3_file = settings.S3_FILE_DEMO # if s3_bucket is None or s3_bucket=="" or s3_file is None or s3_file=="": # return "ERROR: 'S3_BUCKET_DEMO' and 'S3_FILE_DEMO' settings are missing" # return self.get_s3_file(s3_file, s3_bucket) # # def get_s3_file(self, s3_file, s3_bucket ): # if s3_bucket is None or s3_bucket=="" or s3_file is None or s3_file=="": # return "ERROR: 's3_bucket' and 's3_file' parameter are required" # conn = boto.connect_s3() # bucket = conn.get_bucket(s3_bucket) # key = bucket.get_key(s3_file) # response = key.get_contents_as_string() # return response # # # if __name__ == "__main__": # # s3_utils = S3Utils() # # os.environ['S3_BUCKET_DEMO'] = "duploservices-default-demoservice" # # os.environ['S3_FILE_DEMO'] = "duplo-text.txt" # # files= s3_utils.get_s3_list() # # print(files) # # response = s3_utils.get_s3_file() # # print(response)
UTF-8
Python
false
false
1,917
py
18
s3_utils.py2.7.py
12
0.561815
0.535211
0
52
35.865385
86
tomguy04/Algo_Repo
8,478,265,485,785
ea1ff8c12f888594d4eae95ce11610c3f6a7dbfc
2fbd6f5c4fd129c6e22eb716fedacd2729271ad4
/17_RotateMatrix.py
e47276ef7eb614cd34bbaa57ab991660660c9937
[]
no_license
https://github.com/tomguy04/Algo_Repo
e4479fc4a2fdd073cd3251065aa1ffa2179c2d7b
cee7126130c3874c2963dfda4f491edb2782962c
refs/heads/master
2020-03-29T20:08:47.514646
2018-09-25T16:39:55
2018-09-25T16:39:55
150,297,855
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
matrix =[ [1, 1, 1, 2], [4, 0, 0, 2], [4, 0, 0, 2], [4, 3, 3, 3] ] for row in matrix: print row matrixSize =len(matrix) print ('this is a '+ str(matrixSize) +' by ' + str(matrixSize) + ' picture') number = 0 row = 0 temp1 = 0 temp2 = 0 #solution 1 #copy top row to array then copy left to top, bottom to left, right to bottom, temp array (old top) to right oldTopEdge = matrix[0] #left edge to top for row in range(matrixSize-1,0,-1): # print (row) #3,2,1 # print (str(matrix[row][0]) +" "+ str(matrix[0][row])) matrix[0][row]=matrix[row][0] for row in matrix: print row #bottom edge to left for row in range(matrixSize-1,0,-1): # print (row) #3,2,1 print (str(matrixSize-1)+str(row)+str(matrixSize-1-row)+str(0)+"--->"+str(matrix[matrixSize-1][row]) +" "+ str(matrix[matrixSize-1-row][0])) matrix[matrixSize-1-row][0]=matrix[matrixSize-1][row] # matrix[0][row]=matrix[row][0] for row in matrix: print row # for rowIndex in matrix: # number = rowIndex[-1] # print ('looking at '+ str(number)) # if row+1 < matrixSize: # temp = matrix[row+1][matrixSize-1] # print ('replacing '+ str(temp) +' with '+ str(number)) # matrix[row+1][matrixSize-1] = number # row+=1
UTF-8
Python
false
false
1,377
py
23
17_RotateMatrix.py
23
0.548293
0.506173
0
49
25.816327
144
hinamaladkar/BE_project
17,016,660,440,422
2cd3aca3a46bff4104f92e07004cf73aaa1275b7
fac25298f2f78c7f680ed399fa57544c957a8011
/get_val_so.py
4d4fa45db2d90c0ce5658bded42492e99934c2d1
[]
no_license
https://github.com/hinamaladkar/BE_project
50acec58e82e5185ee227f3a99ba736c91962c5d
2e6515b59f0a0c3a0bc7217b8d866a1f60f02144
refs/heads/master
2020-05-21T22:06:49.942771
2016-09-26T11:54:30
2016-09-26T11:54:30
65,819,555
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from bs4 import BeautifulSoup import requests url = "https://www.google.com/finance/historical?cid=13564339&startdate=Jan+01%2C+2015&" \ "enddate=Aug+18%2C+2016&num=30&ei=ilC1V6HlPIasuASP9Y7gAQ&start={}" #url = 'https://www.google.com/finance/historical?cid=13564339&startdate=Aug+21%2C+2014&enddate=Aug+19%2C+2016&num=30&ei=Zva2V6mlC8WsugSomoS4Ag' with requests.session() as s: start = 0 req = s.get(url.format(start)) soup = BeautifulSoup(req.content, "lxml") table = soup.select_one("table.gf-table.historical_price") all_rows = table.find_all("tr") while True: start += 30 soup = BeautifulSoup(s.get(url.format(start)).content, "lxml") table = soup.select_one("table.gf-table.historical_price") if not table: break all_rows.extend(table.find_all("tr"))
UTF-8
Python
false
false
843
py
7
get_val_so.py
5
0.676157
0.604982
0
22
37.318182
144
DDFaller/INF1771_Trab1
7,825,430,417,573
8b325ef7077f45ac4d0058dface32b4d11c69974
17042850060c679af708ebb0a226aba008c87697
/Processingpy/AValues.py
ae8e7d4bdfefb02feba08805928444052367aaf1
[]
no_license
https://github.com/DDFaller/INF1771_Trab1
9870d55941f91d3b6f11b25bb55f04c2c8f19b9d
30b1c8820df647a5c07fd931740576a536facb62
refs/heads/master
2022-12-29T05:49:10.934551
2020-10-19T08:10:02
2020-10-19T08:10:02
296,998,558
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class AValues: def __init__(self): self.f = 0 self.g = 0 self.h = 0 self.previous = None def heuristic(self,position,breakpointsList): lowestDistance = 1000 for pos in breakpointsList: x = pos[0] - position[0] y = pos[1] - position[1] x = x**2 y = y**2 distance =(x + y)**(1/2) if distance < lowestDistance: lowestDistance = distance return lowestDistance def SetPrevious(self,previousSquare): self.previous = previousSquare
UTF-8
Python
false
false
592
py
21
AValues.py
19
0.518581
0.493243
0
21
27.142857
49
EvilBorsch/homework-4
12,635,793,801,609
e18ec070c485ea389e29cff21f6d65582ca061f8
4640b2d6e727941957351aabdc5769e375b0c097
/pages/FoldersPage.py
2031b86bf75cad641e500db2f2f31460010532d3
[]
no_license
https://github.com/EvilBorsch/homework-4
f33c85c117f57e66ddae6cffc1e6522cc2000778
2ffd4d6ca913bfb9d00eef77d77eaaa28c908ebf
refs/heads/master
2023-02-15T05:47:17.355737
2021-01-09T22:09:50
2021-01-09T22:09:50
310,119,397
0
0
null
true
2021-01-08T18:15:34
2020-11-04T21:15:29
2021-01-08T17:57:42
2021-01-08T18:15:34
19,061
0
0
1
Python
false
false
from components.folders.AddFolderForm import AddFolderForm from steps.MainPageFoldersSteps import MainPageFoldersSteps from .BasePage import * class FoldersPage(Page): BASE_URL = "https://e.mail.ru" PATH = "/settings/folders" @property def add_folder(self): return AddFolderForm(self.driver) @property def pop3_steps(self): return MainPageFoldersSteps(self.driver) def click_change_checkbox_pop3(self) -> bool: """ :return: True если checked, else False """ classes_list = self.pop3_steps.toggle_checkbox_POP3() if len(classes_list.split()) == 2: return True return False def click_pencil_icon(self) -> bool: """ :return: True если открылось окно """ return self.pop3_steps.click_pencil_button()
UTF-8
Python
false
false
863
py
38
FoldersPage.py
37
0.635392
0.628266
0
31
26.16129
61
NutKaewnak/main_state
42,949,689,755
019425c0eb3baf07ca2585988415c9f05220b95f
0859d6eb51c7d84b3f60df80d7dc1ed162d1b973
/nodes/include/old_method_in_manipulator_controller.py
4f1f6f6b7f7547afd0d960aac4ea4d2fc40bc698
[]
no_license
https://github.com/NutKaewnak/main_state
b95001cf8e38c935a8de492ca4e6b35854f8a4ae
9ce4875e97f71a08c2cc2be804a93aa943bc94af
refs/heads/master
2021-03-27T11:13:25.465496
2017-04-27T12:49:36
2017-04-27T12:49:36
54,113,012
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def init_position(self, point): """ Init position and flip y-axis for invert kinematic :param point: (geometry/Point) :return: None """ rospy.loginfo("-----INVK INIT POSITION-----") if self.arm_group == 'right_arm': pass elif self.arm_group == 'left_arm': point.y *= -1 self.obj_pos = point self.obj_pos.x -= 0.15 self.obj_pos.y += 0.04 self.obj_pos.z += 0.02 self.pos = self.obj_pos def transform_point(self, pos, origin_frame='base_link'): """ Transform point from origin frame (Default: 'base_link') to 'mani_link' :param pos: (geometry_msgs.msg.PointStamped) :param origin_frame: :return: (geometry_msgs.msg.PointStamped), False if input arm_group is incorrect """ if "right" in self.arm_side: destination_frame = "right_mani_link" elif "left" in self.arm_side: destination_frame = "left_mani_link" tf_points = PointStamped() tf_points.point.x = pos.x tf_points.point.y = pos.y tf_points.point.z = pos.z tf_points.header.stamp = rospy.Time(0) tf_points.header.frame_id = origin_frame rospy.loginfo("Waiting For Transform") self.tf_listener.waitForTransform(destination_frame, origin_frame, rospy.Time(0), rospy.Duration(4.00)) rospy.loginfo("Success Waiting") point_out = self.tf_listener.transformPoint(destination_frame, tf_points) return point_out.point def manipulate(self, pose_target, orientation_rpy=[0, 0, 0], ref_frame="base_link", planning_time=50.00): self.arm_group.set_planning_time(planning_time) self.arm_group.clear_pose_targets() self.arm_group.set_goal_position_tolerance(0.05) self.arm_group.set_goal_orientation_tolerance(0.1) self.arm_group.set_pose_reference_frame(ref_frame) self.arm_group.set_pose_target(pose_target) self.arm_group.go(False) # async_move def get_joint_status(self): joint_state = {} group_joint_names = None group_current_joint_values = None group_joint_names = self.arm_group.get_joints() group_current_joint_values = self.arm_group.get_current_joint_values() for i in range(0, len(group_joint_names)): joint_state[group_joint_names[i]] = group_current_joint_values[i] return joint_state def move_relative(self, relative_goal_translation, relative_goal_rotation): # respect to efflink last_pose = self.arm_group.get_current_pose() rospy.loginfo(str(type(last_pose)) + '\n' + str(last_pose)) rpy = tf.transformations.euler_from_quaternion([last_pose.pose.orientation.x, last_pose.pose.orientation.y, last_pose.pose.orientation.z, last_pose.pose.orientation.w]) new_pose = Pose() new_pose.position.x = last_pose.pose.position.x + relative_goal_translation[0] new_pose.position.y = last_pose.pose.position.y + relative_goal_translation[1] new_pose.position.z = last_pose.pose.position.z + relative_goal_translation[2] new_pose.orientation.x = rpy[0] + relative_goal_rotation[0] new_pose.orientation.y = rpy[1] + relative_goal_rotation[1] new_pose.orientation.z = rpy[2] + relative_goal_rotation[2] self.manipulate(new_pose) def move_joint(self, joint_name, joint_value): print 'joint_name', joint_name print 'joint_value', joint_value print 'self.arm_side', self.arm_side print 'self.arm_group', self.arm_group if (type(joint_name) == str) and (type(joint_value) == float): self.arm_group.clear_pose_targets() self.arm_group.set_joint_value_target(joint_name, joint_value) self.arm_group.go(False) else: rospy.logwarn("Invalid Argument") return False return True # PICKING PROCEDURE pregrasp -> open_gripper -> reach -> grasp def move_arm_group(self, angles): """ Move array of arm joints with specific angle. :param angles: (dict()) dict of angle and arm_joint :return: (None) """ for x in angles: if x in self.arm_group.get_joints(): self.move_joint(x, angles[x]) def static_pose(self, posture, tolerance=[0.05, 0.1]): self.arm_group.clear_pose_targets() self.arm_group.set_goal_position_tolerance(tolerance[0]) self.arm_group.set_goal_orientation_tolerance(tolerance[1]) self.arm_group.set_named_target(posture) self.arm_group.go(False) # async_move def move_arm_pick_object_first(self): """ Move arm to object position : x - 25 cm :param (none) :return: (none) """ self.pos.x = self.obj_pos.x print "obj_pos.x 1 = " + str(self.obj_pos.x) print "pos.x 1 = " + str(self.pos.x) self.pos.y = self.obj_pos.y self.pos.z = self.obj_pos.z+0.1 angle = inverse_kinematics.inverse_kinematic(self.transform_point(self.pos), 0) self.move_arm_pick(angle) def move_arm_pick_object_second(self): """ Move arm to object position :param (none) :return: (None) """ self.pos.x = self.obj_pos.x self.pos.y = self.obj_pos.y self.pos.z = self.obj_pos.z angle = inverse_kinematics.inverse_kinematic(self.transform_point(self.pos), 0) self.move_arm_pick(angle) def move_arm_pick(self, angle): """ Move arm joints with specific angle. :param angle: (dict()) dict of angle and arm_joint :return: (None) """ self.move_joint('right_shoulder_1_joint', inverse_kinematics.in_bound('right_shoulder_1_joint', angle['right_shoulder_1_joint'])) self.move_joint('right_shoulder_2_joint', inverse_kinematics.in_bound('right_shoulder_2_joint', angle['right_shoulder_2_joint'])) self.move_joint('right_elbow_joint', inverse_kinematics.in_bound('right_elbow_joint', angle['right_elbow_joint'])) self.move_joint('right_wrist_1_joint', inverse_kinematics.in_bound('right_wrist_1_joint', angle['right_wrist_1_joint'])) self.move_joint('right_wrist_2_joint', inverse_kinematics.in_bound('right_wrist_2_joint', angle['right_wrist_2_joint'])) self.move_joint('right_wrist_3_joint', inverse_kinematics.in_bound('right_wrist_3_joint', angle['right_wrist_3_joint'])) def move_arm_before_pick_cloth(self): """ Move arm joints with specific angle. :param angle: (dict()) dict of angle and arm_joint :return: (None) """ self.pos.x = self.obj_pos.x self.pos.y = self.obj_pos.y self.pos.z = self.obj_pos.z angle = inverse_kinematics.inverse_kinematic(self.transform_point(self.pos), 1.0/6.0*math.pi) self.move_arm_pick(angle) def move_arm_after_pick_cloth(self): self.static_pose('right_after_pick_cloth') def move_arm_turn_left(self): self.static_pose('turn_arm_left') def move_arm_turn_right(self): self.static_pose('turn_arm_right')
UTF-8
Python
false
false
6,791
py
232
old_method_in_manipulator_controller.py
175
0.656015
0.64556
0
169
39.189349
133
adityabalu/trimesh
3,977,139,744,436
1f354b735a1b68a014d7fcd8082a2a82331326dd
e3eb5e6c52465e78c27550db275238d7059ac8f9
/trimesh/version.py
d55e3e6e53023f103812a5fc715155a1dacaf6c1
[ "MIT" ]
permissive
https://github.com/adityabalu/trimesh
1ce1210918c3ed8c53105aa1614dccfc2c9ab697
b64f9763e48f09efbd1d4195bc34bf2cb7eb9c71
refs/heads/master
2020-04-23T05:44:24.895089
2019-02-15T15:53:15
2019-02-15T15:53:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__version__ = '2.36.28'
UTF-8
Python
false
false
24
py
4
version.py
4
0.5
0.291667
0
1
23
23
Jung-Yuna/ClassRaspberryPi
15,393,162,807,852
1269640f8f4af6b04de2955625fd818b1d8aaf48
2b59789818d6478d074db58193d71c7ce03267ef
/LED.py
e050db0c095d08a0d6644c7c7d7d8343e6b6a268
[]
no_license
https://github.com/Jung-Yuna/ClassRaspberryPi
9deed195068dacd5e7c7cb74d6348fb368004a0f
152749aeb473b81092e2850f22b9d40ff6c868de
refs/heads/main
2023-06-01T12:11:13.222461
2021-06-21T05:29:52
2021-06-21T05:29:52
370,293,096
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) LED1 = 12 LED2 = 10 def main(): GPIO.setup(LED1, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(LED2, GPIO.OUT, initial=GPIO.LOW) while 1: GPIO.output(LED1, GPIO.HIGH) GPIO.output(LED2, GPIO.LOW) time.sleep(1) GPIO.output(LED1, GPIO.LOW) GPIO.output(LED2, GPIO.HIGH) time.sleep(1) if __name__=='__main__': main()
UTF-8
Python
false
false
387
py
4
LED.py
3
0.677003
0.638243
0
22
16.590909
45
liuluyang/miller
7,103,875,936,182
e41513b8c43a6c24e1cd6831b80fd230f69b9ebd
3fc7a6ffc39390c8228b30b6d53a3429104bf5f3
/education/10-16/字典.py
7514f2419bef4d93d9cf5056fe3336553e53027c
[]
no_license
https://github.com/liuluyang/miller
a5463c0f9625570de2cf16a9844ed4c7f82dde76
786f286749972fb2c3a66e068a3874a00aa0f2ee
refs/heads/master
2020-09-21T22:20:22.987833
2019-11-30T03:20:13
2019-11-30T03:20:13
224,952,326
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# staff_list = [ # [“miller”, 23, ‘CEO’, ‘88888’], # [‘黑姑娘’, 24, ‘行政’, ‘55555’], # [‘liuser’, 25, ‘讲师’, ‘44444’], # [‘egon’, ‘33’, ‘组长’, ‘77777’], # xxxxxx # xxxx # xxxxx # ] # for i in staff_list: # if i[0] == "黑姑娘": # print() # user_info1 = {"username": "miller", "password": 123564789} # user_info2 = dict(username="miller", password=123456789) # # user_info3 = {}.fromkeys([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 100) # print(user_info3) # names = {"miller": [23, "CEO", 66666], "blackgirl": [24, "行政", 40000]} # names["liusir"] = [26, "teacher", 5555] # names.setdefault("old_driver", [50, 'driver', 10000]) # print(names.pop("blackgirl")) # print(names) # print(names.popitem()) # # print(names) # dic1 = {"key1": "value1", "key2": "value2", "key3": "value3"} # dic2 = {"key3": "xxxxxx", "key4": "value4"} # # dic1.update(dic2) # # print(dic1) # dic1 = {"key1": "value1", "key2": "value2", "key3": "value3"} # print(dic1["xxxxx"]) # 查询不存在的key 会抛出异常 # print(dic1.get("xxxxx")) # print(dic1.items()) # dic = {"name": "miller", "age": 28, "phone": 132467468, "position": "CEO", "salary": 2222} # li = list(dic.keys()) # for i in enumerate(li): # print(i) # dic = {} # for i in range(100): # dic[i] = i*2 # # print(dic) dic = {"k0": 0, "k1": 1, "k2": 2, "k3": 3, "k4": 4, "k5": 5, "k6": 6, "k7": 7, "k8": 8, "k9": 9} for i in dic: if 5 < int(i.replace("k", "")): print(dic[i]) # for k, v in dic.items(): # if v % 2 == 0 and v != 0: # dic[k] = -1 # # print(dic)
UTF-8
Python
false
false
1,629
py
190
字典.py
180
0.519319
0.414538
0
76
19.065789
96
jaycodeco/ntube
2,087,354,123,848
675304d234a2dea270f8365e01206be35f259a87
d9a327f9f8376ba8e244d385fd37b4963582e6bc
/nBack/search.py
2e1cebebafa1ff5bfa03a75335f64d4e1ab866bd
[]
no_license
https://github.com/jaycodeco/ntube
0e16c7e66273a563e48b2ce33d98e9fd5a43f7fc
2becddc3d61a3192860b312c22e8f4e8cf276b3e
refs/heads/master
2023-05-25T22:23:27.178331
2021-05-27T15:33:13
2021-05-27T15:33:13
360,448,773
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import argparse from googleapiclient.discovery import build from googleapiclient.errors import HttpError DEVELOPER_KEY = 'AIzaSyD6FMCZQyNq0qmnVW_CofjVe-uf3P7DIB0' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' videos = [] def youtube_search(options): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) search_response = youtube.search().list( q=options, part='id,snippet', maxResults=20 ).execute() for search_result in search_response.get('items', []): if search_result['id']['kind'] == 'youtube#video': videos.append(f"{(search_result['id']['videoId'])} ^ {(search_result['snippet']['title'])} ^ {(search_result['snippet']['thumbnails']['medium']['url'])}") def register_search(): file = open("./nBack/search_results.txt", "w") end_vid = "" for video in videos: try: file.write(video.replace('\U0001f525', '').replace('\U0001f34b','')) file.write(" =") end_vid = video except Exception as e: pass file.write(end_vid.replace('\U0001f525', '').replace('\U0001f34b','')) file.close() def search_vids(search_term): try: youtube_search(search_term) register_search() print("yo") except HttpError: print ('An HTTP error occurred')
UTF-8
Python
false
false
1,416
py
26
search.py
4
0.603814
0.579802
0
57
23.701754
166
ChenhongyiYang/Gibson_Detection_Depth
14,929,306,323,968
daac7c9d9d5c662c8230bd2cd5659b049e278101
e9048785bf4f8af1f6baae3f14c1e0f0bfe8e5ce
/visulization/box_vis.py
969ed8132174d06b8cb74bb6ea68cd29f0bc5b78
[]
no_license
https://github.com/ChenhongyiYang/Gibson_Detection_Depth
0d5e9fbce4f781aa2117eb039bcd312d03b6c318
8359a9738d3e7eb61d26bb51bb562d1d6f08a05b
refs/heads/master
2020-06-11T02:58:19.849410
2019-06-26T05:03:33
2019-06-26T05:03:33
193,832,498
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import cv2 import numpy as np import random import os img_width, img_height = 600, 600 def rand_color(): return (random.randint(0,255), random.randint(0,255), random.randint(0,255)) def draw_img(img_file, txt, out_dir): img = cv2.imread(img_file) img = cv2.resize(img, (img_height,img_width)) f = open(txt,'r') lines = f.readlines() rois = [] colors = [] for line in lines: line = line.strip().split(' ') if len(line) == 6 or len(line) == 7: c = int(line[0]) ymin = int(line[1]) xmin = int(line[2]) ymax = int(line[3]) xmax = int(line[4]) score = float(line[5]) rois.append([ymin,xmin,ymax,xmax]) #col = rand_color() col = (0,255,0) colors.append(col) cv2.rectangle(img, (xmin,ymin), (xmax,ymax), color=col, thickness=2) cv2.putText(img, '%.3f'%(score), (xmin,ymin), cv2.FONT_HERSHEY_PLAIN, 1, color=col,thickness=2) if len(line) == 7: cv2.putText(img, '%s'%(line[6]), (xmin, ymax), cv2.FONT_HERSHEY_PLAIN, 1, color=col,thickness=2) else: continue out_name = os.path.join(out_dir,os.path.split(img_file)[-1]) cv2.imwrite(out_name, img) def run(txt_dir, img_dir, out_dir): if not os.path.isdir(out_dir): os.mkdir(out_dir) for name in os.listdir(txt_dir): txt = os.path.join(txt_dir,name) img = os.path.join(img_dir,name.replace('txt', 'png')) draw_img(img, txt, out_dir)
UTF-8
Python
false
false
1,587
py
13
box_vis.py
12
0.540013
0.509137
0
54
28.074074
112
kml27/graphics_algos
13,580,686,612,543
663d69ba486c2cea9baa9031b8f4e73c1de1a95b
735f86b9abcb9e863b26b14abe395eeed172c72c
/archimedes.py
31c2b1511b8ff52ddb4bf40f2f3a61676d661b01
[]
no_license
https://github.com/kml27/graphics_algos
79f2e9656da71a24e99f7e2883790f9dee05e27d
fe9f913b13aca0d03490c0353569eaa192b2bce8
refs/heads/master
2022-07-20T00:43:53.234599
2018-04-21T21:39:44
2018-04-21T21:39:44
264,089,091
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Wed Jun 17 12:21:48 2015 @author: Kenny """ from __future__ import division import math, turtle #archimedes spiral (ish) turtle.speed(0) turtle.getscreen().tracer(16, 5) #iterate from this number of divisions to the min (triangle) max_divisions = 10 triangle_min = 2 just_degrees=360 #full_circle_radians = 2*math.pi #180/pi turtle.home() turtle.clear() iterations=10 #check if there's a relationship between the ratio of geometric sides to interior angles #and the argand(polar) graph of riemman zeta(critical line) #z=x+iy #for set_i in range(-2, 5): for set_i in range(1,2): turtle.pencolor((0,0,0)) for num_fragments in range(triangle_min, max_divisions): #turtle.clear() outer_diameter=math.pow(2, set_i) #dec_amt = 10 turtle.penup() turtle.home() turtle.seth(90) turtle.forward(outer_diameter) turtle.pendown() #interior_angle =(num_fragments-2)*180/num_fragments #works for 4,5,6,? #one_fragment =(num_fragments-2)*180/num_fragments scale_den=num_fragments*iterations scale_den=num_fragments*(1/iterations) scale_den=1/iterations print "scale den", scale_den #one_fragment = full_circle_radians/divisions #works for 3 #one_fragment= just_degrees//(num_fragments*2) one_fragment=just_degrees/num_fragments print "sides: ", num_fragments print "one arc: ", one_fragment cur_heading=0#one_fragment # scale_inc = 360//scale_den scale_dec=(1/iterations)/scale_den print "scale dec",scale_dec scale= 1 for d_it in range(0,num_fragments*iterations): #turtle.pencolor((0.5,0.5,0.5)) #turtle.circle(outer_diameter) length=outer_diameter*scale#*math.cos(scale) turtle.seth(cur_heading) #turtle.left(cur_heading) print "heading ", cur_heading print "scale: ", scale#, math.cos(cur_heading) turtle.forward(length) scale=scale-scale_dec cur_heading=cur_heading-one_fragment#*-1 #print "diameter: ", outer_diameter
UTF-8
Python
false
false
2,520
py
20
archimedes.py
19
0.547222
0.519444
0
96
24.270833
88
trassir/scripts
14,267,881,405,454
7fcafcbd948c661ec769b3ba5c14b57652e37704
0189e2f620de20ae5d087a3d3921332afdabb141
/scripts/universal/alarm_monitor/ts_generator.py
aa6ed95a00a5a60cbc4ef6375f08b3b45e4e5cd9
[]
no_license
https://github.com/trassir/scripts
8ef6ee1f249a4e24390434e979e6aaf067998430
20f8336de76160b65f08e65ec71c3c186e01fb5e
refs/heads/main
2023-04-16T07:31:23.557848
2021-04-28T13:14:25
2021-04-28T13:14:25
344,463,871
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import sys import argparse from datetime import datetime from difflib import get_close_matches sys.path.append('resources') sys.path.append('../../../../') os.environ["SAVE_ORIGINALS"] = "True" from localization.translation_base import load_translation parser = argparse.ArgumentParser() parser.add_argument("target", help="Target lang (ru,en,cn,...)") parser.add_argument("-s", "--source", help="Source language, default: en", default="en") args = parser.parse_args() ts_path = r"resources\%s.ts" % args.target try: load_translation(ts_path) except Exception as err: print("Can't load translation %s" % ts_path) print("Got error: %s" % err) continue_ = raw_input("Would you like to continue? [y/N]: ").lower() or "n" if continue_ != "y": exit() import localization as loc from localization.translation_base import Translated __xml_version__ = "1.0" __encoding__ = "utf-8" __ts_version__ = "2.1" __version__ = "1.0.0" with open("resources/%s.ts" % args.target, "w") as tf: tf.write( '<?xml version="{xml_ver}" encoding="{enc}"?>\n' "<!DOCTYPE TS>\n" "<!-- Automatically generated by ts_generator v{ver} at {today} -->\n" '<TS version="{ts_ver}" language="{a.target}" sourcelanguage="{a.source}">\n' " <context>\n".format( ver=__version__, today=datetime.today().date(), a=args, xml_ver=__xml_version__, enc=__encoding__, ts_ver=__ts_version__, ) ) main = getattr(loc, "main", None) if main: script_name = main.script_name if script_name != Translated.build_default_message("script_name"): tf.write(" <name>%s</name>\n" % script_name) saved_data = {} _all_values = set(loc.translation_base._translation.keys()) for key in sorted(loc.__dict__.keys()): item = loc.__dict__[key] if isinstance(item, Translated): tf.write("\n <!-- %s -->\n" % item.__class__.__name__) # raise ValueError("for instance name: %s, originals: %s" % (item.__class__.__name__, item.originals)) _originals = {value: key for key, value in item.originals.iteritems()} for value in sorted(_originals.keys()): key = _originals[value] translation = loc.translation_base._translation.get(value) if translation: msg = ( " <message>\n" " <source>{source}</source>\n" " <translation>{target}</translation>\n" " </message>\n".format(source=value, target=translation) ) try: _all_values.remove(value) except KeyError: pass else: msg = ( " <message>\n" " <source>{source}</source>\n" " <translation>[{lang}]{source}</translation>\n" " </message>\n".format(source=value, lang=args.target) ) if saved_data.get(value): msg = (" <!-- Translated in '%s' block\n%s -->\n") % ( saved_data[value], msg, ) else: close_match = get_close_matches( value, saved_data.keys(), n=1, cutoff=0.81 ) if close_match: print( "WARNING: '%s' is close match to '%s'" % (value, close_match[0]) ) saved_data[value] = item.__class__.__name__ tf.write(msg) _all_values = list(_all_values) if _all_values: _all_values.sort() msg = "Found %s not used translations in %s (%s" % (len(_all_values), ts_path, ", ".join(_all_values[:3])) if len(_all_values) > 3: msg += "..." print(msg + ")") continue_ = raw_input("Would you like to save them in new file? [Y/n]: ").lower() or "y" if continue_ == "y": tf.write("\n <!-- Not used in current script -->\n") for value in _all_values: translation = loc.translation_base._translation.get(value) msg = ( " <message>\n" " <source>{source}</source>\n" " <translation>{target}</translation>\n" " </message>\n".format(source=value, target=translation) ) tf.write(msg) tf.write(" </context>\n" "</TS>")
UTF-8
Python
false
false
4,840
py
265
ts_generator.py
165
0.47686
0.47376
0
135
34.851852
114
agnunez/IQMon
16,303,695,896,477
770e67f9fdc29004d402de1f4c5b509d3913be86
3c86c755055ca02a0092507e9779eabbe9c3ab0f
/setup.py
772181bc215889c8bbbac74ac0f7bd2b7b16751a
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
https://github.com/agnunez/IQMon
da3c15bc2116d5268f5377b5961d48f298f2e983
14fade394389e4d9ebe9f7c0fe637033a3ebdc12
refs/heads/master
2020-04-07T08:17:19.284403
2016-12-12T01:13:12
2016-12-12T01:13:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from setuptools import setup, find_packages from IQMon import __version__ setup( name = "IQMon", version=__version__, author='Josh Walawender', packages = find_packages(), )
UTF-8
Python
false
false
190
py
9
setup.py
4
0.668421
0.668421
0
8
22.75
43
sevencrime/python
13,159,779,841,593
caf419343eba365fe5d0fa353dc2f0b4725551f4
91ac41baf7b0a91efd8ee657e9fe44fe1835979b
/示例/播放音乐/play_music_demo.py
80f35cab9fd03590a47f9ebe7ff1939a3149b32d
[]
no_license
https://github.com/sevencrime/python
0c3b27e25da1d48ac37950756be5bad821d0948c
2ee80e467cd57db5d113b65eb9dfae2d5a561a43
refs/heads/master
2021-12-15T11:42:16.781369
2021-12-12T13:25:00
2021-12-12T13:25:00
160,919,719
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' pygame.init() 进行全部模块的初始化, pygame.mixer.init() 或者只初始化音频部分 pygame.mixer.music.load('xx.mp3') 使用文件名作为参数载入音乐 ,音乐可以是ogg、mp3等格式。载入的音乐不会全部放到内容中,而是以流的形式播放的,即在播放的时候才会一点点从文件中读取。 pygame.mixer.music.play()播放载入的音乐。该函数立即返回,音乐播放在后台进行。 play方法还可以使用两个参数 pygame.mixer.music.play(loops=0, start=0.0) loops和start分别代表重复的次数和开始播放的位置,如果是-1表示循环播放,省略表示只播放1次。第二个参数和第三个参数分别表示播放的起始和结束位置。 pygame.mixer.music.stop() 停止播放, pygame.mixer.music.pause() 暂停播放。 pygame.mixer.music.unpause() 取消暂停。 pygame.mixer.music.fadeout(time) 用来进行淡出,在time毫秒的时间内音量由初始值渐变为0,最后停止播放。 pygame.mixer.music.set_volume(value) 来设置播放的音量,音量value的范围为0.0到1.0。 pygame.mixer.music.get_busy() 判断是否在播放音乐,返回1为正在播放。 pygame.mixer.music.set_endevent(pygame.USEREVENT + 1) 在音乐播放完成时,用事件的方式通知用户程序,设置当音乐播放完成时发送pygame.USEREVENT+1事件给用户程序。 pygame.mixer.music.queue(filename) 使用指定下一个要播放的音乐文件,当前的音乐播放完成后自动开始播放指定的下一个。一次只能指定一个等待播放的音乐文件。 ''' import pygame import time file = "F:\python\示例\播放音乐\POWDER_SNOW.mp3" pygame.mixer.init() print("播放音乐") pygame.mixer.music.load(file) pygame.mixer.music.play(start = 20) time.sleep(10) # pygame.mixer.music.stop()
UTF-8
Python
false
false
1,895
py
43
play_music_demo.py
40
0.788039
0.769569
0
29
38.068966
207
trtnk/audio_classification_by_tf2
1,915,555,450,677
7c7cc0ae789bb0d432a32219833f75bb91085be8
0f866a525fde956ca418efd05b2a7a5f56c384a1
/util/create_cvset.py
52722f4224b7e934fea6f3e5c11f13c41a6d1a44
[ "MIT" ]
permissive
https://github.com/trtnk/audio_classification_by_tf2
7bb2cdfabbe04334962af3fecd3da27eb6fbd67e
3d18c68315f3d6509bb36ef15d4ec4f9c8f07f61
refs/heads/main
2023-03-12T10:16:31.244991
2021-03-03T02:30:31
2021-03-03T02:30:31
343,843,017
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from util.common import * import pandas as pd from sklearn.model_selection import StratifiedKFold, KFold from iterstrat.ml_stratifiers import MultilabelStratifiedKFold def get_cv_df_from_yaml(config_yaml_path, output_csv_path=None): config = yaml_load(config_yaml_path) directory_label_name = config["directory_label_name"] if "directory_label_name" in config else [] file_label_name = config["file_label_name"] if "file_label_name" in config else [] # create file information df info_df = get_file_info_df(config["data_base_directory"], config["data_extension"], label_csv_path=config["label_csv_path"], directory_label_name=directory_label_name, file_label_name=file_label_name) # filter if "data_constraint" in config: info_df = df_extractor(info_df, config["data_constraint"]) # main label setting if "default_main_label" in config["main_label"]: main_label = config["main_label"] elif "create_main_label" in config["main_label"]: info_df = add_new_column(info_df, "_main_label_", config["main_label"]["create_main_label"], dropna=True) main_label = "_main_label_" if "test_id_path" in config: test_id_list = list(pd.read_csv(config["test_id_path"], header=None)[0].values) else: test_id_list = None if "multi_file_input" in config: multi_file_input = True multi_file_input_config = config["multi_file_input"] else: multi_file_input = False multi_file_input_config = {} random_state = config["cv"]["random_state"] if "random_state" in config["cv"] else None grouped_label = config["cv"]["grouped_label"] if "grouped_label" in config["cv"] else None # create cvset df cv_df = get_cv_df(info_df, main_label, n_splits=config["cv"]["n_splits"], shuffle=bool(config["cv"]["shuffle"]), test_id_list=test_id_list, id_column=config["id_column"], grouped_label=grouped_label, balanced=config["cv"]["balanced"], balanced_other_label=config["cv"]["balanced_other_label"], stratified=config["cv"]["stratified"], stratified_other_labels=config["cv"]["stratified_other_labels"], multi_file_input=multi_file_input, multi_file_identification_info=multi_file_input_config, random_state=random_state, output_csv_path=output_csv_path) return cv_df def get_cv_df(info_df, main_label, n_splits=5, shuffle=True, test_id_list=None, id_column=None, grouped_label=None, balanced=True, balanced_other_label=None, stratified=False, stratified_other_labels=None, multi_file_input=False, multi_file_identification_info={"base_column": "", "divide_column": "", "order":[]}, random_state=None, output_csv_path=None): cv_df = info_df.copy() cv_df.loc[:, "cvset"] = pd.NA info_df_ = info_df.copy() if test_id_list is not None: test_idx = info_df_[info_df_[id_column].isin(test_id_list)].index cv_df.loc[test_idx, "cvset"] = "test" info_df_ = info_df_[~info_df_[id_column].isin(test_id_list)] # grouped if grouped_label is not None: key_df = info_df_.drop_duplicates(subset=grouped_label) else: key_df = info_df_.copy() # balanced if balanced: label_vals = list(dict.fromkeys(key_df[main_label].values)) min_sample_num = key_df[main_label].value_counts().min() key_df_ = pd.DataFrame({}) for label_val in label_vals: each_label_key_df = key_df[key_df[main_label] == label_val] if balanced_other_label is None: key_df_ = key_df_.append(each_label_key_df.sample(min_sample_num, random_state=random_state)).reset_index(drop=True) else: key_df_ = key_df_.append(sample_balanced(each_label_key_df, min_sample_num, balanced_other_label, random_state=random_state)).reset_index(drop=True) else: key_df_ = key_df # stratified if stratified: if stratified_other_labels is not None: kf = MultilabelStratifiedKFold(n_splits=n_splits, shuffle=shuffle, random_state=random_state).split(key_df_, key_df_[[main_label]+stratified_other_labels]) else: kf = StratifiedKFold(n_splits=n_splits, shuffle=shuffle, random_state=random_state).split(key_df_, key_df_[main_label]) else: kf = KFold(n_splits=n_splits, shuffle=shuffle, random_state=random_state).split(key_df_, key_df_[main_label]) # create cv set for cvset, (_, eval_idx) in enumerate(kf, start=1): if grouped_label is None: grouped_label = id_column eval_keys = key_df_.loc[eval_idx, :][grouped_label] cv_df.loc[cv_df[grouped_label].isin(eval_keys), "cvset"] = f"cv{cvset}" cv_df = cv_df.dropna(subset=["cvset"]) if multi_file_input: base_column = multi_file_identification_info["base_column"] divide_column = multi_file_identification_info["divide_column"] order = multi_file_identification_info["order"] cv_df_ = cv_df.copy() cv_df_ = cv_df_.drop_duplicates(subset=base_column) for id_, new_df in cv_df.groupby(base_column): file_paths = [new_df[new_df[divide_column] == val]["filepath"].values[0] for val in order] idx = cv_df_.loc[cv_df_[base_column] == id_, "filepath"].index[0] cv_df_.at[idx, "filepath"] = file_paths cv_df = cv_df_.reset_index(drop=True) if output_csv_path is not None: cv_df.to_csv(output_csv_path, index=False) return cv_df
UTF-8
Python
false
false
5,877
py
10
create_cvset.py
10
0.603199
0.602348
0
136
42.213235
167
liangxuCHEN/A2Z_python
10,393,820,905,610
17fb76eb004ef4c2115bb767ab1d50f0036d324d
ae201b67ef7762623a7b02d324f41f5b283a97ee
/file/db_test.py
3876930ee185adc691e6762e85988555fe1f11c4
[]
no_license
https://github.com/liangxuCHEN/A2Z_python
dfb9c1df5d4f97d1d0588402fce8479881675b7a
b609f0ecdf88929f60745671e3cbb594217a2325
refs/heads/master
2020-09-23T20:25:38.065725
2020-03-31T09:10:32
2020-03-31T09:10:32
225,578,825
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from sqlalchemy import Column, String, Integer, create_engine, ForeignKey from sqlalchemy.orm import sessionmaker,relationship from sqlalchemy.ext.declarative import declarative_base # 创建对象的基类: Base = declarative_base() # 数据库连接字符串 DB_CONNECT_STRING = 'sqlite:///db_test.sqlite' # 定义User对象: class User(Base): # 表的名字: __tablename__ = 'user' # 表的结构: id = Column(Integer, primary_key=True) name = Column(String(20)) # 另外写法 age = Column("age", Integer, default=0) books = relationship('Book') # 创建一个书的类 class Book(Base): __tablename__ = 'book' id = Column(Integer, primary_key=True) name = Column(String(20)) # “多”的一方的book表是通过外键关联到user表的: user_id = Column(String(20), ForeignKey('user.id')) # 初始化数据库连接: engine = create_engine(DB_CONNECT_STRING) # 创建DBSession类型: DBSession = sessionmaker(bind=engine) # 删除所有表 # Base.metadata.drop_all(engine) # 创建数据表,如果数据表存在则忽视!!! Base.metadata.create_all(engine) def add_user(name, age=0): # 创建session对象: session = DBSession() # 创建新User对象: new_user = User(name=name, age=age) # 添加到session: session.add(new_user) # 提交即保存到数据库: session.commit() print("user id", new_user.id) # 关闭session: session.close() return new_user def add_book(book_name, user_id): # 创建session对象: session = DBSession() # 添加到session: # TODO: 写你们的代码 # 提交即保存到数据库: session.commit() # 关闭session: print("book id", new_book.id) session.close() return new_book def get_book(book_id): """ 输入书本id,输出书名和人名 :param book_id: :return: """ pass if __name__ == '__main__': user1 = add_user(name="小灵", age=10) user2 = add_user(name="大鸿", age=18) #book = add_book(book_name='鼠标', user_id=user.id) #print(book.id) #get_book(5)
UTF-8
Python
false
false
2,123
py
29
db_test.py
4
0.636565
0.628255
0
84
20.488095
73
ravina-gelda/arith
6,416,681,145,719
40d5a9b972de4fba18a8e19f3cdfde5ec0b8a8c0
b338af96eeecf70bc18004a0c73b465cc649f919
/arith.py
72384ec159d21e11ff403760f6cae975cff8e5b6
[]
no_license
https://github.com/ravina-gelda/arith
d4954e7cd8ee8972b72b0d3da29577eabc497f9b
d8b4dc21e253d65475e118d138e08c88c23f7c27
refs/heads/master
2022-04-13T12:53:59.398504
2020-04-11T00:16:06
2020-04-11T00:16:06
254,487,479
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 import sys sys.tracebacklimit = 0 class node(): def __init__(self, left, right, op): self.left = left self.right = right self.op = op class parser(): def __init__(self, input): self.input_list = input.split(" ") # print(self.input_list) def AST(self): curr_node = node(None, None, "root") for i in self.input_list: # print(i.lstrip('-+')) if i.lstrip('-+').isdigit(): new_node = node(None, None, i) if curr_node.op == "root": curr_node = new_node elif curr_node.op == "*": curr_node.right = new_node if parent_node.op != None: curr_node = parent_node else: curr_node.right = new_node # print("integer",curr_node.op) elif i == "+": new_node = node(None, None, "+") new_node.left = curr_node curr_node = new_node # print("+",curr_node.op) elif i == "*": new_node = node(None, None, "*") parent_node = node(None, None, None) if curr_node.op.lstrip('-+').isdigit(): new_node.left = curr_node curr_node = new_node else: parent_node = curr_node new_node.left = curr_node.right curr_node.right = new_node curr_node = new_node # print("*", curr_node.op) elif i == "-": new_node = node(None, None, "-") new_node.left = curr_node curr_node = new_node # print("-", curr_node.op) else: Exception("Not a valid operator") return curr_node def evaluate_AST(self, curr_node): # print(curr_node.op) if curr_node.op == "+": return (self.evaluate_AST(curr_node.left) + self.evaluate_AST(curr_node.right)) elif curr_node.op == "-": return (self.evaluate_AST(curr_node.left) - self.evaluate_AST(curr_node.right)) elif curr_node.op == "*": return (self.evaluate_AST(curr_node.left) * self.evaluate_AST(curr_node.right)) else: return int(curr_node.op) def main(): while True: try: # Taking raw inputs text = input("") except EOFError: break object = parser(text) root_node = object.AST() output2 = object.evaluate_AST(root_node) print(str(output2)) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,850
py
3
arith.py
2
0.442807
0.441404
0
99
26.787879
91
eduns/Fatec
4,930,622,469,223
423b6d0bf56a4c2beb31c05e84459efa830c14b0
59ca455b0cb6fc31e8cf2359044d7ba35ea8ba5e
/lista_II.py
16e0b26597299ab95f572e87d0cab971d49fb5a0
[]
no_license
https://github.com/eduns/Fatec
4d298de36e8cad859e91b4204c5da5ae86309275
67ad3caa442cb9008521a8201c492d204f1dee39
refs/heads/master
2020-03-07T16:37:49.998655
2019-03-03T21:16:02
2019-03-03T21:16:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#------------------------------------------------------- # Exercício 1 print("============== Exercício 1 ==============") ladoA = int(input("Lado A: ")) ladoB = int(input("Lado B: ")) ladoC = int(input("Lado C: ")) if ladoA < ladoB + ladoC or ladoB < ladoA + ladoC or ladoC < ladoA + ladoB: if ladoA == ladoB == ladoC: print("Equilátero") elif ladoA == ladoB or ladoA == ladoC or ladoB == ladoC: print("Isósceles") elif ladoA != ladoB and ladoA != ladoC and ladoB != ladoC: print("Escaleno") else: print("Não é um triângulo") #------------------------------------------------------- #------------------------------------------------------- # Exercício 2 print("\n\n============== Exercício 2 ==============") ano = int(input("ano: ")) if ano % 4 == 0: if ano % 100 != 0: print(f"{ano} é bissexto") else: print(f"{ano} não é bissexto") elif ano % 400 == 0: print(f"{ano} é bissexto!") else: print(f"{ano} não é bissexto") #------------------------------------------------------- #------------------------------------------------------- # Exercício 3 print("\n\n============== Exercício 3 ==============") peso = int(input("peso: ")) excesso = multa = 0 if peso > 50: excesso = peso - 50 multa = excesso * 4 print(f"Excesso de peso: {excesso}kg\nMulta: R${multa}") #------------------------------------------------------- #------------------------------------------------------- # Exercício 4 print("\n\n============== Exercício 4 ==============") num1 = int(input("número 1: ")) num2 = int(input("número 2: ")) num3 = int(input("número 3: ")) if num1 > num2 and num1 > num3: print(f"{num1} é o maior") elif num2 > num1 and num2 > num3: print(f"{num2} é o maior") elif num3 > num1 and num3 > num2: print(f"{num3} é o maior") #------------------------------------------------------- #------------------------------------------------------- # Exercício 5 print("\n\n============== Exercício 5 ==============") num1 = int(input("número 1: ")) num2 = int(input("número 2: ")) num3 = int(input("número 3: ")) if num1 > num2 and num1 > num3: print(f"{num1} é o maior") elif num2 > num3: print(f"{num2} é o maior") else: print(f"{num3} é o maior") if num1 < num2 and num1 < num3: print(f"{num1} é o menor") elif num2 < num3: print(f"{num2} é o menor") else: print(f"{num3} é o menor") #------------------------------------------------------- #------------------------------------------------------- # Exercício 6 print("\n\n============== Exercício 6 ==============") valor_hora = int(input("valor por hora: ")) horas_trabalhadas = int(input("horas trabalhadas: ")) salario = valor_hora * horas_trabalhadas imposto_renda = salario * 0.11 inss = salario * 0.08 sindicato = salario * 0.05 salario = salario - sindicato - inss - imposto_renda print(f"salário bruto: R${valor_hora * horas_trabalhadas}") print(f"INSS: R${inss:.2f}") print(f"sindicato: R${sindicato:.2f}") print(f"imposto de renda: R${imposto_renda:.2f}") print(f"salário líquido: R${salario:.2f}") #------------------------------------------------------- #------------------------------------------------------- # Exercício 7 print("\n\n============== Exercício 7 ==============") area = int(input("área: ")) if area % 54 == 0: latas = area / 54 else: latas = int(area / 54) + 1 print(f"preço total: R${latas * 80}\nlatas: {latas}") #-------------------------------------------------------
UTF-8
Python
false
false
3,607
py
7
lista_II.py
6
0.429253
0.401741
0
102
32.921569
75
simon-cutts/message-broker
7,258,494,751,870
d30b68ef0244f4f90bc3b25e7de8b78a03191aa3
d9216275d4c9be88a57d4b0a8b63146ca741193a
/Wlst/wlst/GetParam.py
8d56969c8cf290cc4683356d1bf1a3a49c23ba19
[]
no_license
https://github.com/simon-cutts/message-broker
9fd0363e85d21398048b1f0c4907da7ef3bb8358
8c8a20bf56fd8e101b5e7114f2e8bdd9721c2683
refs/heads/master
2021-04-02T03:41:13.572300
2020-03-18T13:53:07
2020-03-18T13:53:07
248,239,797
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
if __name__ == '__main__': from wlstModule import *#@UnusedWildImport import sys from java.lang import System from java.io import FileInputStream print sys.argv[1]
UTF-8
Python
false
false
174
py
163
GetParam.py
56
0.706897
0.701149
0
8
20.375
46
swipswaps/alexa-controlled-drone
6,090,263,657,327
d03ac135bf2f18a74863aeff3766909b013f50b6
e21df1066e239d16faf60298e7fd43009d84cc0b
/pi-alexa-code/start.py
2cc035aecf7d0f3e0bed1c8273ee514a03aeede6
[]
no_license
https://github.com/swipswaps/alexa-controlled-drone
054a8292a563fdd04b94a364e59337fc69c7799f
00aa987dd792fe14e6cf0d2226e8f1026d69e67c
refs/heads/master
2022-03-28T09:48:24.846275
2020-01-18T07:06:49
2020-01-18T07:06:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json import logging import threading import time import tellopy import queue from command import command from iot_client import awsIoTClient logger = logging.getLogger() logger.setLevel(logging.INFO) aws_client = None speed = 80 drone = None prev_flight_data = None flight_data = None log_data = None is_drone_connected = False command_queue = None initial_data = 'ALT: 0 | SPD: 0 | BAT: 0 | WIFI: 0 | CAM: 0 | MODE: 0' ############################## # Configurations ############################## config = { 'host': '<REST API Endpoint>', 'rootCAName': '<Root certificate file name>', 'certificateName': '<Certificate file name>', 'privateKeyName': '<Private key file name>', 'clientId': 'drone_alexa_client', 'port': 8883 } thing_name = "<THING_NAME>" device_shadow_update_topic = "$aws/things/" + thing_name + "/shadow/update" device_shadow_update_accepted_topic = "$aws/things/" + thing_name + "/shadow/update/accepted" device_shadow_update_rejected_topic = "$aws/things/" + thing_name + "/shadow/update/rejected" ############################## # Drone connection ############################## def connect_drone(): my_drone = tellopy.Tello() my_drone.subscribe(my_drone.EVENT_CONNECTED, drone_event_handler) my_drone.subscribe(my_drone.EVENT_DISCONNECTED, drone_event_handler) my_drone.subscribe(my_drone.EVENT_FLIGHT_DATA, drone_event_handler) my_drone.subscribe(my_drone.EVENT_LOG_DATA, drone_event_handler) my_drone.connect() # my_drone.wait_for_connection(60.0) return my_drone def drone_event_handler(event, sender, data, **args): global prev_flight_data, flight_data, log_data, is_drone_connected my_drone = sender if event is my_drone.EVENT_CONNECTED: logging.info("Connected to drone!...") is_drone_connected = True elif event is my_drone.EVENT_DISCONNECTED: logging.warning("Disconnected from drone!...") is_drone_connected = False elif event is my_drone.EVENT_FLIGHT_DATA: if prev_flight_data != str(data): logging.info(data) prev_flight_data = str(data) flight_data = data elif event is my_drone.EVENT_LOG_DATA: if log_data != str(data): logging.debug(data) log_data = str(data) else: logging.debug('event="%s" data=%s' % (event.getname(), str(data))) ############################## # Telemetry ############################## def compute_telemetry(raw_data, drone_connected): message = {} # flight_data= 'ALT: 0 | SPD: 0 | BAT: 94 | WIFI: 90 | CAM: 0 | MODE: 1' if raw_data is None or len(raw_data) < 1: return message telemetry = {} tele_arr = raw_data.split('|') for element in tele_arr: element = element.replace(" ", "") kv = element.split(':') telemetry[kv[0]] = int(kv[1]) pass message['state'] = {} message['state']['reported'] = {} for key in telemetry: message['state']['reported'][key] = telemetry[key] pass message['state']['reported']['ISONLINE'] = drone_connected return message def send_telemetry_loop(): logging.info("Starting telemetry loop " + str(is_drone_connected)) while is_drone_connected: try: send_telemetry(prev_flight_data, True) time.sleep(500e-3) # 500ms except Exception as e: logging.error("Error occurred while sending telemetry " + str(e)) logging.info("Exiting telemetry loop " + str(is_drone_connected)) def send_telemetry(raw_data, drone_connected): message_json = json.dumps(compute_telemetry(raw_data, drone_connected)) aws_client.publish_message(device_shadow_update_topic, message_json) ############################## # Callback ############################## def message_callback(client, userdata, message): try: topic = message.topic rawdata = str(message.payload.decode("utf-8")) jsondata = json.loads(rawdata) if topic == device_shadow_update_rejected_topic: logging.warning("Telemetry message got rejected...") else: logging.info("Topic: " + message.topic + "\nMessage: " + rawdata) create_commands(jsondata, topic) except Exception as e: logging.error("Error occurred " + str(e)) ################################## # Queue Based Command processing ################################## def create_commands(jsondata, topic): command_delay = 1 stop_delay = 100e-3 # 100ms data = jsondata["value"] if topic == "drone/takeoff": enqueue_command(lambda: drone.takeoff(), 0) elif topic == "drone/land": enqueue_command(lambda: drone.land(), 0) elif topic == "drone/direction": if data == "right": enqueue_command(lambda: drone.right(speed), command_delay) enqueue_command(lambda: drone.right(0), stop_delay) elif data == "left": enqueue_command(lambda: drone.left(speed), command_delay) enqueue_command(lambda: drone.left(0), stop_delay) elif data == "forward": enqueue_command(lambda: drone.forward(speed), command_delay) enqueue_command(lambda: drone.forward(0), stop_delay) elif data == "back": enqueue_command(lambda: drone.backward(speed), command_delay) enqueue_command(lambda: drone.backward(0), stop_delay) elif data == "up": enqueue_command(lambda: drone.up(speed), command_delay) enqueue_command(lambda: drone.up(0), stop_delay) elif data == "down": enqueue_command(lambda: drone.down(speed), command_delay) enqueue_command(lambda: drone.down(0), stop_delay) else: pass elif topic == "drone/flip": enqueue_command(lambda: drone.flip_forward(), 0) elif topic == "drone/rotate": if data == "left": enqueue_command(lambda: drone.counter_clockwise(speed), command_delay) enqueue_command(lambda: drone.counter_clockwise(0), stop_delay) elif data == "right": enqueue_command(lambda: drone.clockwise(speed), command_delay) enqueue_command(lambda: drone.clockwise(0), stop_delay) else: pass else: pass # Enqueuing commands def enqueue_command(command_callback, delay): command_object = command(command_callback, delay) command_queue.put(command_object) def process_command(): while True: try: command_item = command_queue.get_nowait() if command_item is None: break command_item.command_function() time.sleep(command_item.delay) command_queue.task_done() except queue.Empty: # ignore empty queue exceptions pass except Exception as ex: logging.error(str(ex)) logging.info("Command loop finished") def create_wait_threads(): global command_queue command_queue = queue.Queue() command_processor_thread = threading.Thread(target=process_command) # Define a thread command_processor_thread.setDaemon( True) # 'True' means it is a front thread,it would close when the mainloop() closes command_processor_thread.start() drone_telemetry_thread = threading.Thread(target=send_telemetry_loop) # Define a thread drone_telemetry_thread.setDaemon( True) # 'True' means it is a front thread,it would close when the mainloop() closes drone_telemetry_thread.start() # Block the thread drone_telemetry_thread.join() # Block the queue command_queue.join() ############################## # Entry point ############################## if __name__ == "__main__": try: aws_client = awsIoTClient(config) drone = connect_drone() aws_client.subscribe([ 'drone/takeoff', 'drone/land', 'drone/direction', 'drone/rotate', 'drone/flip' # device_shadow_update_rejected_topic ], message_callback) send_telemetry(initial_data, False) logging.info('Initial telemetry sent...') # Waiting for drone connection... while is_drone_connected is False: print("Waiting for connection...", end="\r") time.sleep(100e-3) pass create_wait_threads() # cancelling command loop command_queue.put(None) logging.warning('Sending final telemetry sent...') send_telemetry(initial_data, False) except KeyboardInterrupt: logging.warning('KeyboardInterrupt...') logging.warning('Sending final telemetry sent...') send_telemetry(initial_data, False) time.sleep(1) except Exception as e: # exc_type, exc_value, exc_traceback = sys.exc_info() # traceback.print_exception(exc_type, exc_value, exc_traceback) logging.error(str(e)) finally: if drone is not None: drone.land() drone.quit() if aws_client is not None: aws_client.disconnect() logging.info('Exiting program...') exit(1)
UTF-8
Python
false
false
9,239
py
6
start.py
3
0.597359
0.590973
0
287
31.191638
93
karthikpappu/pyc_source
5,858,335,414,464
861ca8f8ae68498e8ddce47b05d8fa8b11a6894f
91fa095f423a3bf47eba7178a355aab3ca22cf7f
/pypi_install_script/python-simpledaemon-0.1.tar/setup.py
5e9b61d707e9f7e8def38562c686373556af4b89
[]
no_license
https://github.com/karthikpappu/pyc_source
0ff4d03e6d7f88c1aca7263cc294d3fa17145c9f
739e7e73180f2c3da5fd25bd1304a3fecfff8d6e
refs/heads/master
2023-02-04T11:27:19.098827
2020-12-27T04:51:17
2020-12-27T04:51:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python __version__ = '0.1' __author__ = 'Richard Hoop' import sys try: from setuptools import setup except ImportError: print("python-simpledaemon needs setuptools in order to build. Install it using" " your package manager (usually python-setuptools) or via pip (pip" " install setuptools).") sys.exit(1) setup( name='python-simpledaemon', version=__version__, description='Easy Python Daemon', author=__author__, author_email='richard@projecticeland.net', license='GPLv3', data_files=[], url="https://github.com/gemini/python-simpledaemon", packages=['simpledaemon'] )
UTF-8
Python
false
false
658
py
114,545
setup.py
111,506
0.661094
0.655015
0
26
24.307692
84
plasticine/cobracommander-henchman
2,061,584,330,668
1337657dddff70c1ab8b5b09432ab351a1a719fa
5d2c0a3549f394d855c2a2c07db6adc38e62a5d8
/henchman/buildqueue.py
02803fd49f9475b015fad50fb0c5080ed7859b38
[]
no_license
https://github.com/plasticine/cobracommander-henchman
a74abd71e7853b8db2aba4247bdf76611fb5bffb
afe26810a2dfb093d917e64b02b88295a83db174
refs/heads/master
2020-06-09T03:43:57.336757
2012-02-21T07:05:36
2012-02-21T07:05:36
2,833,997
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import gevent import json from .minion import Minion from .utils.logger import get_logger class BuildQueue(object): """ The BuildQueue class is used to manage Minions either currently being built or waiting to be built. Defines socket.io methods for subscribing and updating the build queue. These are wrapped up on django-socketio events. """ def __init__(self): self._queue = [] self._completed = [] self._monitor_sleep_time = 1 self._monitor_hibernate_time = 5 self._current_item = 0 self._logger = get_logger(__name__) self._logger.info('Monitoring queue for incoming builds') gevent.spawn(self._monitor) def __len__(self): return len(self._queue) def __iter__(self): return self def __getitem__(self, key): return self._queue[key] def next(self): if (self._current_item == len(self._queue)): self._current_item = 0 raise StopIteration else: data = self._queue[self._current_item] self._current_item += 1 return data def append(self, id): """ Create a new Minion instance for `id` and append it to the internal queue list. """ self._queue.append(self._wrap_minion(id)) self._logger.info('Appended new build to queue with id:%s, queue length is now %s', id, len(self._queue)) def _wrap_minion(self, id): return Minion(id=id) def _monitor(self): """ Poll `_queue` to see if we need to start a new Minion. """ while True: # filter queue for only items that are waiting to execute. if len(self._queue): if len(filter(lambda x: not x.is_waiting, self._queue)) < 1: minion = self._queue[0] self._logger.info('Putting minion to work') minion.start() self._clean_queue() self._hibernate() gevent.sleep(self._monitor_sleep_time) def _hibernate(self): self._logger.info('Hibernating for %s seconds', self._monitor_hibernate_time) gevent.sleep(self._monitor_hibernate_time) def _clean_queue(self): """ remove completed Minions from the build queue and prepend them to the complete queue for reference. """ self._logger.info('Cleaning internal build queue') completed = self._completed complete = [i for i, x in enumerate(self._queue) if x.is_complete] [completed.insert(0, self._queue[x]) for x in complete] self._completed = completed[:5] self._queue[:] = [x for x in self._queue if not x.is_complete]
UTF-8
Python
false
false
2,489
py
38
buildqueue.py
30
0.64323
0.639614
0
84
28.630952
109
dayjaby/CrowdAnki
9,921,374,484,194
62151f11e05ae017685e8afd3b111ef0f612057b
c604da64c262d6d0244abeaf169ae91e3119884e
/crowd_anki/anki_exporter.py
39a02870d9dddd68eecbcba3dc39de2655298b54
[ "MIT" ]
permissive
https://github.com/dayjaby/CrowdAnki
27d2d7c31d403f6ee98cc2cb8f44fd6f7b4bc395
39c9666d58b16483631c13521597ae38a9d66cfa
refs/heads/master
2021-01-21T08:33:22.067652
2016-09-07T09:59:00
2016-09-07T09:59:00
67,587,160
0
0
null
true
2016-09-07T08:23:13
2016-09-07T08:23:12
2016-09-07T06:04:47
2016-08-31T19:12:32
70
0
0
0
null
null
null
import json import os import shutil from thirdparty.pathlib import Path from crowd_anki.utils.constants import DECK_FILE_EXTENSION, MEDIA_SUBDIRECTORY_NAME from crowd_anki.representation.deck import Deck class AnkiJsonExporter(object): def __init__(self, collection): self.collection = collection def export_deck_to_directory(self, deck_name, output_dir=Path("."), copy_media=True): deck_directory = output_dir.joinpath(deck_name) deck_directory.mkdir(parents=True, exist_ok=True) deck = Deck.from_collection(self.collection, deck_name) deck_filename = deck_directory.joinpath(deck_name).with_suffix(DECK_FILE_EXTENSION) with deck_filename.open(mode='w') as deck_file: deck_file.write(unicode(json.dumps(deck, default=Deck.default_json, sort_keys=True, indent=4, ensure_ascii=False))) self._save_changes() if copy_media: self._copy_media(deck, deck_directory) def _save_changes(self): """Save updates that were maid during the export. E.g. UUID fields""" # This saves decks and deck configurations self.collection.decks.save() self.collection.decks.flush() self.collection.models.save() self.collection.models.flush() # Notes? def _copy_media(self, deck, deck_directory): media_directory = deck_directory.joinpath(MEDIA_SUBDIRECTORY_NAME) media_directory.mkdir(parents=True, exist_ok=True) for file_src in deck.get_media_file_list(): shutil.copy(os.path.join(self.collection.media.dir(), file_src), str(media_directory.resolve()))
UTF-8
Python
false
false
1,853
py
6
anki_exporter.py
5
0.602806
0.602267
0
51
35.333333
91
Tomoki-Kikuta/atcoder
8,718,783,628,295
583d1eb54819c35a4c2ededdec99cf69f4b027c6
796198b4613ae30ff7735d7a8473064b8ecb0247
/atcoder過去問/all_pairs_shortest_path.py
0a59511165ac86b03aa16ed23df703cdd8f36781
[]
no_license
https://github.com/Tomoki-Kikuta/atcoder
993cb13ae30435d02ea2e743cf3cead1a7882830
97b886de867575084bd1a70310a2a9c1c514befe
refs/heads/master
2021-07-16T15:14:00.706609
2020-06-29T06:15:13
2020-06-29T06:15:13
184,001,549
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def warshall_floyd(dp, v): for k in range(v): for i in range(v): for j in range(v): dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]) def check(dp, v): for k in range(v): for i in range(v): for j in range(v): if dp[i][j] > dp[i][k] + dp[k][j]: return False return True def main(): v, e = map(int, input().split()) INF = 10 ** 10 MAX = 2 * (10 ** 7) MIN = -2 * (10 ** 7) dp = [[INF for i in range(v)] for j in range(v)] for i in range(e): s, t, d = map(int, input().split()) dp[s][t] = d for i in range(v): for j in range(v): if i == j: dp[i][j] = 0 warshall_floyd(dp, v) if not check(dp, v): print("NEGATIVE CYCLE") else: for i in range(v): for j in range(v): if j > 0: print(end=' ') if dp[i][j] > MAX * v or dp[i][j] < MIN * v: print("INF", end='') else: print(dp[i][j], end='') print() if __name__ == '__main__': main()
UTF-8
Python
false
false
1,174
py
178
all_pairs_shortest_path.py
178
0.38586
0.373935
0
47
23.978723
61
reachgsreeja/school_management
10,849,087,397,633
d2e63cbff7af8e994a872c8c0942bf89062c3e8f
a2a042e26c2603f1fd831df355f90607eddc0b98
/schoolboard/school_1/admission/models.py
947a96eba6f3a64263b590ec0fb5b6391918a7c0
[]
no_license
https://github.com/reachgsreeja/school_management
8f2f4a0b9aec896881aaded63367d026dcf0d0ef
a20b8b9717a48e49c59efe8b5a2c7dc3fd99cc83
refs/heads/master
2021-01-26T03:11:53.777891
2020-02-27T14:54:13
2020-02-27T14:54:13
243,285,359
0
0
null
false
2020-02-28T13:28:18
2020-02-26T14:40:09
2020-02-27T14:54:43
2020-02-28T13:20:40
26,650
0
0
1
JavaScript
false
false
from django.db import models from datetime import datetime # Create your models here. class StudentInfo(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) student_class = models.PositiveIntegerField() date_of_birth = models.DateField(null=False) acadamic_year = models.PositiveIntegerField(null=True, blank=False) gender = models.CharField(max_length=50) student_image = models.ImageField(null=True, blank=True) def __str__(self): return ( self.first_name + ' ' + self.last_name ) class StudentParentInfo(models.Model): student = models.ForeignKey(StudentInfo, on_delete=models.CASCADE) father_name = models.CharField(max_length=255) mother_name = models.CharField(max_length=255) contact_info = models.CharField(max_length=10) email_id = models.EmailField(max_length=255) address1 = models.CharField(max_length=255) address2 = models.CharField(max_length=255) city = models.CharField(max_length=50) state = models.CharField(max_length=100) country_code = models.CharField(max_length=10) postal_code = models.CharField(max_length=10) def __str__(self): return self.father_name + self.email_id class TeacherInfo(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) gender = models.CharField(max_length=50) date_of_birth = models.DateField() qualifications = models.CharField(max_length=255) subject_teaches = models.CharField(max_length=10) contact_num = models.CharField(max_length=10) email_id = models.EmailField(max_length=100) address = models.CharField(max_length=255) city = models.CharField(max_length=50) state = models.CharField(max_length=100) country = models.CharField(max_length=20) postal_code = models.CharField(max_length=50) def __str__(self): return self.first_name + self.gender class Results(models.Model): semester_choices = ( ('quarterly', 'Quarterly Exam'), ('half_yearly', 'Half Yearly Exam'), ('yearly', 'Yearly Exam'), ) student = models.ForeignKey(StudentInfo, on_delete=models.CASCADE) telugu = models.IntegerField(default=0) hindi = models.IntegerField(default=0) english = models.IntegerField(default=0) maths = models.IntegerField(default=0) science = models.IntegerField(default=0) social = models.IntegerField(default=0) semester = models.CharField(max_length=100, blank=True, choices=semester_choices) def total_marks(self): return self.telugu + self.hindi + self.english + self.maths + self.science + self.social
UTF-8
Python
false
false
2,706
py
30
models.py
16
0.703252
0.675536
0
69
38.15942
96
luimaking/Agriculture
18,519,898,985,401
9832f1fa10e6042f8cbf7334b6b30cccfa2c6a5b
6e971d53fa4e2c37d853a3516a282db00ea70b55
/agricultura/agro/agro/urls.py
fc8e4fa94506d284b1a1d5238962e78a6f3b5248
[]
no_license
https://github.com/luimaking/Agriculture
1522a589e47996fb76ba4396b15252f1bf29fd34
2c4af741e6e5f2b2bf238f213aa9bbf1e083c6bc
refs/heads/master
2015-08-07T14:04:35.529690
2013-04-05T23:30:53
2013-04-05T23:30:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', url(r'^$','miapp.views.clientes_reciente'), url(r'^herramienta/nueva/$','miapp.views.nueva_herramienta'), url(r'^insumo/nuevo/$','miapp.views.nuevo_insumo'), url(r'^empleado/nuevo/$','miapp.views.nuevo_empleado'), url(r'^proveedor/nuevo/$','miapp.views.nuevo_proveedor'), url(r'^galpon/nuevo/$','miapp.views.nuevo_galpones'), url(r'^campo/nuevo/$','miapp.views.nuevo_campo'), url(r'^stock/nuevo/$','miapp.views.nuevo_stock'), url(r'^cliente/nuevo/$','miapp.views.nuevo_cliente'), url(r'^clientes/$','miapp.views.lista_clientes'), url(r'^detalle/cliente/(?P<id_clt>\d+)$','miapp.views.detalle_cliente'), url(r'^telefono/cliente/(?P<id_clt>\d+)$','miapp.views.telefono_cliente'), url(r'^borrar/(?P<id_cliente>\d+)$','miapp.views.borrar_cliente'), url(r'^editar/(?P<id_cliente>\d+)$','miapp.views.editar_cliente'), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), )
UTF-8
Python
false
false
1,125
py
14
urls.py
5
0.683556
0.683556
0
25
44
76
gercaballero/U5-PRACTICO-WEB
8,495,445,354,453
50268cabca8e5bcacf2b76da2a8a2d17804bb8f2
15149551d64b767d7c776c2bc81811f6ee5aaef3
/app.py
d75490eff089686ba56e20d1fa6afab16ba1aa63
[]
no_license
https://github.com/gercaballero/U5-PRACTICO-WEB
7ef04b87a5d8e4d4c8aa55de5d96f9fab0fd0a72
133c1fee99d61a0cfc6c51f1cae510af858020ba
refs/heads/main
2023-08-23T19:51:46.423705
2021-10-05T21:26:39
2021-10-05T21:26:39
376,780,631
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from datetime import datetime from flask import Flask, redirect, request, render_template, flash,session, url_for from flask_sqlalchemy import SQLAlchemy from werkzeug.security import generate_password_hash, check_password_hash import hashlib app = Flask(__name__) app.config.from_pyfile('config.py') from models import db from models import Usuario,Viaje, Movil @app.route('/') def inicio(): return render_template('inicio.html') '''REGISTRO DE USUARIO''' @app.route('/registro_usuario', methods= ['GET','POST']) def registro_usuario(): if request.method=='POST': if not request.form['DNI'] or not request.form['password']: return render_template('error.html', error="Los datos ingresados no son correctos...") else: usuario_actual = Usuario.query.filter_by(DNI = request.form['DNI']).first() if usuario_actual is not None: return render_template('error.html', error="ERROR: USUARIO CON DNI EXISTENTE") else: clave= request.form['password'] Clave=hashlib.md5(bytes(clave, encoding='utf-8')) nuevo_usuario = Usuario(DNI=request.form['DNI'],nombre=request.form['nombre'], clave=Clave.hexdigest(), tipo=request.form['tipo']) db.session.add(nuevo_usuario) db.session.commit() return render_template('error.html', error="Usuario Registrado con exito...") return render_template('registro.html') '''INICIAR SESION''' @app.route('/login', methods = ['GET','POST']) def login(): if request.method == 'POST': if not request.form['DNI'] or not request.form['password']: return render_template('error.html', error="Por favor ingrese los datos requeridos") else: usuario_actual = Usuario.query.filter_by(DNI = request.form['DNI']).first() if usuario_actual is None: return render_template('error.html', error="El DNI no está registrado") else: verif=request.form['password'] verificacion = hashlib.md5(bytes(verif, encoding='utf-8')) if verificacion.hexdigest() ==usuario_actual.clave: if usuario_actual.tipo == 'cli': return redirect(url_for('cliente', cliente_dni = usuario_actual.DNI)) elif usuario_actual.tipo == 'op': return redirect(url_for('operador',operador_dni=usuario_actual.DNI)) else: return render_template('error.html', error="El tipo no es Valido") else: return render_template('error.html', error="La contraseña no es válida") else: return render_template('login.html') '''FUNCIONALIDADES CLIENTE''' @app.route('/cliente/<cliente_dni>',methods=['GET','POST']) def cliente(cliente_dni): usuario_actual = Usuario.query.filter_by(DNI = cliente_dni).first() return render_template('vistaCliente.html',usuario=usuario_actual) @app.route('/cliente/<cliente_dni>/solicitarMovil/', methods = ['POST', 'GET']) def solicitarMovil(cliente_dni): usuario_actual = Usuario.query.filter_by(DNI = cliente_dni).first() if request.method == 'POST': listadeviajes = Viaje.query.all() id = int(len(listadeviajes)) + 1 fecha1=datetime.now() fecha = datetime.strftime(fecha1, '%Y-%m-%d %H:%M:%S') fecha = datetime.strptime(fecha, '%Y-%m-%d %H:%M:%S') importe = 0 # sin calcular origen = request.form['origen'] destino = request.form['destino'] numeromovil = 0 demora = 0 duracion = 0 viaje = Viaje(IDViaje = id, origen = origen, destino = destino, fecha = fecha, demora = demora, duracion = duracion, importe = importe, DNICliente = cliente_dni, numMovil = numeromovil) db.session.add(viaje) db.session.commit() usuario_actual = Usuario.query.filter_by(DNI = cliente_dni).first() return render_template('alerta_cli.html', error='Se ha solicitado el movil de forma correcta', usuario=usuario_actual) return render_template('solicitarMovil.html',usuario=usuario_actual) @app.route('/cliente/<cliente_dni>/consultar_movil/', methods = ['POST', 'GET']) def consultar_movil(cliente_dni): usuario_actual = Usuario.query.filter_by(DNI = cliente_dni).first() lista = Viaje.query.filter_by(importe = 0).all() listaMoviles = Movil.query.all() listaViajes=[] for viaje in lista: if viaje.duracion==0 and viaje.DNICliente == usuario_actual.DNI: listaViajes.append(viaje) longitud=len(listaViajes) return render_template('consultar_movil.html', usuario=usuario_actual,viajes=listaViajes,moviles=listaMoviles,len=longitud) '''FUNCIONALIDADES OPERADOR''' @app.route('/operador/<operador_dni>') def operador(operador_dni): usuario_actual = Usuario.query.filter_by(DNI = operador_dni).first() return render_template('vistaOperador.html',usuario=usuario_actual) @app.route('/operador/<operador_dni>/asigno', methods = ['POST', 'GET']) def asigno(operador_dni): usuario_actual = Usuario.query.filter_by(DNI = operador_dni).first() listadeviajes = Viaje.query.filter_by(numMovil = 0).all() longitud=len(listadeviajes) return render_template('asignar_movil.html', usuario=usuario_actual,viajes = listadeviajes,len=longitud) @app.route('/operador/<operador_dni>/asigno/<viajeID>/elegirMovil', methods = ['POST', 'GET']) def elegirMovil(operador_dni,viajeID): usuario_actual = Usuario.query.filter_by(DNI = operador_dni).first() viaje_actual= Viaje.query.filter_by(IDViaje=int(viajeID)).first() lista=Movil.query.all() listademoviles=[] for movil in lista: if movil.viajeBool==0: listademoviles.append(movil) longitud=len(listademoviles) if request.method == 'POST': num=int(request.form['MovilNum']) movil_actual =Movil.query.filter_by(numero = request.form['MovilNum']).first() demora=int(request.form['espera']) viaje_actual.numMovil=num viaje_actual.demora=demora movil_actual.viajeBool = int(viajeID) db.session.commit() return render_template('alerta_op.html', error='MOVIL ASIGNADO',usuario=usuario_actual) else: return render_template('elegirMovil.html',moviles=listademoviles,usuario=usuario_actual,viaje=viaje_actual,len=longitud) @app.route('/operador/<operador_dni>/finalizar_viaje', methods = ['POST', 'GET']) def finalizar_viaje(operador_dni): usuario_actual = Usuario.query.filter_by(DNI = operador_dni).first() if request.method == 'POST': viaje = Viaje.query.filter_by(IDViaje = int(request.form['finalizar'])).first() duracion=int(request.form['duracion']) movil = Movil.query.filter_by(numero = str(viaje.numMovil)).first() movil.viajeBool = int(0) importe=100.0+(duracion*5) if viaje.demora>15: importe+=importe*0.10 viaje.duracion=duracion viaje.importe=importe db.session.commit() return render_template ('alerta_op.html',usuario=usuario_actual ,error='Viaje Finalizado',aviso=('Importe final:{}'.format(importe))) else: listaViajes = Viaje.query.filter_by(duracion = 0).all() listaDef=[] print(listaViajes) for viaje in listaViajes: if viaje.numMovil != 0: listaDef.append(viaje) longitud=len(listaDef) return render_template('finalizar_viaje.html',usuario=usuario_actual,viajes=listaDef,len=longitud) @app.route('/operador/<operador_dni>/consultar_viaje_movil', methods = ['POST', 'GET']) def consultar_viaje_movil(operador_dni): usuario_actual = Usuario.query.filter_by(DNI = operador_dni).first() if request.method == 'POST': impTotal=0 movilNum=int(request.form['ElegirMovil']) fecha=request.form['fecha_elegir'] listademoviles = Movil.query.all() listaViajes = Viaje.query.all() listaViajesFinalizados=[] for viaje in listaViajes: if viaje.duracion>0: listaViajesFinalizados.append(viaje) listaViajesDeMovil=[] for viaje in listaViajesFinalizados: if int(viaje.numMovil)==movilNum: fechaSinHORA=datetime.strftime(viaje.fecha, '%Y-%m-%d') if fechaSinHORA==fecha: impTotal=impTotal+viaje.importe listaViajesDeMovil.append(viaje) longitud=len(listaViajesDeMovil) return render_template('consultar_viaje2.html',usuario=usuario_actual,viajes=listaViajesDeMovil,importe=impTotal,len=longitud ) else: listademoviles = Movil.query.all() return render_template('consultar_viaje.html',usuario=usuario_actual,moviles=listademoviles) if __name__ == '__main__': db.create_all() app.run(debug = True)
UTF-8
Python
false
false
9,297
py
19
app.py
3
0.625457
0.622122
0
201
44.238806
197
vodolazik/CC-homework-1
10,995,116,325,785
4db80cc62c2435fcdb84c43afc8418117fb3a6fd
620157db586d43cf27bc93ae08a1d3219dc71c0b
/Code Club. Homework1.py
ba143981a783eb7902d77210797f0b628de541dd
[]
no_license
https://github.com/vodolazik/CC-homework-1
7905df1727226d7134e4c4d64186002dabf22f94
88e80bc449cee24d000f4ce781e64ca290decd69
refs/heads/master
2022-12-11T21:11:19.861469
2020-08-29T16:10:44
2020-08-29T16:10:44
291,304,280
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import tkinter as tk import json import requests response = requests.get("https://bank.gov.ua/NBUStatService/v1/statdirectory/exchangenew?json&valcode=USD") todos = json.loads(response.text) a = todos[0] b = a['rate'] class SampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.lable1 = tk.Label(text="Курс доллара на сегодня " + str(a['rate'])) self.lable1.pack() self.lable2 = tk.Label(text="Введите цену товара в Долларах США") self.lable2.pack() self.entry = tk.Entry(self) self.button = tk.Button(self, text="Рассчитать", command=self.on_button) self.entry.pack() self.button.pack() def on_button(self): content = float((self.entry.get())) c = int(content * b) self.lable3 = tk.Label(text="Цена товара в Гривнах: " + str(c)) self.lable3.pack() app = SampleApp() app.mainloop()
UTF-8
Python
false
false
1,016
py
1
Code Club. Homework1.py
1
0.604899
0.596379
0
31
28.354839
107
Delta-Lyceum/Delta-Lyceum
111,669,168,370
f0485b35c01744120b09622bd2be9c65954eb4f4
056f615b2911f2f144ba25dfc69f7429f8b73de8
/nexus/urls.py
ea13bb5d607f36d8801a6bd9225a5f76fda9358a
[ "Apache-2.0" ]
permissive
https://github.com/Delta-Lyceum/Delta-Lyceum
3067430de45ed10a89a62ae9f6bd1f5b6e2bf7d6
534fc6fa82b831d13bb3fe34980d29da42746e37
refs/heads/master
2020-03-21T21:14:13.838939
2019-02-19T03:47:11
2019-02-19T03:47:11
139,053,778
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.urls import path, include from . import views app_name = 'nexus' urlpatterns = [ path('nexus/create/', views.create_nexus, name='create_nexus'), path('nexus/<int:nexus_id>/edit/', views.edit_nexus, name='edit_nexus'), path('nexus/<int:nexus_id>/view/', views.view_nexus, name='view_nexus'), path('nexus/<int:nexus_id>/media/upload/', views.upload_media, name='upload_media'), path('nexus/<int:nexus_id>/image/load/', views.load_image, name='load_image'), path('nexus/<int:nexus_id>/audio/load/', views.load_audio, name='load_audio'), path('nexus/<int:nexus_id>/video/load/', views.load_video, name='load_video'), path('nexus/<int:nexus_id>/image/remove/', views.remove_image, name='remove_image'), path('nexus/<int:nexus_id>/audio/remove/', views.remove_audio, name='remove_audio'), path('nexus/<int:nexus_id>/video/remove/', views.remove_video, name='remove_video'), path('nexus/<int:nexus_id>/applause/', views.display_applause, name='display_applause'), path('nexus/<int:nexus_id>/reverbs/', views.display_reverbs, name='display_reverbs'), path('nexus/<int:nexus_id>/delete/', views.delete_nexus, name='delete_nexus'), #Ajax path('ajax/nexus/feed/views/', views.add_feed_views, name='add_feed_views'), path('ajax/nexus/tags/track/', views.track_tags, name='track_tags'), path('ajax/nexus/<int:nexus_id>/update/', views.update_nexus, name='update_nexus'), path('ajax/nexus/<int:nexus_id>/image/save/', views.save_image, name='save_image'), path('ajax/nexus/<int:nexus_id>/youtube/save/', views.save_youtube_video, name='save_youtube_video'), path('ajax/nexus/<int:nexus_id>/score/remove/', views.remove_score, name='remove_score'), path('ajax/nexus/<int:nexus_id>/notio/remove/', views.remove_notio, name='remove_notio'), path('ajax/nexus/<int:nexus_id>/tags/search/', views.search_tags, name='search_tags'), path('ajax/nexus/<int:nexus_id>/tags/add/', views.add_tag, name='add_tag'), path('ajax/nexus/<int:nexus_id>/tags/remove/', views.remove_tag, name='remove_tag'), path('ajax/nexus/<int:nexus_id>/info/', views.get_nexus_info, name='get_nexus_info'), path('ajax/nexus/<int:nexus_id>/applaud/', views.applaud_nexus, name='applaud_nexus'), path('ajax/nexus/<int:nexus_id>/reverb/', views.reverb_nexus, name='reverb_nexus'), path('ajax/nexus/<int:nexus_id>/reverb/user/', views.get_reverb_user, name='get_reverb_user'), path('ajax/nexus/<int:nexus_id>/comment/', views.nexus_comment, name='nexus_comment'), ]
UTF-8
Python
false
false
2,543
py
240
urls.py
90
0.679512
0.679512
0
36
69.638889
105
lepy/phuzzy
3,753,801,453,100
b7c95f3f0a70a610b41a5f6991eb0d7c7db531d2
4e77443a5659825a53b94014462afc9fcb1b4dc9
/tests/test_regression.py
fec222d581786ef447ab776887beaf2a691b6b1c
[ "MIT" ]
permissive
https://github.com/lepy/phuzzy
f745c5619f9efca45c9f5f8340514e2117e65c78
22321dadc1d70b25d1213ddabcdbb99c40d15d6d
refs/heads/master
2023-08-19T02:59:43.627881
2020-12-11T07:08:59
2020-12-11T07:08:59
95,642,408
2
3
MIT
false
2020-12-07T17:22:07
2017-06-28T07:38:13
2020-12-03T18:40:32
2020-12-07T17:22:05
6,714
2
2
3
Jupyter Notebook
false
false
# -*- coding: utf-8 -*- import numpy as np import xgboost from sklearn.model_selection import RandomizedSearchCV from sklearn.metrics import make_scorer from scipy.stats import spearmanr def spearman_score(x, y): return spearmanr(x, y)[0] def test_CV2(): def func(X): return ((X[:,0]+0.1)*(X[:,1]-2.2))**2 np.random.seed(101) X_train = np.random.random((1000, 2)) y_train = func(X_train) # print(y_train) params = {'learning_rate':[0.5, 0.2, 0.1, 0.05, 0.02, 0.01], 'gamma':[0.1, 0.2, 0.5, 1, 2, 5], 'reg_alpha':10. * np.arange(-8, 2, .25), 'reg_lambda':10. * np.arange(-8, 2, .25), 'subsample': [0.1, 0.2, 0.5, 0.7, 0.9], 'max_depth': [1, 2, 3] } model = RandomizedSearchCV(xgboost.XGBRegressor(), param_distributions=params, n_iter=100, scoring=make_scorer(spearman_score), cv=5, n_jobs=-1, verbose=1, random_state=1001) model.fit(X_train, y_train) def test_CV(): import numpy as np from time import time from scipy.stats import randint as sp_randint from sklearn.model_selection import GridSearchCV from sklearn.model_selection import RandomizedSearchCV from sklearn.datasets import load_digits from sklearn.ensemble import RandomForestClassifier # get some data digits = load_digits() X, y = digits.data, digits.target # build a classifier clf = RandomForestClassifier(n_estimators=20) # Utility function to report best scores def report(results, n_top=3): for i in range(1, n_top + 1): candidates = np.flatnonzero(results['rank_test_score'] == i) for candidate in candidates: print("Model with rank: {0}".format(i)) print("Mean validation score: {0:.3f} (std: {1:.3f})".format( results['mean_test_score'][candidate], results['std_test_score'][candidate])) print("Parameters: {0}".format(results['params'][candidate])) print("") # specify parameters and distributions to sample from param_dist = {"max_depth": [3, None], "max_features": sp_randint(1, 11), "min_samples_split": sp_randint(2, 11), "min_samples_leaf": sp_randint(1, 11), "bootstrap": [True, False], "criterion": ["gini", "entropy"]} # run randomized search n_iter_search = 20 random_search = RandomizedSearchCV(clf, param_distributions=param_dist, n_iter=n_iter_search) start = time() random_search.fit(X, y) print("RandomizedSearchCV took %.2f seconds for %d candidates" " parameter settings." % ((time() - start), n_iter_search)) report(random_search.cv_results_) # use a full grid over all parameters param_grid = {"max_depth": [3, None], "max_features": [1, 3, 10], "min_samples_split": [2, 3, 10], "min_samples_leaf": [1, 3, 10], "bootstrap": [True, False], "criterion": ["gini", "entropy"]} # run grid search grid_search = GridSearchCV(clf, param_grid=param_grid) start = time() grid_search.fit(X, y) print("GridSearchCV took %.2f seconds for %d candidate parameter settings." % (time() - start, len(grid_search.cv_results_['params']))) report(grid_search.cv_results_)
UTF-8
Python
false
false
3,526
py
91
test_regression.py
57
0.568633
0.536018
0
100
34.26
114
boringPpl/Crash-Course-on-Python
9,569,187,164,388
430dfe6d1636c691e37695eb83fd33bb396ce0c4
f7afcb4c1022b685364d7dfac01b07e6a5ced73f
/Exercises on IDE/2 Data types, Variables, Expressions/ex2_4_expression.py
ee0ccb6be0c96d53e6e34526361fc8fa161f8d9a
[]
no_license
https://github.com/boringPpl/Crash-Course-on-Python
8d65c22f2a11483f21c136365903bdc8d6c81982
d42c37fac9b34d3b87ff6527a7fb847b31d69586
refs/heads/master
2023-04-21T01:59:58.615826
2021-05-17T10:40:21
2021-05-17T10:40:21
281,635,893
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Question 2.4: Keeping in mind there are 86400 seconds per day, write a program that calculates how many seconds there are in a year, if a year is 365 days.Print the result on the screen. Note: Your result should be in the format of just a number, not a sentence. '''
UTF-8
Python
false
false
277
py
40
ex2_4_expression.py
39
0.736462
0.700361
0
7
38.142857
75
0xchase/angr-ctf
14,903,536,533,422
2f37553757a5cb9ad226bc7143d635677dcc28a9
9f17f11bf247a7751952ef624ab42b8d7b3d1f30
/07_angr_symbolic_file/solve.py
32050a9b4ae35b948175f8085cd68042e7dcfcbd
[]
no_license
https://github.com/0xchase/angr-ctf
27deaf271a704b395eb710ff3ea878abe3ac74d2
f080003bf99b13596357a8e0b25c6736c5687639
refs/heads/master
2022-03-30T01:16:40.227595
2020-02-04T13:55:41
2020-02-04T13:55:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3 import angr project = angr.Project("07_angr_symbolic_file") state = project.factory.entry_state() simgr = project.factory.simgr(state) simgr.explore(find=0x80489b2, avoid=0x8048998) if simgr.found: print(simgr.found[0].posix.dumps(0).decode()) else: print("No solution found")
UTF-8
Python
false
false
308
py
11
solve.py
10
0.730519
0.665584
0
14
21
49
sunniee/OMGEmotionChallengeCode
3,109,556,352,716
38d9dae169368862edaf4939d72bf8bbb2fb9721
05e805726cfdf7a40e2d49e4fcef4417b88e92b7
/codes/CNN_model.py
cf8a07606c2304358311fede5ac0789d881ec39b
[]
no_license
https://github.com/sunniee/OMGEmotionChallengeCode
0943aff3326e7bf30628e31d66487df19644bfa7
1f893b38afa7e160fb6ea3ec3a030ef5596b2765
refs/heads/master
2020-08-01T19:52:14.597775
2018-04-30T18:59:07
2018-04-30T18:59:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import tensorflow as tf from keras.models import * from keras.layers import * from keras.optimizers import * from keras import regularizers def model(timesteps=64, dim=512, unit=256, filters=128, ac='sigmoid',mode='pred'): inputs = Input((timesteps, dim)) x1 = Conv1D(filters, 5, strides=1, padding='valid', input_shape=(timesteps, dim),name='conv1')(inputs) x1 = BatchNormalization(name='bn1')(x1) x1 = Activation('relu')(x1) x1 = GlobalMaxPooling1D()(x1) x2 = Conv1D(filters, 4, strides=1, padding='valid', input_shape=(timesteps, dim),name='conv2')(inputs) x2 = BatchNormalization(name='bn2')(x2) x2 = Activation('relu')(x2) x2 = GlobalMaxPooling1D()(x2) x3 = Conv1D(filters, 3, strides=1, padding='valid', input_shape=(timesteps, dim),name='conv3')(inputs) x3 = BatchNormalization(name='bn3')(x3) x3 = Activation('relu')(x3) x3 = GlobalMaxPooling1D()(x3) x4 = Conv1D(filters, 2, strides=1, padding='valid', input_shape=(timesteps, dim),name='conv4')(inputs) x4 = BatchNormalization(name='bn4')(x4) x4 = Activation('relu')(x4) x4 = GlobalMaxPooling1D()(x4) x = Concatenate()([x1, x2, x3, x4]) x = Dense(256, activation='relu',name='dense1')(x) if mode=='feat': output=x else: x = Dropout(0.25)(x) if ac == 'tanh': output = Dense(1, activation='tanh',name='last_dense')(x) elif ac == 'tanh+sigmoid' or ac == 'sigmoid+tanh': x1 = Dense(1, activation='sigmoid',name='last_dense_1')(x) x2 = Dense(1, activation='tanh',name='last_dense_2')(x) output = [x1, x2] else: output = Dense(1, activation='sigmoid',name='last_dense')(x) return Model(inputs=inputs, outputs=output)
UTF-8
Python
false
false
1,771
py
9
CNN_model.py
7
0.621683
0.574252
0
44
39.272727
106
KirillGordievich/mas_framework
11,862,699,718,234
2dbb4d18b4e880b81a2b93216d16ad49b3436ac0
2dfa266ca8dd3bc17bf0cb0c6d292ecff5756649
/src/spawn_turtle.py
568879006be43f63d7debd5f96f0a002adc70a1f
[]
no_license
https://github.com/KirillGordievich/mas_framework
66d944eca1f88a445ddc790f8ac6b34f0fca2f6e
0d3cb556a504f46cef52165cd75a50d6dc8da979
refs/heads/master
2020-04-21T09:05:13.500200
2019-02-13T15:35:09
2019-02-13T15:35:09
169,438,024
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import rospy import math import random import geometry_msgs.msg from turtlesim.srv import Spawn from mas_framework.msg import base from mas_framework.msg import status import turtlesim.msg as turtle class Turtle: def __init__(self, number): self.number = number self.name = 'turtle'+str(self.number) self.status = "wait" self.base_msg = base() self.geometry_msg = geometry_msgs.msg.Twist() self.subscriber_pose = rospy.Subscriber(str( self.name)+'/pose', turtle.Pose, self.callback_pose, queue_size=1) self.velocity_publisher = rospy.Publisher("/turtle"+str( self.number)+"/cmd_vel", geometry_msgs.msg.Twist, queue_size=1) self.coordinate_publisher = rospy.Publisher( "/environment", base, queue_size=1) self.action_publisher = rospy.Publisher("/turtle"+str( self.number)+"/action", base, queue_size=1) self.subscriber_coordinate = rospy.Subscriber( "/environment", base, self.callback_coordinate, queue_size=10) self.subscriber_status_msg = rospy.Subscriber( "/status", status, self.callback_status, queue_size=1) self.general_goal_name = "turtle1" self.local_goal_name = None self.x = 0 self.y = 0 self.phi = 0 self.linear_velocity = 1 self.angular_velocity = 1 self.turtles = {self.name: [self.x, self.y, self.phi]} self.borders_points = {"first_point": [0, 10], "second_point": [10, 0]} def start(self): while self.general_goal_name not in self.turtles: rospy.sleep(3) if self.name != self.general_goal_name: self.trade() self.status = "move" while not rospy.is_shutdown(): if self.name != self.general_goal_name: if self.status == "move": if self.detect_border(): self.border() rospy.loginfo("border") self.move() def move(self): x_goal = self.turtles[self.local_goal_name][0] y_goal = self.turtles[self.local_goal_name][1] if self.phi > math.pi: self.phi = self.phi - 2*math.pi if self.phi < -math.pi: self.phi = self.phi + 2*math.pi phi = self.phi theta = self.get_angle(y_goal - self.y, x_goal - self.x) distance = self.get_distance(x_goal, y_goal, self.x, self.y) angular = self.angular_velocity linear = self.linear_velocity if distance > 1: angular, linear = self.get_velocity(phi, theta) self.geometry_msg.angular.z = angular self.geometry_msg.linear.x = linear else: self.geometry_msg.angular.z = 0 self.geometry_msg.linear.x = 0 self.velocity_publisher.publish(self.geometry_msg) def detect_border(self): for point in self.borders_points: if abs(self.x-self.borders_points[point][0]) < 1: return True for point in self.borders_points: if abs(self.y - self.borders_points[point][1]) < 1: return True def border(self): while self.detect_border(): if self.phi > math.pi: self.phi = self.phi - 2*math.pi if self.phi < -math.pi: self.phi = self.phi + 2*math.pi phi = self.phi theta = self.get_angle(5 - self.y, 5 - self.x) delta = phi - theta angular, linear = self.get_velocity(phi, theta) self.geometry_msg.angular.z = angular self.geometry_msg.linear.x = linear self.velocity_publisher.publish(self.geometry_msg) def callback_pose(self, data): self.x = data.x self.y = data.y self.phi = data.theta self.base_msg.x = data.x self.base_msg.y = data.y self.base_msg.theta = data.theta self.base_msg.load = self.name self.coordinate_publisher.publish(self.base_msg) def callback_coordinate(self, data): self.turtles[data.load] = [data.x, data.y, data.theta] def trade(self): turtles = (sorted(self.turtles.items(), key=lambda item: ( item[1][0] - self.turtles[self.general_goal_name][0]) ** 2 + ( item[1][1] - self.turtles[self.general_goal_name][1]) ** 2)) turtles_order = dict( [(turtles[i][0], i) for i in range(0, len(self.turtles))]) inv_turtles_order = {v: k for k, v in turtles_order.items()} self.local_goal_name = inv_turtles_order[turtles_order[self.name]-1] def callback_status(self, data): if self.name != self.general_goal_name: self.trade() self.status = data.status rospy.sleep(1) def get_distance(self, x1, y1, x2, y2): return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) def get_angle(self, y, x): return math.atan2(y, x) def get_velocity(self, phi, theta): delta = phi - theta linear = self.linear_velocity angular = self.angular_velocity if abs(delta) > 0.1: if phi > 0: if theta > 0: if delta > 0: return -angular, linear else: return angular, linear else: if delta > math.pi: return angular, linear else: return -angular, linear else: if theta > 0: if delta > -math.pi: return angular, linear else: return -angular, linear else: if delta > 0: return -angular, linear else: return angular, linear else: return 0, linear if __name__ == "__main__": rospy.init_node("~turtle", anonymous=True) number = rospy.get_param("~number") rospy.wait_for_service('spawn') if number != 1: x = rospy.get_param("~x_coordinate") y = rospy.get_param("~y_coordinate") theta = rospy.get_param("~theta_coordinate") spawn_turtle_x = rospy.ServiceProxy('/spawn', Spawn) spawn_turtle_x(x, y, theta, '') x = Turtle(number) x.start() rospy.spin()
UTF-8
Python
false
false
6,551
py
2
spawn_turtle.py
1
0.532743
0.522516
0
229
27.606987
79
medularis/medularis-django-utils
7,146,825,614,877
47b92d89def489076ac9b6f410faa7fbf53f49f7
eeee39dbf68c1863548de8240fd47dcc93c1f487
/med_djutils/model_fields.py
6ced563fe79e6e37b14626a7d34f50b1d2dbc3e5
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
https://github.com/medularis/medularis-django-utils
7c3d819ee3d690d446e47e9dc33df7a4433b0581
7b8cde7bea1f45850f1e587eccfb5e6e3444ab58
refs/heads/master
2021-01-15T22:47:56.327687
2015-03-17T00:56:02
2015-03-17T00:56:02
32,344,730
0
1
BSD-3-Clause
true
2018-03-04T20:51:06
2015-03-16T18:28:06
2015-03-17T00:57:39
2015-03-26T14:55:00
171
0
1
1
Python
false
null
# coding: utf-8 """Some useful Django model fields. Source: lookup_www.common.fields (but just a subset). """ from __future__ import absolute_import, print_function, unicode_literals import django.db.models import django.forms import med_djutils.hex class Hex32Field(django.db.models.CharField): """Hex digits string of length 32, very practical for hash keys. Default value is calculated by :func:`med_djutils.hex.random_hex_32` (UUID version 4). Although it's very unlikely that it returns a repeated value, uniqueness is enforced at database level as precautionary measure. """ description = "32-hex-digits string" def __init__(self, *args, **kwargs): kwargs['blank'] = False kwargs['default'] = med_djutils.hex.random_hex_32 kwargs['max_length'] = 32 kwargs['unique'] = True kwargs.setdefault('editable', False) super(Hex32Field, self).__init__(*args, **kwargs) class Hex6Field(django.db.models.CharField): """Hex digits string of length 6. Default value is calculated by :func:`med_djutils.hex.random_hex_6` (substring of UUID version 4). Uniqueness is enforced at database level as precautionary measure. """ description = "6-hex-digits string" def __init__(self, *args, **kwargs): kwargs['blank'] = False kwargs['default'] = med_djutils.hex.random_hex_6 kwargs['max_length'] = 6 kwargs['unique'] = True kwargs.setdefault('editable', False) super(Hex6Field, self).__init__(*args, **kwargs) # Tell South about the custom field. Since it's essentially an IntegerField (as # South and DB are concerned), the definitions are as simple as they can be. # Read: # * http://south.readthedocs.org/en/latest/customfields.html#extending-introspection # * http://south.readthedocs.org/en/latest/tutorial/part4.html#simple-inheritance from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^common\.fields\.Hex32Field"]) add_introspection_rules([], ["^common\.fields\.Hex6Field"])
UTF-8
Python
false
false
2,079
py
24
model_fields.py
17
0.688312
0.674844
0
64
31.484375
90
ArijitBasu/streamlit
4,458,176,101,304
a388002f33e1ec124f7b5569b44f5f3493274b2d
8ca47ca4f36d829d9045aa203a78eba1e9f5d5e3
/apps/data.py
5122a592bd83b61d26cc078207a5b741a4fe2594
[]
no_license
https://github.com/ArijitBasu/streamlit
dc0e87b906b8393412e22a5c952b5e9b391c979d
944d478c64f4e80934c6b89f4bfa6762650f0b9b
refs/heads/main
2023-04-15T05:42:19.745065
2021-04-27T14:58:32
2021-04-27T14:58:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import streamlit as st import pandas as pd from PIL import Image def app(): data = st.beta_container() df = pd.read_csv('Books_universe.csv') with data: st.write("""In this project, we navigate through [GoodReads](https://www.goodreads.com/list/show/264.Books_That_Everyone_Should_Read_At_Least_Once) to scrape data of the best books that everyone should read at least once in their life time. From the scraped data, we got some interesting insights that you might be curious to know and stored the answers in a readable format for your convinience.""") st.title('Data') st.markdown("![Data](https://media4.giphy.com/media/xT9C25UNTwfZuk85WP/200.webp?cid=ecf05e47844brv5239cczg9hqo5ernebyirvx4xaua7k2dk8&rid=200.webp&ct=g)") if st.checkbox('Reveal The Library'): st.subheader('Books') st.write(df) #.header(50) inside the the ()
UTF-8
Python
false
false
948
py
8
data.py
6
0.675105
0.639241
0
21
42.904762
161
SergeyParamonov/sketching
12,627,203,889,950
5f80306e264bcd28666cb3c22659f12e2cc1000d
ee0973b340e9e7eb4b3544105245bd39a6e989cf
/solver/asp_py_parsetab.py
8b086d964531d1b6b1d8d5e4b278bb381ebe0ad5
[]
no_license
https://github.com/SergeyParamonov/sketching
cd89fb604a584336e92b1510a1ee391a631d15f6
750bbf9f81741237b210ff72f4615f317f7b06f0
refs/heads/master
2021-06-02T01:45:41.579907
2020-04-13T18:28:00
2020-04-13T18:28:00
90,079,587
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# asp_py_parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = b'H<\t\xc8tV\xb4?\x0e/8*\xe5\xcc\x8a\x82' _lr_action_items = {'STRING':([6,7,16,17,],[13,13,13,13,]),'SPACE':([1,2,3,15,18,],[5,-4,-6,-3,-5,]),'LP':([2,3,12,],[6,7,17,]),'NUM':([6,7,16,17,],[11,11,11,11,]),'IDENT':([0,5,6,7,16,17,],[2,2,12,12,12,12,]),'COMMA':([10,11,12,13,21,],[16,-12,-11,-10,-9,]),'MIDENT':([0,5,],[3,3,]),'RP':([9,10,11,12,13,14,19,20,21,],[15,-8,-12,-11,-10,18,-7,21,-9,]),'$end':([1,2,3,4,8,15,18,],[-2,-4,-6,0,-1,-3,-5,]),} _lr_action = { } for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = { } _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'atom':([0,5,],[1,1,]),'terms':([6,7,16,17,],[9,14,19,20,]),'term':([6,7,16,17,],[10,10,10,10,]),'answerset':([0,5,],[4,8,]),} _lr_goto = { } for _k, _v in _lr_goto_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_goto: _lr_goto[_x] = { } _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> answerset","S'",1,None,None,None), ('answerset -> atom SPACE answerset','answerset',3,'p_answerset','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',188), ('answerset -> atom','answerset',1,'p_answerset','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',189), ('atom -> IDENT LP terms RP','atom',4,'p_atom','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',194), ('atom -> IDENT','atom',1,'p_atom','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',195), ('atom -> MIDENT LP terms RP','atom',4,'p_atom','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',196), ('atom -> MIDENT','atom',1,'p_atom','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',197), ('terms -> term COMMA terms','terms',3,'p_terms','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',211), ('terms -> term','terms',1,'p_terms','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',212), ('term -> IDENT LP terms RP','term',4,'p_term','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',220), ('term -> STRING','term',1,'p_term','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',221), ('term -> IDENT','term',1,'p_term','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',222), ('term -> NUM','term',1,'p_term','/home/sergey/.local/lib/python3.4/site-packages/pyasp/asp.py',223), ]
UTF-8
Python
false
false
2,549
py
67
asp_py_parsetab.py
29
0.596312
0.494704
0.002746
40
62.7
405
xingxu21/Yale_CPSC
6,296,422,066,724
5d54f6906b99608ce9077e26a7a4792ae6f9a612
f53a17c670cd73068169705ceb7b87d137c6d0ab
/CPSC_327/P4/board.py
61743f30e0d4d3e7226893e8b4650fb657216326
[]
no_license
https://github.com/xingxu21/Yale_CPSC
f75e15093270097d870b415cfb251a19278a6045
5fa80ebd65a5def21328ac22d0f6fcc56672496c
refs/heads/master
2023-01-29T01:29:55.471333
2020-12-08T09:22:14
2020-12-08T09:22:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#board import piece_factory from constants import * import constants class game_state: #stack for keeping track of past states orig_board = [] past_states = [] future_states = [] size = 0 all_pieces = None def __init__(self, size, player = WHITE): #generate board of specified size self.player = player self.board = [] first_row = [1*(-1)**i for i in range(size)] self.board.append(first_row) for i in range(1, size): new_row = [i * -1 for i in self.board[-1]] self.board.append(new_row) for row in range(size): for column in range(size): if self.board[row][column] == 1: self.board[row][column] = BLACK_SQUARE else: self.board[row][column] = WHITE_SQUARE game_state.size = size for row in self.board: game_state.orig_board.append(row[:]) def print_board(self): "shows the current board" count = 1 alph = 'abcdefghijklmnopqrstuvwxyz' for row in self.board: print(count, end = " ") for e in row: print (e, end = " ") count +=1 print("\n", end="") print(" ", end = "") for i in range(count-1): print(alph[i], end = " ") print("\n", end = "") if self.player == WHITE: color = "white" else: color = "black" string = "Turn: %s, %s"%(constants.TURN, color) print(string) def undo_move(self): "return the previous game state" return game_state.past_states.pop() def valid_position(self, position): "returns truth value of whether a position is on the board" row = position[0] col = position[1] row_truth = row >= 0 and row < game_state.size col_truth = col >= 0 and col < game_state.size return col_truth and row_truth def set_up(self): "sets up board and creates all_pieces object with all of the checker pieces. This is stored in game_state.all_pieces" all_pieces = piece_factory.all_checker_pieces() factory = piece_factory.checkers_factory() for row in range(game_state.size): for column in range(game_state.size): factory.create_checkers(self.board, (row, column), all_pieces) game_state.all_pieces = all_pieces
UTF-8
Python
false
false
2,080
py
139
board.py
38
0.648077
0.641346
0
87
22.83908
119
priyankagandhi996/lawyer
5,128,190,958,682
3c49f58012aac8d92250e2074bb288673906b2a4
81fe5b46549bb716f677e200847b6438918b9592
/law/app/urls.py
97d9e9bda1fb6e60f5557899508dcb6ed301d136
[]
no_license
https://github.com/priyankagandhi996/lawyer
59dbdf8692640a22ca86d4364c74d04a481ce449
6dab8e4886b577fd5e300d12bcecae7b5028abba
refs/heads/master
2020-03-25T14:35:37.637502
2018-08-07T11:51:49
2018-08-07T11:51:49
143,862,519
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home,name='home'), url(r'/signup/admin/$', views.CreateAdmin,name='adminsignup'), url(r'/signup/user/$', views.CreateCustomer,name='customer'), ]
UTF-8
Python
false
false
246
py
6
urls.py
5
0.670732
0.670732
0
8
29.625
66
tarunrockr/python-pytest
16,569,983,866,358
714f86fff20a70694c4edab8a5668c60444d3c69
aad597c1b3cd4ba8b9af91d094dc6505a7c89db9
/parameterized_test.py
11540332723069b5b6dac4d896890618d2f2031d
[]
no_license
https://github.com/tarunrockr/python-pytest
ad93b329471ffa87afd3aa8ed4220299fe913a35
ab477535665229bf436e8c31f6e19106b25ad54b
refs/heads/master
2023-07-09T02:56:27.998290
2021-08-15T18:20:57
2021-08-15T18:20:57
396,436,867
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pytest # ------------------ Run Command for following function | pytest parameterized_test.py ---------------------- @pytest.mark.parametrize('x,y,z',[(10,20,200),(20,40,200)]) def test_function(x,y,z): assert x*y == z
UTF-8
Python
false
false
232
py
6
parameterized_test.py
6
0.568966
0.508621
0
5
45.6
112
eDeliveryApp/edelivery-api
2,851,858,290,915
73f4cbb6ef71bf888c6467e17373fc32b0337ac3
557cae0c1aca5ca775ea3fc38438e1d981e44f80
/manage.py
34d4d9b6790339ff8ca568fe2420224a8c6d7bc7
[]
no_license
https://github.com/eDeliveryApp/edelivery-api
8ed1c1a27f048bb393aabee77ab361e532a56c10
a96a0b8d048a22260f812383962c979b7c78fb6d
refs/heads/master
2021-01-02T06:31:35.119810
2015-07-05T03:36:49
2015-07-05T03:36:49
38,555,588
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from flask.ext.script import Manager from api.app import create_app from api.models import db manager = Manager(create_app) @manager.command def createdb(): app = create_app() with app.app_context(): db.drop_all() db.create_all() @manager.command def test(): from subprocess import call call(['nosetests', '-v', '--with-coverage', '--cover-package=api', '--cover-branches', '--cover-erase', '--cover-html', '--cover-html-dir=cover']) if __name__ == '__main__': manager.run()
UTF-8
Python
false
false
561
py
7
manage.py
7
0.613191
0.613191
0
26
20.538462
71
alejocano22/TETbigdata
5,909,875,023,843
b9bf9a3135fc8f7306aff27e407e730383693e8b
4f122900ac54def923b25767e8e729d1714ebd1a
/Programas/Stocks/stocks-risenstable-mr.py
7669bd22de4e0f3bbe6818668a6b843ff1b41e2d
[]
no_license
https://github.com/alejocano22/TETbigdata
c585bf599b8242b382e464f0fe0402bbd3966fd4
c7d58ca5e91ec037ab6c86a61250e7fa25a1bd23
refs/heads/master
2021-06-13T15:58:49.583685
2020-05-04T02:06:33
2020-05-04T02:06:33
254,438,158
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from mrjob.job import MRJob from operator import itemgetter class RisenStable(MRJob): def mapper(self, _, line): company, price, date = line.split(',') data = [price, date] yield company, data def reducer(self, company, values): data = list(values) data = sorted(data, key=itemgetter(1)) for i in range(len(data)-1): if float(data[i+1][0]) < float(data[i][0]): return yield company, "Raise or stable all time." if __name__ == '__main__': RisenStable.run()
UTF-8
Python
false
false
558
py
12
stocks-risenstable-mr.py
3
0.569892
0.560932
0
22
24.363636
55
kayjayk/Algorithms_py
4,715,874,127,582
ab8115257b076fa9477dad9b61f4468338a29fc4
16147cb4f47d8a4fadaa8c9b5778f6581ff1871f
/Exam10989.py
a22e7bbf4cc419111bf32a74d1dec92349e4506f
[]
no_license
https://github.com/kayjayk/Algorithms_py
45acaf189ac9f0ed7e3ae4829d15c5b059edea1a
d1189937c59deb3eeed8e1d0ad0efe56ea7ac160
refs/heads/master
2023-03-17T22:19:44.378677
2021-03-19T09:44:10
2021-03-19T09:44:10
204,250,000
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys from collections import defaultdict N = int(sys.stdin.readline()) num_dict = defaultdict(int) for i in range(N): num_dict[int(sys.stdin.readline())] += 1 num_keys = [] for key in num_dict.keys(): num_keys.append(key) sorted_keys = sorted(num_keys) for i in range(len(sorted_keys)): key = sorted_keys[i] for j in range(num_dict[key]): print(key)
UTF-8
Python
false
false
384
py
53
Exam10989.py
52
0.658854
0.65625
0
19
19.263158
44
epigen-UCSD/MERlin
18,683,107,771,026
722e1c6a68b37664567f507afcec6f8d907defa0
942aea94961e56340c526c46eecf236f3fcbb368
/merlin/plots/__init__.py
0f3a244f2a2ee5ab3ebfda771c986b00cf4a676b
[ "MIT" ]
permissive
https://github.com/epigen-UCSD/MERlin
562a1eb9f31a90a5979063a2a13375b78281b1c8
1479c9605c6e4ede9c15eb9f11d8d70fc691bf7d
refs/heads/master
2023-08-08T20:52:29.979999
2023-08-07T22:44:03
2023-08-07T22:44:03
254,443,213
1
2
NOASSERTION
true
2021-04-06T22:27:59
2020-04-09T18:00:59
2020-04-24T19:58:31
2021-04-06T22:27:58
16,810
0
0
1
null
false
false
import importlib import inspect import pkgutil from typing import List, Set import merlin from merlin.plots._base import AbstractPlot def get_available_plots() -> Set: """Get all plots defined within any submodule of merlin.plots. Returns: a set of references to the plots """ plots = set() for _, modname, _ in pkgutil.iter_modules(merlin.plots.__path__): module = importlib.import_module(merlin.plots.__name__ + "." + modname) for _, obj in inspect.getmembers(module): if inspect.isclass(obj) and issubclass(obj, AbstractPlot) and obj != AbstractPlot: plots.add(obj) return plots class PlotEngine: def __init__(self, plot_task, tasks): """Create a new plot engine. Args: plot_task: the analysis task to save the plots and plot metadata into tasks: a dictionary containing references to the analysis tasks to use for plotting results. """ self.tasks = tasks available_plots = [x(plot_task) for x in get_available_plots()] self.plots = [x for x in available_plots if x.is_relevant(tasks)] required_metadata = {m for p in self.plots for m in p.required_metadata if m} self.metadata = {x.metadata_name(): x(plot_task, tasks) for x in required_metadata} for metadata in self.metadata.values(): metadata.load_state() def get_plots(self) -> List[AbstractPlot]: """Get a list of the plots that this plot engine will generate. Returns: A list of the plot objects that will be generated by this plot engine. """ return self.plots def take_step(self) -> bool: """Generate metadata and plots from newly available analysis results. Returns: True if all plots have been generated and otherwise false. """ incomplete_plots = [p for p in self.plots if not p.is_complete()] if len(incomplete_plots) == 0: return True for m in self.metadata.values(): m.update() complete_tasks = [k for k, v in self.tasks.items() if v.is_complete()] complete_metadata = [k for k, v in self.metadata.items() if v.is_complete()] ready_plots = [p for p in incomplete_plots if p.is_ready(complete_tasks, complete_metadata)] for p in ready_plots: p.plot(self.tasks, self.metadata) return len([p for p in self.plots if not p.is_complete()]) == 0
UTF-8
Python
false
false
2,510
py
93
__init__.py
65
0.622709
0.621912
0
69
35.376812
100
NCiobo/iem
8,203,387,556,550
654926add63d15bac2ee5a9f45873efad374d0f7
fd877cb919622d6a4efa305fb9eaec8a31e8dd37
/scripts/outgoing/kcci/wxc_top5gusts.py
5aead76f3c803b963e02d1ededb5da2414b98528
[ "MIT" ]
permissive
https://github.com/NCiobo/iem
37df9bc466ffcbe4f6b1f9c29c6b5266559f200c
75da5e681b073c6047f5a2fb76721eaa0964c2ed
refs/heads/master
2021-01-23T09:39:33.090955
2017-09-05T16:34:12
2017-09-05T16:34:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import subprocess import datetime import sys import tempfile import pyiem.tracker as tracker qc = tracker.loadqc() import psycopg2 IEM = psycopg2.connect(database="iem", host='iemdb', user='nobody') icursor = IEM.cursor() icursor.execute("""SELECT t.id as station from current c, stations t WHERE t.network = 'KCCI' and valid > 'TODAY' and t.iemid = c.iemid ORDER by gust DESC""") data = {} data['timestamp'] = datetime.datetime.now() i = 1 for row in icursor: if i == 6: break if qc.get(row[0], {}).get('wind', False): continue data['sid%s' % (i,)] = row[0] i += 1 if 'sid5' not in data: sys.exit() fd, path = tempfile.mkstemp() os.write(fd, open('top5gusts.tpl', 'r').read() % data) os.close(fd) subprocess.call("/home/ldm/bin/pqinsert -p 'auto_top5gusts.scn' %s" % (path,), shell=True) os.remove(path) fd, path = tempfile.mkstemp() os.write(fd, open('top5gusts_time.tpl', 'r').read() % data) os.close(fd) subprocess.call(("/home/ldm/bin/pqinsert -p 'auto_top5gusts_time.scn' %s" "") % (path, ), shell=True) os.remove(path)
UTF-8
Python
false
false
1,120
py
144
wxc_top5gusts.py
134
0.633929
0.623214
0
44
24.454545
78
expert360/consumerism
14,319,420,975,885
7cae467dfec42baf838417f831afa4a082c5be91
ef877a0ebf805bf38b5bf15254f3034e3d3d4d5e
/setup.py
6858d03c5911d16e7d5ff75b181a6c1e871ce496
[ "MIT" ]
permissive
https://github.com/expert360/consumerism
51045a642d80da79453f42b8cce894ddcee130c0
412847e6ff6f3087decf4212b32842ec017cc344
refs/heads/master
2016-09-06T01:42:23.960512
2016-01-11T05:53:00
2016-01-11T05:53:00
31,235,106
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from setuptools import setup, find_packages setup( name='consumerism', version='0.3.11', description='Expert360 Python SQS consumer library', author='Expert360', author_email='info@expert360.com', license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], keywords='boto sqs consumer', url='https://github.com/expert360/consumerism', packages=find_packages(exclude=['tests']), install_requires=[ 'boto>=2.34.0', ], )
UTF-8
Python
false
false
649
py
20
setup.py
18
0.624037
0.588598
0
23
27.217391
56
RevansChen/online-judge
10,746,008,206,908
48394dd68432ba18150e70a7c98a9ec8f5b0944e
abad82a1f487c5ff2fb6a84059a665aa178275cb
/Codewars/8kyu/crash-override/Python/solution1.py
052b13e1287ea3ea75a577a1280bb1ffc2657c8c
[ "MIT" ]
permissive
https://github.com/RevansChen/online-judge
8ae55f136739a54f9c9640a967ec931425379507
ad1b07fee7bd3c49418becccda904e17505f3018
refs/heads/master
2021-01-19T23:02:58.273081
2019-07-05T09:42:40
2019-07-05T09:42:40
88,911,035
9
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Python - 3.6.0 def alias_gen(f_name, l_name): f = f_name[0].upper() l = l_name[0].upper() if (f in FIRST_NAME) and (l in SURNAME): return f'{FIRST_NAME[f]} {SURNAME[l]}' return 'Your name must start with a letter from A - Z.'
UTF-8
Python
false
false
254
py
2,569
solution1.py
1,607
0.574803
0.555118
0
9
27.222222
59
amar-jain/fluence
4,715,874,135,532
4c45e5b6ed6ed54002e06af81440cab7718dc0b5
1090105e9be55a2806b4586b4c17e525c188ee55
/deploy/docker.py
f53bbde3472ab94ad9402a3f38b18ce7b64bbb43
[ "Apache-2.0" ]
permissive
https://github.com/amar-jain/fluence
0b1c181ebad17d6ba67dc148b868d7eb4a1633b4
ee2b2aad5290247a2c7e679020abb2337ab1b399
refs/heads/master
2023-04-12T00:27:28.634027
2021-05-17T11:08:10
2021-05-17T11:08:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2020 Fluence Labs Limited # # Licensed under the Apache 'License', Version 2.0 (the "'License'"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in 'writing', 'software' # distributed under the License is distributed on an "AS IS" ''BASIS'', # WITHOUT WARRANTIES OR CONDITIONS OF ANY 'KIND', either express or 'implied'. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement from fabric.api import * from utils import * from docker import * import json @task @runs_once def install_docker(): load_config() execute(do_install_docker) @task @parallel def do_install_docker(): puts("TODO: WRITE LOGGING DRIVER SETUP TO daemon.json https://docs.docker.com/config/containers/logging/json-file/") with hide('running'): sudo("apt-get remove --yes docker docker-engine docker.io containerd runc || true") sudo("apt-get update") puts("preparing to install docker") sudo("apt-get install --yes haveged apt-transport-https ca-certificates curl gnupg-agent software-properties-common") sudo("curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -") sudo("apt-key fingerprint 0EBFCD88") sudo("""add-apt-repository -y "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable" """) sudo("apt-get update") puts("installing docker") sudo("apt-get install --yes docker-ce docker-ce-cli containerd.io") puts("installing docker-compose") sudo("""curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose """) sudo("chmod +x /usr/local/bin/docker-compose") @task @runs_once def deploy_watchdog(): load_config() execute(do_deploy_watchdog) @task @parallel def do_deploy_watchdog(): # 'running', 'output' with hide('running', 'output'): run("docker rm -f docker_watchdog || true") run( "docker run --name docker_watchdog --detach --restart=unless-stopped " + "-e HOST={} ".format(env.host_string) + "-e SLACK_CHANNEL='#endurance' " + "-e SLACK_URL=SECRET " + "-v /var/run/docker.sock:/var/run/docker.sock " + "leonardofalk/docker-watchdog" ) @task @parallel def deploy_caddy(): load_config() for node in env.config['caddy']['nodes']: env.hosts = [node['addr']] puts("node: {}".format(node)) execute(do_deploy_caddy, node['ports'], node['host']) @task def do_deploy_caddy(ports, host): ip = env.host_string fname = 'Caddyfile' prefix = '1' container = 'caddy' run('rm {} || true'.format(fname)) def append(line): run('echo "{}" >> {}'.format(line, fname)) # Generated config will be as follows: # # { # email alexey@fluence.one # } # # host:prefixport { # add 'prefix', e.g.: 9001 => 19001 # log { # format console # } # reverse_proxy ip:port # } append(''' { email alexey@fluence.one } ''') for port in ports: append(''' wss://{}:{}{} {{ log {{ format console }} reverse_proxy wss://{}:{} }}'''.format(host, prefix, port, ip, port)) # -p prefixport:prefixport open_ports = " ".join("-p {}{}:{}{}".format(prefix, p, prefix, p) for p in ports) run('docker rm -f {} || true'.format(container)) run('docker pull caddy:latest') run('docker run --name {} -d -p 80:80 {} -v $PWD/Caddyfile:/etc/caddy/Caddyfile -v caddy_data:/data caddy:latest'.format(container, open_ports))
UTF-8
Python
false
false
3,881
py
47
docker.py
27
0.620201
0.612213
0
121
31.07438
161
linbarbell/ProjectEuler
4,002,909,569,670
a63cd8a01b38ba2e378c52428ac3923a129d0a62
e9f142b9839732f1a4cdda69d6fd8382b4457356
/Code/39.py
d91880d42624d8464b9c8ca1a99a28783fa2ce20
[]
no_license
https://github.com/linbarbell/ProjectEuler
89561d3c85b92944af14fa478ff8a9890787cdf2
b54e01d18ca8517b11b7595bfecd7930528f282a
refs/heads/master
2021-09-28T20:09:01.066898
2018-11-20T01:57:14
2018-11-20T01:57:14
29,401,770
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
pmax = 0 solmax = 0 for i in range(12, 1001): currmax = 0 c_min = i//3 + 1 if i % 3 == 0 else i//3 c_max = i//2 + 1 if i % 2 == 0 else i//2 for c in range(c_min, c_max+1): a_max = (i-c)//2 for a in range(1, a_max+1): b = i-c-a if a*a + b*b == c*c: currmax += 1 if currmax > solmax: solmax = currmax pmax = i print(pmax)
UTF-8
Python
false
false
343
py
69
39.py
65
0.521866
0.451895
0
17
19.235294
41
BazBazz/elih
5,935,644,807,873
c7ab7a110e69bf596aeefddbf9c89804ebfef576
ccdaa8577dc6b9e49d16420ea9c929dabf1db45b
/elih/__init__.py
530f84a511bc79d575e40d276be9c9a60a3ca029
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
https://github.com/BazBazz/elih
e470e2a74e8d3a166551c78e00ca457a5c535d5f
99d7066091b7709c77b515b96f0643700582d78f
refs/heads/master
2021-01-19T17:10:39.904582
2017-08-13T21:14:36
2017-08-13T21:14:36
101,055,825
0
0
null
true
2017-08-22T11:31:16
2017-08-22T11:31:16
2017-05-16T17:04:14
2017-08-13T21:14:42
565
0
0
0
null
null
null
# -*- encoding: utf-8 -*- from __future__ import absolute_import __version__ = '0.1' from .explanation import HumanExplanation from .features import apply_rules_layer from .features import FeatureWeightGroup from .scoring import score from .formatters import ( percent, delta_percent, value, text, integer, value_simplified )
UTF-8
Python
false
false
337
py
2
__init__.py
2
0.738872
0.72997
0
20
15.85
41
poojas1992/Classification-Algorithm
85,899,345,999
0b13048e86805a66edca8dfbbb4ee629f408c254
dc1e1321e5d3439fe90c496cc8b5c81e8e32d2b2
/KNN_Digital_Sky.py
83687e7a80af2d27ba0008a9b07bf1b1bf9e2166
[]
no_license
https://github.com/poojas1992/Classification-Algorithm
4a4e0a8841afc2dbf9d934ea65b81a0ea0645dab
1f724390507f0d8b6908de66bd76321792431f6b
refs/heads/master
2020-05-16T09:45:07.953499
2019-04-23T08:06:19
2019-04-23T08:06:19
182,960,107
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # coding: utf-8 # In[2]: import pandas as pd import numpy as np # In[3]: #Step 1 #import dataset using pandas sky_data = pd.read_csv() sky_data.head() # In[4]: #Step 2 #Dropping the id feature sky_data.drop(columns = ['objid'], inplace = True) sky_data.head() #Converting non-numeric data to numeric dataset diag_map = {'STAR':1, 'GALAXY':2, 'QSO':3} sky_data['class'] = sky_data['class'].map(diag_map) #Preparing the data set class_all = list(sky_data.shape)[0] class_categories = list(sky_data['class'].value_counts()) print("The dataset has {} classes, {} stars, {} galaxies and {} quasars.".format(class_all, class_categories[0], class_categories[1], class_categories[2])) sky_data.describe() # In[5]: #Creating training and test datasets from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import accuracy_score y = sky_data["class"].values X = sky_data.drop(["class"], axis = 1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 41) # In[6]: #Step 3 #Training Model from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors=4) classifier.fit(X_train, y_train) # In[7]: #Step 4 #Testing the model from sklearn.metrics import classification_report, confusion_matrix y_pred = classifier.predict(X_test) print(np.mean(y_pred != y_test)) print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) # In[8]: #Step 5 #Improve Model Performance #z-score transformed from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(X_train) #Training the model X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) classifier = KNeighborsClassifier(n_neighbors=4) classifier.fit(X_train, y_train) #Testing the model y_pred = classifier.predict(X_test) print(np.mean(y_pred != y_test)) print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) # In[21]: import matplotlib.pyplot as plt error = [] # Calculating error for K values between 1 and 300 for i in range(1, 300): knn = KNeighborsClassifier(n_neighbors=i) knn.fit(X_train, y_train) pred_i = knn.predict(X_test) error.append(np.mean(pred_i != y_test)) plt.figure(figsize=(12, 6)) plt.plot(range(1, 300), error, color='red', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=10) plt.title('Error Rate K Value') plt.xlabel('K Value') plt.ylabel('Mean Error') plt.show() # In[22]: #Training Model from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors=11) classifier.fit(X_train, y_train) #Testing the model from sklearn.metrics import classification_report, confusion_matrix y_pred = classifier.predict(X_test) print(np.mean(y_pred != y_test)) print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) # In[13]: #Training Model from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors=50) classifier.fit(X_train, y_train) #Testing the model from sklearn.metrics import classification_report, confusion_matrix y_pred = classifier.predict(X_test) print(np.mean(y_pred != y_test)) print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) # In[14]: #Training Model from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors=100) classifier.fit(X_train, y_train) #Testing the model from sklearn.metrics import classification_report, confusion_matrix y_pred = classifier.predict(X_test) print(np.mean(y_pred != y_test)) print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) # In[ ]:
UTF-8
Python
false
false
4,102
py
8
KNN_Digital_Sky.py
8
0.671624
0.65724
0
179
21.893855
102
avinashjsap/GFG
4,157,528,372,425
bbf38c8f55e47d85b51793a8a29aa1a2db8326c3
b1c91f772b3d6310190133ebf866ae4ec55386a2
/GFG/DataStructures/LinkedList/Make_middle_node_head_in_a_linked_list.py
6320eb5eaefe72d016bd817804e43f193ac75602
[]
no_license
https://github.com/avinashjsap/GFG
43dbc1dc7c5d03ef77f747759803d821a224398b
da327238a0dad6bf550bdccdce17009531d3435c
refs/heads/master
2020-04-24T18:37:51.223670
2019-02-23T07:38:26
2019-02-23T07:38:26
172,185,890
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Python Script to make middle node as head of Linked list """ class Node: """Class representing a Node""" def __init__(self, data): self.data = data self.next = None def link_node(self, node): """Links the next node with the current node Args: node (Node): Node which is to be linked """ self.next = node def create_nodes(number): """Creates a linked list with the given number Args: number (int): Number of nodes to be created and chained Returns: Node : First and foremost Node """ head = None while number: new_node = Node(number) new_node.link_node(head) head = new_node number -= 1 return head def print_nodes(head): """Prints the linked list Args: head (Node): Node from which the list is to be printed """ while head: print(head.data, end=" ") head = head.next print() def set_middle_as_head(head): """Exchanges the middle node value with the head node Args: head (Node) : Node where the linked list begins Returns: Node : Head node after exchange of value with the middle """ if head is None: # Return if head is None return None node_1 = node_2 = head # assigns the reference of head to node_1 and node_2 while node_2 and node_2.next: # Stop when "node_2 is None" or "node_2 is valid but node_2.next is None" node_1 = node_1.next # Traverse one node each iteration node_2 = node_2.next.next # Traverse two node each iteration head.data, node_1.data = node_1.data, head.data # Swap Data return head # Main Boiler plate where execution begins if __name__ == "__main__": NUMBER_OF_NODES = 6 head_node = create_nodes(NUMBER_OF_NODES) print_nodes(head_node) head_node = set_middle_as_head(head_node) print_nodes(head_node)
UTF-8
Python
false
false
2,070
py
3
Make_middle_node_head_in_a_linked_list.py
3
0.567633
0.55942
0
83
22.939759
109
Elbagoury/eyefashion
377,957,157,154
ca2f771a33ac29a53e67e42e92701c3754876367
d207c1fe9bb534419ae16d5d1cbc650597a092fd
/pos_parent_discount/models/__init__.py
a66e62ba0e08b1628ad934b468698568d84670ee
[]
no_license
https://github.com/Elbagoury/eyefashion
6bad9d27a0337e7eae688f66ae8b6322bfcfa80c
e5796f80c2c5854cda5bcbb879c586254c9378c6
refs/heads/master
2020-04-19T17:55:26.547757
2018-10-06T15:12:04
2018-10-06T15:12:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from . import res_partner from . import account_journal from . import pos_order from . import pos_session
UTF-8
Python
false
false
132
py
150
__init__.py
88
0.69697
0.689394
0
6
20.833333
29
lowlandresearch/larcutils
12,068,858,124,509
578801543d91d51cada1d4b003eb7e8da7a7d8db
9cb4e52d1df02347791a66155fd0ac18da375105
/larcutils/logging.py
483ad172ace4297b182bebedd2321919141f60fb
[ "MIT" ]
permissive
https://github.com/lowlandresearch/larcutils
21a5eea762cb1147fbde1c0b887a3b3d1dd071c3
66e68ce566f47b7c2f806ae3008a3e9d66c937ea
refs/heads/master
2020-04-17T18:48:54.167898
2019-10-21T03:47:24
2019-10-21T03:47:24
166,842,583
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import logging import coloredlogs def setup_logging(loglevel: str): level = logging.getLevelName(loglevel.upper()) fmt = ( '{asctime} {levelname: <8} [{name}]:{lineno: >4}: {message}' ) datefmt = '%Y-%m-%d %H:%M:%S' coloredlogs.install(level=level) logging.basicConfig(level=level, datefmt=datefmt, format=fmt, style='{')
UTF-8
Python
false
false
356
py
10
logging.py
8
0.640449
0.634831
0
11
31.272727
76
OhadRubin/Awesome-System-Design
16,320,875,747,386
569980416707bbc47ec7fc3d094de0cec64602a6
4c0330fab17c6babb4f1fcc84afb073e30a9c8db
/asd/parsers/__init__.py
7889ca184ec542a7881844a1ce96a62d7057d852
[]
no_license
https://github.com/OhadRubin/Awesome-System-Design
1912685b2efe23d929b8b87873ad2661a51f2b7f
9696320e4516cba2ea97743a36bc023df8108d7f
refs/heads/master
2022-12-09T13:52:55.014245
2020-06-06T20:18:17
2020-06-06T20:18:17
227,002,991
0
2
null
false
2022-12-08T07:28:48
2019-12-10T01:33:03
2020-06-06T20:18:44
2022-12-08T07:28:47
82,954
0
1
20
Jupyter Notebook
false
false
import types import pathlib from os.path import dirname, isfile, join import asd.utils.asd_pb2 as asd_pb2 import os from asd.utils import mq import glob import json modules = {} modules_list = glob.glob(join(dirname(__file__), "*.py")) for path in modules_list: if isfile(path) and not path.endswith('__init__.py') and not path.endswith('__main__.py'): mod_name = pathlib.Path(path).name[:-3] module = types.ModuleType(mod_name) with open(path) as f: module_str = f.read() exec(module_str, module.__dict__) modules[mod_name] = module parser_list = {} snapshot_fields = set() for module_name, module in modules.items(): for el in dir(module): if el.endswith("Parser"): obj = module.__dict__[el]() parser_list[module_name] = obj.parse snapshot_fields.add(obj.field) if el.startswith("parse"): parser_list[module_name] = module.__dict__[el] snapshot_fields.add(module.__dict__[el].field) snapshot_fields = list(snapshot_fields) class Context: def __init__(self, user_id, timestamp): self.user_id = user_id self.timestamp = timestamp def path(self, filename): # print(self.timestamp) os.makedirs(f"data/{self.user_id}/{self.timestamp}", exist_ok=True) return f"data/{self.user_id}/{self.timestamp}/{filename}" def save(self, filename, data): filename = self.path(filename) os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w") as f: f.write(data) def run_parser(parser_name, packet): parse_method = parser_list[parser_name] packet = asd_pb2.Packet.FromString(packet) context = Context(user_id=packet.user.user_id, timestamp=packet.snapshot.datetime) res = parse_method(context=context, snapshot=packet.snapshot) user = dict(username=packet.user.username, user_id=packet.user.user_id, gender=packet.user.gender, birthday=packet.user.birthday) return json.dumps({"parser_name": parser_name, "data": {"user": user, "timestamp": packet.snapshot.datetime, "result": res}}) def parse(parser_name, path): assert isinstance(path, str) and path.endswith(".raw") with open(path, "rb") as x: return run_parser(parser_name, packet=x.read())
UTF-8
Python
false
false
2,465
py
35
__init__.py
23
0.609331
0.607708
0
71
33.704225
98
muraleo/django-practice
16,801,912,077,542
6b28b45273c372621da750f417fd95c05a48abbe
0743fa60ed316325c89c65a127ca5b365a1fcb0b
/first_app/views.py
5db9a91f8e11cc9fc1724b80a40e660c00b8e8f3
[]
no_license
https://github.com/muraleo/django-practice
a93c7202ae4edb04a52b7c465926d703bdd30379
05e4f6a89c08de955b19fb1b2fa140b585566886
refs/heads/master
2020-04-05T02:45:51.635556
2018-11-08T02:13:09
2018-11-08T02:13:09
156,489,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.shortcuts import render from django.http import HttpResponse from first_app.models import Topic, Webpage, AccessRecord # Create your views here. def index(req): webpages_list = Webpage.objects.order_by('name') # my_dict = {'insert_me': "Hello I am from the views.py"} date_dict = {'access_record':webpages_list} return render(req, 'first_app/index.html', context = date_dict)
UTF-8
Python
false
false
404
py
1
views.py
1
0.725248
0.725248
0
10
39.5
67
nathanmargaglio/bfds
9,105,330,672,621
1bd95486bbb2885cacdaedb6f276a00dc2454803
0842ff1fc6e57fedd864318be0784faf212a4161
/server/rest/migrations/0001_initial.py
620c6e6784a9470a8ccc5a2270f3b84125dcf466
[]
no_license
https://github.com/nathanmargaglio/bfds
f21dd54255ceec171b2313a6d6ab3752eda55a1c
355b4a5edc4d785ef570dc84f033040f7ebad37d
refs/heads/master
2021-04-27T09:59:24.511584
2018-03-13T12:53:18
2018-03-13T12:53:18
122,527,216
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 2.0.2 on 2018-02-23 01:23 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Owner', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=128)), ('last_name', models.CharField(max_length=128)), ('phone', models.CharField(max_length=128)), ('email', models.CharField(max_length=128)), ('street_number', models.IntegerField()), ('route', models.CharField(max_length=128)), ('locality', models.CharField(max_length=128)), ('county', models.CharField(max_length=128)), ('state', models.CharField(max_length=128)), ('postal_code', models.CharField(max_length=128)), ('lat', models.FloatField()), ('lon', models.FloatField()), ], ), ]
UTF-8
Python
false
false
1,143
py
19
0001_initial.py
16
0.538058
0.501312
0
32
34.71875
114
ccsourcecode/Blockchain_Survival_Guide
17,300,128,273,794
93c01311d3274fe94dd32f6a181bc0cf16d0709c
248f9e4f0f9de0413ca950d61dc81a4699beefd5
/2_1.py
ff7dd274dce0039be43e150269b8418392f9fc20
[]
no_license
https://github.com/ccsourcecode/Blockchain_Survival_Guide
6f413859b9d4d7c9747534007b41e7f83e6391dd
1d619f4ceccef610b8648372baa542c4099c29ae
refs/heads/main
2023-03-27T12:20:54.632777
2021-03-16T08:34:43
2021-03-16T08:34:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import time class Transaction: def __init__(self, sender, receiver, amounts, fee, message): self.sender = sender self.receiver = receiver self.amounts = amounts self.fee = fee self.message = message class Block: def __init__(self, previous_hash, difficulty, miner, miner_rewards): self.previous_hash = previous_hash self.hash = '' self.difficulty = difficulty self.nonce = 0 self.timestamp = int(time.time()) self.transactions = [] self.miner = miner self.miner_rewards = miner_rewards class BlockChain: def __init__(self): self.adjust_difficulty_blocks = 10 self.difficulty = 1 self.block_time = 30 self.miner_rewards = 10 self.block_limitation = 32 self.chain = [] self.pending_transactions = []
UTF-8
Python
false
false
876
py
8
2_1.py
7
0.590183
0.578767
0
33
25.545455
72
Tribal1012/mipsHex
12,455,405,199,016
dc9b3efd6fbac4e90c2cda62ecb9b21f763b792a
cb6eb98d07724e0603d8bce7366d5ce5aee20c30
/old/base/error.py
5f3843682f68e90aaf256c59cec7e33eed0f2f71
[]
no_license
https://github.com/Tribal1012/mipsHex
7720f4670ad81783621e997a064f03ea56bca2e3
23c307db5230dc470ee4baa9cb1a184f826949e6
refs/heads/master
2020-03-21T05:45:50.826039
2018-10-22T12:28:31
2018-10-22T12:28:31
138,178,456
12
2
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys ''' print error and exit ''' def error(msg): print msg sys.exit(-1) ''' for assert check ''' def check_assert(tag, result): try: assert result except: error(tag)
UTF-8
Python
false
false
186
py
31
error.py
28
0.639785
0.634409
0
18
9.333333
30
chyidl/chyidlTutorial
6,708,738,930,670
23dff31b1cb5ce21827d2f2ef3d3958296c1b910
96bf2ec5c1536831b6a3e08675286770d44d858c
/root/python/PythonPyCon/Python_Concurrency_From_the_Ground_Up/threading_communication.py
14a2abab67433575aa0549351b698cf65e4a1e8b
[ "MIT" ]
permissive
https://github.com/chyidl/chyidlTutorial
aa15d6c8526e87a34ed63f79bd541d10ee43b820
d7f74280725149be11d818b4fbca6cb23ffa4e25
refs/heads/master
2022-05-11T13:33:47.015661
2022-05-04T13:42:20
2022-05-04T13:42:20
156,686,624
4
3
MIT
false
2021-04-14T13:58:38
2018-11-08T10:02:35
2021-04-14T01:00:00
2021-04-14T13:58:37
83,671
3
2
0
Python
false
false
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # ____ # / . .\ # Life is short \ ---< # I use Python \ / # __________/ / # -=:___________/ # threading_communication.py # Python_Concurrency_From_the_Ground_Up # # Created by Chyi Yaqing on 05/23/19 18:46. # Copyright © 2019. Chyi Yaqing. # All rights reserved. # # Distributed under terms of the MIT """ Python threads: communication and stopping 1. How to stop / kill a thread 2. How to safely pass data to a thread and back Here's a sample "worker" thread implementation. It can be given tasks, where each task is a directory name, and it does useful work. This work is recursively listing all the files contained in the given directory and its sub-directories """ import os import time import threading from queue import Queue class WorkerThread(threading.Thread): """A worker thread that takes"""
UTF-8
Python
false
false
907
py
751
threading_communication.py
389
0.655629
0.635762
0
34
25.647059
74
v2psv/crowd_count
12,051,678,238,159
6a295f8be10ab81b8937b5df153755b155b27b16
e3aae0e629504b8a4f8cd5612e9b74d9fda00243
/loss.py
1bc538506b9eda9f22349189ebda71f9e06e86e8
[]
no_license
https://github.com/v2psv/crowd_count
7f9d0b7fa7753d331e257d0d501f0faafcdb7a91
082c9bf5b6252b1465c88e6dca71b7397755ed3a
refs/heads/master
2021-01-19T14:50:51.797133
2018-04-11T18:50:25
2018-04-11T18:50:25
100,930,786
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import torch import numpy as np import torch.nn as nn from torch.nn.modules.loss import _Loss import torch.nn.functional as F class ContrastiveLoss(torch.nn.Module): def __init__(self, margin=2.0): super(ContrastiveLoss, self).__init__() self.margin = margin def forward(self, output1, output2, label): euclidean_distance = F.pairwise_distance(output1, output2) loss_contrastive = torch.mean((1-label) * torch.pow(euclidean_distance, 2) + (label) * torch.pow(torch.clamp(self.margin - euclidean_distance, min=0.0), 2)) return loss_contrastive class ContrastiveLoss2(torch.nn.Module): def __init__(self): super(ContrastiveLoss2, self).__init__() def forward(self, output1, output2, label): euclidean_distance = F.pairwise_distance(output1, output2) loss_contrastive = torch.mean(torch.pow(euclidean_distance-label, 2)) return loss_contrastive class MSELoss(_Loss): def __init__(self): super(MSELoss, self).__init__() def forward(self, pred, target): # _assert_no_grad(target) loss = torch.sum((pred - target)**2) / pred.size(0) return loss class RelativeLoss(_Loss): def forward(self, pred, target): # _assert_no_grad(target) loss = torch.sum(((pred-target)/(target+1))**2) / pred.size(0) return loss class LogMSELoss(_Loss): def forward(self, pred, target): # _assert_no_grad(target) loss = torch.sum((torch.log(pred+1) - torch.log(target+1))**2) / pred.size(0) return loss class L1Loss(_Loss): def __init__(self, size_average=True, reduce=True, relative=False): super(L1Loss, self).__init__(size_average) self.reduce = reduce self.size_average = size_average self.relative = relative def forward(self, input, target): # _assert_no_grad(target) if self.relative: input = input / target target = target / target return F.l1_loss(input, target, size_average=self.size_average) class PmapLoss(_Loss): def __init__(self, ksize=15): self.ksize = ksize self.avg_pool = nn.AvgPool1d(kernel_size=ksize, stride=ksize) def forward(self, pred, target, avg_density, mask): x = self.avg_pool(torch.sum(pred, dim=3)) * self.ksize y = self.avg_pool(torch.sum(target, dim=3)) * self.ksize n1 = y[:, :, :-1] n2 = y[:, :, 1:] class GradientLoss(_Loss): def __init__(self, alpha=1): super(GradientLoss, self).__init__() self.alpha = alpha self.pad_left = nn.ConstantPad2d((1,0,0,0), 0) self.pad_top = nn.ConstantPad2d((0,0,1,0), 0) def forward(self, pred, true): x1 = torch.abs(pred[:,:,:,1:] - pred[:,:,:,:-1]) x2 = torch.abs(true[:,:,:,1:] - true[:,:,:,:-1]) y1 = torch.abs(pred[:,:,1:,:] - pred[:,:,:-1,:]) y2 = torch.abs(true[:,:,1:,:] - true[:,:,:-1,:]) x1 = self.pad_left(x1) x2 = self.pad_left(x2) y1 = self.pad_top(y1) y2 = self.pad_top(y2) loss = torch.sum(torch.abs(x1-x2)**self.alpha+torch.abs(y1-y2)**self.alpha) / pred.size(0) return loss class L2_Grad_Loss(_Loss): def __init__(self, alpha=1, lambda_g=1): super(L2_Grad_Loss, self).__init__() self.lambda_g = lambda_g self.alpha = alpha self.pad_left = nn.ConstantPad2d((1,0,0,0), 0) self.pad_top = nn.ConstantPad2d((0,0,1,0), 0) def forward(self, pred, true): l2_loss = torch.sum((pred - true)**2) / pred.size(0) x1 = torch.abs(pred[:,:,:,1:] - pred[:,:,:,:-1]) x2 = torch.abs(true[:,:,:,1:] - true[:,:,:,:-1]) y1 = torch.abs(pred[:,:,1:,:] - pred[:,:,:-1,:]) y2 = torch.abs(true[:,:,1:,:] - true[:,:,:-1,:]) x1 = self.pad_left(x1) x2 = self.pad_left(x2) y1 = self.pad_top(y1) y2 = self.pad_top(y2) grad_loss = torch.sum((x1-x2)**self.alpha + (y1-y2)**self.alpha) / pred.size(0) return l2_loss + self.lambda_g * grad_loss class KLLoss(_Loss): def forward(self, pred, target): loss = torch.sum(target*(torch.log(target+1e-6) - torch.log(pred+1e-6))) / pred.size(0) return loss class CrossEntropyLoss2d(nn.Module): def __init__(self, weight=None, size_average=True, ignore_index=255): super(CrossEntropyLoss2d, self).__init__() self.nll_loss = nn.NLLLoss2d(weight, size_average, ignore_index) def forward(self, inputs, targets): return self.nll_loss(F.log_softmax(inputs, dim=1), targets) class FocalLoss2d(nn.Module): def __init__(self, gamma=2, weight=[1,3,10,100,1000], size_average=True, ignore_index=255): super(FocalLoss2d, self).__init__() self.gamma = gamma weight = torch.from_numpy(np.array(weight)).type(torch.cuda.FloatTensor) self.nll_loss = nn.NLLLoss2d(weight, size_average, ignore_index) def forward(self, inputs, targets): inputs += 1e-6 if targets.dim() == 4: n, c, h, w = targets.size() targets = targets.contiguous().view(n, h, w) return self.nll_loss((1 - F.softmax(inputs, dim=1)) ** self.gamma * F.log_softmax(inputs, dim=1), targets) class OrderLoss(_Loss): def __init__(self, num=[1,1,1,1]): super(OrderLoss, self).__init__() n = np.sqrt(num) self.weight = torch.from_numpy(n/np.sum(n)) def forward(self, pred, target): n, c, h, w = target.size() W = self.weight.clone().repeat(n, h, w, 1).transpose(2, 3).transpose(1, 2).contiguous() W = torch.autograd.Variable(W, requires_grad=False).type(torch.cuda.FloatTensor) target = target.type(torch.cuda.FloatTensor) # cross_entropy = nn.BCELoss(weight=W) # loss = cross_entropy(pred, target) loss = F.binary_cross_entropy(pred, target, weight=W) # loss = torch.log(pred + 1e-10).mul(target) + torch.log(1 - pred + 1e-10).mul((1-target)) # loss = loss * W # loss = -loss.mean() return loss
UTF-8
Python
false
false
6,122
py
33
loss.py
27
0.579059
0.550474
0
169
35.224852
117
Intervencion/-PKMNFCbot
14,181,982,032,069
c01cd34bd17cce73df321d88c1adc69719c9bc49
3eaf2b0f95f8af34d81cc0f261781ff025f7126b
/Bot/NOTOCAR/info.py
7d951426d63b11b1f4a36a9b6c03dbd7a4c45bd6
[]
no_license
https://github.com/Intervencion/-PKMNFCbot
a14cfa41ff753cc91c3688fb425b9f5a0c54d787
b21d04e37a1b9f7b63fb1cfcf6814214e61ad2a4
refs/heads/master
2020-06-12T17:37:00.316130
2019-02-27T13:20:15
2019-02-27T13:20:15
75,786,677
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from config import * @bot.message_handler(commands=['info']) def command_info(m): cid = m.chat.id try: dex = m.text.split(' ', 1)[1].replace(" ","_") bot.reply_to(m,f'https://www.wikidex.net/wiki/{dex}', disable_web_page_preview=True) try: c.execute("SELECT Contador FROM TContador WHERE Nombre ='info'") for i in c: print(i[0]) increment = i[0] +1 c.execute("UPDATE TContador SET Contador = Contador + 1 WHERE Nombre = 'info'") except: mensaje = f"No he contado bien mamá.\n" mensaje += f"User: {ufm}\n" mensaje += f"Chat: {mct}\n" mensaje += f"Hora: {hora}\n" mensaje += f"UserID: [{uid}]" mensaje += f" ChatID: [{cid}]" mensaje += "\n" mensaje += f"Mensaje: {texto}\n" mensaje += "-------------------------------\n" bot.send_message(admins[0], mensaje, parse_mode = "Markdown") except: bot.send_message(cid, "El formato del comando es /info *X* donde X es el nombre del pokémon, movimiento u objeto.", parse_mode = "Markdown")
UTF-8
Python
false
false
993
py
25
info.py
23
0.607467
0.600404
0
27
35.740741
142
harsh7742/music_system
11,338,713,679,638
b80913b74e623f023de64c5e5eb0af7c1040534a
038abb327e31acae36a5933111611592846895fa
/musicplayer.py
26517479fc6974ae6c1f9abec4e5c1ee40b5ce8e
[]
no_license
https://github.com/harsh7742/music_system
f980324746e6becc2c4b92dd7cc285bdecaa2680
679a9916416a675254d9aa8eb50159e695ae3c56
refs/heads/main
2023-06-26T16:14:42.379152
2021-07-28T06:16:57
2021-07-28T06:16:57
390,235,973
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def resumemusic(): root.pauseButton.grid() root.resumeButton.grid_remove() def volumeup(): vol = mixer.music.get_volume() mixer.music.set_volume(vol+0.1) def volumedown(): vol = mixer.music.get_volume() mixer.music.set_volume(vol-0.1) def stopmusic(): mixer.music.stop() def pausemusic(): mixer.music.pause() root.resumeButton.grid() root.pauseButton.grid_remove() def playmusic(): h=audiotrack.get() mixer.music.load(h) mixer.music.play() def music(): d=filedialog.askopenfilename() audiotrack.set(d) def createwidthes(): global imbrowse,impause,imbrowse,imvolumeup,imvolumedown,imstop,implay,iresume #images res=gister implay=PhotoImage(file='play.png') impause=PhotoImage(file='pause1.png') imbrowse=PhotoImage(file='browse.png') imstop=PhotoImage(file='stop1.png') imvolumeup=PhotoImage(file='volumeup.png') imvolumedown=PhotoImage(file='volumedown.png') imresume = PhotoImage(file='play.png') #change size of imgae imbrowse =imbrowse.subsample(1,1) impause = impause.subsample(20,20) imvolumeup = imvolumeup.subsample(1, 1) imvolumedown = imvolumedown.subsample(2,2) implay = implay.subsample(2,2) imstop = imstop.subsample(110,110) imresume = imresume.subsample(2,2) #labels TrackLabel = Label(root,text='Audio Track :',bg='azure',font=('verdana',14,'italic bold')) TrackLabel.grid(row=0,column=0,padx=22,pady=22) #entry box LabelEntry=Entry(root,font=('verdana',14,'italic bold'),width=30,textvariable=audiotrack) LabelEntry.grid(row=0,column=1,padx=22,pady=22) #button browsseButton=Button(root,text='Search',bg='azure',font=('verdana',14,'italic bold'),width=200,relief='solid', activebackground='lightskyblue3',image=imbrowse,compound=RIGHT,command=music) browsseButton.grid(row=0,column=2,padx=22,pady=22) playButton=Button(root,text='Play',bg='azure',font=('verdana',14,'italic bold'),width=200,relief='solid', activebackground='lightskyblue3',image=implay,compound=RIGHT,command=playmusic) playButton.grid(row=1,column=0,padx=22,pady=22) root.pasueButton = Button(root, text='Pause', bg='azure', font=('verdana', 14, 'italic bold'), width=200, relief='solid', activebackground='lightskyblue3',image=impause,compound=RIGHT,command=pausemusic) root.pasueButton.grid(row=1, column=1, padx=22, pady=22) root.resumeButton = Button(root, text='resume', bg='azure', font=('verdana', 14, 'italic bold'), width=200, relief='solid', activebackground='lightskyblue3', image=imresume, compound=RIGHT, command=resumemusic) root.resumeButton.grid(row=1, column=1, padx=22, pady=22) root.resumeButton.grid_remove() stopButton=Button(root,text='Stop',bg='azure',font=('verdana',14,'italic bold'),width=200,relief='solid', activebackground='lightskyblue3',image=imstop,compound=RIGHT,command=stopmusic) stopButton.grid(row=2,column=0,padx=22,pady=22) volumeupButton = Button(root, text='VolumeUp', bg='azure', font=('verdana', 14, 'italic bold'), width=200, relief='solid', activebackground='lightskyblue3',image=imvolumeup,compound=RIGHT,command=volumeup) volumeupButton.grid(row=1, column=2, padx=22, pady=22) volumedownButton = Button(root, text='Volumedown', bg='azure', font=('verdana', 14, 'italic bold'), width=200, relief='solid', activebackground='lightskyblue3',image=imvolumedown,compound=RIGHT,command=volumedown) volumedownButton.grid(row=2, column=2, padx=22, pady=22) ############################################################# from tkinter import * from tkinter import filedialog from pygame import mixer root = Tk() root.geometry('1100x500+200+50') root.title('Music Player') root.iconbitmap('music.ico') root.resizable(False,False) root.configure(bg='aqua') #gobal variable audiotrack = StringVar() #create a slider h="Developed by Harsh Sharma" count=0 text ='' sliderLabel=Label(root,text=h,bg='aqua', font=('verdana', 32, 'italic bold')) sliderLabel.grid(row=3,column=0,padx=22,pady=22,columnspan=3) def IntroLabelTrick(): global count,text if(count>=len(h)): count = -1 text='' sliderLabel.configure(text=text) else: text= text+h[count] sliderLabel.configure(text=text) count +=1 sliderLabel.after(200,IntroLabelTrick) IntroLabelTrick() mixer.init() createwidthes() root.mainloop()
UTF-8
Python
false
false
4,657
py
1
musicplayer.py
1
0.665879
0.632596
0
113
39.230088
130
epi052/recon-pipeline
3,229,815,430,894
6af8caf22e1a8bcd201df027eff66aa975af4ebf
67e7c0f06e8aef9579bf3761ff6af76e5eafb590
/tests/test_web/test_waybackurls.py
8c08f028d779221a76d93b115017cd81d7a77b91
[ "MIT" ]
permissive
https://github.com/epi052/recon-pipeline
d1c711f5fd7ceccc95eda13004287d030452fe90
4930f4064ca42c4b3669444b92dee355dd68b81e
refs/heads/main
2023-02-23T06:02:26.055102
2023-01-27T00:20:30
2023-01-27T00:20:30
205,856,988
413
102
MIT
false
2023-02-13T16:35:28
2019-09-02T12:54:26
2023-02-05T12:43:20
2023-02-13T16:35:28
63,776
375
89
12
Python
false
false
import shutil import tempfile from pathlib import Path from unittest.mock import MagicMock, patch from pipeline.recon.web import WaybackurlsScan, GatherWebTargets class TestGatherWebTargets: def setup_method(self): self.tmp_path = Path(tempfile.mkdtemp()) self.scan = WaybackurlsScan( target_file=__file__, results_dir=str(self.tmp_path), db_location=str(self.tmp_path / "testing.sqlite") ) self.scan.exception = False def teardown_method(self): shutil.rmtree(self.tmp_path) def test_scan_requires(self): with patch("pipeline.recon.web.GatherWebTargets"): with patch("pipeline.recon.web.waybackurls.meets_requirements"): retval = self.scan.requires() assert isinstance(retval, GatherWebTargets) def test_scan_creates_database(self): assert self.scan.db_mgr.location.exists() assert self.tmp_path / "testing.sqlite" == self.scan.db_mgr.location def test_scan_creates_results_dir(self): assert self.scan.results_subfolder == self.tmp_path / "waybackurls-results" def test_scan_run(self): with patch("subprocess.run", autospec=True) as mocked_run: self.scan.results_subfolder = self.tmp_path / "waybackurls-results" self.scan.db_mgr.get_all_hostnames = MagicMock() self.scan.db_mgr.get_all_hostnames.return_value = ["google.com"] completed_process_mock = MagicMock() completed_process_mock.stdout.return_value = b"https://drive.google.com\nhttps://maps.google.com\n\n" completed_process_mock.stdout.decode.return_value = "https://drive.google.com\nhttps://maps.google.com\n\n" completed_process_mock.stdout.decode.splitlines.return_value = [ "https://drive.google.com", "https://maps.google.com", ] mocked_run.return_value = completed_process_mock self.scan.db_mgr.add = MagicMock() self.scan.db_mgr.get_or_create = MagicMock() self.scan.db_mgr.get_or_create_target_by_ip_or_hostname = MagicMock() self.scan.run() assert mocked_run.called assert self.scan.db_mgr.add.called assert self.scan.db_mgr.get_or_create.called assert self.scan.db_mgr.get_or_create_target_by_ip_or_hostname.called
UTF-8
Python
false
false
2,396
py
1,013
test_waybackurls.py
48
0.64399
0.64399
0
59
39.610169
119
zhangsong1417/xx
8,169,027,819,964
7fd68afe645e538bf19f62db1d4506c5fac8372a
27ff7fec0ae3f29f58089a2acab0aa3bc4e6e1f7
/RIDE-python3/utest/ui/test_namedialogs.py
0576cfc0057ce75ed9d33e0992c36f1859fca2d5
[ "Apache-2.0" ]
permissive
https://github.com/zhangsong1417/xx
01435d6057364991b649c1acc00b36ab13debe5a
c40cfdede194daf3bdf91b36c1936150577128b9
refs/heads/master
2020-04-06T14:06:23.011363
2019-07-09T02:38:02
2019-07-09T02:38:02
157,528,207
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest from nose.tools import assert_equal from robotide.controller.filecontrollers import TestCaseFileController from robotide.editor.editordialogs import ( TestCaseNameDialog, UserKeywordNameDialog) from robotide.robotapi import TestCaseFile from resources import PYAPP_REFERENCE, wx def file_controller(): return TestCaseFileController(TestCaseFile()) class TestNameDialogTest(unittest.TestCase): _frame = wx.Frame(None) def test_creation(self): test_ctrl = file_controller().create_test('A test') dlg = TestCaseNameDialog(test_ctrl) assert_equal(dlg.get_name(), '') class UserKeywordNameDialogTest(unittest.TestCase): def test_creation(self): kw_ctrl = file_controller().create_keyword('Keyword it is') dlg = UserKeywordNameDialog(kw_ctrl) assert_equal(dlg.get_name(), '') def test_arguments_are_returned(self): kw_ctrl = file_controller().create_keyword('Keyword it is') dlg = UserKeywordNameDialog(kw_ctrl) assert_equal(dlg.get_args(), '')
UTF-8
Python
false
false
1,062
py
176
test_namedialogs.py
157
0.717514
0.717514
0
35
29.342857
70
alekseystryukov/simple-chat
11,982,958,765,732
ea0a865357b93e130fbfc8950153d18d6d17d83c
aafc464037938a5c32cf83e63107e946f49de8f2
/simple_chat/models.py
5e87f890cbd23196fe5cfad18caad3afb1f3849b
[]
no_license
https://github.com/alekseystryukov/simple-chat
ca53bd6dc95531248ff9907907f07a1dd9472305
623568a25eaa250e56fc20402763e9fc1bbdcad8
refs/heads/master
2016-08-12T06:37:43.484252
2015-11-09T16:16:59
2015-11-09T16:16:59
45,549,375
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from collections import deque from datetime import datetime class Message: """ Instances of this class keep info about every message from chat. Class doesn't inherit django.db.models, because we do not need to save them to db. Instances keep the data in slots, it saves a bit memory. Class property last_id saves last message id. It useful for recipients to track messages, that they already received """ __slots__ = ('id', 'name', 'message', 'time') last_id = 0 @staticmethod def get_id(): """ Method returns incremented message_id Return: int: next message id """ Message.last_id += 1 return Message.last_id def to_json(self): """ Method that returns the message data in format suited for json.dumps function Return: dict: message data that will be send to chat message recipients """ return {'id': self.id, 'name': self.name, 'message': self.message, 'time': self.time.strftime('%d %b %Y %H:%M:%S')} def __init__(self, **kwargs): self.id = self.get_id() self.name = kwargs['name'] self.message = kwargs['message'] self.time = datetime.now() def __repr__(self): return u"[{}] #{} {}: <{}>".format(self.time, self.id, self.name, self.message) MessagesPoll = deque(maxlen=500) #messages queue
UTF-8
Python
false
false
1,382
py
12
models.py
6
0.617221
0.613603
0
41
32.682927
123
peter302/password-locker
15,839,839,417,472
655c048edc9ae1bb7ea84f595cae4486c0c1dbba
46102c1049ccc6447e4e69867ce3997d7bd3999d
/user.py
2f6141e9ed9eb68cf27948a765fe0c22cb23f7c4
[ "MIT" ]
permissive
https://github.com/peter302/password-locker
356a8bcdb48e8dad31a7375ce1b91ec16177d806
1fa10dafb6aa95511044543c5673a6212fe13fbc
refs/heads/master
2020-11-23T22:31:19.636350
2019-12-16T14:16:33
2019-12-16T14:16:33
227,847,593
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pyperclip,string,random class User: user_list=[] #a list to hold user details def __init__(self,f_name,l_name,password): "a method acting as constructor to initalize instances of a class" self.f_name=f_name self.l_name=l_name self.password=password def user_save(self): "a method to save a new user object when ceated" User.user_list.append(self) class Credentials: "this class will hold users details including names and passwords for user's site plus funtions and method to alter those dtails" Credentials_list=[] user_credentials_list=[] @classmethod def user_auth(cls,f_name,password): '''this method will authenticate user''' loged_user='' for user in User.user_list: if(user.f_name==f_name and user.password==password): loded_user=user.f_name return loged_user def __init__(self,user_name,web_site,account_name,password): "this method initializes our credentials class with the propertis for user credentials" self.user_name=user_name self.web_site=web_site self.account_name=account_name self.password=password def save_credentials(self): "this method will save a newly user created credentials" Credentials.Credentials_list.append(self) def pass_gen(pass_size=6,char=string.ascii_uppercase+string.ascii_lowercase+string.digits): "this function will generate a password if user chooses automatic pass word generation" pass_choice=''.join(random.choice(char) for _ in range(pass_size)) return pass_choice @classmethod def show_credentials(cls,user_name): "this method will show all credentials stored for the loged user" for j in cls.user_credetials_list: if j.user_name==user_name: user_credetials_list.append(j) return user_credetials_list @classmethod def search_site_name(cls,web_site): "this method will search a web_site by name" for k in cls.Credentials_list: if k.web_site==web_site: return k def copy_site(cls,web_site): "class methods to copy a site name to our clip board" copy_credentials=Credentials.search_site_name(web_site) return pyperclip.copy(copy_credentials.password)
UTF-8
Python
false
false
2,567
py
4
user.py
3
0.613557
0.613167
0
61
41.081967
137
jemmelot/Heuristieken
3,453,153,716,571
dd6ab2c37098d5d71a48cc5a6381feefa90d7cab
94bf3533dea38ed3c6ee0501a16e180b53cb700d
/classes/ScoreIntegrated.py
2cd8e23d1f0c3c1aaf844af822db2ef12b0c1389
[]
no_license
https://github.com/jemmelot/Heuristieken
71572f8194da7c94ea55e371d685a8894ee64758
e89adf9b47d7761cf08a81b646845de27a42f661
refs/heads/master
2021-08-30T22:09:47.928773
2017-12-19T16:14:05
2017-12-19T16:14:05
109,595,024
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3 # https://github.com/jemmelot/Heuristieken.git import numpy as np import csv import sys sys.path.append('../classes/') sys.path.append('../functions/') sys.path.append('../algorithms/') import matplotlib.pyplot as plt class score_integrated(): def __init__(self, main_array, visited_connections, stations, route, critical_stations, trains, iteration): self.main_array = main_array self.visited_connections = visited_connections self.stations = stations self.route = route self.critical_stations = critical_stations self.trains = trains self.iteration = iteration self.t = self.t() self.min = self.min() self.p = self.p() self.totalscore = self.totalscore(self.p, self.t, self.min) def __float__(self): return self.totalscore def t(self): t = self.trains return t def min(self): min = 0 for i in range(self.iteration): min += self.route[i][0] return min def p(self): if len(self.critical_stations) != len(self.stations): all_criticals = 0 missed_criticals = 0 # compare the t array to the main array to check for missed critical connections for i in range(len(self.stations)): if self.stations[i] in self.critical_stations: x = np.count_nonzero(self.main_array[i, :] > 0) all_criticals += x y = np.count_nonzero(self.visited_connections[i, :] > 0) if not x == y: missed_criticals += (x - y) p = ((all_criticals - missed_criticals)/all_criticals) else: all_criticals = 0 missed_criticals = 0 for i in range(len(self.visited_connections)): x = np.count_nonzero(self.main_array[i, :] > 0) all_criticals += x y = np.count_nonzero(self.visited_connections[i, :] > 0) if not x == y: missed_criticals += (x - y) p = ((all_criticals - missed_criticals)/all_criticals) return p def totalscore(self, p, t, min): totalscore = (p * 10000) - ((t * 20) + (min/10000)) return totalscore
UTF-8
Python
false
false
1,995
py
21
ScoreIntegrated.py
11
0.643108
0.631579
0
78
24.576923
108
pkofod/vfi
4,286,377,387,604
875554747ce520bf8f63a067015b3f9adb6bc80d
38452ad0e05ed8b8755717e7710b55108e438156
/vfi/optimize_1d.py
4e53f14e9d0447a484bc32d7bb480b359fb2acd8
[ "MIT" ]
permissive
https://github.com/pkofod/vfi
c6ffda4e4d4f0e71f1ddc40587b041434b4fd2ca
38a0dd02b9a01c37f5a11252feaebad13c2010aa
refs/heads/master
2020-03-28T23:02:15.522151
2018-08-09T20:01:05
2018-08-09T20:01:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import math import numba # constants inv_phi = (math.sqrt(5) - 1) / 2 # 1/phi inv_phi_sq = (3 - math.sqrt(5)) / 2 # 1/phi^2 # create def create_optimizer(f): @numba.njit def golden_section_search(a,b,tol,*args): # a. distance dist = b - a if dist <= tol: return (a+b)/2 # b. number of iterations n = int(math.ceil(math.log(tol/dist)/math.log(inv_phi))) # c. potential new mid-points c = a + inv_phi_sq * dist d = a + inv_phi * dist yc = f(c,*args) yd = f(d,*args) # d. loop for _ in range(n-1): if yc < yd: b = d d = c yd = yc dist = inv_phi*dist c = a + inv_phi_sq * dist yc = f(c,*args) else: a = c c = d yc = yd dist = inv_phi*dist d = a + inv_phi * dist yd = f(d,*args) # e. return if yc < yd: return (a+d)/2 else: return (c+b)/2 return golden_section_search
UTF-8
Python
false
false
1,102
py
10
optimize_1d.py
5
0.424682
0.412886
0
51
20.627451
159
alimirakim/sbade
6,382,321,433,072
4740d9d6c037d13b54ac7a1049d37daf972a851a
b351351bc1f643ce9645e2c5c91eef5caaa3eb76
/skeleton/migrations/versions/5f553ea80cc6_new_seeder_data.py
53250c51d098795bb4b8f44ac5dfdee4a0ffe7a2
[]
no_license
https://github.com/alimirakim/sbade
64051ac366fb5aa8b8cfc6434c94fb446213e43e
137bc7fed59472658872de4fbfdf227ff4c22283
refs/heads/main
2023-01-24T09:04:33.752364
2020-12-04T17:21:06
2020-12-04T17:21:06
313,983,847
0
0
null
false
2020-12-01T15:33:41
2020-11-18T15:55:57
2020-12-01T15:01:11
2020-12-01T15:33:41
3,045
1
0
0
Python
false
false
"""new seeder data Revision ID: 5f553ea80cc6 Revises: Create Date: 2020-12-01 03:14:35.021979 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5f553ea80cc6' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('colors', sa.Column('id', sa.Integer(), nullable=False), sa.Column('hex', sa.String(length=7), nullable=False), sa.Column('name', sa.String(length=50), nullable=True), sa.Column('mode', sa.String(length=50), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('hex'), sa.UniqueConstraint('name') ) op.create_table('stamps', sa.Column('id', sa.Integer(), nullable=False), sa.Column('stamp', sa.String(length=50), nullable=False), sa.Column('type', sa.String(length=50), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('stamp') ) op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=50), nullable=False), sa.Column('first_name', sa.String(length=50), nullable=False), sa.Column('last_name', sa.String(length=50), nullable=True), sa.Column('email', sa.String(length=50), nullable=False), sa.Column('color_id', sa.Integer(), nullable=True), sa.Column('stamp_id', sa.Integer(), nullable=False), sa.Column('birthday', sa.Date(), nullable=True), sa.Column('hashed_password', sa.String(length=255), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['color_id'], ['colors.id'], ), sa.ForeignKeyConstraint(['stamp_id'], ['stamps.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email'), sa.UniqueConstraint('username') ) op.create_table('bonds', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user1_id', sa.Integer(), nullable=False), sa.Column('user2_id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['user1_id'], ['users.id'], ), sa.ForeignKeyConstraint(['user2_id'], ['users.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('programs', sa.Column('id', sa.Integer(), nullable=False), sa.Column('program', sa.String(length=50), nullable=False), sa.Column('description', sa.String(length=250), nullable=True), sa.Column('color_id', sa.Integer(), nullable=True), sa.Column('stamp_id', sa.Integer(), nullable=False), sa.Column('creator_id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['color_id'], ['colors.id'], ), sa.ForeignKeyConstraint(['creator_id'], ['users.id'], ), sa.ForeignKeyConstraint(['stamp_id'], ['stamps.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('habits', sa.Column('id', sa.Integer(), nullable=False), sa.Column('habit', sa.String(length=50), nullable=False), sa.Column('description', sa.String(length=250), nullable=True), sa.Column('frequency', sa.String(length=7), nullable=False), sa.Column('color_id', sa.Integer(), nullable=True), sa.Column('stamp_id', sa.Integer(), nullable=False), sa.Column('program_id', sa.Integer(), nullable=True), sa.Column('creator_id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['color_id'], ['colors.id'], ), sa.ForeignKeyConstraint(['creator_id'], ['users.id'], ), sa.ForeignKeyConstraint(['program_id'], ['programs.id'], ), sa.ForeignKeyConstraint(['stamp_id'], ['stamps.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('members', sa.Column('id', sa.Integer(), nullable=False), sa.Column('program_id', sa.Integer(), nullable=False), sa.Column('member_id', sa.Integer(), nullable=False), sa.Column('stamper_id', sa.Integer(), nullable=True), sa.Column('points', sa.Integer(), nullable=False), sa.Column('joined_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['member_id'], ['users.id'], ), sa.ForeignKeyConstraint(['program_id'], ['programs.id'], ), sa.ForeignKeyConstraint(['stamper_id'], ['users.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('rewards', sa.Column('id', sa.Integer(), nullable=False), sa.Column('type', sa.String(length=50), nullable=False), sa.Column('reward', sa.String(length=50), nullable=False), sa.Column('description', sa.String(length=250), nullable=True), sa.Column('cost', sa.Integer(), nullable=False), sa.Column('color_id', sa.Integer(), nullable=True), sa.Column('limit_per_member', sa.Integer(), nullable=False), sa.Column('quantity', sa.Integer(), nullable=False), sa.Column('stamp_id', sa.Integer(), nullable=False), sa.Column('program_id', sa.Integer(), nullable=True), sa.Column('creator_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['color_id'], ['colors.id'], ), sa.ForeignKeyConstraint(['creator_id'], ['users.id'], ), sa.ForeignKeyConstraint(['program_id'], ['programs.id'], ), sa.ForeignKeyConstraint(['stamp_id'], ['stamps.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('daily_stamps', sa.Column('id', sa.Integer(), nullable=False), sa.Column('date', sa.Date(), nullable=False), sa.Column('status', sa.Enum('unstamped', 'pending', 'stamped', name='status'), nullable=True), sa.Column('habit_id', sa.Integer(), nullable=False), sa.Column('member_id', sa.Integer(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['habit_id'], ['habits.id'], ), sa.ForeignKeyConstraint(['member_id'], ['members.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('redeemed', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('reward_id', sa.Integer(), nullable=False), sa.Column('redeemed_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['reward_id'], ['rewards.id'], ), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('redeemed') op.drop_table('daily_stamps') op.execute('drop type status;') op.drop_table('rewards') op.drop_table('members') op.drop_table('habits') op.drop_table('programs') op.drop_table('bonds') op.drop_table('users') op.drop_table('stamps') op.drop_table('colors') # ### end Alembic commands ###
UTF-8
Python
false
false
6,892
py
40
5f553ea80cc6_new_seeder_data.py
32
0.648433
0.637406
0
159
42.345912
98
1299172402/up366
970,662,640,119
9b28ba1a709bffcbec4a3e69957a125a5c00aac7
2eff86f2b5ed6ca040c35ce360caff2238ae5cca
/load.py
b81124f8a5e6719666f14b09cedefe0d27e119e0
[]
no_license
https://github.com/1299172402/up366
2fdc816df83e5444bd2cb0762b918bcf4df7d44b
1fe7748d6cb680c2f7c9e5652f05ee4c17010b4e
refs/heads/master
2020-12-22T07:49:13.793663
2020-02-13T13:22:36
2020-02-13T13:22:36
236,716,689
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests from bs4 import BeautifulSoup import urllib.request from lxml import html etree = html.etree # 欢迎文字 print('\n\n') print('####### 天学网登录程序 #######\n') # print('Author~~') print('Jellow 看见我请一定一定叫我学习') print('Creative By ZhiyuShang With Love\n') # print('Thanks for being addicted') print('') headers = { 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'Host': 'live-api.up366.cn', 'Origin': 'http://me.up366.cn', 'Referer': 'http://me.up366.cn/center/student/course/liveclasses.html?courseId=89440&createTime=undefined', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36', 'X-Requested-With': 'XMLHttpRequest', 'Cookie': 'acw_tc=7b39758215802092127684930e1234175f6acbea06d4bbf933eca866daecde; BIGipServercn_liveclass-api_pool=2467735744.38175.0000; SESSION=301df37e-80f0-4372-b3a1-2ab37363de0e' } print('测试获取直播课列表\n') print('出现我校直播课名称即为获取成功\n') play_url = 'http://live-api.up366.cn/client/liveclass/list' s = requests.session() response = s.get(play_url, headers=headers).content s = BeautifulSoup(response, 'lxml') print(s)
UTF-8
Python
false
false
1,339
py
5
load.py
2
0.709237
0.604819
0
38
30.815789
184
rcrowther/Gravel
11,553,462,038,408
431998f40f0227dfbacb0ea4567d670c7e9ce5a5
a07694aab30198bc11965d0dae11471b0a004957
/interpreter/__init__.py
3c16d9a645d7378407efdd76dac36d151cda0256
[]
no_license
https://github.com/rcrowther/Gravel
6fccf500f680ea70371c4d889d6f2930c1a7727e
86f22a2c1d561983020949cf5dc75cfb3004919b
refs/heads/master
2021-08-25T06:21:34.317932
2021-06-11T19:14:24
2021-06-11T19:14:24
135,619,592
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from .Engines import FileEngine
UTF-8
Python
false
false
32
py
175
__init__.py
147
0.84375
0.84375
0
1
31
31
CmJustice/Mc-Admin
7,215,545,084,499
2dd41bc03518a4ce04285888242a069f2179b386
4552ca62b4b47a10da893f009f5bf25323fe30df
/main.py
7012971d431f6dc8b92c78429b450d73a339a8d1
[]
no_license
https://github.com/CmJustice/Mc-Admin
8e566273254659c36eec477aba9c913da02f7d57
be0e6fa888bb46f5cf8477d4fa8d1acfd74a08d2
refs/heads/master
2016-09-09T19:13:32.766843
2015-09-15T17:14:51
2015-09-15T17:14:51
42,507,912
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#-*- coding: utf-8 -*- __author__ = 'Cem' import sys import os import utils.screenutils.screen import utils.screenutils.errors import utils.color color = utils.color import konsol screenutil = utils.screenutils.screen print "MC-ADMIN VERSIYON 0.1" print "Hosgeldin!" print "\nLütfen giris yapin!" def selamla(isim): print "Hoşgeldiniz", isim, "bey" print "Umarım iyi vakit geçirirsiniz." print("") print("") print("") print("") print("") print("") print("") konsol.konsol() while True: id = raw_input("Kullanici adi:") sifre = raw_input("Sifre:") if id == 'Cem' and sifre == '1234' : selamla(id) break else: print color.bcolors.FAIL + "Sifre veya Kullanici Adi hatali!"
UTF-8
Python
false
false
775
py
5
main.py
4
0.614786
0.605707
0
50
14.36
69
coolsnake/JupyterNotebook
7,619,271,986,562
1114def8a5f97064b9d83e97085660ccded181ed
da29f1f5b4459fbfec968bb694bedb9586f87b14
/new_algs/Graph+algorithms/Dijkstra's+algorithm/Dijsktra's.py
47b7ea49a77d30c80ff268b241a34013b2e3ef3e
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
https://github.com/coolsnake/JupyterNotebook
547806a45a663f090f313dc3e70f779ad9b213c0
20d8df6172906337f81583dabb841d66b8f31857
refs/heads/master
2023-01-13T18:55:38.615312
2020-11-17T22:55:12
2020-11-17T22:55:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import math import copy import time def searchForLeastCost(costs, processed): lowestCost = math.inf lowestCostNode = None for node in costs: cost = costs[node] #check if cheapest if cost < lowestCost and node not in processed: lowestCost = cost lowestCostNode = node return(lowestCostNode) def formulate(graph, startNode): costs = {} parents = {} processed = [] #making costs for w in graph: costs[w] = math.inf #adding costs from start node costs[startNode] = 0 for x in graph[startNode]: costs[x] = graph[startNode][x] #creating parents for y in graph: parents[y] = None #adding parents from start node parents[startNode] = 0 for z in graph[startNode]: parents[z] = startNode #creating processed processed.append(startNode) return(parents, costs, processed) def dijkstra(graph, startNode): parents, costs, processed = formulate(graph, startNode) node = searchForLeastCost(costs, processed) #if while loop over nodes all processed while node is not None: #get all neighbours from node & their total costs cost = costs[node] neighbours = graph[node] for n in neighbours: newCost = cost + neighbours[n] #if newcost less than previous noted 'shortest' cost... if costs[n] > newCost: #then update costs and parents to say so costs[n] = newCost parents[n] = node #now all neighbours noted node has been processed processed.append(node) #find next node node = searchForLeastCost(costs, processed) return(parents, costs, processed) def main(): ''' target = "End" #make graph graph = {} #nodes graph["Start"] = {} graph["A"] = {} graph["B"] = {} graph["End"] = {} #node connections graph["Start"]["A"] = 6 graph["Start"]["B"] = 2 graph["A"]["End"] = 1 graph["B"]["A"] = 3 graph["B"]["End"] = 5 ''' #travelling salesman #make graph graph = {} #nodes graph["A"] = {} graph["B"] = {} graph["C"] = {} graph["D"] = {} graph["E"] = {} graph["F"] = {} #node connections graph["A"]["B"] = 5 graph["A"]["C"] = 3 graph["A"]["D"] = 3 graph["B"]["A"] = 5 graph["B"]["F"] = 2 graph["C"]["A"] = 3 graph["C"]["F"] = 3 graph["C"]["E"] = 3 graph["D"]["A"] = 3 graph["D"]["E"] = 2 graph["E"]["C"] = 3 graph["E"]["D"] = 2 graph["F"]["B"] = 2 graph["F"]["C"] = 3 graphList = [] for v in graph: graphList.append(v) graphString = ", ".join(graphList) print("The nodes are", graphString) inputLoop = True while inputLoop == True: startNode = input("Please enter the start node: \n").upper() targetNode = input("Please enter the target node: \n").upper() if startNode in graph and targetNode in graph: print("\n") target = targetNode inputLoop = False else: print("\nPlease enter a nodes in the graph") #Start the clock! startTime = time.time() #use dijkstras parents, costs, processed = dijkstra(graph, startNode) # Node must be in graph #Stop the clock! endTime = time.time() - startTime #give answer travelList = [target] parent = parents[target] if parent == 0: pass else: travelList.insert(0, parent) while parent != 0: parent = parents[parent] if parent == 0: pass else: travelList.insert(0, parent) #formatting the answers print("The path of "+", ".join(travelList)+" was taken") print("With a total cost of "+str(costs[target])) print("The nodes were processed in the order "+", ".join(parents)) print("The program took", endTime , "second/s") mainLoop = True print("----------- Welcome To Dijsktra's Algorithm -----------") while mainLoop == True: main() print("\n") userSelect = input("Please press enter to continue, or E to exit") if userSelect == "e" or userSelect == "E": mainLoop = False
UTF-8
Python
false
false
4,533
py
1,523
Dijsktra's.py
1,515
0.52195
0.516214
0
156
26.608974
82