hexsha
stringlengths
40
40
size
int64
7
1.04M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
247
max_stars_repo_name
stringlengths
4
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
247
max_issues_repo_name
stringlengths
4
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
247
max_forks_repo_name
stringlengths
4
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.04M
avg_line_length
float64
1.77
618k
max_line_length
int64
1
1.02M
alphanum_fraction
float64
0
1
original_content
stringlengths
7
1.04M
filtered:remove_function_no_docstring
int64
-102
942k
filtered:remove_class_no_docstring
int64
-354
977k
filtered:remove_delete_markers
int64
0
60.1k
623cc4a88cf805a2be9181a128ec45d41da45e39
746
py
Python
camera/camera-test.py
Mejdi-Thabet/streo-measurment-vision
8fa55dbcb40c24c0d80bc062fc88f5abca3afdd1
[ "MIT" ]
null
null
null
camera/camera-test.py
Mejdi-Thabet/streo-measurment-vision
8fa55dbcb40c24c0d80bc062fc88f5abca3afdd1
[ "MIT" ]
null
null
null
camera/camera-test.py
Mejdi-Thabet/streo-measurment-vision
8fa55dbcb40c24c0d80bc062fc88f5abca3afdd1
[ "MIT" ]
null
null
null
import cv2 # import OpenCv lib cap = cv2.VideoCapture(0) # create cap object # set the format into MJPG in the FourCC format # cap.set(cv2.CAP_PROP_FOURCC,cv2.VideoWriter_fourcc('M','J','P','G')) cap.set(cv2.CAP_PROP_FOURCC,cv2.VideoWriter_fourcc('J','P','E','G')) if not cap.isOpened(): # check if the camera is opened print('Cannot open webcam') else: while True: success, frame = cap. read() # read frames cv2.imshow(" Captured: " , frame) # show frames in the window if cv2.waitKey(1) == 27: # check if the user press ESC or not break cap.release() # stop cv2. destroyAllWindows()
39.263158
82
0.563003
import cv2 # import OpenCv lib cap = cv2.VideoCapture(0) # create cap object # set the format into MJPG in the FourCC format # cap.set(cv2.CAP_PROP_FOURCC,cv2.VideoWriter_fourcc('M','J','P','G')) cap.set(cv2.CAP_PROP_FOURCC,cv2.VideoWriter_fourcc('J','P','E','G')) if not cap.isOpened(): # check if the camera is opened print('Cannot open webcam') else: while True: success, frame = cap. read() # read frames cv2.imshow(" Captured: " , frame) # show frames in the window if cv2.waitKey(1) == 27: # check if the user press ESC or not break cap.release() # stop cv2. destroyAllWindows()
0
0
0
8daaf49581c6c124d1d1ca6059bbf42aec8dc61e
760
py
Python
final_project/machinetranslation/tests/tests.py
singhashwini12/xzceb-flask_eng_fr
ac5cac807078b4adfec65c4ff20287afe5658f81
[ "Apache-2.0" ]
null
null
null
final_project/machinetranslation/tests/tests.py
singhashwini12/xzceb-flask_eng_fr
ac5cac807078b4adfec65c4ff20287afe5658f81
[ "Apache-2.0" ]
null
null
null
final_project/machinetranslation/tests/tests.py
singhashwini12/xzceb-flask_eng_fr
ac5cac807078b4adfec65c4ff20287afe5658f81
[ "Apache-2.0" ]
null
null
null
""" Module for unit tests for translations """ import unittest from translator import french_to_english, english_to_french class TranslationTest(unittest.TestCase): """This Class contains the unit tests for translations""" def test_french_to_english(self): """This method tests the French to English Translations""" self.assertEqual(french_to_english(""),None) self.assertEqual(french_to_english("Bonjour"),[{'translation': 'Hello'}]) def test_english_to_french(self): """This method tests the English to French Translations""" self.assertEqual(english_to_french(""),None) self.assertEqual(english_to_french("Hello"),[{'translation': 'Bonjour'}]) if __name__=='__main__': unittest.main()
29.230769
81
0.711842
""" Module for unit tests for translations """ import unittest from translator import french_to_english, english_to_french class TranslationTest(unittest.TestCase): """This Class contains the unit tests for translations""" def test_french_to_english(self): """This method tests the French to English Translations""" self.assertEqual(french_to_english(""),None) self.assertEqual(french_to_english("Bonjour"),[{'translation': 'Hello'}]) def test_english_to_french(self): """This method tests the English to French Translations""" self.assertEqual(english_to_french(""),None) self.assertEqual(english_to_french("Hello"),[{'translation': 'Bonjour'}]) if __name__=='__main__': unittest.main()
0
0
0
acf3bb14a90d358bd06a4aeaf84395cbe98bf174
47
py
Python
Parte1/Cap4/numbers.py
fabianoflorentino/python-CursoIntensivoDePython
822288cc4b382936dde1bc647e3f8c2b925ced70
[ "Apache-2.0" ]
null
null
null
Parte1/Cap4/numbers.py
fabianoflorentino/python-CursoIntensivoDePython
822288cc4b382936dde1bc647e3f8c2b925ced70
[ "Apache-2.0" ]
null
null
null
Parte1/Cap4/numbers.py
fabianoflorentino/python-CursoIntensivoDePython
822288cc4b382936dde1bc647e3f8c2b925ced70
[ "Apache-2.0" ]
1
2020-02-05T13:07:08.000Z
2020-02-05T13:07:08.000Z
for value in range(1,11): print(str(value))
23.5
25
0.659574
for value in range(1,11): print(str(value))
0
0
0
76f27aff2a93ba3677a16d1134cdc05204043038
852
py
Python
day21/part02.py
Berteun/adventofcode2019
39fdd90073491cd698b1a310c789b577b305d314
[ "MIT" ]
null
null
null
day21/part02.py
Berteun/adventofcode2019
39fdd90073491cd698b1a310c789b577b305d314
[ "MIT" ]
null
null
null
day21/part02.py
Berteun/adventofcode2019
39fdd90073491cd698b1a310c789b577b305d314
[ "MIT" ]
null
null
null
import operator import sys sys.path.append("..") from collections import defaultdict, namedtuple from intcode import IntCodeMachine, open_file # The logic is as follows. # If we would fall into a gap otherwise, we jump (NOT A T // OR T J) # We jump early, that is a gap at B or C if we have an out, that is we can move to E or we can jump to H. input_string = """\ OR B J AND C J NOT J J AND D J OR E T OR H T AND T J NOT A T OR T J RUN """ inputs = [ord(c) for c in input_string] if __name__ == '__main__': run()
20.285714
105
0.664319
import operator import sys sys.path.append("..") from collections import defaultdict, namedtuple from intcode import IntCodeMachine, open_file # The logic is as follows. # If we would fall into a gap otherwise, we jump (NOT A T // OR T J) # We jump early, that is a gap at B or C if we have an out, that is we can move to E or we can jump to H. input_string = """\ OR B J AND C J NOT J J AND D J OR E T OR H T AND T J NOT A T OR T J RUN """ inputs = [ord(c) for c in input_string] def oninput(): result = inputs.pop(0) sys.stdout.write(chr(result)) return result def onoutput(i): if i < 256: sys.stdout.write(chr(i)) else: print(i) def run(): memory = open_file("input_day21.txt") machine = IntCodeMachine(memory, onread=oninput, onwrite=onoutput) machine.run() if __name__ == '__main__': run()
263
0
69
63a6a1b1ae7ec796ed219f0066ef0827b8930884
281
py
Python
lambda/models/candidate.py
SujeethJinesh/presidential-sentiment-translator
262724930f49714724f6bd0a8c833872fafccd09
[ "MIT" ]
null
null
null
lambda/models/candidate.py
SujeethJinesh/presidential-sentiment-translator
262724930f49714724f6bd0a8c833872fafccd09
[ "MIT" ]
4
2021-03-10T08:37:55.000Z
2022-02-27T00:02:34.000Z
lambda/models/candidate.py
SujeethJinesh/presidential-sentiment-translator
262724930f49714724f6bd0a8c833872fafccd09
[ "MIT" ]
null
null
null
from .party_affiliation import PartyAffiliation
31.222222
92
0.75089
from .party_affiliation import PartyAffiliation class Candidate: def __init__(self, name: str, twitter_handle: str, party_affiliation: PartyAffiliation): self.name = name self.twitter_handle = twitter_handle self.party_affiliation = party_affiliation
188
-5
49
197b93869990d0f3d97546f1dea1622b5635a527
448
py
Python
Python Exercises/Mundo1/exercicio35.py
joaopblume/Curso-em-video-exercicios
d554c0c07c8d65b3a219d76fc487a78c11eaf874
[ "MIT" ]
null
null
null
Python Exercises/Mundo1/exercicio35.py
joaopblume/Curso-em-video-exercicios
d554c0c07c8d65b3a219d76fc487a78c11eaf874
[ "MIT" ]
null
null
null
Python Exercises/Mundo1/exercicio35.py
joaopblume/Curso-em-video-exercicios
d554c0c07c8d65b3a219d76fc487a78c11eaf874
[ "MIT" ]
null
null
null
# Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem # ou não formar um triângulo. r1 = int(input('Valor do primeiro segmento: ')) r2 = int(input('Valor do segundo segmento: ')) r3 = int(input('Valor do terceiro segmento: ')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('Os segmentos acima PODEM formar um triângulo!') else: print('Os segmentos acima não podem formar um triângulo!')
37.333333
93
0.700893
# Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem # ou não formar um triângulo. r1 = int(input('Valor do primeiro segmento: ')) r2 = int(input('Valor do segundo segmento: ')) r3 = int(input('Valor do terceiro segmento: ')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('Os segmentos acima PODEM formar um triângulo!') else: print('Os segmentos acima não podem formar um triângulo!')
0
0
0
61a4af5829698981e3b9c360f342edf02730b98a
415
py
Python
helper.py
devnoaman/GIZ-pass-python
49bcf3af21053a934959ca89f360a12b2c967820
[ "MIT" ]
null
null
null
helper.py
devnoaman/GIZ-pass-python
49bcf3af21053a934959ca89f360a12b2c967820
[ "MIT" ]
null
null
null
helper.py
devnoaman/GIZ-pass-python
49bcf3af21053a934959ca89f360a12b2c967820
[ "MIT" ]
1
2021-09-28T19:44:24.000Z
2021-09-28T19:44:24.000Z
name='Noaman Monther Mahmood' job='Full-Stack Mobile Developer' header= 'This Job is Done By' desc='And it is one of the requirements to be accepted in th Full-Stack Development Bootcamp \nthat is implemented by Computiq and and GIZ Interview'
41.5
149
0.643373
def printConsoleFotter(): print("\n\n\n-------------------------------------") print('Give this job a 🚀\n\n') print(header+'\n'+name+'\n'+job+'\n'+desc+'\n') name='Noaman Monther Mahmood' job='Full-Stack Mobile Developer' header= 'This Job is Done By' desc='And it is one of the requirements to be accepted in th Full-Stack Development Bootcamp \nthat is implemented by Computiq and and GIZ Interview'
151
0
23
8c42367d2e5da1623ac19d6395db113c71f802ca
2,166
py
Python
tortuga_kits/ganglia_3_7_2/kit.py
UnivaCorporation/tortuga-kit-ganglia
af8f6b76c7548687177be27f2aec32c7a96b9325
[ "Apache-2.0" ]
3
2018-03-03T15:44:50.000Z
2019-03-14T17:42:21.000Z
tortuga_kits/ganglia_3_7_2/kit.py
UnivaCorporation/tortuga-kit-ganglia
af8f6b76c7548687177be27f2aec32c7a96b9325
[ "Apache-2.0" ]
null
null
null
tortuga_kits/ganglia_3_7_2/kit.py
UnivaCorporation/tortuga-kit-ganglia
af8f6b76c7548687177be27f2aec32c7a96b9325
[ "Apache-2.0" ]
3
2018-03-03T14:24:59.000Z
2018-12-12T17:57:03.000Z
#!/usr/bin/env python # Copyright 2008-2018 Univa Corporation # # 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 os import shutil from tortuga.kit.installer import KitInstallerBase from tortuga.kit.manager import KitManager from tortuga.os_utility import tortugaSubprocess
34.380952
74
0.66205
#!/usr/bin/env python # Copyright 2008-2018 Univa Corporation # # 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 os import shutil from tortuga.kit.installer import KitInstallerBase from tortuga.kit.manager import KitManager from tortuga.os_utility import tortugaSubprocess class GangliaInstaller(KitInstallerBase): puppet_modules = ['univa-tortuga_kit_ganglia'] def action_post_install(self, *args, **kwargs): super().action_post_install(*args, **kwargs) # # Cache Ganglia packages from EPEL # os.system(os.path.join(self.install_path, 'bin', "dl.sh")) kit = KitManager().getKit('ganglia') kit_repo_dir = os.path.join( self.config_manager.getReposDir(), kit.getKitRepoDir() ) cmd = 'rsync -a {}/ {}'.format('/var/cache/tortuga/pkgs/ganglia', kit_repo_dir) tortugaSubprocess.executeCommandAndIgnoreFailure(cmd) cmd = 'cd %s; createrepo .'.format(kit_repo_dir) tortugaSubprocess.executeCommandAndIgnoreFailure(cmd) # # Copy default configuration file into place # dst_path = os.path.join(self.config_manager.getKitConfigBase(), 'ganglia') if not os.path.exists(dst_path): os.makedirs(dst_path) shutil.copyfile( os.path.join(self.files_path, 'gmond-component.conf'), os.path.join(dst_path, 'gmond-component.conf') ) def action_post_uninstall(self, *args, **kwargs): tortugaSubprocess.executeCommand( 'rm -rf /var/cache/tortuga/pkgs/ganglia')
1,240
125
23
3733083b91aea75ae2b9c0f4c328355efaeea6f4
5,569
py
Python
JupyterNotebooks/DataLoading/preprocessing/images/convert_birdify_to_tfrecord.py
afarkasattila/Birdify2
3dcc373762a901f27cb9d5060785b75ff17b58a7
[ "MIT" ]
null
null
null
JupyterNotebooks/DataLoading/preprocessing/images/convert_birdify_to_tfrecord.py
afarkasattila/Birdify2
3dcc373762a901f27cb9d5060785b75ff17b58a7
[ "MIT" ]
null
null
null
JupyterNotebooks/DataLoading/preprocessing/images/convert_birdify_to_tfrecord.py
afarkasattila/Birdify2
3dcc373762a901f27cb9d5060785b75ff17b58a7
[ "MIT" ]
null
null
null
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .dataset_utils import image_to_tfexample from json import dump from numpy import arange, empty, array, empty_like from numpy.random import shuffle from os import walk from PIL import Image from six.moves import urllib import sys import tensorflow as tf _IMAGE_SIZE = 224 _NUM_CHANNELS = 3 def _add_to_tfrecord(images, labels, num_images, tfrecord_writer): """ Loads data from the binary MNIST files and writes files to a TFRecord. Args: data_filename: The filename of the MNIST images. labels_filename: The filename of the MNIST labels. num_images: The number of images in the dataset. """ shape = (_IMAGE_SIZE, _IMAGE_SIZE, _NUM_CHANNELS) with tf.Graph().as_default(): image = tf.placeholder(dtype=tf.uint8, shape=shape) encoded_png = tf.image.encode_png(image) with tf.Session('') as sess: for j in range(num_images): sys.stdout.write('\r>> Converting image %d/%d' % (j + 1, num_images)) sys.stdout.flush() png_string = sess.run(encoded_png, feed_dict={image: images[j]}) example = image_to_tfexample(png_string, 'png'.encode(), _IMAGE_SIZE, _IMAGE_SIZE, labels[j]) tfrecord_writer.write(example.SerializeToString())
38.406897
123
0.661519
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .dataset_utils import image_to_tfexample from json import dump from numpy import arange, empty, array, empty_like from numpy.random import shuffle from os import walk from PIL import Image from six.moves import urllib import sys import tensorflow as tf _IMAGE_SIZE = 224 _NUM_CHANNELS = 3 def _get_labels(filename, nr_of_labels): print('Get labels from: ', filename) with open("%s/labels.txt"%(filename), "r") as f: data = f.read() labels = empty_like(arange(nr_of_labels)) labels = data.split(" ") labels_1 = [] k =0 for x in labels: k += 1 if x == '': labels_1.append(0) else: labels_1.append(int(x)) return labels_1 def _shuffle_all(data_names, labels, path_to_file_names=None): indexes = arange(len(data_names)) shuffle(indexes) indexes = [ int(x) for x in indexes ] shuffled_labels = [] shuffled_names = [] shuffled_path_to_file_names = [] for i in arange(len(data_names)): shuffled_labels.append(labels[indexes[i]]) shuffled_names.append(data_names[indexes[i]]) if path_to_file_names is not None: shuffled_path_to_file_names.append(path_to_file_names[indexes[i]]) return shuffled_names, shuffled_labels, shuffled_path_to_file_names def _create_all_tf_record_name(destination_directory, num_images, nr_of_train): nr_of_val = nr_of_train tfrecord_name = [] len_max = len(str(nr_of_train)) len_number = len_max + 1 str_tran_and_val = "0" str_tran_and_val += str(nr_of_train) for i in arange(nr_of_train): len_i = len(str(i)) nr_0 = len_number - len_i str_nr = "" for _ in arange(nr_0): str_nr += "0" str_nr += str(i) tfrecord_name.append("%s/birdify_train_%s-of-%s.tfrecord"%(destination_directory, str_nr, str_tran_and_val)) tfrecord_name.append("%s/birdify_validation_%s-of-%s.tfrecord"%(destination_directory,str_nr, str_tran_and_val)) return tfrecord_name def _add_to_tfrecord(images, labels, num_images, tfrecord_writer): """ Loads data from the binary MNIST files and writes files to a TFRecord. Args: data_filename: The filename of the MNIST images. labels_filename: The filename of the MNIST labels. num_images: The number of images in the dataset. """ shape = (_IMAGE_SIZE, _IMAGE_SIZE, _NUM_CHANNELS) with tf.Graph().as_default(): image = tf.placeholder(dtype=tf.uint8, shape=shape) encoded_png = tf.image.encode_png(image) with tf.Session('') as sess: for j in range(num_images): sys.stdout.write('\r>> Converting image %d/%d' % (j + 1, num_images)) sys.stdout.flush() png_string = sess.run(encoded_png, feed_dict={image: images[j]}) example = image_to_tfexample(png_string, 'png'.encode(), _IMAGE_SIZE, _IMAGE_SIZE, labels[j]) tfrecord_writer.write(example.SerializeToString()) def _get_image_data(path_filename, filenames, num_data_per_tfrecord): data = empty([num_data_per_tfrecord, _IMAGE_SIZE, _IMAGE_SIZE, _NUM_CHANNELS]) i = 0 for picture in filenames: with Image.open("%s/%s"%(path_filename[i], picture)) as im: pix = array(im)[:,:,:3] data[i] = pix i += 1 return data def run(destination_directory, spectro_path, num_data_per_tfrecord_train, num_data_per_tfrecord_val): num_data = 0 file_names = [] path_to_file_names = [] labels = [] class_names = {} for root, dirs, files in walk(spectro_path): root = root.replace("\\","/") print(root) if len(dirs) > 0: nr_of_classes = 0 for name_class in dirs: class_names[name_class] = nr_of_classes nr_of_classes += 1 else: class_id = -1 for key in class_names: if key in root: class_id = class_names[key] for spectro_file in files: num_data += 1 file_names.append(spectro_file) labels.append(class_id) path_to_file_names.append(root) print(num_data) nr_train_tfrecord = int(num_data / (num_data_per_tfrecord_train + num_data_per_tfrecord_val)) nr_of_tfrecord = nr_train_tfrecord * 2 file_names, labels, path_to_file_names = _shuffle_all(file_names, labels, path_to_file_names) tfrecord_name = _create_all_tf_record_name(destination_directory, num_data, nr_train_tfrecord) end_ind = 0 for i in arange(nr_of_tfrecord): tfrecords_filename = tfrecord_name[i] if "train" in tfrecords_filename: num_data_per_tfrecord = num_data_per_tfrecord_train else: num_data_per_tfrecord = num_data_per_tfrecord_val start_ind = end_ind end_ind = start_ind + num_data_per_tfrecord data = _get_image_data(path_to_file_names[start_ind:end_ind], file_names[start_ind:end_ind], num_data_per_tfrecord) label = labels[start_ind:end_ind] print("%d'th tfrecord %s: pictures %d to %d" % (i, tfrecords_filename, start_ind, end_ind)) writer = tf.python_io.TFRecordWriter(tfrecords_filename) _add_to_tfrecord(data, label, num_data_per_tfrecord, writer) with open('%s/labels.txt'%(destination_directory), 'w+') as fp: dump(class_names, fp)
4,054
0
115
9c7100ba70e063698a89485b827c82e2a9d0ab07
1,710
py
Python
notas_de_clase/img/metodos/esquema_newton.py
AppliedMechanics-EAFIT/Mod_Temporal
6a0506d906ed42b143b773777e8dc0da5af763eb
[ "MIT" ]
5
2019-02-20T18:14:01.000Z
2020-07-19T22:44:44.000Z
notas_de_clase/img/metodos/esquema_newton.py
AppliedMechanics-EAFIT/Mod_Temporal
6a0506d906ed42b143b773777e8dc0da5af763eb
[ "MIT" ]
3
2020-04-15T00:22:58.000Z
2020-07-04T17:03:54.000Z
notas_de_clase/img/metodos/esquema_newton.py
AppliedMechanics-EAFIT/Mod_Temporal
6a0506d906ed42b143b773777e8dc0da5af763eb
[ "MIT" ]
3
2020-05-14T18:17:09.000Z
2020-10-27T06:37:05.000Z
# -*- coding: utf-8 -*- """ Ilustra el método de Newton-Raphson @author: Nicolas Guarin-Zapata """ from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt plt.rcParams["mathtext.fontset"] = "cm" plt.rcParams["axes.spines.top"] = False plt.rcParams["axes.spines.right"] = False fun = lambda x: 0.3*np.abs(x)*x grad = lambda x: 0.6*np.abs(x) x = np.linspace(-2, 4, 100) y = fun(x) #%% Graficacion plt.figure(figsize=(4, 3)) ax = plt.gca() ax.plot(x, y, linewidth=2) x0 = 4 x_iter = [x0] ax.plot([x0, x0], [fun(x0), 0], color="#3f3f3f", linewidth=1.5, linestyle="dashed") ax.plot([x0], [fun(x0)], marker="o", mec="black", mfc="white", linewidth=0, zorder=5) for cont in range(3): x1 = x0 - fun(x0)/grad(x0) x_iter.append(x1) ax.plot([x0, x1], [fun(x0), 0], color="#3f3f3f", linewidth=1.5, linestyle="dashed", zorder=4) ax.plot([x1, x1], [fun(x1), 0], color="#3f3f3f", linewidth=1.5, linestyle="dashed", zorder=4) ax.plot([x1], [fun(x1)], marker="o", mec="black", mfc="white", linewidth=0, zorder=5) x0 = x1 ax.plot([0], [0], marker="o", mec="black", mfc="black", linewidth=0) plt.xticks(x_iter + [0], [r"$x_{}$".format(k) for k in range(4)] + [r"$x^*$"]) plt.yticks([]) plt.xlabel(r"$x$", horizontalalignment="right", fontsize=12) plt.ylabel(r"$f(x)$", fontsize=12) ax.spines['bottom'].set_position(('data',0)) ax.xaxis.set_label_coords(1.05, 0.25) ax.yaxis.set_label_coords(-0.05, 0.9) plt.savefig("newton_iter.pdf", bbox_inches="tight") plt.savefig("newton_iter.svg", bbox_inches="tight", transparent=True) plt.show()
30
79
0.605848
# -*- coding: utf-8 -*- """ Ilustra el método de Newton-Raphson @author: Nicolas Guarin-Zapata """ from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt plt.rcParams["mathtext.fontset"] = "cm" plt.rcParams["axes.spines.top"] = False plt.rcParams["axes.spines.right"] = False fun = lambda x: 0.3*np.abs(x)*x grad = lambda x: 0.6*np.abs(x) x = np.linspace(-2, 4, 100) y = fun(x) #%% Graficacion plt.figure(figsize=(4, 3)) ax = plt.gca() ax.plot(x, y, linewidth=2) x0 = 4 x_iter = [x0] ax.plot([x0, x0], [fun(x0), 0], color="#3f3f3f", linewidth=1.5, linestyle="dashed") ax.plot([x0], [fun(x0)], marker="o", mec="black", mfc="white", linewidth=0, zorder=5) for cont in range(3): x1 = x0 - fun(x0)/grad(x0) x_iter.append(x1) ax.plot([x0, x1], [fun(x0), 0], color="#3f3f3f", linewidth=1.5, linestyle="dashed", zorder=4) ax.plot([x1, x1], [fun(x1), 0], color="#3f3f3f", linewidth=1.5, linestyle="dashed", zorder=4) ax.plot([x1], [fun(x1)], marker="o", mec="black", mfc="white", linewidth=0, zorder=5) x0 = x1 ax.plot([0], [0], marker="o", mec="black", mfc="black", linewidth=0) plt.xticks(x_iter + [0], [r"$x_{}$".format(k) for k in range(4)] + [r"$x^*$"]) plt.yticks([]) plt.xlabel(r"$x$", horizontalalignment="right", fontsize=12) plt.ylabel(r"$f(x)$", fontsize=12) ax.spines['bottom'].set_position(('data',0)) ax.xaxis.set_label_coords(1.05, 0.25) ax.yaxis.set_label_coords(-0.05, 0.9) plt.savefig("newton_iter.pdf", bbox_inches="tight") plt.savefig("newton_iter.svg", bbox_inches="tight", transparent=True) plt.show()
0
0
0
d65c64f8dfacbef7a7b78ee233ba2f34a6a4c059
2,192
py
Python
test/core/tests/card_extension_test.py
jinnovation/metaflow
540f21133b08108f7129ce42b1c6a24fd9175b2f
[ "Apache-2.0" ]
null
null
null
test/core/tests/card_extension_test.py
jinnovation/metaflow
540f21133b08108f7129ce42b1c6a24fd9175b2f
[ "Apache-2.0" ]
null
null
null
test/core/tests/card_extension_test.py
jinnovation/metaflow
540f21133b08108f7129ce42b1c6a24fd9175b2f
[ "Apache-2.0" ]
null
null
null
from metaflow_test import MetaflowTest, ExpectationFailed, steps, tag class CardExtensionsImportTest(MetaflowTest): """ - Requires on tests/extensions/packages to be installed. """ PRIORITY = 5 @tag('card(type="card_ext_init_b",save_errors=False)') @tag('card(type="card_ext_init_a",save_errors=False)') @tag('card(type="card_ns_subpackage",save_errors=False)') @tag('card(type="card_init",save_errors=False)') @steps(0, ["start"]) @steps(1, ["all"])
37.152542
74
0.522354
from metaflow_test import MetaflowTest, ExpectationFailed, steps, tag class CardExtensionsImportTest(MetaflowTest): """ - Requires on tests/extensions/packages to be installed. """ PRIORITY = 5 @tag('card(type="card_ext_init_b",save_errors=False)') @tag('card(type="card_ext_init_a",save_errors=False)') @tag('card(type="card_ns_subpackage",save_errors=False)') @tag('card(type="card_init",save_errors=False)') @steps(0, ["start"]) def step_start(self): from metaflow import current self.task = current.pathspec @steps(1, ["all"]) def step_all(self): pass def check_results(self, flow, checker): run = checker.get_run() if run is None: # This means CliCheck is in context. for step in flow: if step.name != "start": continue cli_check_dict = checker.artifact_dict(step.name, "task") for task_pathspec in cli_check_dict: full_pathspec = "/".join([flow.name, task_pathspec]) task_id = task_pathspec.split("/")[-1] cards_info = checker.list_cards(step.name, task_id) # Just check if the cards are created. assert_equals( cards_info is not None and "cards" in cards_info and len(cards_info["cards"]) == 4, True, ) else: # This means MetadataCheck is in context. for step in flow: if step.name != "start": continue meta_check_dict = checker.artifact_dict(step.name, "task") for task_id in meta_check_dict: full_pathspec = meta_check_dict[task_id]["task"] cards_info = checker.list_cards(step.name, task_id) assert_equals( cards_info is not None and "cards" in cards_info and len(cards_info["cards"]) == 4, True, )
1,617
0
79
adf5e0106200486694e07b437ba6cce25229450b
580
py
Python
DisguiseGenerator/yapfLib/main.py
oscarkarnalim/csd
cd62ce5e8a2d86ce5a5f73838738d90b68c98439
[ "Apache-2.0" ]
2
2020-11-19T22:31:57.000Z
2020-11-20T02:30:14.000Z
STRANGETool/yapfLib/main.py
ShivaShirsath/strange
8ea04100c79c77654c37394dea349dd60aac92d9
[ "Apache-2.0" ]
2
2022-01-01T19:50:55.000Z
2022-01-04T10:51:36.000Z
STRANGETool/yapfLib/main.py
ShivaShirsath/strange
8ea04100c79c77654c37394dea349dd60aac92d9
[ "Apache-2.0" ]
2
2021-10-19T12:27:48.000Z
2022-01-04T09:20:19.000Z
from yapf.yapflib.yapf_api import FormatFile import sys # using yapf library taken from https://github.com/google/yapf/ # version v0.28.0 # take the source path sourcePath = sys.argv[1] # take the first argument as the filepath # then update the targeted code with their format corrected. # this function returns an array consisting the formatted code, type, and a boolean. # that boolean is assigned to true if the function works. result = FormatFile(sourcePath, in_place=True, style_config=sys.argv[2]) # this program will display error output once the code is not parseable.
38.666667
84
0.782759
from yapf.yapflib.yapf_api import FormatFile import sys # using yapf library taken from https://github.com/google/yapf/ # version v0.28.0 # take the source path sourcePath = sys.argv[1] # take the first argument as the filepath # then update the targeted code with their format corrected. # this function returns an array consisting the formatted code, type, and a boolean. # that boolean is assigned to true if the function works. result = FormatFile(sourcePath, in_place=True, style_config=sys.argv[2]) # this program will display error output once the code is not parseable.
0
0
0
0a3e1af84ab44a2a22acee03efc442791eaa6c38
9,044
py
Python
src/opendr/perception/activity_recognition/cox3d/algorithm/pooling.py
makistsantekidis/opendr
07dee3b59d3487b9c5a93d6946317178a02c9890
[ "Apache-2.0" ]
217
2020-04-10T16:39:36.000Z
2022-03-30T15:39:04.000Z
src/opendr/perception/activity_recognition/cox3d/algorithm/pooling.py
makistsantekidis/opendr
07dee3b59d3487b9c5a93d6946317178a02c9890
[ "Apache-2.0" ]
79
2021-06-23T10:40:10.000Z
2021-12-16T07:59:42.000Z
src/opendr/perception/activity_recognition/cox3d/algorithm/pooling.py
makistsantekidis/opendr
07dee3b59d3487b9c5a93d6946317178a02c9890
[ "Apache-2.0" ]
29
2021-12-16T09:26:13.000Z
2022-03-29T15:19:18.000Z
""" Copyright (c) Lukas Hedegaard. All Rights Reserved. Included in the OpenDR Toolit with permission from the author. """ from typing import Tuple, Union import torch from torch import Tensor from torch.nn.modules.pooling import ( AdaptiveAvgPool1d, AdaptiveAvgPool2d, AdaptiveAvgPool3d, AdaptiveMaxPool1d, AdaptiveMaxPool2d, AdaptiveMaxPool3d, AvgPool2d, AvgPool3d, MaxPool2d, MaxPool3d, _triple, ) from logging import getLogger from .utils import FillMode State = Tuple[Tensor, int] Pool2D = Union[AvgPool2d, MaxPool2d, AdaptiveAvgPool2d, AdaptiveMaxPool2d] logger = getLogger(__name__) __all__ = [ "AvgPoolCo3d", "MaxPoolCo3d", "AdaptiveAvgPoolCo3d", "AdaptiveMaxPoolCo3d", "convert_avgpool3d", "convert_maxpool3d", "convert_adaptiveavgpool3d", "convert_adaptivemaxpool3d", ] def RecursivelyWindowPooled(cls: Pool2D) -> torch.nn.Module: # noqa: C901 """Wraps a pooling module to create a recursive version which pools across execusions Args: cls (Pool2D): A 2D pooling Module """ assert cls in {AdaptiveAvgPool2d, MaxPool2d, AvgPool2d, AdaptiveMaxPool2d} RePooled.__doc__ = f""" Recursive {cls.__name__} Pooling results are stored between `forward` exercutions and used to pool subsequent inputs along the temporal dimension with a spacified `window_size`. Example: For `window_size = 3`, the two previous results are stored and used for pooling. `temporal_fill` determines whether to initialize the state with a ``'replicate'`` of the output of the first execution or with with ``'zeros'``. Parent doc: {cls.__doc__} """ return RePooled AvgPoolCo3d = RecursivelyWindowPooled(AvgPool2d) MaxPoolCo3d = RecursivelyWindowPooled(MaxPool2d) AdaptiveAvgPoolCo3d = RecursivelyWindowPooled(AdaptiveAvgPool2d) AdaptiveMaxPoolCo3d = RecursivelyWindowPooled(AdaptiveMaxPool2d)
32.532374
109
0.613777
""" Copyright (c) Lukas Hedegaard. All Rights Reserved. Included in the OpenDR Toolit with permission from the author. """ from typing import Tuple, Union import torch from torch import Tensor from torch.nn.modules.pooling import ( AdaptiveAvgPool1d, AdaptiveAvgPool2d, AdaptiveAvgPool3d, AdaptiveMaxPool1d, AdaptiveMaxPool2d, AdaptiveMaxPool3d, AvgPool2d, AvgPool3d, MaxPool2d, MaxPool3d, _triple, ) from logging import getLogger from .utils import FillMode State = Tuple[Tensor, int] Pool2D = Union[AvgPool2d, MaxPool2d, AdaptiveAvgPool2d, AdaptiveMaxPool2d] logger = getLogger(__name__) __all__ = [ "AvgPoolCo3d", "MaxPoolCo3d", "AdaptiveAvgPoolCo3d", "AdaptiveMaxPoolCo3d", "convert_avgpool3d", "convert_maxpool3d", "convert_adaptiveavgpool3d", "convert_adaptivemaxpool3d", ] def RecursivelyWindowPooled(cls: Pool2D) -> torch.nn.Module: # noqa: C901 """Wraps a pooling module to create a recursive version which pools across execusions Args: cls (Pool2D): A 2D pooling Module """ assert cls in {AdaptiveAvgPool2d, MaxPool2d, AvgPool2d, AdaptiveMaxPool2d} class RePooled(cls): def __init__( self, window_size: int, temporal_fill: FillMode = "replicate", temporal_dilation: int = 1, *args, **kwargs, ): assert window_size > 0 assert temporal_fill in {"zeros", "replicate"} self.window_size = window_size self.temporal_dilation = temporal_dilation self.make_padding = {"zeros": torch.zeros_like, "replicate": torch.clone}[ temporal_fill ] super(RePooled, self).__init__(*args, **kwargs) self.temporal_pool = ( AdaptiveAvgPool1d if "avg" in str(cls.__name__).lower() else AdaptiveMaxPool1d )(1) if self.temporal_dilation > 1: self.frame_index_selection = torch.tensor( range(0, self.window_size, self.temporal_dilation) ) # state is initialised in self.forward def init_state(self, first_output: Tensor,) -> State: padding = self.make_padding(first_output) state_buffer = torch.stack( [padding for _ in range(self.window_size)], dim=0 ) state_index = 0 if not hasattr(self, "state_buffer"): self.register_buffer("state_buffer", state_buffer, persistent=False) return state_buffer, state_index def clean_state(self): self.state_buffer = None self.state_index = None def get_state(self): if ( hasattr(self, "state_buffer") and self.state_buffer is not None and hasattr(self, "state_index") and self.state_buffer is not None ): return (self.state_buffer, self.state_index) else: return None def forward(self, input: Tensor) -> Tensor: output, (self.state_buffer, self.state_index) = self._forward( input, self.get_state() ) return output def _forward(self, input: Tensor, prev_state: State,) -> Tuple[Tensor, State]: assert ( len(input.shape) == 4 ), "Only a single frame should be passed at a time." pooled_frame = super(RePooled, self).forward(input) if prev_state is None: buffer, index = self.init_state(pooled_frame) else: buffer, index = prev_state buffer[index] = pooled_frame if self.temporal_dilation == 1: frame_selection = buffer else: frame_selection = buffer.index_select( dim=0, index=self.frame_index_selection ) # Pool along temporal dimension T, B, C, H, W = frame_selection.shape x = frame_selection.permute(1, 3, 4, 2, 0) # B, H, W, C, T x = x.reshape(B * H * W, C, T) x = self.temporal_pool(x) x = x.reshape(B, H, W, C) x = x.permute(0, 3, 1, 2) # B, C, H, W pooled_window = x new_index = (index + 1) % self.window_size new_buffer = buffer.clone() if self.training else buffer.detach() return pooled_window, (new_buffer, new_index) def forward3d(self, input: Tensor): """ If input.shape[2] == self.window_size, a global pooling along temporal dimension is performed Otherwise, the pooling is performed per frame """ assert ( len(input.shape) == 5 ), "A tensor of size B,C,T,H,W should be passed as input." outs = [] for t in range(input.shape[2]): o = self.forward(input[:, :, t]) if self.window_size - 1 <= t: outs.append(o) if len(outs) == 0: return torch.tensor([]) if input.shape[2] == self.window_size: # In order to be compatible with downstream forward3d, select only last frame # This corrsponds to the regular global pool return outs[-1].unsqueeze(2) else: return torch.stack(outs, dim=2) RePooled.__doc__ = f""" Recursive {cls.__name__} Pooling results are stored between `forward` exercutions and used to pool subsequent inputs along the temporal dimension with a spacified `window_size`. Example: For `window_size = 3`, the two previous results are stored and used for pooling. `temporal_fill` determines whether to initialize the state with a ``'replicate'`` of the output of the first execution or with with ``'zeros'``. Parent doc: {cls.__doc__} """ return RePooled AvgPoolCo3d = RecursivelyWindowPooled(AvgPool2d) MaxPoolCo3d = RecursivelyWindowPooled(MaxPool2d) AdaptiveAvgPoolCo3d = RecursivelyWindowPooled(AdaptiveAvgPool2d) AdaptiveMaxPoolCo3d = RecursivelyWindowPooled(AdaptiveMaxPool2d) def convert_avgpool3d( instance: AvgPool3d, window_size: int = None, # Not used: only there to satisfy interface temporal_fill: FillMode = "replicate", ): kernel_size = _triple(instance.kernel_size) padding = _triple(instance.padding) stride = _triple(instance.stride) assert padding[0] == 0, "Cannot convert AvgPool3d with padding[0] != 0" assert stride[0] == 1, "Cannot convert AvgPool3d with stride[0] != 1" return AvgPoolCo3d( window_size=kernel_size[0], temporal_fill=temporal_fill, kernel_size=kernel_size[1:], stride=stride[1:], padding=padding[1:], ceil_mode=instance.ceil_mode, count_include_pad=instance.count_include_pad, divisor_override=instance.divisor_override, ) def convert_maxpool3d( instance: MaxPool3d, window_size: int = None, # Not used: only there to satisfy interface temporal_fill: FillMode = "replicate", ): kernel_size = _triple(instance.kernel_size) padding = _triple(instance.padding) stride = _triple(instance.stride) dilation = _triple(instance.dilation) assert padding[0] == 0, "Cannot convert MaxPool3d with padding[0] != 0" assert stride[0] == 1, "Cannot convert MaxPool3d with stride[0] != 1" assert dilation[0] == 1, "Cannot convert MaxPool3d with dilation[0] != 1" assert ( instance.return_indices is False ), "return_indices currently not supported for MaxPool3d" return MaxPoolCo3d( window_size=kernel_size[0], temporal_fill=temporal_fill, kernel_size=kernel_size[1:], stride=stride[1:], padding=padding[1:], dilation=dilation[1:], return_indices=instance.return_indices, ceil_mode=instance.ceil_mode, ) def convert_adaptiveavgpool3d( instance: AdaptiveAvgPool3d, window_size: int, temporal_fill: FillMode = "replicate", ): assert ( instance.output_size[0] == 1 ), "Cannot convert AdaptiveAvgPool3d without output_size[0] != 1" return AdaptiveAvgPoolCo3d( window_size=window_size, temporal_fill=temporal_fill, output_size=instance.output_size[1:], ) def convert_adaptivemaxpool3d( instance: AdaptiveMaxPool3d, window_size: int, temporal_fill: FillMode = "replicate", ): assert ( instance.output_size[0] == 1 ), "Cannot convert AdaptiveMaxPool3d without output_size[0] != 1" assert ( instance.return_indices is False ), "return_indices currently not supported for AdaptiveMaxPool3d" return AdaptiveAvgPoolCo3d( window_size=window_size, temporal_fill=temporal_fill, output_size=instance.output_size, )
5,854
1,135
119
23ceb4be40ab14b96763eb535badca57463b0253
8,099
py
Python
summarise_results.py
MDBAuth/EWR_tool
5b05cf276822d97a38a32a5fc031209224a04fb3
[ "CC0-1.0" ]
5
2021-03-17T00:33:53.000Z
2022-03-07T18:16:25.000Z
summarise_results.py
MDBAuth/EWR_tool
5b05cf276822d97a38a32a5fc031209224a04fb3
[ "CC0-1.0" ]
null
null
null
summarise_results.py
MDBAuth/EWR_tool
5b05cf276822d97a38a32a5fc031209224a04fb3
[ "CC0-1.0" ]
2
2022-01-14T03:50:10.000Z
2022-02-14T00:45:56.000Z
import pandas as pd import numpy as np import data_inputs, evaluate_EWRs #-------------------------------------------------------------------------------------------------- def sum_events(events): '''returns a sum of events''' return int(round(events.sum(), 0)) def get_frequency(events): '''Returns the frequency of years they occur in''' if events.count() == 0: result = 0 else: result = (int(events.sum())/int(events.count()))*100 return int(round(result, 0)) def get_average(input_events): '''Returns overall average length of events''' events = input_events.dropna() if len(events) == 0: result = 0 else: result = round(sum(events)/len(events),1) return result def initialise_summary_df_columns(input_dict): '''Ingest a dictionary of ewr yearly results and a list of statistical tests to perform initialises a dataframe with these as a multilevel heading and returns this''' analysis = data_inputs.analysis() column_list = [] list_of_arrays = [] for scenario, scenario_results in input_dict.items(): for sub_col in analysis: column_list = tuple((scenario, sub_col)) list_of_arrays.append(column_list) array_of_arrays =tuple(list_of_arrays) multi_col_df = pd.MultiIndex.from_tuples(array_of_arrays, names = ['scenario', 'type']) return multi_col_df def initialise_summary_df_rows(input_dict): '''Ingests a dictionary of ewr yearly results pulls the location information and the assocaited ewrs at each location, saves these as respective indexes and return the multi-level index''' index_1 = list() index_2 = list() index_3 = list() combined_index = list() # Get unique col list: for scenario, scenario_results in input_dict.items(): for site, site_results in scenario_results.items(): for PU in site_results: site_list = [] for col in site_results[PU]: if '_' in col: all_parts = col.split('_') remove_end = all_parts[:-1] if len(remove_end) > 1: EWR_code = '_'.join(remove_end) else: EWR_code = remove_end[0] else: EWR_code = col if EWR_code in site_list: continue else: site_list.append(EWR_code) add_index = tuple((site, PU, EWR_code)) if add_index not in combined_index: combined_index.append(add_index) unique_index = tuple(combined_index) multi_index = pd.MultiIndex.from_tuples(unique_index, names = ['gauge', 'planning unit', 'EWR']) return multi_index def allocate(df, add_this, idx, site, PU, EWR, scenario, category): '''Save element to a location in the dataframe''' df.loc[idx[[site], [PU], [EWR]], idx[scenario, category]] = add_this return df def summarise(input_dict): '''Ingests a dictionary with ewr pass/fails summarises these results and returns a single summary dataframe''' PU_items = data_inputs.get_planning_unit_info() EWR_table, see_notes_ewrs, undefined_ewrs, noThresh_df, no_duration, DSF_ewrs = data_inputs.get_EWR_table() # Initialise dataframe with multi level column heading and multi-index: multi_col_df = initialise_summary_df_columns(input_dict) index = initialise_summary_df_rows(input_dict) df = pd.DataFrame(index = index, columns=multi_col_df) # Run the analysis and add the results to the dataframe created above: for scenario, scenario_results in input_dict.items(): for site, site_results in scenario_results.items(): for PU in site_results: for col in site_results[PU]: all_parts = col.split('_') remove_end = all_parts[:-1] if len(remove_end) > 1: EWR = '_'.join(remove_end) else: EWR = remove_end[0] idx = pd.IndexSlice if ('_eventYears' in col): S = sum_events(site_results[PU][col]) df = allocate(df, S, idx, site, PU, EWR, scenario, 'Event years') F = get_frequency(site_results[PU][col]) df = allocate(df, F, idx, site, PU, EWR, scenario, 'Frequency') PU_num = PU_items['PlanningUnitID'].loc[PU_items[PU_items['PlanningUnitName'] == PU].index[0]] EWR_info = evaluate_EWRs.get_EWRs(PU_num, site, EWR, EWR_table, None, ['TF']) TF = EWR_info['frequency'] df = allocate(df, TF, idx, site, PU, EWR, scenario, 'Target frequency') elif ('_numAchieved' in col): S = sum_events(site_results[PU][col]) df = allocate(df, S, idx, site, PU, EWR, scenario, 'Achievement count') ME = get_average(site_results[PU][col]) df = allocate(df, ME, idx, site, PU, EWR, scenario, 'Achievements per year') elif ('_numEvents' in col): S = sum_events(site_results[PU][col]) df = allocate(df, S, idx, site, PU, EWR, scenario, 'Event count') ME = get_average(site_results[PU][col]) df = allocate(df, ME, idx, site, PU, EWR, scenario, 'Events per year') elif ('_eventLength' in col): EL = get_event_length(site_results[PU][col], S) df = allocate(df, EL, idx, site, PU, EWR, scenario, 'Event length') elif ('_totalEventDays' in col): AD = get_average(site_results[PU][col]) df = allocate(df, AD, idx, site, PU, EWR, scenario, 'Threshold days') elif ('daysBetweenEvents' in col): PU_num = PU_items['PlanningUnitID'].loc[PU_items[PU_items['PlanningUnitName'] == PU].index[0]] EWR_info = evaluate_EWRs.get_EWRs(PU_num, site, EWR, EWR_table, None, ['MIE']) DB = count_exceedence(site_results[PU][col], EWR_info) df = allocate(df, DB, idx, site, PU, EWR, scenario, 'Inter-event exceedence count') # Also save the max inter-event period to the data summary for reference EWR_info = evaluate_EWRs.get_EWRs(PU_num, site, EWR, EWR_table, None, ['MIE']) MIE = EWR_info['max_inter-event'] df = allocate(df, MIE, idx, site, PU, EWR, scenario, 'Max inter event period (years)') elif ('_missingDays' in col): MD = sum_events(site_results[PU][col]) df = allocate(df, MD, idx, site, PU, EWR, scenario, 'No data days') elif ('_totalPossibleDays' in col): TD = sum_events(site_results[PU][col]) df = allocate(df, TD, idx, site, PU, EWR, scenario, 'Total days') return df
47.087209
118
0.548463
import pandas as pd import numpy as np import data_inputs, evaluate_EWRs #-------------------------------------------------------------------------------------------------- def sum_events(events): '''returns a sum of events''' return int(round(events.sum(), 0)) def get_frequency(events): '''Returns the frequency of years they occur in''' if events.count() == 0: result = 0 else: result = (int(events.sum())/int(events.count()))*100 return int(round(result, 0)) def get_average(input_events): '''Returns overall average length of events''' events = input_events.dropna() if len(events) == 0: result = 0 else: result = round(sum(events)/len(events),1) return result def get_event_length(input_events, num_events): events = input_events.dropna() if num_events == 0: EL = 0 else: EL = round(sum(events)/num_events,1) return EL def count_exceedence(input_events, EWR_info): events = input_events.copy(deep=True) if EWR_info['max_inter-event'] == None: return 'N/A' else: masking = events.isna() events[masking] = '' total = 0 for year in events.index: if list(events[year]) != '': count = len(events[year]) total = total + count return int(total) def initialise_summary_df_columns(input_dict): '''Ingest a dictionary of ewr yearly results and a list of statistical tests to perform initialises a dataframe with these as a multilevel heading and returns this''' analysis = data_inputs.analysis() column_list = [] list_of_arrays = [] for scenario, scenario_results in input_dict.items(): for sub_col in analysis: column_list = tuple((scenario, sub_col)) list_of_arrays.append(column_list) array_of_arrays =tuple(list_of_arrays) multi_col_df = pd.MultiIndex.from_tuples(array_of_arrays, names = ['scenario', 'type']) return multi_col_df def initialise_summary_df_rows(input_dict): '''Ingests a dictionary of ewr yearly results pulls the location information and the assocaited ewrs at each location, saves these as respective indexes and return the multi-level index''' index_1 = list() index_2 = list() index_3 = list() combined_index = list() # Get unique col list: for scenario, scenario_results in input_dict.items(): for site, site_results in scenario_results.items(): for PU in site_results: site_list = [] for col in site_results[PU]: if '_' in col: all_parts = col.split('_') remove_end = all_parts[:-1] if len(remove_end) > 1: EWR_code = '_'.join(remove_end) else: EWR_code = remove_end[0] else: EWR_code = col if EWR_code in site_list: continue else: site_list.append(EWR_code) add_index = tuple((site, PU, EWR_code)) if add_index not in combined_index: combined_index.append(add_index) unique_index = tuple(combined_index) multi_index = pd.MultiIndex.from_tuples(unique_index, names = ['gauge', 'planning unit', 'EWR']) return multi_index def allocate(df, add_this, idx, site, PU, EWR, scenario, category): '''Save element to a location in the dataframe''' df.loc[idx[[site], [PU], [EWR]], idx[scenario, category]] = add_this return df def summarise(input_dict): '''Ingests a dictionary with ewr pass/fails summarises these results and returns a single summary dataframe''' PU_items = data_inputs.get_planning_unit_info() EWR_table, see_notes_ewrs, undefined_ewrs, noThresh_df, no_duration, DSF_ewrs = data_inputs.get_EWR_table() # Initialise dataframe with multi level column heading and multi-index: multi_col_df = initialise_summary_df_columns(input_dict) index = initialise_summary_df_rows(input_dict) df = pd.DataFrame(index = index, columns=multi_col_df) # Run the analysis and add the results to the dataframe created above: for scenario, scenario_results in input_dict.items(): for site, site_results in scenario_results.items(): for PU in site_results: for col in site_results[PU]: all_parts = col.split('_') remove_end = all_parts[:-1] if len(remove_end) > 1: EWR = '_'.join(remove_end) else: EWR = remove_end[0] idx = pd.IndexSlice if ('_eventYears' in col): S = sum_events(site_results[PU][col]) df = allocate(df, S, idx, site, PU, EWR, scenario, 'Event years') F = get_frequency(site_results[PU][col]) df = allocate(df, F, idx, site, PU, EWR, scenario, 'Frequency') PU_num = PU_items['PlanningUnitID'].loc[PU_items[PU_items['PlanningUnitName'] == PU].index[0]] EWR_info = evaluate_EWRs.get_EWRs(PU_num, site, EWR, EWR_table, None, ['TF']) TF = EWR_info['frequency'] df = allocate(df, TF, idx, site, PU, EWR, scenario, 'Target frequency') elif ('_numAchieved' in col): S = sum_events(site_results[PU][col]) df = allocate(df, S, idx, site, PU, EWR, scenario, 'Achievement count') ME = get_average(site_results[PU][col]) df = allocate(df, ME, idx, site, PU, EWR, scenario, 'Achievements per year') elif ('_numEvents' in col): S = sum_events(site_results[PU][col]) df = allocate(df, S, idx, site, PU, EWR, scenario, 'Event count') ME = get_average(site_results[PU][col]) df = allocate(df, ME, idx, site, PU, EWR, scenario, 'Events per year') elif ('_eventLength' in col): EL = get_event_length(site_results[PU][col], S) df = allocate(df, EL, idx, site, PU, EWR, scenario, 'Event length') elif ('_totalEventDays' in col): AD = get_average(site_results[PU][col]) df = allocate(df, AD, idx, site, PU, EWR, scenario, 'Threshold days') elif ('daysBetweenEvents' in col): PU_num = PU_items['PlanningUnitID'].loc[PU_items[PU_items['PlanningUnitName'] == PU].index[0]] EWR_info = evaluate_EWRs.get_EWRs(PU_num, site, EWR, EWR_table, None, ['MIE']) DB = count_exceedence(site_results[PU][col], EWR_info) df = allocate(df, DB, idx, site, PU, EWR, scenario, 'Inter-event exceedence count') # Also save the max inter-event period to the data summary for reference EWR_info = evaluate_EWRs.get_EWRs(PU_num, site, EWR, EWR_table, None, ['MIE']) MIE = EWR_info['max_inter-event'] df = allocate(df, MIE, idx, site, PU, EWR, scenario, 'Max inter event period (years)') elif ('_missingDays' in col): MD = sum_events(site_results[PU][col]) df = allocate(df, MD, idx, site, PU, EWR, scenario, 'No data days') elif ('_totalPossibleDays' in col): TD = sum_events(site_results[PU][col]) df = allocate(df, TD, idx, site, PU, EWR, scenario, 'Total days') return df
570
0
46
f247545caa576995f4dbbcab2062f6ee8bbeab4d
849
py
Python
ex070.py
felipesch92/PythonExercicios
73edcbde6beaabcfc86af3dd6e58473f1eecabd3
[ "MIT" ]
null
null
null
ex070.py
felipesch92/PythonExercicios
73edcbde6beaabcfc86af3dd6e58473f1eecabd3
[ "MIT" ]
null
null
null
ex070.py
felipesch92/PythonExercicios
73edcbde6beaabcfc86af3dd6e58473f1eecabd3
[ "MIT" ]
null
null
null
# Crie um programa que leia o nome e o preço de vários produtos. # O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre: # A) qual é o total gasto na compra. # B) quantos produtos custam mais de R$1000. # C) qual é o nome do produto mais barato. n = '' p = 0 t = 0 c = 0 b_p = 0 # preço produto mais barato b_n = '' # nome produto mais barato while True: n = input('Nome do produto: ') p = float(input('Valor: ')) if t == 0 or p < b_p: b_n = n b_p = p if p > 1000: c += 1 t += p flag = ' ' while flag not in 'SN': flag = input('Deseja continuar? [S/N] ').upper()[0] if flag == 'N': break print(f'Total gasto na compra: R$ {t:.2f}') print(f'{c} produtos custaram mais que R$ 1000,00') print(f'{b_n} foi o produto mais barato custando R$ {b_p:.2f}')
29.275862
82
0.59364
# Crie um programa que leia o nome e o preço de vários produtos. # O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre: # A) qual é o total gasto na compra. # B) quantos produtos custam mais de R$1000. # C) qual é o nome do produto mais barato. n = '' p = 0 t = 0 c = 0 b_p = 0 # preço produto mais barato b_n = '' # nome produto mais barato while True: n = input('Nome do produto: ') p = float(input('Valor: ')) if t == 0 or p < b_p: b_n = n b_p = p if p > 1000: c += 1 t += p flag = ' ' while flag not in 'SN': flag = input('Deseja continuar? [S/N] ').upper()[0] if flag == 'N': break print(f'Total gasto na compra: R$ {t:.2f}') print(f'{c} produtos custaram mais que R$ 1000,00') print(f'{b_n} foi o produto mais barato custando R$ {b_p:.2f}')
0
0
0
302b08f7c01bb97345c6e836aa5a2613fe0bec05
1,123
py
Python
libs/sdc_etl_libs/database_helpers/DatabaseFactory.py
darknegma/docker-airflow
44e3d02d7ac43c8876145ae47acfbbbde67230df
[ "Apache-2.0" ]
null
null
null
libs/sdc_etl_libs/database_helpers/DatabaseFactory.py
darknegma/docker-airflow
44e3d02d7ac43c8876145ae47acfbbbde67230df
[ "Apache-2.0" ]
3
2021-03-31T19:26:57.000Z
2021-12-13T20:33:01.000Z
libs/sdc_etl_libs/database_helpers/DatabaseFactory.py
darknegma/docker-airflow
44e3d02d7ac43c8876145ae47acfbbbde67230df
[ "Apache-2.0" ]
null
null
null
import os import sys import logging sys.path.append(os.path.dirname(os.path.realpath(__file__))) from sdc_etl_libs.database_helpers.SnowflakeDatabase import SnowflakeDatabase from sdc_etl_libs.database_helpers.NexusDatabase import NexusDatabase from sdc_etl_libs.database_helpers.MySqlDatabase import MySqlDatabase from sdc_etl_libs.database_helpers.PostgresSqlDatabase import PostgresSqlDatabase logging.basicConfig( format='%(levelname)s: %(asctime)s: ' '%(funcName)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO)
35.09375
81
0.722173
import os import sys import logging sys.path.append(os.path.dirname(os.path.realpath(__file__))) from sdc_etl_libs.database_helpers.SnowflakeDatabase import SnowflakeDatabase from sdc_etl_libs.database_helpers.NexusDatabase import NexusDatabase from sdc_etl_libs.database_helpers.MySqlDatabase import MySqlDatabase from sdc_etl_libs.database_helpers.PostgresSqlDatabase import PostgresSqlDatabase logging.basicConfig( format='%(levelname)s: %(asctime)s: ' '%(funcName)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class DatabaseFactory(object): @staticmethod def get_database(database_name_, **kwargs): logging.info(kwargs) if database_name_ == "snowflake": return SnowflakeDatabase(**kwargs) elif database_name_ == "nexus": return NexusDatabase() elif database_name_ == "mysql": return MySqlDatabase() elif database_name_ == "postgres": return PostgresSqlDatabase(**kwargs) else: raise Exception(f"{database_name_} is an invalid database option.")
476
54
23
9d2fd0de485396dcbbf68d054d38cd532366fff7
686
py
Python
flow/delete_orphaned_datasets/code.py
dataiku/dss-code-samples
fceebfaf1c3fa0fefa5df4c5862b5befa386040f
[ "Apache-2.0" ]
12
2018-05-21T18:05:55.000Z
2021-10-29T23:40:28.000Z
flow/delete_orphaned_datasets/code.py
dataiku/dss-code-samples
fceebfaf1c3fa0fefa5df4c5862b5befa386040f
[ "Apache-2.0" ]
12
2019-02-12T17:46:15.000Z
2021-08-17T09:22:33.000Z
flow/delete_orphaned_datasets/code.py
dataiku/dss-code-samples
fceebfaf1c3fa0fefa5df4c5862b5befa386040f
[ "Apache-2.0" ]
8
2018-09-06T17:40:18.000Z
2022-02-28T02:28:34.000Z
import dataiku def delete_orphaned_datasets(client=None, project_key=None, drop_data=False, dry_run=True): """Delete datasets that are not linked to any recipe. """ prj = client.get_project(project_key) flow = prj.get_flow() graph = flow.get_graph() cpt = 0 for name, props in graph.nodes.items(): if not props["predecessors"] and not props["successors"]: print(f"- Deleting {name}...") ds = prj.get_dataset(name) if not dry_run: ds.delete(drop_data=drop_data) cpt +=1 else: print("Dry run: nothing was deleted.") print(f"{cpt} datasets deleted.")
34.3
91
0.593294
import dataiku def delete_orphaned_datasets(client=None, project_key=None, drop_data=False, dry_run=True): """Delete datasets that are not linked to any recipe. """ prj = client.get_project(project_key) flow = prj.get_flow() graph = flow.get_graph() cpt = 0 for name, props in graph.nodes.items(): if not props["predecessors"] and not props["successors"]: print(f"- Deleting {name}...") ds = prj.get_dataset(name) if not dry_run: ds.delete(drop_data=drop_data) cpt +=1 else: print("Dry run: nothing was deleted.") print(f"{cpt} datasets deleted.")
0
0
0
02c495ae19bd0973705888f46d3438af6a3fbc59
598
py
Python
macOS/ss_rss_decode.py
enihsyou/dotfiles
7805f496405fe1b5795a11cc9c3b7ebfc21f5302
[ "MIT" ]
null
null
null
macOS/ss_rss_decode.py
enihsyou/dotfiles
7805f496405fe1b5795a11cc9c3b7ebfc21f5302
[ "MIT" ]
null
null
null
macOS/ss_rss_decode.py
enihsyou/dotfiles
7805f496405fe1b5795a11cc9c3b7ebfc21f5302
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 from urllib.request import urlopen from urllib.parse import unquote import base64 import re n3ro_rss_link = input("N3RO SIP002 URIs: ").strip() data = urlopen(n3ro_rss_link).read() links = base64.b64decode(data).decode() for link in links.splitlines(): matcher = re.match(r"ss://(.+)@(.+)#(.+)", link) a = base64.b64decode(matcher.group(1)).decode() b = matcher.group(2) c = unquote(matcher.group(3)) ss_link = base64.b64encode((a + '@' + b).encode()).decode() remark = c[:c.index('#')].replace(' ', '') print('ss://' + ss_link + '#' + remark)
29.9
63
0.635452
#!/usr/bin/env python3 from urllib.request import urlopen from urllib.parse import unquote import base64 import re n3ro_rss_link = input("N3RO SIP002 URIs: ").strip() data = urlopen(n3ro_rss_link).read() links = base64.b64decode(data).decode() for link in links.splitlines(): matcher = re.match(r"ss://(.+)@(.+)#(.+)", link) a = base64.b64decode(matcher.group(1)).decode() b = matcher.group(2) c = unquote(matcher.group(3)) ss_link = base64.b64encode((a + '@' + b).encode()).decode() remark = c[:c.index('#')].replace(' ', '') print('ss://' + ss_link + '#' + remark)
0
0
0
be5dba132045cad3c5008ecb5d5399651de45f89
5,482
py
Python
Fib_It.py
TheScott463/NN_tools
56fe08261827d6e28b4322ea464f4250bbfaac27
[ "MIT" ]
null
null
null
Fib_It.py
TheScott463/NN_tools
56fe08261827d6e28b4322ea464f4250bbfaac27
[ "MIT" ]
null
null
null
Fib_It.py
TheScott463/NN_tools
56fe08261827d6e28b4322ea464f4250bbfaac27
[ "MIT" ]
null
null
null
import math from itertools import islice from time import ctime print(ctime()) print("" "fibonacci algorithms.py") print("Iterative positive and negative") print(ctime()) print(ctime()) print("expected Output:") print( "-832040 514229 -317811 196418 -121393 75025 -46368 28657 -17711 " "10946 -6765 4181 -2584 1597 -987 610 -377 233 -144 89 -55 34 -21 13" " -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 " "2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040") for i in range(-30, 31): print(fib(i)) print(ctime()) print("Analytic") print("Binget formula:") for i in range(1, 31): print(analytic_fibonacci(i)) print("expected Output:") print( "1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 " "4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040") print("Iterative") print("Recursive") print("Recursive with Memoization") fm = fib_memo() for i in range(1, 31): print(fm(i)) print("expected Output:") print("1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 " "2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 " "317811 514229 832040") print("Better Recursive doesn't need Memoization") print("The recursive code as written two sections above is incredibly " "slow and inefficient" " due to the nested recursion calls. Although the memoization " "above makes the code " "run faster, it is at the cost of extra memory use. The below " "code is syntactically " "recursive but actually encodes the efficient iterative process, and thus doesn't " "require memoization: ") print("However, although much faster and not requiring memory, the above " "code can only work to a limited 'n' due to the limit on stack " "recursion " "depth by Python; it is better to use the iterative code above or " "the generative one below.") print("Generative") for i in fib_gen(11): print(i) print("Example use: " "for i in fibGen(11)") print("expect: [0,1,1,2,3,5,8,13,21,34,55]") print("Matrix-Based") print("Translation of the matrix-based approach used in F#.") print("Large step recurrence") print("This is much faster for a single, large value of n: ") print("calculating it takes a few seconds, printing it takes eons... original ex. 100000000 now 1024") print("fib(1024)") print(fib(1024)) print("Same as above but slightly faster") print("Putting the dictionary outside the function makes this about 2 seconds faster, could just make a wrapper:") F = {0: 0, 1: 1, 2: 1} print(fib(1024)) print("Generative with Recursion") print("This can get very slow and uses a lot of memory. Can be sped up by caching the generator results.") print("Yield fib[n+1] + fib[n]") print("yield 1 ; have to start somewhere") print("Yield fib[n+1] + fib[n]") f = fib() for _ in range(1, 9): print(next(f)) print("expected Output:") print("[1, 1, 2, 3, 5, 8, 13, 21, 34]") print("Another version of recursive generators solution, starting from 0") print(tuple(islice(fib2(), 10)))
21.667984
114
0.579898
import math from itertools import islice from time import ctime print(ctime()) print("" "fibonacci algorithms.py") print("Iterative positive and negative") print(ctime()) def fib(n, x=None): if x is None: x = [0, 1] for i in range(abs(n) - 1): x = [x[1], sum(x)] return x[1] * math.pow(-1, abs(n) - 1) if n < 0 else x[1] if n else 0 print(ctime()) print("expected Output:") print( "-832040 514229 -317811 196418 -121393 75025 -46368 28657 -17711 " "10946 -6765 4181 -2584 1597 -987 610 -377 233 -144 89 -55 34 -21 13" " -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 " "2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040") for i in range(-30, 31): print(fib(i)) print(ctime()) print("Analytic") print("Binget formula:") def analytic_fibonacci(n): sqrt_5: float = math.sqrt(5) p = (1 + sqrt_5) / 2 q = 1 / p return int((p ** n + q ** n) / sqrt_5 + 0.5) for i in range(1, 31): print(analytic_fibonacci(i)) print("expected Output:") print( "1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 " "4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040") print("Iterative") def fib_iter(n): if n < 2: return n fib_prev = 1 fib = 1 for num in range(2, n): fib_prev, fib = fib, fib + fib_prev return fib print("Recursive") def fib_rec(n): if n < 2: return n else: return fib_rec(n - 1) + fib_rec(n - 2) print("Recursive with Memoization") def fib_memo(): pad = {0: 0, 1: 1} def func(n): if n not in pad: pad[n] = func(n - 1) + func(n - 2) return pad[n] return func fm = fib_memo() for i in range(1, 31): print(fm(i)) print("expected Output:") print("1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 " "2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 " "317811 514229 832040") print("Better Recursive doesn't need Memoization") print("The recursive code as written two sections above is incredibly " "slow and inefficient" " due to the nested recursion calls. Although the memoization " "above makes the code " "run faster, it is at the cost of extra memory use. The below " "code is syntactically " "recursive but actually encodes the efficient iterative process, and thus doesn't " "require memoization: ") def fib_fast_rec(n): def fib(prv_prv, prv, c): if c < 1: return prv_prv else: return fib(prv, prv_prv + prv, c - 1) return fib(0, 1, n) print("However, although much faster and not requiring memory, the above " "code can only work to a limited 'n' due to the limit on stack " "recursion " "depth by Python; it is better to use the iterative code above or " "the generative one below.") print("Generative") def fib_gen(n): a, b = 0, 1 while n > 0: yield a a, b, n = b, a + b, n - 1 for i in fib_gen(11): print(i) print("Example use: " "for i in fibGen(11)") print("expect: [0,1,1,2,3,5,8,13,21,34,55]") print("Matrix-Based") print("Translation of the matrix-based approach used in F#.") def prev_pow_two(n): print("Gets the power of two that is less than or equal to the given input") if (n & -n) == n: return n else: n -= 1 n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 n += 1 return n / 2 def crazy_fib(n): print("Crazy fast fibonacci number calculation") pow_two = prev_pow_two(n) q = r = i = 1 s = 0 while i < pow_two: i *= 2 q, r, s = q * q + r * r, r * (q + s), (r * r + s * s) while i < n: i += 1 q, r, s = q + r, q, r return q print("Large step recurrence") print("This is much faster for a single, large value of n: ") def fib(n, c=None): if c is None: c = {0: 1, 1: 1} if n not in c: x = n // 2 c[n] = fib(x - 1) * fib(n - x - 1) + fib(x) * fib(n - x) return c[n] print("calculating it takes a few seconds, printing it takes eons... original ex. 100000000 now 1024") print("fib(1024)") print(fib(1024)) print("Same as above but slightly faster") print("Putting the dictionary outside the function makes this about 2 seconds faster, could just make a wrapper:") F = {0: 0, 1: 1, 2: 1} def fib(n): if n in F: return F[n] f1 = fib(n // 2 + 1) f2 = fib((n - 1) // 2) F[n] = (f1 * f1 + f2 * f2 if n & 1 else f1 * f1 - f2 * f2) return F[n] print(fib(1024)) print("Generative with Recursion") print("This can get very slow and uses a lot of memory. Can be sped up by caching the generator results.") print("Yield fib[n+1] + fib[n]") print("yield 1 ; have to start somewhere") print("Yield fib[n+1] + fib[n]") def fib(): yield 1 # have to start somewhere lhs, rhs = fib(), fib() yield next(lhs) # move lhs one iteration ahead while True: yield next(lhs) + next(rhs) f = fib() for _ in range(1, 9): print(next(f)) print("expected Output:") print("[1, 1, 2, 3, 5, 8, 13, 21, 34]") print("Another version of recursive generators solution, starting from 0") def fib2(): yield 0 yield 1 a, b = fib2(), fib2() next(b) while True: yield next(a) + next(b) print(tuple(islice(fib2(), 10)))
2,050
0
299
3c75fc14c1dbc3a08513e1f8a3cda194ef98c85d
4,498
py
Python
src/model_training/trainer.py
dishamehra/merlin-on-gcp
6050b31689ecb585e2298a27300aa9bf9433e7cd
[ "Apache-2.0" ]
2
2021-07-08T16:02:50.000Z
2022-03-29T08:30:18.000Z
src/model_training/trainer.py
dishamehra/merlin-on-gcp
6050b31689ecb585e2298a27300aa9bf9433e7cd
[ "Apache-2.0" ]
1
2021-08-03T16:36:42.000Z
2021-08-03T19:58:02.000Z
src/model_training/trainer.py
dishamehra/merlin-on-gcp
6050b31689ecb585e2298a27300aa9bf9433e7cd
[ "Apache-2.0" ]
7
2021-07-08T21:46:27.000Z
2021-08-03T16:02:53.000Z
# Copyright 2021 Google LLC # # 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. """Train and evaluate the model.""" import os import logging import tensorflow as tf from tensorflow import keras import nvtabular as nvt from nvtabular.loader.tensorflow import KerasSequenceLoader, KerasSequenceValidater from nvtabular.inference.triton import export_tensorflow_ensemble from src.common import features, utils from src.model_training import model HIDDEN_UNITS = [128, 128] LEARNING_RATE = 0.001 BATCH_SIZE = 1024 * 32 NUM_EPOCHS = 1
33.819549
92
0.724322
# Copyright 2021 Google LLC # # 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. """Train and evaluate the model.""" import os import logging import tensorflow as tf from tensorflow import keras import nvtabular as nvt from nvtabular.loader.tensorflow import KerasSequenceLoader, KerasSequenceValidater from nvtabular.inference.triton import export_tensorflow_ensemble from src.common import features, utils from src.model_training import model HIDDEN_UNITS = [128, 128] LEARNING_RATE = 0.001 BATCH_SIZE = 1024 * 32 NUM_EPOCHS = 1 def update_hyperparams(hyperparams: dict) -> dict: if "hidden_units" not in hyperparams: hyperparams["hidden_units"] = HIDDEN_UNITS else: if not isinstance(hyperparams["hidden_units"], list): hyperparams["hidden_units"] = [ int(v) for v in hyperparams["hidden_units"].split(",") ] if "learning_rate" not in hyperparams: hyperparams["learning_rate"] = LEARNING_RATE if "batch_size" not in hyperparams: hyperparams["batch_size"] = BATCH_SIZE if "num_epochs" not in hyperparams: hyperparams["num_epochs"] = NUM_EPOCHS return hyperparams def train(train_data_file_pattern, nvt_workflow, hyperparams, log_dir=None): hyperparams = update_hyperparams(hyperparams) logging.info("Hyperparameter:") logging.info(hyperparams) logging.info("") logging.info("Preparing train dataset loader...") train_dataset = KerasSequenceLoader( train_data_file_pattern, batch_size=hyperparams["batch_size"], label_names=features.TARGET_FEATURE_NAME, cat_names=features.get_categorical_feature_names(), cont_names=features.NUMERICAL_FEATURE_NAMES, engine="parquet", shuffle=True, buffer_size=0.06, # how many batches to load at once parts_per_chunk=1, ) embedding_shapes, embedding_shapes_multihot = nvt.ops.get_embedding_sizes( nvt_workflow ) embedding_shapes.update(embedding_shapes_multihot) logging.info(f"Embedding shapes: {embedding_shapes}") hidden_units = hyperparams["hidden_units"] recommendation_model = model.create(embedding_shapes, hidden_units) optimizer = keras.optimizers.Adam(learning_rate=hyperparams["learning_rate"]) loss = keras.losses.BinaryCrossentropy(from_logits=True) metrics = [keras.metrics.MeanAbsoluteError(name="mae")] logging.info("Compiling the model...") recommendation_model.compile(optimizer=optimizer, loss=loss, metrics=metrics) logging.info("Model fitting started...") history = recommendation_model.fit( train_dataset, epochs=hyperparams["num_epochs"], # callbacks=[evaluation_callback], ) logging.info("Model fitting finished.") return recommendation_model def evaluate(recommendation_model, eval_data_file_pattern, hyperparams): logging.info("Preparing evaluation dataset loader...") eval_dataset = KerasSequenceLoader( eval_data_file_pattern, batch_size=hyperparams["batch_size"], label_names=features.TARGET_FEATURE_NAME, cat_names=features.get_categorical_feature_names(), cont_names=features.NUMERICAL_FEATURE_NAMES, engine="parquet", shuffle=False, buffer_size=0.06, # how many batches to load at once parts_per_chunk=1, ) logging.info("Evaluating the model...") evaluation_metrics = recommendation_model.evaluate(eval_dataset) logging.info( f"Evaluation loss: {evaluation_metrics[0]} - Evaluation MAE {evaluation_metrics[1]}" ) return evaluation_metrics def export(recommendation_model, nvt_workflow, model_name, export_dir): for feature_name in features.CATEGORICAL_FEATURE_NAMES: nvt_workflow.output_dtypes[feature_name] = "int32" export_tensorflow_ensemble( recommendation_model, nvt_workflow, model_name, export_dir, features.TARGET_FEATURE_NAME, )
3,374
0
92
2ee25cc12a87f3fa2f796eb4786dd982677dce46
797
py
Python
ctf/Google-ctf/image-to-string.py
Sylhare/Flag
8f056593466c8611fae0f5ed0d39c711f694f41b
[ "MIT" ]
null
null
null
ctf/Google-ctf/image-to-string.py
Sylhare/Flag
8f056593466c8611fae0f5ed0d39c711f694f41b
[ "MIT" ]
4
2019-02-06T16:08:56.000Z
2019-03-17T20:12:50.000Z
ctf/Google-ctf/image-to-string.py
Sylhare/Flag
8f056593466c8611fae0f5ed0d39c711f694f41b
[ "MIT" ]
null
null
null
import pytesseract from PIL import Image img = Image.open("flag.png") text = pytesseract.image_to_string(img) print(rot_encode(7)(text)) if __name__ == '__main__': pass
24.151515
70
0.648683
import pytesseract from PIL import Image img = Image.open("flag.png") text = pytesseract.image_to_string(img) def rot(*symbols): def _rot(n): encoded = ''.join(sy[n:] + sy[:n] for sy in symbols) lookup = str.maketrans(''.join(symbols), encoded) return lambda s: s.translate(lookup) return _rot def rot_alpha(n): from string import ascii_lowercase as lc, ascii_uppercase as uc lookup = str.maketrans(lc + uc, lc[n:] + lc[:n] + uc[n:] + uc[:n]) return lambda s: s.translate(lookup) def rot_encode(n): from string import ascii_lowercase as lc, ascii_uppercase as uc lookup = str.maketrans(lc + uc, lc[n:] + lc[:n] + uc[n:] + uc[:n]) return lambda s: s.translate(lookup) print(rot_encode(7)(text)) if __name__ == '__main__': pass
548
0
69
3e46954c165d1812f769952525be44965339574a
5,180
py
Python
script/compile_content.py
GameTechDev/gametechdev-site
05a99f542a8ff57700e3df1f16afb16a6837ad75
[ "MIT" ]
1
2021-12-28T10:57:22.000Z
2021-12-28T10:57:22.000Z
script/compile_content.py
GameTechDev/gametechdev-site
05a99f542a8ff57700e3df1f16afb16a6837ad75
[ "MIT" ]
null
null
null
script/compile_content.py
GameTechDev/gametechdev-site
05a99f542a8ff57700e3df1f16afb16a6837ad75
[ "MIT" ]
null
null
null
import json import requests import sys import yaml from bs4 import BeautifulSoup from os.path import exists from os import mkdir, environ if __name__ == '__main__': reposUrl = '' authToken = '' if len(sys.argv) > 1: reposUrl = sys.argv[1] authToken = sys.argv[2] else: # an orgs' repo list API url, in form of https://api.github.com/orgs/{org}/repos reposUrl = environ['GITHUB_CONTENT_SYNC_ORG_REPOS_URL'] # an auth token for example a PAT authToken = environ['GITHUB_CONTENT_SYNC_PAT'] # info to be pulled from github initDict = { 'id': 0, 'name': '', 'description': '', 'created_at': '', 'updated_at': '', 'pushed_at': '', 'license': '', 'html_url': '', 'topics': [], 'homepage': '', # we won't be getting the social img url from github's data source, but we need to instantiate it 'social_img_url': '' } headerValues = { # We should explicitly access the latest api version per github api 'default': 'application/vnd.github.v3+json', # To access topics, we must explicitly access a preview api version 'topics': 'application/vnd.github.mercy-preview+json' } contentOutput = [] repos = [] topics = set(()) keepIndexing = True print(f'Attempting to get content from {reposUrl}.') apiPage = 1 while keepIndexing: requestParams = {'page': apiPage, 'sort': 'updated'} getRepos = requests.get( reposUrl, headers={ 'Accept': headerValues['topics'], 'Authorization': f'token {authToken}' }, params=requestParams ) if getRepos.status_code != 200: keepIndexing = False print('Received non-200 status code', getRepos.status_code, 'while trying to scan repos. This generally ' 'means the process will fail. Likely you need ' 'to authenticate to get past Github API ' 'Limits. Halting content generation.') raise ValueError('Got non-200 status when trying to get content.') # Repo information syncing loop elif keepIndexing: if not json.loads(getRepos.text): keepIndexing = False print(f'End of list reached.') else: print(f'Saving page {apiPage} of API response and getting imagery URLs...') for repo in json.loads(getRepos.text): if not repo['archived'] and not repo['private']: for topic in repo['topics']: topics.add(topic) # Initialize an empty list entry compileRepoInfo = initDict.copy() # Iterate over data placeholders and pull the data from the correct repo in memory for detail in compileRepoInfo: if detail in repo: compileRepoInfo[detail] = repo[detail] if detail == 'html_url': pageContent = requests.get(repo[detail]).text parsePage = BeautifulSoup(pageContent, "html.parser") # limit tag search to head pageHead = parsePage.html.find('head') socialImageElement = pageHead.find("meta", attrs={"property": "og:image"}) if socialImageElement: if socialImageElement.has_attr('content'): compileRepoInfo['social_img_url'] = socialImageElement['content'] # Add to list of compiled repo entries for final output contentOutput.append(compileRepoInfo) apiPage += 1 print('Collating content...') if not exists('../assets/img/thumb/'): mkdir('../assets/img/thumb/') sortedTopics = list(topics) sortedTopics.sort() dump_json('../_data/topics.json', sortedTopics) dump_json('../_data/projects.json', contentOutput) print('Downloading images...') for repo in contentOutput: response = requests.get(repo['social_img_url']) if response.ok: file_name = repo['name'] file_type = response.headers['content-type'].split('/')[1] with open(f'../assets/img/thumb/{file_name}.{file_type}', 'wb') as file: file.write(response.content)
37.810219
119
0.528185
import json import requests import sys import yaml from bs4 import BeautifulSoup from os.path import exists from os import mkdir, environ def dump_json(output, data_to_save): save = open(output, 'w') json.dump(data_to_save, save) save.close() print('Saved json to', output) def dump_yaml(output, data_to_save): save = open(output, 'w') yaml.dump(data_to_save, save) save.close() print('Saved yaml to', output) if __name__ == '__main__': reposUrl = '' authToken = '' if len(sys.argv) > 1: reposUrl = sys.argv[1] authToken = sys.argv[2] else: # an orgs' repo list API url, in form of https://api.github.com/orgs/{org}/repos reposUrl = environ['GITHUB_CONTENT_SYNC_ORG_REPOS_URL'] # an auth token for example a PAT authToken = environ['GITHUB_CONTENT_SYNC_PAT'] # info to be pulled from github initDict = { 'id': 0, 'name': '', 'description': '', 'created_at': '', 'updated_at': '', 'pushed_at': '', 'license': '', 'html_url': '', 'topics': [], 'homepage': '', # we won't be getting the social img url from github's data source, but we need to instantiate it 'social_img_url': '' } headerValues = { # We should explicitly access the latest api version per github api 'default': 'application/vnd.github.v3+json', # To access topics, we must explicitly access a preview api version 'topics': 'application/vnd.github.mercy-preview+json' } contentOutput = [] repos = [] topics = set(()) keepIndexing = True print(f'Attempting to get content from {reposUrl}.') apiPage = 1 while keepIndexing: requestParams = {'page': apiPage, 'sort': 'updated'} getRepos = requests.get( reposUrl, headers={ 'Accept': headerValues['topics'], 'Authorization': f'token {authToken}' }, params=requestParams ) if getRepos.status_code != 200: keepIndexing = False print('Received non-200 status code', getRepos.status_code, 'while trying to scan repos. This generally ' 'means the process will fail. Likely you need ' 'to authenticate to get past Github API ' 'Limits. Halting content generation.') raise ValueError('Got non-200 status when trying to get content.') # Repo information syncing loop elif keepIndexing: if not json.loads(getRepos.text): keepIndexing = False print(f'End of list reached.') else: print(f'Saving page {apiPage} of API response and getting imagery URLs...') for repo in json.loads(getRepos.text): if not repo['archived'] and not repo['private']: for topic in repo['topics']: topics.add(topic) # Initialize an empty list entry compileRepoInfo = initDict.copy() # Iterate over data placeholders and pull the data from the correct repo in memory for detail in compileRepoInfo: if detail in repo: compileRepoInfo[detail] = repo[detail] if detail == 'html_url': pageContent = requests.get(repo[detail]).text parsePage = BeautifulSoup(pageContent, "html.parser") # limit tag search to head pageHead = parsePage.html.find('head') socialImageElement = pageHead.find("meta", attrs={"property": "og:image"}) if socialImageElement: if socialImageElement.has_attr('content'): compileRepoInfo['social_img_url'] = socialImageElement['content'] # Add to list of compiled repo entries for final output contentOutput.append(compileRepoInfo) apiPage += 1 print('Collating content...') if not exists('../assets/img/thumb/'): mkdir('../assets/img/thumb/') sortedTopics = list(topics) sortedTopics.sort() dump_json('../_data/topics.json', sortedTopics) dump_json('../_data/projects.json', contentOutput) print('Downloading images...') for repo in contentOutput: response = requests.get(repo['social_img_url']) if response.ok: file_name = repo['name'] file_type = response.headers['content-type'].split('/')[1] with open(f'../assets/img/thumb/{file_name}.{file_type}', 'wb') as file: file.write(response.content)
260
0
46
01c7d781c8bc2ec107e76b32652f3677ea1f3046
2,927
py
Python
enaml/wx/wx_application.py
pberkes/enaml
cbcbee929e3117dfe56c0b06dc2385acc832b0e8
[ "BSD-3-Clause-Clear" ]
11
2015-03-14T14:30:51.000Z
2022-03-15T13:01:44.000Z
enaml/wx/wx_application.py
pberkes/enaml
cbcbee929e3117dfe56c0b06dc2385acc832b0e8
[ "BSD-3-Clause-Clear" ]
3
2015-01-31T11:12:56.000Z
2022-03-14T00:53:25.000Z
enaml/wx/wx_application.py
pberkes/enaml
cbcbee929e3117dfe56c0b06dc2385acc832b0e8
[ "BSD-3-Clause-Clear" ]
4
2015-01-27T01:56:14.000Z
2021-02-23T07:21:20.000Z
#------------------------------------------------------------------------------ # Copyright (c) 2013, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #------------------------------------------------------------------------------ import wx from atom.api import Typed from enaml.application import Application, ProxyResolver from .wx_deferred_caller import DeferredCall, TimedCall from .wx_factories import WX_FACTORIES class WxApplication(Application): """ A Wx implementation of an Enaml application. A WxApplication uses the Wx toolkit to implement an Enaml UI that runs in the local process. """ #: The private QApplication instance. _wxapp = Typed(wx.App) def __init__(self): """ Initialize a WxApplication. """ super(WxApplication, self).__init__() self._wxapp = wx.GetApp() or wx.PySimpleApp() self.resolver = ProxyResolver(factories=WX_FACTORIES) #-------------------------------------------------------------------------- # Abstract API Implementation #-------------------------------------------------------------------------- def start(self): """ Start the application's main event loop. """ app = self._wxapp if not app.IsMainLoopRunning(): app.MainLoop() def stop(self): """ Stop the application's main event loop. """ app = self._wxapp if app.IsMainLoopRunning(): app.Exit() def deferred_call(self, callback, *args, **kwargs): """ Invoke a callable on the next cycle of the main event loop thread. Parameters ---------- callback : callable The callable object to execute at some point in the future. *args, **kwargs Any additional positional and keyword arguments to pass to the callback. """ DeferredCall(callback, *args, **kwargs) def timed_call(self, ms, callback, *args, **kwargs): """ Invoke a callable on the main event loop thread at a specified time in the future. Parameters ---------- ms : int The time to delay, in milliseconds, before executing the callable. callback : callable The callable object to execute at some point in the future. *args, **kwargs Any additional positional and keyword arguments to pass to the callback. """ TimedCall(ms, callback, *args, **kwargs) def is_main_thread(self): """ Indicates whether the caller is on the main gui thread. Returns ------- result : bool True if called from the main gui thread. False otherwise. """ return wx.Thread_IsMain()
28.980198
79
0.546293
#------------------------------------------------------------------------------ # Copyright (c) 2013, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #------------------------------------------------------------------------------ import wx from atom.api import Typed from enaml.application import Application, ProxyResolver from .wx_deferred_caller import DeferredCall, TimedCall from .wx_factories import WX_FACTORIES class WxApplication(Application): """ A Wx implementation of an Enaml application. A WxApplication uses the Wx toolkit to implement an Enaml UI that runs in the local process. """ #: The private QApplication instance. _wxapp = Typed(wx.App) def __init__(self): """ Initialize a WxApplication. """ super(WxApplication, self).__init__() self._wxapp = wx.GetApp() or wx.PySimpleApp() self.resolver = ProxyResolver(factories=WX_FACTORIES) #-------------------------------------------------------------------------- # Abstract API Implementation #-------------------------------------------------------------------------- def start(self): """ Start the application's main event loop. """ app = self._wxapp if not app.IsMainLoopRunning(): app.MainLoop() def stop(self): """ Stop the application's main event loop. """ app = self._wxapp if app.IsMainLoopRunning(): app.Exit() def deferred_call(self, callback, *args, **kwargs): """ Invoke a callable on the next cycle of the main event loop thread. Parameters ---------- callback : callable The callable object to execute at some point in the future. *args, **kwargs Any additional positional and keyword arguments to pass to the callback. """ DeferredCall(callback, *args, **kwargs) def timed_call(self, ms, callback, *args, **kwargs): """ Invoke a callable on the main event loop thread at a specified time in the future. Parameters ---------- ms : int The time to delay, in milliseconds, before executing the callable. callback : callable The callable object to execute at some point in the future. *args, **kwargs Any additional positional and keyword arguments to pass to the callback. """ TimedCall(ms, callback, *args, **kwargs) def is_main_thread(self): """ Indicates whether the caller is on the main gui thread. Returns ------- result : bool True if called from the main gui thread. False otherwise. """ return wx.Thread_IsMain()
0
0
0
0b1a0b850c9213734b43e7e8487946f434190431
1,206
py
Python
test/testings/platform.py
HansBug/hbutils
6872311c8a441c5955572e0093b10189a2b90708
[ "Apache-2.0" ]
null
null
null
test/testings/platform.py
HansBug/hbutils
6872311c8a441c5955572e0093b10189a2b90708
[ "Apache-2.0" ]
25
2021-10-03T06:19:05.000Z
2022-03-27T12:48:57.000Z
test/testings/platform.py
HansBug/hbutils
6872311c8a441c5955572e0093b10189a2b90708
[ "Apache-2.0" ]
null
null
null
import os import platform import pytest _is_win = bool(os.environ.get('IS_WIN', None)) _is_macos = bool(os.environ.get('IS_MAC', None)) _is_linux = not _is_macos and not _is_win windows_mark = pytest.mark.unittest if _is_win else pytest.mark.ignore macos_mark = pytest.mark.unittest if _is_macos else pytest.mark.ignore linux_mark = pytest.mark.unittest if _is_linux else pytest.mark.ignore _is_pypy = bool(os.environ.get('IS_PYPY', None)) _is_cpython = not _is_pypy pypy_mark = pytest.mark.unittest if _is_pypy else pytest.mark.ignore cpython_mark = pytest.mark.unittest if _is_cpython else pytest.mark.ignore vpy_tuple = platform.python_version_tuple() _is_py36 = vpy_tuple[:2] == ('3', '6') _is_py37 = vpy_tuple[:2] == ('3', '7') _is_py38 = vpy_tuple[:2] == ('3', '8') _is_py39 = vpy_tuple[:2] == ('3', '9') _is_py310 = vpy_tuple[:2] == ('3', '10') py36_mark = pytest.mark.unittest if _is_py36 else pytest.mark.ignore py37_mark = pytest.mark.unittest if _is_py37 else pytest.mark.ignore py38_mark = pytest.mark.unittest if _is_py38 else pytest.mark.ignore py39_mark = pytest.mark.unittest if _is_py39 else pytest.mark.ignore py310_mark = pytest.mark.unittest if _is_py310 else pytest.mark.ignore
37.6875
74
0.759536
import os import platform import pytest _is_win = bool(os.environ.get('IS_WIN', None)) _is_macos = bool(os.environ.get('IS_MAC', None)) _is_linux = not _is_macos and not _is_win windows_mark = pytest.mark.unittest if _is_win else pytest.mark.ignore macos_mark = pytest.mark.unittest if _is_macos else pytest.mark.ignore linux_mark = pytest.mark.unittest if _is_linux else pytest.mark.ignore _is_pypy = bool(os.environ.get('IS_PYPY', None)) _is_cpython = not _is_pypy pypy_mark = pytest.mark.unittest if _is_pypy else pytest.mark.ignore cpython_mark = pytest.mark.unittest if _is_cpython else pytest.mark.ignore vpy_tuple = platform.python_version_tuple() _is_py36 = vpy_tuple[:2] == ('3', '6') _is_py37 = vpy_tuple[:2] == ('3', '7') _is_py38 = vpy_tuple[:2] == ('3', '8') _is_py39 = vpy_tuple[:2] == ('3', '9') _is_py310 = vpy_tuple[:2] == ('3', '10') py36_mark = pytest.mark.unittest if _is_py36 else pytest.mark.ignore py37_mark = pytest.mark.unittest if _is_py37 else pytest.mark.ignore py38_mark = pytest.mark.unittest if _is_py38 else pytest.mark.ignore py39_mark = pytest.mark.unittest if _is_py39 else pytest.mark.ignore py310_mark = pytest.mark.unittest if _is_py310 else pytest.mark.ignore
0
0
0
0a97a4190c7e21d95b9fda88952299aa6a1aae1f
1,813
py
Python
adventofcode2020/12.py
matslindh/codingchallenges
b6792808b03ea07304fda7e74c874c2c4d200dac
[ "MIT" ]
2
2016-12-28T09:40:07.000Z
2020-12-08T13:58:15.000Z
adventofcode2020/12.py
matslindh/codingchallenges
b6792808b03ea07304fda7e74c874c2c4d200dac
[ "MIT" ]
null
null
null
adventofcode2020/12.py
matslindh/codingchallenges
b6792808b03ea07304fda7e74c874c2c4d200dac
[ "MIT" ]
null
null
null
if __name__ == '__main__': print(navigation_schmavigation([l.strip() for l in open('input/12')])) print(navigation_schmavigation_2([l.strip() for l in open('input/12')]))
22.949367
88
0.447876
def rotate(current, dir, num): seq = ['E', 'S', 'W', 'N'] if dir == 'L': seq.reverse() num //= 90 return seq[(seq.index(current) + num) % len(seq)] def navigation_schmavigation(instructions): dir = 'E' x, y = 0, 0 for instr in instructions: inp = instr[0] op = int(instr[1:]) if inp == 'F': inp = dir if inp in ('L', 'R'): dir = rotate(dir, inp, op) elif inp == 'E': x += op elif inp == 'S': y -= op elif inp == 'W': x -= op elif inp == 'N': y += op return abs(x) + abs(y) def navigation_schmavigation_2(instructions): x_d, y_d = 10, 1 x, y = 0, 0 for instr in instructions: inp = instr[0] op = int(instr[1:]) if inp == 'F': x += x_d * op y += y_d * op if inp in ('L', 'R'): for _ in range(0, op, 90): if inp == 'L': s = 1 else: s = -1 x_d, y_d = -y_d * s, x_d * s elif inp == 'E': x_d += op elif inp == 'S': y_d -= op elif inp == 'W': x_d -= op elif inp == 'N': y_d += op return abs(x) + abs(y) def test_navigation_schmavigation(): assert navigation_schmavigation([l.strip() for l in open('input/12.test')]) == 25 def test_navigation_schmavigation_2(): assert navigation_schmavigation_2([l.strip() for l in open('input/12.test')]) == 286 if __name__ == '__main__': print(navigation_schmavigation([l.strip() for l in open('input/12')])) print(navigation_schmavigation_2([l.strip() for l in open('input/12')]))
1,515
0
114
d247cd9a1a8e1b6e437b537d633be0d901ef036e
170
py
Python
15. Chapter_/tasks.py
Mikma03/Python_Bill_Lubanovic_BookCodes
8b5b228bb500a08af645a1db6f7c5f33ef5f0512
[ "MIT" ]
null
null
null
15. Chapter_/tasks.py
Mikma03/Python_Bill_Lubanovic_BookCodes
8b5b228bb500a08af645a1db6f7c5f33ef5f0512
[ "MIT" ]
null
null
null
15. Chapter_/tasks.py
Mikma03/Python_Bill_Lubanovic_BookCodes
8b5b228bb500a08af645a1db6f7c5f33ef5f0512
[ "MIT" ]
null
null
null
from invoke import task @task
21.25
48
0.676471
from invoke import task @task def mytime(ctx): import time now = time.time() time_str = time.asctime(time.localtime(now)) print("Bieżący czas:", timestr)
120
0
22
510784fb3b0fea6c94638a9a31c35e3c758d9b66
3,638
py
Python
align/cell_fabric/gen_magic.py
thesourcerer8/ALIGN-public
2e061c719e15f5e4ffafde6b3bfdc1f5dbb45654
[ "BSD-3-Clause" ]
2
2020-12-15T11:16:23.000Z
2021-05-10T08:08:34.000Z
align/cell_fabric/gen_magic.py
thesourcerer8/ALIGN-public
2e061c719e15f5e4ffafde6b3bfdc1f5dbb45654
[ "BSD-3-Clause" ]
1
2020-08-26T08:01:53.000Z
2020-08-29T04:24:00.000Z
align/cell_fabric/gen_magic.py
thesourcerer8/ALIGN-public
2e061c719e15f5e4ffafde6b3bfdc1f5dbb45654
[ "BSD-3-Clause" ]
2
2020-08-15T07:09:52.000Z
2020-08-16T10:19:58.000Z
#!/usr/bin/python import re import json import datetime from . import pdk import logging logger = logging.getLogger(__name__)
38.294737
170
0.575316
#!/usr/bin/python import re import json import datetime from . import pdk import logging logger = logging.getLogger(__name__) def translate_data( macro_name, exclude_pattern, pdkfile, pinSwitch, data, via_gen_tbl, timestamp=None): j = pdk.Pdk().load(pdkfile) with open(pdkfile, "rt") as fp1: j1 = json.load(fp1) if timestamp is not None: ts = timestamp else: ts = datetime.datetime.now() techname="scmos" if 'Magic' in j1: techname=j1['Magic']['Techname'] else: logger.warning("Warning: This PDK does not support MAGIC export, to make sure to get proper MAGIC export, please use the correct PDK or enhance the PDK for MAGIC.") top = "magic\ntech "+techname+"\ntimestamp "+ts+"\n" def scale(x): result = x*4//j1['ScaleFactor']//1000 if isinstance(result, float): logger.warning(f"translate_data:scale: Coord {x} ({result}) not integral") intresult = int(round(result,0)) assert abs(intresult-result) < 0.001 return intresult else: return result pat = None if exclude_pattern != '': pat = re.compile( exclude_pattern) def exclude_based_on_name( nm): return pat and nm is not None and pat.match( nm) # non-vias for obj in data['terminals']: k = obj['layer'] if k in via_gen_tbl: continue if exclude_based_on_name( obj['netName']): continue r=list(map(scale,obj['rect'])) layername=k if 'MagicLayerName' in j[k]: layername=j[k]['MagicLayerName'] top+="<< "+layername+" >>\n" top+="#NON-VIA:\nrect "+str(r[0])+" "+str(r[1])+" "+str(r[2])+" "+str(r[3])+"\n" #strct["elements"].append ({"type": "boundary", "layer" : j[k]['GdsLayerNo'], # "datatype" : j[k]['GdsDatatype']['Draw'], # "xy" : flat_rect_to_boundary( list(map(scale,obj['rect'])))}) if ('color' in obj): top+="#color "+str(j[k]['GdsDatatype'][obj['color']])+"\n" # strct["elements"].append ({"type": "boundary", "layer" : j[k]['GdsLayerNo'], # "datatype" : j[k]['GdsDatatype'][obj['color']], # "xy" : flat_rect_to_boundary( list(map(scale,obj['rect'])))}) if ('pin' in obj) and pinSwitch !=0: top+="#pin "+layername+" "+str(r[0])+" "+str(r[1])+" "+str(r[2])+" "+str(r[3])+"\n" # strct["elements"].append ({"type": "boundary", "layer" : j[k]['GdsLayerNo'], # "datatype" : j[k]['GdsDatatype']['Pin'], # "xy" : flat_rect_to_boundary( list(map(scale,obj['rect'])))}) # vias for obj in data['terminals']: k = obj['layer'] if k not in via_gen_tbl: continue if exclude_based_on_name( obj['netName']): continue r = list(map( scale, obj['rect'])) xc = (r[0]+r[2])//2 yc = (r[1]+r[3])//2 layername=j['Bbox']['layer'] if 'MagicLayerName' in j['Bbox']: layername=j['Bbox']['MagicLayerName'] top+="<< "+layername+" >>\n" top+="#VIA:\nrect "+str(r[0])+" "+str(r[1])+" "+str(r[2])+" "+str(r[3])+"\n" #strct["elements"].append ({"type": "sref", "sname" : via_gen_tbl[k][0], "xy" : [xc, yc]}) #strct["elements"].append ({"type": "boundary", "layer" : j['Bbox']['GdsLayerNo'], "datatype" : j['Bbox']['GdsDatatype']['Draw'], # # "xy" : flat_rect_to_boundary( list(map(scale,data['bbox'])))}) top+="<< end >>\n" return top def translate( macro_name, exclude_pattern, pinSwitch, fp, ofile, timestamp=None, p=None): ofile.write(translate_data( macro_name, exclude_pattern, p.layerfile, pinSwitch, json.load(fp), {}, timestamp))
3,466
0
46
b9c787700d0831ebd09156e925743799a1f8c4a0
1,256
py
Python
src/posts/templatetags/posts_tags.py
pratik-devkota/notesewa
f93e8da43ce48aba43d86ed21861acf099b03f40
[ "MIT" ]
null
null
null
src/posts/templatetags/posts_tags.py
pratik-devkota/notesewa
f93e8da43ce48aba43d86ed21861acf099b03f40
[ "MIT" ]
null
null
null
src/posts/templatetags/posts_tags.py
pratik-devkota/notesewa
f93e8da43ce48aba43d86ed21861acf099b03f40
[ "MIT" ]
1
2021-04-12T12:12:23.000Z
2021-04-12T12:12:23.000Z
""" File defining custom template tags for our project """ # Core Django imports from django import template from django.utils.safestring import mark_safe # app-imports from posts.models import Post # third-party imports import markdown register = template.Library() @register.simple_tag def total_posts(): """ A simple template tag that shows the number of posts that have been uploaded so far """ return Post.published.count() @register.inclusion_tag('posts/latest_uploads.html') def show_latest_uploads(count=3): """ An inclusion template tag that renders the latest_uploads.html template with context variables including the latest uploads. The number of latest uploads to display can be passed to the tag as the value of the 'count' variable. """ latest_uploads = Post.published.order_by('-created')[:count] return { 'latest_uploads': latest_uploads } # template filters are registered the same as template tags @register.filter(name='markdown') def markdown_format(text): """ Template filter function that renders the text given in markdown syntax as HTML """ # mark the output as safe HTML to be rendered in the template return mark_safe(markdown.markdown(text))
28.545455
75
0.735669
""" File defining custom template tags for our project """ # Core Django imports from django import template from django.utils.safestring import mark_safe # app-imports from posts.models import Post # third-party imports import markdown register = template.Library() @register.simple_tag def total_posts(): """ A simple template tag that shows the number of posts that have been uploaded so far """ return Post.published.count() @register.inclusion_tag('posts/latest_uploads.html') def show_latest_uploads(count=3): """ An inclusion template tag that renders the latest_uploads.html template with context variables including the latest uploads. The number of latest uploads to display can be passed to the tag as the value of the 'count' variable. """ latest_uploads = Post.published.order_by('-created')[:count] return { 'latest_uploads': latest_uploads } # template filters are registered the same as template tags @register.filter(name='markdown') def markdown_format(text): """ Template filter function that renders the text given in markdown syntax as HTML """ # mark the output as safe HTML to be rendered in the template return mark_safe(markdown.markdown(text))
0
0
0
9c684ca6bfbf0f62dc9afeed12f0225ec579b3a7
13,179
py
Python
tests/models/test_gpu.py
djbyrne/pytorch-lightning
dab3b965cb9ceacc3f44aa2240b495d5996c6011
[ "Apache-2.0" ]
null
null
null
tests/models/test_gpu.py
djbyrne/pytorch-lightning
dab3b965cb9ceacc3f44aa2240b495d5996c6011
[ "Apache-2.0" ]
null
null
null
tests/models/test_gpu.py
djbyrne/pytorch-lightning
dab3b965cb9ceacc3f44aa2240b495d5996c6011
[ "Apache-2.0" ]
null
null
null
import os import pytest import torch import tests.base.utils as tutils from pytorch_lightning import Trainer from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.core import memory from pytorch_lightning.trainer.distrib_parts import ( parse_gpu_ids, determine_root_gpu_device, ) from pytorch_lightning.utilities.debugging import MisconfigurationException from tests.base import LightningTestModel PRETEND_N_OF_GPUS = 16 def test_multi_gpu_model_ddp2(tmpdir): """Make sure DDP2 works.""" if not tutils.can_run_gpu_test(): return tutils.reset_seed() tutils.set_random_master_port() model, hparams = tutils.get_default_model() trainer_options = dict( default_save_path=tmpdir, show_progress_bar=True, max_epochs=1, train_percent_check=0.4, val_percent_check=0.2, gpus=2, weights_summary=None, distributed_backend='ddp2' ) tutils.run_model_test(trainer_options, model) def test_multi_gpu_model_ddp(tmpdir): """Make sure DDP works.""" if not tutils.can_run_gpu_test(): return tutils.reset_seed() tutils.set_random_master_port() model, hparams = tutils.get_default_model() trainer_options = dict( default_save_path=tmpdir, show_progress_bar=False, max_epochs=1, train_percent_check=0.4, val_percent_check=0.2, gpus=[0, 1], distributed_backend='ddp' ) tutils.run_model_test(trainer_options, model) def test_ddp_all_dataloaders_passed_to_fit(tmpdir): """Make sure DDP works with dataloaders passed to fit()""" if not tutils.can_run_gpu_test(): return tutils.reset_seed() tutils.set_random_master_port() model, hparams = tutils.get_default_model() trainer_options = dict(default_save_path=tmpdir, show_progress_bar=False, max_epochs=1, train_percent_check=0.4, val_percent_check=0.2, gpus=[0, 1], distributed_backend='ddp') fit_options = dict(train_dataloader=model.train_dataloader(), val_dataloaders=model.val_dataloader()) trainer = Trainer(**trainer_options) result = trainer.fit(model, **fit_options) assert result == 1, "DDP doesn't work with dataloaders passed to fit()." def test_cpu_slurm_save_load(tmpdir): """Verify model save/load/checkpoint on CPU.""" tutils.reset_seed() hparams = tutils.get_default_hparams() model = LightningTestModel(hparams) # logger file to get meta logger = tutils.get_default_testtube_logger(tmpdir, False) version = logger.version trainer_options = dict( max_epochs=1, logger=logger, checkpoint_callback=ModelCheckpoint(tmpdir) ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) real_global_step = trainer.global_step # traning complete assert result == 1, 'amp + ddp model failed to complete' # predict with trained model before saving # make a prediction dataloaders = model.test_dataloader() if not isinstance(dataloaders, list): dataloaders = [dataloaders] for dataloader in dataloaders: for batch in dataloader: break x, y = batch x = x.view(x.size(0), -1) model.eval() pred_before_saving = model(x) # test HPC saving # simulate snapshot on slurm saved_filepath = trainer.hpc_save(tmpdir, logger) assert os.path.exists(saved_filepath) # new logger file to get meta logger = tutils.get_default_testtube_logger(tmpdir, False, version=version) trainer_options = dict( max_epochs=1, logger=logger, checkpoint_callback=ModelCheckpoint(tmpdir), ) trainer = Trainer(**trainer_options) model = LightningTestModel(hparams) # set the epoch start hook so we can predict before the model does the full training model.on_epoch_start = assert_pred_same # by calling fit again, we trigger training, loading weights from the cluster # and our hook to predict using current model before any more weight updates trainer.fit(model) def test_multi_gpu_none_backend(tmpdir): """Make sure when using multiple GPUs the user can't use `distributed_backend = None`.""" tutils.reset_seed() if not tutils.can_run_gpu_test(): return model, hparams = tutils.get_default_model() trainer_options = dict( default_save_path=tmpdir, show_progress_bar=False, max_epochs=1, train_percent_check=0.1, val_percent_check=0.1, gpus='-1' ) with pytest.warns(UserWarning): tutils.run_model_test(trainer_options, model) def test_multi_gpu_model_dp(tmpdir): """Make sure DP works.""" tutils.reset_seed() if not tutils.can_run_gpu_test(): return model, hparams = tutils.get_default_model() trainer_options = dict( default_save_path=tmpdir, show_progress_bar=False, distributed_backend='dp', max_epochs=1, train_percent_check=0.1, val_percent_check=0.1, gpus='-1' ) tutils.run_model_test(trainer_options, model) # test memory helper functions memory.get_memory_profile('min_max') @pytest.fixture @pytest.fixture @pytest.mark.gpus_param_tests @pytest.mark.parametrize(["gpus", "expected_num_gpus", "distributed_backend"], [ pytest.param(None, 0, None, id="None - expect 0 gpu to use."), pytest.param(0, 0, None, id="Oth gpu, expect 1 gpu to use."), pytest.param(1, 1, None, id="1st gpu, expect 1 gpu to use."), pytest.param(-1, PRETEND_N_OF_GPUS, "ddp", id="-1 - use all gpus"), pytest.param('-1', PRETEND_N_OF_GPUS, "ddp", id="'-1' - use all gpus"), pytest.param(3, 3, "ddp", id="3rd gpu - 1 gpu to use (backend:ddp)") ]) @pytest.mark.gpus_param_tests @pytest.mark.parametrize(["gpus", "expected_num_gpus", "distributed_backend"], [ pytest.param(None, 0, None, id="None - expect 0 gpu to use."), pytest.param(None, 0, "ddp", id="None - expect 0 gpu to use."), ]) @pytest.mark.gpus_param_tests @pytest.mark.parametrize(['gpus', 'expected_root_gpu', "distributed_backend"], [ pytest.param(None, None, "ddp", id="None is None"), pytest.param(0, None, "ddp", id="O gpus, expect gpu root device to be None."), pytest.param(1, 0, "ddp", id="1 gpu, expect gpu root device to be 0."), pytest.param(-1, 0, "ddp", id="-1 - use all gpus, expect gpu root device to be 0."), pytest.param('-1', 0, "ddp", id="'-1' - use all gpus, expect gpu root device to be 0."), pytest.param(3, 0, "ddp", id="3 gpus, expect gpu root device to be 0.(backend:ddp)") ]) @pytest.mark.gpus_param_tests @pytest.mark.parametrize([ 'gpus', 'expected_root_gpu', "distributed_backend"], [ pytest.param(None, None, None, id="None is None"), pytest.param(None, None, "ddp", id="None is None"), pytest.param(0, None, "ddp", id="None is None"), ]) # Asking for a gpu when non are available will result in a MisconfigurationException @pytest.mark.gpus_param_tests @pytest.mark.parametrize([ 'gpus', 'expected_root_gpu', "distributed_backend"], [ pytest.param(1, None, "ddp"), pytest.param(3, None, "ddp"), pytest.param(3, None, "ddp"), pytest.param([1, 2], None, "ddp"), pytest.param([0, 1], None, "ddp"), pytest.param(-1, None, "ddp"), pytest.param('-1', None, "ddp") ]) @pytest.mark.gpus_param_tests @pytest.mark.parametrize(['gpus', 'expected_root_gpu'], [ pytest.param(None, None, id="No gpus, expect gpu root device to be None"), pytest.param([0], 0, id="Oth gpu, expect gpu root device to be 0."), pytest.param([1], 1, id="1st gpu, expect gpu root device to be 1."), pytest.param([3], 3, id="3rd gpu, expect gpu root device to be 3."), pytest.param([1, 2], 1, id="[1, 2] gpus, expect gpu root device to be 1."), ]) @pytest.mark.gpus_param_tests @pytest.mark.parametrize(['gpus', 'expected_gpu_ids'], [ pytest.param(None, None), pytest.param(0, None), pytest.param(1, [0]), pytest.param(3, [0, 1, 2]), pytest.param(-1, list(range(PRETEND_N_OF_GPUS)), id="-1 - use all gpus"), pytest.param([0], [0]), pytest.param([1, 3], [1, 3]), pytest.param('0', [0]), pytest.param('3', [3]), pytest.param('1, 3', [1, 3]), pytest.param('-1', list(range(PRETEND_N_OF_GPUS)), id="'-1' - use all gpus"), ]) @pytest.mark.gpus_param_tests @pytest.mark.parametrize(['gpus'], [ pytest.param(0.1), pytest.param(-2), pytest.param(False), pytest.param([]), pytest.param([-1]), pytest.param([None]), pytest.param(['0']), pytest.param((0, 1)), ]) @pytest.mark.gpus_param_tests @pytest.mark.parametrize("gpus", ['']) @pytest.mark.gpus_param_tests @pytest.mark.parametrize("gpus", [[1, 2, 19], -1, '-1']) @pytest.mark.gpus_param_tests @pytest.mark.gpus_param_tests @pytest.mark.parametrize("gpus", [-1, '-1']) # if __name__ == '__main__': # pytest.main([__file__])
32.9475
100
0.684574
import os import pytest import torch import tests.base.utils as tutils from pytorch_lightning import Trainer from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.core import memory from pytorch_lightning.trainer.distrib_parts import ( parse_gpu_ids, determine_root_gpu_device, ) from pytorch_lightning.utilities.debugging import MisconfigurationException from tests.base import LightningTestModel PRETEND_N_OF_GPUS = 16 def test_multi_gpu_model_ddp2(tmpdir): """Make sure DDP2 works.""" if not tutils.can_run_gpu_test(): return tutils.reset_seed() tutils.set_random_master_port() model, hparams = tutils.get_default_model() trainer_options = dict( default_save_path=tmpdir, show_progress_bar=True, max_epochs=1, train_percent_check=0.4, val_percent_check=0.2, gpus=2, weights_summary=None, distributed_backend='ddp2' ) tutils.run_model_test(trainer_options, model) def test_multi_gpu_model_ddp(tmpdir): """Make sure DDP works.""" if not tutils.can_run_gpu_test(): return tutils.reset_seed() tutils.set_random_master_port() model, hparams = tutils.get_default_model() trainer_options = dict( default_save_path=tmpdir, show_progress_bar=False, max_epochs=1, train_percent_check=0.4, val_percent_check=0.2, gpus=[0, 1], distributed_backend='ddp' ) tutils.run_model_test(trainer_options, model) def test_ddp_all_dataloaders_passed_to_fit(tmpdir): """Make sure DDP works with dataloaders passed to fit()""" if not tutils.can_run_gpu_test(): return tutils.reset_seed() tutils.set_random_master_port() model, hparams = tutils.get_default_model() trainer_options = dict(default_save_path=tmpdir, show_progress_bar=False, max_epochs=1, train_percent_check=0.4, val_percent_check=0.2, gpus=[0, 1], distributed_backend='ddp') fit_options = dict(train_dataloader=model.train_dataloader(), val_dataloaders=model.val_dataloader()) trainer = Trainer(**trainer_options) result = trainer.fit(model, **fit_options) assert result == 1, "DDP doesn't work with dataloaders passed to fit()." def test_optimizer_return_options(): tutils.reset_seed() trainer = Trainer() model, hparams = tutils.get_default_model() # single optimizer opt_a = torch.optim.Adam(model.parameters(), lr=0.002) opt_b = torch.optim.SGD(model.parameters(), lr=0.002) optim, lr_sched = trainer.init_optimizers(opt_a) assert len(optim) == 1 and len(lr_sched) == 0 # opt tuple opts = (opt_a, opt_b) optim, lr_sched = trainer.init_optimizers(opts) assert len(optim) == 2 and optim[0] == opts[0] and optim[1] == opts[1] assert len(lr_sched) == 0 # opt list opts = [opt_a, opt_b] optim, lr_sched = trainer.init_optimizers(opts) assert len(optim) == 2 and optim[0] == opts[0] and optim[1] == opts[1] assert len(lr_sched) == 0 # opt tuple of lists scheduler = torch.optim.lr_scheduler.StepLR(opt_a, 10) opts = ([opt_a], [scheduler]) optim, lr_sched = trainer.init_optimizers(opts) assert len(optim) == 1 and len(lr_sched) == 1 assert optim[0] == opts[0][0] and \ lr_sched[0] == dict(scheduler=scheduler, interval='epoch', frequency=1, reduce_on_plateau=False, monitor='val_loss') def test_cpu_slurm_save_load(tmpdir): """Verify model save/load/checkpoint on CPU.""" tutils.reset_seed() hparams = tutils.get_default_hparams() model = LightningTestModel(hparams) # logger file to get meta logger = tutils.get_default_testtube_logger(tmpdir, False) version = logger.version trainer_options = dict( max_epochs=1, logger=logger, checkpoint_callback=ModelCheckpoint(tmpdir) ) # fit model trainer = Trainer(**trainer_options) result = trainer.fit(model) real_global_step = trainer.global_step # traning complete assert result == 1, 'amp + ddp model failed to complete' # predict with trained model before saving # make a prediction dataloaders = model.test_dataloader() if not isinstance(dataloaders, list): dataloaders = [dataloaders] for dataloader in dataloaders: for batch in dataloader: break x, y = batch x = x.view(x.size(0), -1) model.eval() pred_before_saving = model(x) # test HPC saving # simulate snapshot on slurm saved_filepath = trainer.hpc_save(tmpdir, logger) assert os.path.exists(saved_filepath) # new logger file to get meta logger = tutils.get_default_testtube_logger(tmpdir, False, version=version) trainer_options = dict( max_epochs=1, logger=logger, checkpoint_callback=ModelCheckpoint(tmpdir), ) trainer = Trainer(**trainer_options) model = LightningTestModel(hparams) # set the epoch start hook so we can predict before the model does the full training def assert_pred_same(): assert trainer.global_step == real_global_step and trainer.global_step > 0 # predict with loaded model to make sure answers are the same trainer.model.eval() new_pred = trainer.model(x) assert torch.all(torch.eq(pred_before_saving, new_pred)).item() == 1 model.on_epoch_start = assert_pred_same # by calling fit again, we trigger training, loading weights from the cluster # and our hook to predict using current model before any more weight updates trainer.fit(model) def test_multi_gpu_none_backend(tmpdir): """Make sure when using multiple GPUs the user can't use `distributed_backend = None`.""" tutils.reset_seed() if not tutils.can_run_gpu_test(): return model, hparams = tutils.get_default_model() trainer_options = dict( default_save_path=tmpdir, show_progress_bar=False, max_epochs=1, train_percent_check=0.1, val_percent_check=0.1, gpus='-1' ) with pytest.warns(UserWarning): tutils.run_model_test(trainer_options, model) def test_multi_gpu_model_dp(tmpdir): """Make sure DP works.""" tutils.reset_seed() if not tutils.can_run_gpu_test(): return model, hparams = tutils.get_default_model() trainer_options = dict( default_save_path=tmpdir, show_progress_bar=False, distributed_backend='dp', max_epochs=1, train_percent_check=0.1, val_percent_check=0.1, gpus='-1' ) tutils.run_model_test(trainer_options, model) # test memory helper functions memory.get_memory_profile('min_max') @pytest.fixture def mocked_device_count(monkeypatch): def device_count(): return PRETEND_N_OF_GPUS monkeypatch.setattr(torch.cuda, 'device_count', device_count) @pytest.fixture def mocked_device_count_0(monkeypatch): def device_count(): return 0 monkeypatch.setattr(torch.cuda, 'device_count', device_count) @pytest.mark.gpus_param_tests @pytest.mark.parametrize(["gpus", "expected_num_gpus", "distributed_backend"], [ pytest.param(None, 0, None, id="None - expect 0 gpu to use."), pytest.param(0, 0, None, id="Oth gpu, expect 1 gpu to use."), pytest.param(1, 1, None, id="1st gpu, expect 1 gpu to use."), pytest.param(-1, PRETEND_N_OF_GPUS, "ddp", id="-1 - use all gpus"), pytest.param('-1', PRETEND_N_OF_GPUS, "ddp", id="'-1' - use all gpus"), pytest.param(3, 3, "ddp", id="3rd gpu - 1 gpu to use (backend:ddp)") ]) def test_trainer_gpu_parse(mocked_device_count, gpus, expected_num_gpus, distributed_backend): assert Trainer(gpus=gpus, distributed_backend=distributed_backend).num_gpus == expected_num_gpus @pytest.mark.gpus_param_tests @pytest.mark.parametrize(["gpus", "expected_num_gpus", "distributed_backend"], [ pytest.param(None, 0, None, id="None - expect 0 gpu to use."), pytest.param(None, 0, "ddp", id="None - expect 0 gpu to use."), ]) def test_trainer_num_gpu_0(mocked_device_count_0, gpus, expected_num_gpus, distributed_backend): assert Trainer(gpus=gpus, distributed_backend=distributed_backend).num_gpus == expected_num_gpus @pytest.mark.gpus_param_tests @pytest.mark.parametrize(['gpus', 'expected_root_gpu', "distributed_backend"], [ pytest.param(None, None, "ddp", id="None is None"), pytest.param(0, None, "ddp", id="O gpus, expect gpu root device to be None."), pytest.param(1, 0, "ddp", id="1 gpu, expect gpu root device to be 0."), pytest.param(-1, 0, "ddp", id="-1 - use all gpus, expect gpu root device to be 0."), pytest.param('-1', 0, "ddp", id="'-1' - use all gpus, expect gpu root device to be 0."), pytest.param(3, 0, "ddp", id="3 gpus, expect gpu root device to be 0.(backend:ddp)") ]) def test_root_gpu_property(mocked_device_count, gpus, expected_root_gpu, distributed_backend): assert Trainer(gpus=gpus, distributed_backend=distributed_backend).root_gpu == expected_root_gpu @pytest.mark.gpus_param_tests @pytest.mark.parametrize([ 'gpus', 'expected_root_gpu', "distributed_backend"], [ pytest.param(None, None, None, id="None is None"), pytest.param(None, None, "ddp", id="None is None"), pytest.param(0, None, "ddp", id="None is None"), ]) def test_root_gpu_property_0_passing( mocked_device_count_0, gpus, expected_root_gpu, distributed_backend): assert Trainer(gpus=gpus, distributed_backend=distributed_backend).root_gpu == expected_root_gpu # Asking for a gpu when non are available will result in a MisconfigurationException @pytest.mark.gpus_param_tests @pytest.mark.parametrize([ 'gpus', 'expected_root_gpu', "distributed_backend"], [ pytest.param(1, None, "ddp"), pytest.param(3, None, "ddp"), pytest.param(3, None, "ddp"), pytest.param([1, 2], None, "ddp"), pytest.param([0, 1], None, "ddp"), pytest.param(-1, None, "ddp"), pytest.param('-1', None, "ddp") ]) def test_root_gpu_property_0_raising( mocked_device_count_0, gpus, expected_root_gpu, distributed_backend): with pytest.raises(MisconfigurationException): Trainer(gpus=gpus, distributed_backend=distributed_backend).root_gpu @pytest.mark.gpus_param_tests @pytest.mark.parametrize(['gpus', 'expected_root_gpu'], [ pytest.param(None, None, id="No gpus, expect gpu root device to be None"), pytest.param([0], 0, id="Oth gpu, expect gpu root device to be 0."), pytest.param([1], 1, id="1st gpu, expect gpu root device to be 1."), pytest.param([3], 3, id="3rd gpu, expect gpu root device to be 3."), pytest.param([1, 2], 1, id="[1, 2] gpus, expect gpu root device to be 1."), ]) def test_determine_root_gpu_device(gpus, expected_root_gpu): assert determine_root_gpu_device(gpus) == expected_root_gpu @pytest.mark.gpus_param_tests @pytest.mark.parametrize(['gpus', 'expected_gpu_ids'], [ pytest.param(None, None), pytest.param(0, None), pytest.param(1, [0]), pytest.param(3, [0, 1, 2]), pytest.param(-1, list(range(PRETEND_N_OF_GPUS)), id="-1 - use all gpus"), pytest.param([0], [0]), pytest.param([1, 3], [1, 3]), pytest.param('0', [0]), pytest.param('3', [3]), pytest.param('1, 3', [1, 3]), pytest.param('-1', list(range(PRETEND_N_OF_GPUS)), id="'-1' - use all gpus"), ]) def test_parse_gpu_ids(mocked_device_count, gpus, expected_gpu_ids): assert parse_gpu_ids(gpus) == expected_gpu_ids @pytest.mark.gpus_param_tests @pytest.mark.parametrize(['gpus'], [ pytest.param(0.1), pytest.param(-2), pytest.param(False), pytest.param([]), pytest.param([-1]), pytest.param([None]), pytest.param(['0']), pytest.param((0, 1)), ]) def test_parse_gpu_fail_on_unsupported_inputs(mocked_device_count, gpus): with pytest.raises(MisconfigurationException): parse_gpu_ids(gpus) @pytest.mark.gpus_param_tests @pytest.mark.parametrize("gpus", ['']) def test_parse_gpu_fail_on_empty_string(mocked_device_count, gpus): # This currently results in a ValueError instead of MisconfigurationException with pytest.raises(ValueError): parse_gpu_ids(gpus) @pytest.mark.gpus_param_tests @pytest.mark.parametrize("gpus", [[1, 2, 19], -1, '-1']) def test_parse_gpu_fail_on_non_existant_id(mocked_device_count_0, gpus): with pytest.raises(MisconfigurationException): parse_gpu_ids(gpus) @pytest.mark.gpus_param_tests def test_parse_gpu_fail_on_non_existant_id_2(mocked_device_count): with pytest.raises(MisconfigurationException): parse_gpu_ids([1, 2, 19]) @pytest.mark.gpus_param_tests @pytest.mark.parametrize("gpus", [-1, '-1']) def test_parse_gpu_returns_None_when_no_devices_are_available(mocked_device_count_0, gpus): with pytest.raises(MisconfigurationException): parse_gpu_ids(gpus) # if __name__ == '__main__': # pytest.main([__file__])
3,635
0
357
e6eae9d4ee68ccc71c708a9780a57c29e6399525
99
py
Python
goodocityAPI/apps.py
juansjimenez/goodocity-backend
77b2ab3f11047e2896e81358b8d8c63d7952b521
[ "MIT" ]
1
2020-09-26T02:27:05.000Z
2020-09-26T02:27:05.000Z
goodocityAPI/apps.py
juansjimenez/goodocity-backend
77b2ab3f11047e2896e81358b8d8c63d7952b521
[ "MIT" ]
null
null
null
goodocityAPI/apps.py
juansjimenez/goodocity-backend
77b2ab3f11047e2896e81358b8d8c63d7952b521
[ "MIT" ]
null
null
null
from django.apps import AppConfig
16.5
36
0.777778
from django.apps import AppConfig class GoodocityapiConfig(AppConfig): name = 'goodocityAPI'
0
41
23
b975ce79701ed12694c8ee7194a12a5b3297a9db
6,908
py
Python
src/sage/tests/french_book/integration_doctest.py
bopopescu/sage
2d495be78e0bdc7a0a635454290b27bb4f5f70f0
[ "BSL-1.0" ]
3
2019-07-15T13:48:24.000Z
2019-11-08T12:31:43.000Z
src/sage/tests/french_book/integration_doctest.py
bopopescu/sage
2d495be78e0bdc7a0a635454290b27bb4f5f70f0
[ "BSL-1.0" ]
2
2018-10-30T13:40:20.000Z
2020-07-23T12:13:30.000Z
src/sage/tests/french_book/integration_doctest.py
bopopescu/sage
2d495be78e0bdc7a0a635454290b27bb4f5f70f0
[ "BSL-1.0" ]
7
2021-11-08T10:01:59.000Z
2022-03-03T11:25:52.000Z
## -*- encoding: utf-8 -*- """ This file (./integration_doctest.sage) was *autogenerated* from ./integration.tex, with sagetex.sty version 2011/05/27 v2.3.1. It contains the contents of all the sageexample environments from this file. You should be able to doctest this file with: sage -t ./integration_doctest.sage It is always safe to delete this file; it is not used in typesetting your document. Sage example in ./integration.tex, line 44:: sage: x = var('x'); f(x) = exp(-x^2) * log(x) sage: N(integrate(f, x, 1, 3)) 0.035860294991267694 sage: plot(f, 1, 3, fill='axis') Graphics object consisting of 2 graphics primitives Sage example in ./integration.tex, line 103:: sage: fp = plot(f, 1, 3, color='red') sage: n = 4 sage: interp_points = [(1+2*u/(n-1), N(f(1+2*u/(n-1)))) ....: for u in range(n)] sage: A = PolynomialRing(RR, 'x') sage: pp = plot(A.lagrange_polynomial(interp_points), 1, 3, fill='axis') sage: show(fp+pp) Sage example in ./integration.tex, line 346:: sage: N(integrate(exp(-x^2)*log(x), x, 17, 42)) # rel tol 7e-15 2.5657285006962035e-127 Sage example in ./integration.tex, line 355:: sage: integrate(log(1+x)*x, x, 0, 1) 1/4 sage: N(integrate(log(1+x)*x, x, 0, 1)) 0.250000000000000 Sage example in ./integration.tex, line 372:: sage: numerical_integral(exp(-x^2)*log(x), 17, 42) # rel tol 7e-12 (2.5657285006962035e-127, 3.3540254049238093e-128) Sage example in ./integration.tex, line 394:: sage: numerical_integral(exp(-x^100), 0, 1.1) (0.99432585119150..., 4.0775730...e-09) sage: numerical_integral(exp(-x^100), 0, 1.1, algorithm='qng') (0.994327538576531..., 0.016840666914...) Sage example in ./integration.tex, line 404:: sage: integrate(exp(-x^2)*log(x), x, 17, 42) integrate(e^(-x^2)*log(x), x, 17, 42) Sage example in ./integration.tex, line 412:: sage: N(integrate(exp(-x^2)*log(x), x, 17, 42), 200) # rel tol 7e-15 2.5657285006962035e-127 Sage example in ./integration.tex, line 417:: sage: N(integrate(sin(x)*exp(cos(x)), x, 0, pi), 200) 2.3504023872876029137647637011912016303114359626681917404591 Sage example in ./integration.tex, line 430:: sage: sage.calculus.calculus.nintegral(sin(sin(x)), x, 0, 1) (0.430606103120690..., 4.78068810228705...e-15, 21, 0) Sage example in ./integration.tex, line 436:: sage: g(x) = sin(sin(x)) sage: g.nintegral(x, 0, 1) (0.430606103120690..., 4.78068810228705...e-15, 21, 0) Sage example in ./integration.tex, line 465:: sage: gp('intnum(x=17, 42, exp(-x^2)*log(x))') # rel tol 1e-17 2.5657285005610514829176211363206621657 E-127 Sage example in ./integration.tex, line 474:: sage: gp('intnum(x=0, 1, sin(sin(x)))') 0.430606103120690604912377355... sage: old_prec = gp.set_precision(50) sage: gp('intnum(x=0, 1, sin(sin(x)))') 0.43060610312069060491237735524846578643360804182200 Sage example in ./integration.tex, line 490:: sage: p = gp.set_precision(old_prec) # on remet la précision par défaut sage: gp('intnum(x=0, 1, x^(-1/2))') 1.99999999999999999999... Sage example in ./integration.tex, line 496:: sage: gp('intnum(x=[0, -1/2], 1, x^(-1/2))') 2.000000000000000000000000000... Sage example in ./integration.tex, line 504:: sage: gp('intnum(x=[0, -1/42], 1, x^(-1/2))') 1.99999999999999999999... Sage example in ./integration.tex, line 518:: sage: import mpmath sage: mpmath.mp.prec = 53 sage: mpmath.quad(lambda x: mpmath.sin(mpmath.sin(x)), [0, 1]) mpf('0.43060610312069059') Sage example in ./integration.tex, line 526:: sage: mpmath.mp.prec = 113 sage: mpmath.quad(lambda x: mpmath.sin(mpmath.sin(x)), [0, 1]) mpf('0.430606103120690604912377355248465809') sage: mpmath.mp.prec = 114 sage: mpmath.quad(lambda x: mpmath.sin(mpmath.sin(x)), [0, 1]) mpf('0.430606103120690604912377355248465785') Sage example in ./integration.tex, line 550:: sage: mpmath.quad(sin(sin(x)), [0, 1]) Traceback (most recent call last): ... TypeError: no canonical coercion from <type 'sage.libs.mpmath.ext_main.mpf'> to Symbolic Ring Sage example in ./integration.tex, line 565:: sage: g(x) = max_symbolic(sin(x), cos(x)) sage: mpmath.mp.prec = 100 sage: mpmath.quadts(lambda x: g(N(x, 100)), [0, 1]) mpf('0.873912416263035435957979086252') Sage example in ./integration.tex, line 574:: sage: mpmath.mp.prec = 170 sage: mpmath.quadts(lambda x: g(N(x, 190)), [0, 1]) mpf('0.87391090757400975205393005981962476344054148354188794') sage: N(sqrt(2) - cos(1), 100) 0.87391125650495533140075211677 Sage example in ./integration.tex, line 585:: sage: mpmath.quadts(lambda x: g(N(x, 170)), [0, mpmath.pi / 4, 1]) mpf('0.87391125650495533140075211676672147483736145475902551') Sage example in ./integration.tex, line 750:: sage: T = ode_solver() Sage example in ./integration.tex, line 761:: sage: def f_1(t,y,params): return [y[1],params[0]*(1-y[0]^2)*y[1]-y[0]] sage: T.function = f_1 Sage example in ./integration.tex, line 776:: sage: def j_1(t,y,params): ....: return [[0, 1], ....: [-2*params[0]*y[0]*y[1]-1, params[0]*(1-y[0]^2)], ....: [0,0]] sage: T.jacobian = j_1 Sage example in ./integration.tex, line 786:: sage: T.algorithm = "rk8pd" sage: T.ode_solve(y_0=[1,0], t_span=[0,100], params=[10], ....: num_points=1000) sage: f = T.interpolate_solution() Sage example in ./integration.tex, line 801:: sage: plot(f, 0, 100) Graphics object consisting of 1 graphics primitive Sage example in ./integration.tex, line 838:: sage: t, y = var('t, y') sage: desolve_rk4(t*y*(2-y), y, ics=[0,1], end_points=[0, 1], step=0.5) [[0, 1], [0.5, 1.12419127424558], [1.0, 1.461590162288825]] Sage example in ./integration.tex, line 861:: sage: import mpmath sage: mpmath.mp.prec = 53 sage: sol = mpmath.odefun(lambda t, y: y, 0, 1) sage: sol(1) mpf('2.7182818284590451') sage: mpmath.mp.prec = 100 sage: sol(1) mpf('2.7182818284590452353602874802307') sage: N(exp(1), 100) 2.7182818284590452353602874714 Sage example in ./integration.tex, line 889:: sage: mpmath.mp.prec = 53 sage: f = mpmath.odefun(lambda t, y: [-y[1], y[0]], 0, [1, 0]) sage: f(3) [mpf('-0.98999249660044542'), mpf('0.14112000805986721')] sage: (cos(3.), sin(3.)) (-0.989992496600445, 0.141120008059867) Sage example in ./integration.tex, line 939:: sage: mpmath.mp.prec = 10 sage: sol = mpmath.odefun(lambda t, y: y, 0, 1) sage: sol(1) mpf('2.7148') sage: mpmath.mp.prec = 100 sage: sol(1) mpf('2.7135204235459511323824699502438') """ # This file was *autogenerated* from the file integration_doctest.sage.
31.257919
82
0.640562
## -*- encoding: utf-8 -*- """ This file (./integration_doctest.sage) was *autogenerated* from ./integration.tex, with sagetex.sty version 2011/05/27 v2.3.1. It contains the contents of all the sageexample environments from this file. You should be able to doctest this file with: sage -t ./integration_doctest.sage It is always safe to delete this file; it is not used in typesetting your document. Sage example in ./integration.tex, line 44:: sage: x = var('x'); f(x) = exp(-x^2) * log(x) sage: N(integrate(f, x, 1, 3)) 0.035860294991267694 sage: plot(f, 1, 3, fill='axis') Graphics object consisting of 2 graphics primitives Sage example in ./integration.tex, line 103:: sage: fp = plot(f, 1, 3, color='red') sage: n = 4 sage: interp_points = [(1+2*u/(n-1), N(f(1+2*u/(n-1)))) ....: for u in range(n)] sage: A = PolynomialRing(RR, 'x') sage: pp = plot(A.lagrange_polynomial(interp_points), 1, 3, fill='axis') sage: show(fp+pp) Sage example in ./integration.tex, line 346:: sage: N(integrate(exp(-x^2)*log(x), x, 17, 42)) # rel tol 7e-15 2.5657285006962035e-127 Sage example in ./integration.tex, line 355:: sage: integrate(log(1+x)*x, x, 0, 1) 1/4 sage: N(integrate(log(1+x)*x, x, 0, 1)) 0.250000000000000 Sage example in ./integration.tex, line 372:: sage: numerical_integral(exp(-x^2)*log(x), 17, 42) # rel tol 7e-12 (2.5657285006962035e-127, 3.3540254049238093e-128) Sage example in ./integration.tex, line 394:: sage: numerical_integral(exp(-x^100), 0, 1.1) (0.99432585119150..., 4.0775730...e-09) sage: numerical_integral(exp(-x^100), 0, 1.1, algorithm='qng') (0.994327538576531..., 0.016840666914...) Sage example in ./integration.tex, line 404:: sage: integrate(exp(-x^2)*log(x), x, 17, 42) integrate(e^(-x^2)*log(x), x, 17, 42) Sage example in ./integration.tex, line 412:: sage: N(integrate(exp(-x^2)*log(x), x, 17, 42), 200) # rel tol 7e-15 2.5657285006962035e-127 Sage example in ./integration.tex, line 417:: sage: N(integrate(sin(x)*exp(cos(x)), x, 0, pi), 200) 2.3504023872876029137647637011912016303114359626681917404591 Sage example in ./integration.tex, line 430:: sage: sage.calculus.calculus.nintegral(sin(sin(x)), x, 0, 1) (0.430606103120690..., 4.78068810228705...e-15, 21, 0) Sage example in ./integration.tex, line 436:: sage: g(x) = sin(sin(x)) sage: g.nintegral(x, 0, 1) (0.430606103120690..., 4.78068810228705...e-15, 21, 0) Sage example in ./integration.tex, line 465:: sage: gp('intnum(x=17, 42, exp(-x^2)*log(x))') # rel tol 1e-17 2.5657285005610514829176211363206621657 E-127 Sage example in ./integration.tex, line 474:: sage: gp('intnum(x=0, 1, sin(sin(x)))') 0.430606103120690604912377355... sage: old_prec = gp.set_precision(50) sage: gp('intnum(x=0, 1, sin(sin(x)))') 0.43060610312069060491237735524846578643360804182200 Sage example in ./integration.tex, line 490:: sage: p = gp.set_precision(old_prec) # on remet la précision par défaut sage: gp('intnum(x=0, 1, x^(-1/2))') 1.99999999999999999999... Sage example in ./integration.tex, line 496:: sage: gp('intnum(x=[0, -1/2], 1, x^(-1/2))') 2.000000000000000000000000000... Sage example in ./integration.tex, line 504:: sage: gp('intnum(x=[0, -1/42], 1, x^(-1/2))') 1.99999999999999999999... Sage example in ./integration.tex, line 518:: sage: import mpmath sage: mpmath.mp.prec = 53 sage: mpmath.quad(lambda x: mpmath.sin(mpmath.sin(x)), [0, 1]) mpf('0.43060610312069059') Sage example in ./integration.tex, line 526:: sage: mpmath.mp.prec = 113 sage: mpmath.quad(lambda x: mpmath.sin(mpmath.sin(x)), [0, 1]) mpf('0.430606103120690604912377355248465809') sage: mpmath.mp.prec = 114 sage: mpmath.quad(lambda x: mpmath.sin(mpmath.sin(x)), [0, 1]) mpf('0.430606103120690604912377355248465785') Sage example in ./integration.tex, line 550:: sage: mpmath.quad(sin(sin(x)), [0, 1]) Traceback (most recent call last): ... TypeError: no canonical coercion from <type 'sage.libs.mpmath.ext_main.mpf'> to Symbolic Ring Sage example in ./integration.tex, line 565:: sage: g(x) = max_symbolic(sin(x), cos(x)) sage: mpmath.mp.prec = 100 sage: mpmath.quadts(lambda x: g(N(x, 100)), [0, 1]) mpf('0.873912416263035435957979086252') Sage example in ./integration.tex, line 574:: sage: mpmath.mp.prec = 170 sage: mpmath.quadts(lambda x: g(N(x, 190)), [0, 1]) mpf('0.87391090757400975205393005981962476344054148354188794') sage: N(sqrt(2) - cos(1), 100) 0.87391125650495533140075211677 Sage example in ./integration.tex, line 585:: sage: mpmath.quadts(lambda x: g(N(x, 170)), [0, mpmath.pi / 4, 1]) mpf('0.87391125650495533140075211676672147483736145475902551') Sage example in ./integration.tex, line 750:: sage: T = ode_solver() Sage example in ./integration.tex, line 761:: sage: def f_1(t,y,params): return [y[1],params[0]*(1-y[0]^2)*y[1]-y[0]] sage: T.function = f_1 Sage example in ./integration.tex, line 776:: sage: def j_1(t,y,params): ....: return [[0, 1], ....: [-2*params[0]*y[0]*y[1]-1, params[0]*(1-y[0]^2)], ....: [0,0]] sage: T.jacobian = j_1 Sage example in ./integration.tex, line 786:: sage: T.algorithm = "rk8pd" sage: T.ode_solve(y_0=[1,0], t_span=[0,100], params=[10], ....: num_points=1000) sage: f = T.interpolate_solution() Sage example in ./integration.tex, line 801:: sage: plot(f, 0, 100) Graphics object consisting of 1 graphics primitive Sage example in ./integration.tex, line 838:: sage: t, y = var('t, y') sage: desolve_rk4(t*y*(2-y), y, ics=[0,1], end_points=[0, 1], step=0.5) [[0, 1], [0.5, 1.12419127424558], [1.0, 1.461590162288825]] Sage example in ./integration.tex, line 861:: sage: import mpmath sage: mpmath.mp.prec = 53 sage: sol = mpmath.odefun(lambda t, y: y, 0, 1) sage: sol(1) mpf('2.7182818284590451') sage: mpmath.mp.prec = 100 sage: sol(1) mpf('2.7182818284590452353602874802307') sage: N(exp(1), 100) 2.7182818284590452353602874714 Sage example in ./integration.tex, line 889:: sage: mpmath.mp.prec = 53 sage: f = mpmath.odefun(lambda t, y: [-y[1], y[0]], 0, [1, 0]) sage: f(3) [mpf('-0.98999249660044542'), mpf('0.14112000805986721')] sage: (cos(3.), sin(3.)) (-0.989992496600445, 0.141120008059867) Sage example in ./integration.tex, line 939:: sage: mpmath.mp.prec = 10 sage: sol = mpmath.odefun(lambda t, y: y, 0, 1) sage: sol(1) mpf('2.7148') sage: mpmath.mp.prec = 100 sage: sol(1) mpf('2.7135204235459511323824699502438') """ # This file was *autogenerated* from the file integration_doctest.sage.
0
0
0
625ef7eed497f262e56e5bba6003fd8511f923b6
2,568
py
Python
apps/bookstore/migrations/0001_initial.py
goutomroy/django_select_prefetch_related
489d7e058c6283b52c8b2690aaff0dfed93cfc07
[ "Apache-2.0" ]
17
2019-12-11T11:02:01.000Z
2021-10-06T11:58:23.000Z
apps/bookstore/migrations/0001_initial.py
goutomroy/django_select_prefetch_related
489d7e058c6283b52c8b2690aaff0dfed93cfc07
[ "Apache-2.0" ]
8
2019-12-04T23:09:42.000Z
2021-06-10T17:45:57.000Z
apps/bookstore/migrations/0001_initial.py
goutomroy/django_select_prefetch_related
489d7e058c6283b52c8b2690aaff0dfed93cfc07
[ "Apache-2.0" ]
7
2019-12-11T11:02:06.000Z
2021-10-06T09:55:25.000Z
# Generated by Django 3.0.2 on 2020-07-21 00:58 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
40.125
148
0.593458
# Generated by Django 3.0.2 on 2020-07-21 00:58 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=300)), ('price', models.IntegerField(default=0)), ], ), migrations.CreateModel( name='BookInStore', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('added', models.DateTimeField(auto_now_add=True)), ('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='bookstore.Book')), ], ), migrations.CreateModel( name='Store', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=300)), ('books', models.ManyToManyField(related_name='stores', through='bookstore.BookInStore', to='bookstore.Book')), ], ), migrations.CreateModel( name='Publisher', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=300)), ('owner', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='publisher', to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='bookinstore', name='store', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='bookstore.Store'), ), migrations.AddField( model_name='book', name='publisher', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='books', to='bookstore.Publisher'), ), migrations.AddConstraint( model_name='bookinstore', constraint=models.UniqueConstraint(fields=('book', 'store'), name='a book can be added in a store only once.'), ), ]
0
2,388
23
0f091f16a19a47d5d8e327b5b69ae8e7dc948189
114
py
Python
multimeter/__init__.py
wowace/multimeter
24eed9cd59819a27c110b10c637e14735b29710f
[ "MIT" ]
null
null
null
multimeter/__init__.py
wowace/multimeter
24eed9cd59819a27c110b10c637e14735b29710f
[ "MIT" ]
48
2018-03-02T14:57:01.000Z
2020-02-13T10:08:12.000Z
multimeter/__init__.py
kafitimi/multimeter
24eed9cd59819a27c110b10c637e14735b29710f
[ "MIT" ]
null
null
null
""" Заголовок пакета """ default_app_config = 'multimeter.apps.MultimeterConfig' # pylint: disable=invalid-name
28.5
87
0.763158
""" Заголовок пакета """ default_app_config = 'multimeter.apps.MultimeterConfig' # pylint: disable=invalid-name
0
0
0
1fa3a09416c6649076d6bef859c6fa35a7ef1972
2,256
py
Python
C3CTF/2019 36C3/bacon/brute.py
PurpEth/solved-hacking-problem
6f289d1647eb9c091caa580c7aae673e3ba02952
[ "Unlicense" ]
1
2021-08-24T22:16:41.000Z
2021-08-24T22:16:41.000Z
C3CTF/2019 36C3/bacon/brute.py
PurpEth/solved-hacking-problem
6f289d1647eb9c091caa580c7aae673e3ba02952
[ "Unlicense" ]
null
null
null
C3CTF/2019 36C3/bacon/brute.py
PurpEth/solved-hacking-problem
6f289d1647eb9c091caa580c7aae673e3ba02952
[ "Unlicense" ]
null
null
null
#!/usr/bin/env python3 import itertools import sys MASK = 0xffffff # did I implement this correctly? assert forward(*map(bytes.fromhex, ('1211100a0908020100', '20796c6c6172'))) == b'\xc0\x49\xa5\x38\x5a\xdc' if len(sys.argv) < 2: print(f"Usage: python3 {sys.argv[0]} <hex>") exit(1) target = bytes.fromhex(sys.argv[1]) key = (18).to_bytes(9, 'big') start = bytes(6) end = backward(key, target) assert(forward(key, end) == target) forward_dict = {} backward_dict = {} all_bytes = [i.to_bytes(1, 'big') for i in range(256)] for k in itertools.product(all_bytes, repeat=9): key = b''.join(k) f = forward(key, start) forward_dict[f] = key if f in backward_dict: ans = key + backward_dict[f] break b = backward(key, end) backward_dict[b] = key if b in forward_dict: ans = forward_dict[b] + key break print(ans.hex()) assert H(ans) == target
26.541176
84
0.51906
#!/usr/bin/env python3 import itertools import sys MASK = 0xffffff def forward(key, blk): assert tuple(map(len, (key, blk))) == (9, 6) def S(j, v): return (v << j | (v & MASK) >> 24-j) & MASK ws = blk[:3], blk[3:], key[:3], key[3:6], key[6:] x, y, l1, l0, k0 = (int.from_bytes(w, 'big') for w in ws) l, k = [l0, l1], [k0] for i in range(21): l.append((S(16, l[i]) + k[i] ^ i) & MASK) k.append(S(3, k[i]) ^ l[-1]) for i in range(22): x = (S(16, x) + y ^ k[i]) & MASK y = (S(3, y) ^ x) & MASK return b''.join(z.to_bytes(3, 'big') for z in (x, y)) def backward(key, cipher): assert tuple(map(len, (key, cipher))) == (9, 6) def S(j, v): return (v << j | (v & MASK) >> 24-j) & MASK ws = cipher[:3], cipher[3:], key[:3], key[3:6], key[6:] x, y, l1, l0, k0 = (int.from_bytes(w, 'big') for w in ws) l, k = [l0, l1], [k0] for i in range(21): l.append((S(16, l[i]) + k[i] ^ i) & MASK) k.append(S(3, k[i]) ^ l[-1]) for i in range(21, -1, -1): y = S(21, y ^ x) x = S(8, (x ^ k[i]) - y) x, y = (z & 0xffffff for z in (x, y)) return b''.join(z.to_bytes(3, 'big') for z in (x, y)) # did I implement this correctly? assert forward(*map(bytes.fromhex, ('1211100a0908020100', '20796c6c6172'))) == b'\xc0\x49\xa5\x38\x5a\xdc' def H(m): s = bytes(6) v = m + bytes(-len(m) % 9) + len(m).to_bytes(9, 'big') for i in range(0, len(v), 9): s = forward(v[i:i+9], s) return s if len(sys.argv) < 2: print(f"Usage: python3 {sys.argv[0]} <hex>") exit(1) target = bytes.fromhex(sys.argv[1]) key = (18).to_bytes(9, 'big') start = bytes(6) end = backward(key, target) assert(forward(key, end) == target) forward_dict = {} backward_dict = {} all_bytes = [i.to_bytes(1, 'big') for i in range(256)] for k in itertools.product(all_bytes, repeat=9): key = b''.join(k) f = forward(key, start) forward_dict[f] = key if f in backward_dict: ans = key + backward_dict[f] break b = backward(key, end) backward_dict[b] = key if b in forward_dict: ans = forward_dict[b] + key break print(ans.hex()) assert H(ans) == target
1,231
0
69
ae68e1d05aa2cc50e49cb492dc00efe34def4ab5
879
py
Python
day-7-finding-the-percentage.py
roshansinghbisht/hello-python
595418a47e66217ed8759c91cdb535e8fa88412b
[ "MIT" ]
null
null
null
day-7-finding-the-percentage.py
roshansinghbisht/hello-python
595418a47e66217ed8759c91cdb535e8fa88412b
[ "MIT" ]
null
null
null
day-7-finding-the-percentage.py
roshansinghbisht/hello-python
595418a47e66217ed8759c91cdb535e8fa88412b
[ "MIT" ]
null
null
null
if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() average = sum(student_marks[query_name])/ len(student_marks[query_name]) print("{:.2f}".format(average)) # Passing an integer after the ':' will cause that field to be a minimum # number of characters wide. # str.format(): Perform a string formatting operation. The string on which # this method is called can contain literal text or replacement fields # delimited by braces {}. Each replacement field contains either the # numeric index of a positional argument, or the name of a keyword # argument. Returns a copy of the string where each replacement field is # replaced with the string value of the corresponding argument.
41.857143
76
0.701934
if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() average = sum(student_marks[query_name])/ len(student_marks[query_name]) print("{:.2f}".format(average)) # Passing an integer after the ':' will cause that field to be a minimum # number of characters wide. # str.format(): Perform a string formatting operation. The string on which # this method is called can contain literal text or replacement fields # delimited by braces {}. Each replacement field contains either the # numeric index of a positional argument, or the name of a keyword # argument. Returns a copy of the string where each replacement field is # replaced with the string value of the corresponding argument.
0
0
0
30ed6383084d2cfbd8d6b41733e49f997dcaedcb
96
py
Python
venv/lib/python3.8/site-packages/past/types/basestring.py
Retraces/UkraineBot
3d5d7f8aaa58fa0cb8b98733b8808e5dfbdb8b71
[ "MIT" ]
2
2022-03-13T01:58:52.000Z
2022-03-31T06:07:54.000Z
venv/lib/python3.8/site-packages/past/types/basestring.py
DesmoSearch/Desmobot
b70b45df3485351f471080deb5c785c4bc5c4beb
[ "MIT" ]
19
2021-11-20T04:09:18.000Z
2022-03-23T15:05:55.000Z
venv/lib/python3.8/site-packages/past/types/basestring.py
DesmoSearch/Desmobot
b70b45df3485351f471080deb5c785c4bc5c4beb
[ "MIT" ]
null
null
null
/home/runner/.cache/pip/pool/aa/b2/26/72bdb8c2f74308cbc5f71d13cb1f12d650ade8623046fcee026be0fd38
96
96
0.895833
/home/runner/.cache/pip/pool/aa/b2/26/72bdb8c2f74308cbc5f71d13cb1f12d650ade8623046fcee026be0fd38
0
0
0
8f4929cdba696e92236ff3ff30c4593997b2dc01
9,400
py
Python
scripts/nasqm.py
PotentialParadox/pynasqm
1bd51299b6ca7f8229d8a15428515d53a358903c
[ "MIT" ]
1
2020-03-13T22:34:03.000Z
2020-03-13T22:34:03.000Z
scripts/nasqm.py
PotentialParadox/pynasqm
1bd51299b6ca7f8229d8a15428515d53a358903c
[ "MIT" ]
null
null
null
scripts/nasqm.py
PotentialParadox/pynasqm
1bd51299b6ca7f8229d8a15428515d53a358903c
[ "MIT" ]
null
null
null
''' Run NASQM created by Dustin Tracy (dtracy.uf@gmail.com) This program is used to automate NASQM job creations. You'll find the parameters to change in the file nasqm_user_input.py ''' import argparse import time from pynasqm.initialize import initialize from pynasqm.inputceon import InputCeon from pynasqm.write import (write_omega_vs_time, write_spectra_flu_input, write_average_coeffs) from pynasqm.spectracollection import write_spectra_input from pynasqm.userinput import UserInput from pynasqm.trajectories.qmgroundstatetrajectories import QmGroundTrajectories from pynasqm.trajectories.qmexcitedstatetrajectories import QmExcitedStateTrajectories from pynasqm.trajectories.pulsepump import PulsePump from pynasqm.initialexcitedstates import get_energies_and_strenghts from pynasqm.trajectories.mmgroundstatetrajectory import groundStateDynamics from pynasqm.trajectories.absorptionsnaps import AbsorptionSnaps from pynasqm.trajectories.fluorescencesnaps import FluorescenceSnaps from pynasqm.sed import sed_inplace, sed_global from pynasqm.nasqmslurm import restart_nasqm from pynasqm.trajectories.combine_trajectories import combine_trajectories from pynasqm.collect_coeffs import collect_coeffs import subprocess def main(): ''' The primary nasqm automation function call. All changable parameters can be found in userinput.py ''' parser = argparse.ArgumentParser() parser.add_argument("--init", help="initialize the directory for nasqm", action="store_true") parser.add_argument("--job", help="0-ground, 1-qmground, 2-qmexcited", default=0, type=int) parser.add_argument("--restart", help="restart attempt, 0 for first run", default=0, type=int) args = parser.parse_args() if args.init: title_print('Initializing Directory') print("Amber Input File: md_qmmm_amb.in") print("NEXMD Input File: input.ceon") print("PYNASQM Input File: pynasqm.in") print("Please rename your coordinate file to m1_md2.rst") print("Please rename your parmtop file to m1.prmtop") initialize() exit() user_input = UserInput() user_input.restart_attempt = args.restart if args.restart != 0: if args.job > 0: user_input.run_ground_state_dynamics = False if args.job > 1: user_input.run_qmground_trajectories = False user_input.run_absorption_collection = False original_inputs = copy_inputs() input_ceon = create_input(user_input) start_time = time.time() if user_input.run_ground_state_dynamics: run_mm_ground_state_dynamics(input_ceon, user_input) if user_input.run_qmground_trajectories: run_qm_ground_state_trajectories(input_ceon, user_input) if user_input.run_absorption_snapshots: run_absorption_snaps(input_ceon, user_input) if user_input.run_absorption_collection: run_absorption_collection(user_input) if should_perform_pulse_pump(user_input, args.restart): run_pulse_pump_prep(input_ceon, user_input) if should_perform_pulse_pump_collection(user_input, args.restart): run_pulse_pump_prep_collection(input_ceon, user_input) if user_input.run_excited_state_trajectories: run_excited_state_trajectories(input_ceon, user_input) if user_input.run_fluorescence_snapshots: run_fluorescence_snaps(input_ceon, user_input) if user_input.run_fluorescence_collection: run_fluorescence_collection(user_input) if not user_input.is_hpc: restore_inputs(original_inputs) input_ceon.write_log() end_time = time.time() print("Job finished in %s seconds" % (end_time - start_time)) def run_mm_ground_state_dynamics(md_qmmm_amb, user_input): ''' Run the ground state trajectory that will be used to generate initial geometries for future calculations ''' title_print("MM Ground-State Trajectory") groundStateDynamics(md_qmmm_amb, user_input) manage_restart(0, user_input, user_input.restart_attempt) def run_qm_ground_state_trajectories(input_ceon, user_input): ''' Now we want to take the original trajectory snapshots and run more trajectories using random velocities to make them different from each other ''' title_print("QM Ground-State Trajectories") QmGroundTrajectories(user_input, input_ceon).run() manage_restart(1, user_input, user_input.restart_attempt) def run_absorption_snaps(input_ceon, user_input): ''' Take snapshots from the qmground trajectories ignoring a time delay. Run singlepoints on these snaphsots ''' title_print("Absorption Snaps") AbsorptionSnaps(user_input, input_ceon).run() def run_absorption_collection(user_input): ''' Parse the output data from amber for absorption energies and create a spectra_abs.input file ''' title_print("Absorption Parsing") write_spectra_input(user_input, 'absorption') energies, strengths = get_energies_and_strenghts('spectra_absorption.input') print_energies_and_strengths(energies, strengths) def run_excited_state_trajectories(input_ceon, user_input): ''' We take the original trajectory snapshots and run further trajectories from those at the excited state ''' print("!!!!!!!!!!!!!!!!!!!! Running Excited States !!!!!!!!!!!!!!!!!!!!") QmExcitedStateTrajectories(user_input, input_ceon).run() manage_restart(2, user_input, user_input.restart_attempt) if user_input.is_tully: collect_coeffs( number_trajectories=user_input.n_snapshots_ex, number_restarts=user_input.n_exc_runs - 1 ) def run_fluorescence_snaps(input_ceon, user_input): ''' Take snapshots from the qmground trajectories ignoring a time delay. Run singlepoints on these snaphsots ''' title_print("Fluorescence Snaps") FluorescenceSnaps(user_input, input_ceon).run() def run_fluorescence_collection(user_input): ''' Parse the output data from amber for fluorescene energies and create a spectra_flu.input file ''' print("!!!!!!!!!!!!!!!!!!!! Parsing Fluorescences !!!!!!!!!!!!!!!!!!!!") # combine_trajectories("qmexcited", user_input.n_snapshots_ex, user_input.n_exc_runs) exc_state_init = user_input.exc_state_init_ex_param exc_state_prop = user_input.n_exc_states_propagate_ex_param n_completed = write_spectra_flu_input(user_input) write_omega_vs_time(n_trajectories=n_completed, n_states=exc_state_init) if user_input.is_tully: write_average_coeffs(n_trajectories=user_input.n_snapshots_ex, n_states=exc_state_prop) try: main() except KeyboardInterrupt: print("You canceled the operation")
38.683128
98
0.738191
''' Run NASQM created by Dustin Tracy (dtracy.uf@gmail.com) This program is used to automate NASQM job creations. You'll find the parameters to change in the file nasqm_user_input.py ''' import argparse import time from pynasqm.initialize import initialize from pynasqm.inputceon import InputCeon from pynasqm.write import (write_omega_vs_time, write_spectra_flu_input, write_average_coeffs) from pynasqm.spectracollection import write_spectra_input from pynasqm.userinput import UserInput from pynasqm.trajectories.qmgroundstatetrajectories import QmGroundTrajectories from pynasqm.trajectories.qmexcitedstatetrajectories import QmExcitedStateTrajectories from pynasqm.trajectories.pulsepump import PulsePump from pynasqm.initialexcitedstates import get_energies_and_strenghts from pynasqm.trajectories.mmgroundstatetrajectory import groundStateDynamics from pynasqm.trajectories.absorptionsnaps import AbsorptionSnaps from pynasqm.trajectories.fluorescencesnaps import FluorescenceSnaps from pynasqm.sed import sed_inplace, sed_global from pynasqm.nasqmslurm import restart_nasqm from pynasqm.trajectories.combine_trajectories import combine_trajectories from pynasqm.collect_coeffs import collect_coeffs import subprocess def main(): ''' The primary nasqm automation function call. All changable parameters can be found in userinput.py ''' parser = argparse.ArgumentParser() parser.add_argument("--init", help="initialize the directory for nasqm", action="store_true") parser.add_argument("--job", help="0-ground, 1-qmground, 2-qmexcited", default=0, type=int) parser.add_argument("--restart", help="restart attempt, 0 for first run", default=0, type=int) args = parser.parse_args() if args.init: title_print('Initializing Directory') print("Amber Input File: md_qmmm_amb.in") print("NEXMD Input File: input.ceon") print("PYNASQM Input File: pynasqm.in") print("Please rename your coordinate file to m1_md2.rst") print("Please rename your parmtop file to m1.prmtop") initialize() exit() user_input = UserInput() user_input.restart_attempt = args.restart if args.restart != 0: if args.job > 0: user_input.run_ground_state_dynamics = False if args.job > 1: user_input.run_qmground_trajectories = False user_input.run_absorption_collection = False original_inputs = copy_inputs() input_ceon = create_input(user_input) start_time = time.time() if user_input.run_ground_state_dynamics: run_mm_ground_state_dynamics(input_ceon, user_input) if user_input.run_qmground_trajectories: run_qm_ground_state_trajectories(input_ceon, user_input) if user_input.run_absorption_snapshots: run_absorption_snaps(input_ceon, user_input) if user_input.run_absorption_collection: run_absorption_collection(user_input) if should_perform_pulse_pump(user_input, args.restart): run_pulse_pump_prep(input_ceon, user_input) if should_perform_pulse_pump_collection(user_input, args.restart): run_pulse_pump_prep_collection(input_ceon, user_input) if user_input.run_excited_state_trajectories: run_excited_state_trajectories(input_ceon, user_input) if user_input.run_fluorescence_snapshots: run_fluorescence_snaps(input_ceon, user_input) if user_input.run_fluorescence_collection: run_fluorescence_collection(user_input) if not user_input.is_hpc: restore_inputs(original_inputs) input_ceon.write_log() end_time = time.time() print("Job finished in %s seconds" % (end_time - start_time)) def should_perform_pulse_pump(user_input, restart): return ( user_input.run_pulse_pump_singlepoints and restart == 0 ) def should_perform_pulse_pump_collection(user_input, restart): return ( user_input.run_pulse_pump_collection and restart == 0 ) def create_input(user_input): input_ceon = InputCeon(amber_input='md_qmmm_amb.in', directory='./') input_ceon.set_periodic(user_input.is_qmmm, user_input.constant_value) return input_ceon def copy_inputs(): input_ceon_bac = open('input.ceon', 'r').read() md_qmmm_amb = open('md_qmmm_amb.in', 'r').read() return [input_ceon_bac, md_qmmm_amb] def restore_inputs(origninal_inputs): open('input.ceon', 'w').write(origninal_inputs[0]) open('md_qmmm_amb.in', 'w').write(origninal_inputs[1]) def should_restart(n_runs, restart_attempt): if restart_attempt + 1 >= n_runs: return False return True def restart(user_input, job_id, restart_attempt): if user_input.is_hpc: restart_nasqm(user_input, job_id, restart_attempt) else: restart_for_pc(job_id, restart_attempt) exit() def restart_for_pc(job_id, restart_attempt): subprocess.call(["nasqm.py", "--job", "{}".format(job_id), "--restart", "{}".format(restart_attempt)]) def manage_restart(job_id, user_input, restart_attempt): runs = [user_input.n_ground_runs, user_input.n_qmground_runs, user_input.n_exc_runs] n_runs = runs[job_id] job_desciption = ["mmground", "qmground", "qmexcited"] if should_restart(n_runs, restart_attempt): print(f"restarting with {job_desciption[job_id]}\n") restart(user_input, job_id, restart_attempt+1) user_input.restart_attempt = 0 def title_print(label): break_width = 80 offset = int(break_width/2) - int(len(label)/2) break_line = "!"*break_width + "\n" info_line = "!" + " "*offset + label + "\n" print(break_line + info_line + break_line) def run_mm_ground_state_dynamics(md_qmmm_amb, user_input): ''' Run the ground state trajectory that will be used to generate initial geometries for future calculations ''' title_print("MM Ground-State Trajectory") groundStateDynamics(md_qmmm_amb, user_input) manage_restart(0, user_input, user_input.restart_attempt) def run_qm_ground_state_trajectories(input_ceon, user_input): ''' Now we want to take the original trajectory snapshots and run more trajectories using random velocities to make them different from each other ''' title_print("QM Ground-State Trajectories") QmGroundTrajectories(user_input, input_ceon).run() manage_restart(1, user_input, user_input.restart_attempt) def run_absorption_snaps(input_ceon, user_input): ''' Take snapshots from the qmground trajectories ignoring a time delay. Run singlepoints on these snaphsots ''' title_print("Absorption Snaps") AbsorptionSnaps(user_input, input_ceon).run() def run_absorption_collection(user_input): ''' Parse the output data from amber for absorption energies and create a spectra_abs.input file ''' title_print("Absorption Parsing") write_spectra_input(user_input, 'absorption') energies, strengths = get_energies_and_strenghts('spectra_absorption.input') print_energies_and_strengths(energies, strengths) def print_energies_and_strengths(energies, strengths): with open('absorption_summary.txt', 'w') as fout: fout.write('Energies and Strengths\n') for i, (e, s) in enumerate(zip(energies, strengths)): fout.write('State {}: Energy:{:14.10f}, Strength: {:14.10f}\n'.format(i+1, e, s)) def run_pulse_pump_prep(input_ceon, user_input): title_print("Performing Pulse Pump Single Points") PulsePump(user_input, input_ceon).run() def run_pulse_pump_prep_collection(input_ceon, user_input): title_print("Performing Pulse Pump Collection") PulsePump(user_input, input_ceon).write_pulse_pump_states() write_spectra_input(user_input, 'pulse_pump') def run_excited_state_trajectories(input_ceon, user_input): ''' We take the original trajectory snapshots and run further trajectories from those at the excited state ''' print("!!!!!!!!!!!!!!!!!!!! Running Excited States !!!!!!!!!!!!!!!!!!!!") QmExcitedStateTrajectories(user_input, input_ceon).run() manage_restart(2, user_input, user_input.restart_attempt) if user_input.is_tully: collect_coeffs( number_trajectories=user_input.n_snapshots_ex, number_restarts=user_input.n_exc_runs - 1 ) def run_fluorescence_snaps(input_ceon, user_input): ''' Take snapshots from the qmground trajectories ignoring a time delay. Run singlepoints on these snaphsots ''' title_print("Fluorescence Snaps") FluorescenceSnaps(user_input, input_ceon).run() def run_fluorescence_collection(user_input): ''' Parse the output data from amber for fluorescene energies and create a spectra_flu.input file ''' print("!!!!!!!!!!!!!!!!!!!! Parsing Fluorescences !!!!!!!!!!!!!!!!!!!!") # combine_trajectories("qmexcited", user_input.n_snapshots_ex, user_input.n_exc_runs) exc_state_init = user_input.exc_state_init_ex_param exc_state_prop = user_input.n_exc_states_propagate_ex_param n_completed = write_spectra_flu_input(user_input) write_omega_vs_time(n_trajectories=n_completed, n_states=exc_state_init) if user_input.is_tully: write_average_coeffs(n_trajectories=user_input.n_snapshots_ex, n_states=exc_state_prop) try: main() except KeyboardInterrupt: print("You canceled the operation")
2,373
0
299
4a8b715fe771ab67480fb9b37145118295310381
224
py
Python
run_gunicorn.py
SlideAtlas/SlideAtlas-Server
3b9cbd56eaa29ae08ae521e75616ea230fe26397
[ "Apache-2.0" ]
3
2015-10-10T10:17:26.000Z
2020-12-14T09:42:19.000Z
run_gunicorn.py
SlideAtlas/SlideAtlas-Server
3b9cbd56eaa29ae08ae521e75616ea230fe26397
[ "Apache-2.0" ]
41
2015-02-03T19:47:28.000Z
2017-02-06T23:24:26.000Z
run_gunicorn.py
SlideAtlas/SlideAtlas-Server
3b9cbd56eaa29ae08ae521e75616ea230fe26397
[ "Apache-2.0" ]
2
2016-04-04T18:23:27.000Z
2017-11-14T22:34:58.000Z
# coding=utf-8 # Development server from slideatlas import create_app app = create_app() # app.run(host='0.0.0.0', port=8080) if __name__ == "__main__": print "To run:\ngunicorn run_gunicorn:app -b localhost:8080 -w 4"
24.888889
69
0.714286
# coding=utf-8 # Development server from slideatlas import create_app app = create_app() # app.run(host='0.0.0.0', port=8080) if __name__ == "__main__": print "To run:\ngunicorn run_gunicorn:app -b localhost:8080 -w 4"
0
0
0
a8bf0c58483a2e21ccdf3815d73bbf19efd309c2
990
py
Python
examples/608_plan_pick_trajectory.py
djprohasky/workshop_swinburne_2021
596eb12595ef7c2522dc8e03163e917ca43d2a0a
[ "MIT" ]
4
2021-12-13T09:57:06.000Z
2022-01-04T15:04:58.000Z
examples/608_plan_pick_trajectory.py
djprohasky/workshop_swinburne_2021
596eb12595ef7c2522dc8e03163e917ca43d2a0a
[ "MIT" ]
3
2021-06-16T10:27:09.000Z
2021-06-17T02:37:04.000Z
examples/608_plan_pick_trajectory.py
djprohasky/workshop_swinburne_2021
596eb12595ef7c2522dc8e03163e917ca43d2a0a
[ "MIT" ]
3
2021-06-15T12:43:22.000Z
2021-06-16T11:01:38.000Z
import os import helpers from compas_fab.backends import RosClient from compas_fab.robots import PlanningScene import compas HERE = os.path.dirname(__file__) MAX_STEP = 0.01 # Load assembly filename = os.path.join(HERE, 'assembly.json') assembly = compas.json_load(filename) with RosClient() as client: robot = client.load_robot() scene = PlanningScene(robot) # Prepare scene for planning helpers.attach_vacuum_gripper(scene) helpers.add_static_objects(scene) trajectory = robot.plan_cartesian_motion(assembly.pick_t0cf_frames(), start_configuration=assembly.attributes['home_config'], options=dict(max_step=MAX_STEP)) if trajectory and trajectory.fraction < 1.0: raise Exception('Incomplete trajectory. Fraction={}'.format(trajectory.fraction)) assembly.pick_trajectory = trajectory # Save assembly compas.json_dump(assembly, filename, pretty=True)
28.285714
100
0.70202
import os import helpers from compas_fab.backends import RosClient from compas_fab.robots import PlanningScene import compas HERE = os.path.dirname(__file__) MAX_STEP = 0.01 # Load assembly filename = os.path.join(HERE, 'assembly.json') assembly = compas.json_load(filename) with RosClient() as client: robot = client.load_robot() scene = PlanningScene(robot) # Prepare scene for planning helpers.attach_vacuum_gripper(scene) helpers.add_static_objects(scene) trajectory = robot.plan_cartesian_motion(assembly.pick_t0cf_frames(), start_configuration=assembly.attributes['home_config'], options=dict(max_step=MAX_STEP)) if trajectory and trajectory.fraction < 1.0: raise Exception('Incomplete trajectory. Fraction={}'.format(trajectory.fraction)) assembly.pick_trajectory = trajectory # Save assembly compas.json_dump(assembly, filename, pretty=True)
0
0
0
48f81270935a674567f3e6de615f1bc99760148d
2,009
py
Python
src/doit/sanitizedtable/sqlalchemy/sqlmodel.py
khusmann/doit
305c04bda1ccfc38c86b97e4360481af654827e7
[ "MIT" ]
null
null
null
src/doit/sanitizedtable/sqlalchemy/sqlmodel.py
khusmann/doit
305c04bda1ccfc38c86b97e4360481af654827e7
[ "MIT" ]
null
null
null
src/doit/sanitizedtable/sqlalchemy/sqlmodel.py
khusmann/doit
305c04bda1ccfc38c86b97e4360481af654827e7
[ "MIT" ]
null
null
null
from __future__ import annotations import typing as t import enum from sqlalchemy import ( Column, Integer, String, ForeignKey, MetaData, Table, JSON, ) from sqlalchemy.orm import ( relationship, RelationshipProperty, ) from ...common.sqlalchemy import ( declarative_base, RequiredColumn, OptionalColumn, RequiredEnumColumn, ) Base = declarative_base()
25.75641
75
0.683922
from __future__ import annotations import typing as t import enum from sqlalchemy import ( Column, Integer, String, ForeignKey, MetaData, Table, JSON, ) from sqlalchemy.orm import ( relationship, RelationshipProperty, ) from ...common.sqlalchemy import ( declarative_base, RequiredColumn, OptionalColumn, RequiredEnumColumn, ) Base = declarative_base() def datatablecolumn_from_columnentrytype(type: ColumnEntryType): match type: case ColumnEntryType.ORDINAL: return Integer case ColumnEntryType.MULTISELECT: return JSON(none_as_null=True) case ColumnEntryType.TEXT: return String def setup_datatable(metadata: MetaData, table: TableEntrySql) -> Table: return Table( table.name, metadata, *[ Column( i.name, datatablecolumn_from_columnentrytype(i.type), ) for i in table.columns ] ) class TableEntrySql(Base): __tablename__ = "__table_entries__" id = RequiredColumn(Integer, primary_key=True) name = RequiredColumn(String, unique=True) title = RequiredColumn(String) source = RequiredColumn(String) data_checksum = RequiredColumn(String) schema_checksum = RequiredColumn(String) columns: RelationshipProperty[t.List[ColumnEntrySql]] = relationship( "ColumnEntrySql", order_by="ColumnEntrySql.id", ) class ColumnEntryType(enum.Enum): ORDINAL = 'ordinal' MULTISELECT = 'multiselect' TEXT = 'text' class ColumnEntrySql(Base): __tablename__ = "__column_entries" id = RequiredColumn(Integer, primary_key=True) parent_table_id = RequiredColumn(Integer, ForeignKey(TableEntrySql.id)) name = RequiredColumn(String) type = RequiredEnumColumn(ColumnEntryType) sortkey = RequiredColumn(String) prompt = OptionalColumn(String) sanitizer_checksum = OptionalColumn(String) codes = OptionalColumn(JSON)
546
941
115
0edbcf145b35a1d7ce69dc123941f51b9137fada
13,087
py
Python
src/test/tinc/tincrepo/mpp/lib/gpdbSegmentConfig.py
rodel-talampas/gpdb
9c955e350334abbd922102f289f782697eb52069
[ "PostgreSQL", "Apache-2.0" ]
9
2018-04-20T03:31:01.000Z
2020-05-13T14:10:53.000Z
src/test/tinc/tincrepo/mpp/lib/gpdbSegmentConfig.py
rodel-talampas/gpdb
9c955e350334abbd922102f289f782697eb52069
[ "PostgreSQL", "Apache-2.0" ]
36
2017-09-21T09:12:27.000Z
2020-06-17T16:40:48.000Z
src/test/tinc/tincrepo/mpp/lib/gpdbSegmentConfig.py
rodel-talampas/gpdb
9c955e350334abbd922102f289f782697eb52069
[ "PostgreSQL", "Apache-2.0" ]
32
2017-08-31T12:50:52.000Z
2022-03-01T07:34:53.000Z
#!/usr/bin/env python # Line too long - pylint: disable=C0301 # Invalid name - pylint: disable=C0103 """ Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the 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. Capture the information regarding gpdb """ try: import sys, time import traceback #from generalUtil import GeneralUtil from gppylib.commands.base import Command from PSQL import PSQL #from cdbfastUtil import PrettyPrint from datetime import datetime except Exception, e: sys.exit('Cannot import modules GpdbSegmentConfig. Please check that you have sourced greenplum_path.sh. Detail: ' + str(e)) ##### class GpdbSegmentConfig: """ Capture the information regarding Gpdb Segment Configuration @class GpdbSegmentConfig @organization: DCD Partner Engineering @contact: Kenneth Wong """ ### def __init__(self): """ Constructor for GpdbSegmentConfig """ #self.generalUtil = GeneralUtil() self.psql = PSQL ### def GetSqlData(self, sql): """ Execute the sql statement and returns the data @param sql: The sql command to execute @return: data """ data = [] # use run_sql_command in SQL instead of run #(rc, out) = psql.run(dbname='gptest', cmd='%s' % (sql), ofile='-', flag='-q -t') out = self.psql.run_sql_command(sql_cmd='%s' % (sql), dbname='gptest', out_file='-', flags='-q -t') for line in out: line = line.strip() if line: data.append(line) return 0, data def hasStandbyMaster( self ): ''' check if a greenplum database has standby master configured @return: True or False which indicates whether or not the gpdb has standby master configured ''' cmd = 'SELECT CASE WHEN count(*) > 0 THEN \'True\' ELSE \'False\' END AS hasstandby FROM pg_catalog.gp_segment_configuration WHERE content = -1 AND role = \'m\';' # use run_sql_command in SQL instead of runcmd #( ok, out ) = psql.runcmd( cmd ) out = self.psql.run_sql_command(sql_cmd='%s' % (cmd), out_file='-', flags='-t -q') #if not ok: if out and out[0].strip() == 'True': return True else: return False def hasMirrors( self ): ''' check if a greenplum database has mirrors configured @return: True or False which indicates whether or not the gpdb has mirrors configured ''' cmd = 'SELECT CASE WHEN count(*) > 0 THEN \'True\' ELSE \'False\' END AS hasstandby FROM pg_catalog.gp_segment_configuration WHERE content > -1 AND role = \'m\';' # use run_sql_command in SQL instead of runcmd #( ok, out ) = psql.runcmd( cmd ) out = self.psql.run_sql_command(sql_cmd='%s' % (cmd), out_file='-', flags='-t -q') if out.strip() == 'True': return True else: return False ### def GetSegmentInvalidCount(self): """ @return: Number of invalid segment servers """ """ """ cmd = "psql gptest -c 'SET search_path To public,gp_toolkit; SELECT COUNT(*) as invalid FROM gp_pgdatabase_invalid' | sed -n '3,3 s/^[ ]*//p'" # use Command instead of ShellCommand #rc, data = self.generalUtil.ShellCommand("psql gptest -c 'SET search_path To public,gp_toolkit; SELECT COUNT(*) as invalid FROM gp_pgdatabase_invalid' | sed -n '3,3 s/^[ ]*//p'") generalUtil = Command(name='psql gptest -c',cmdStr=cmd) generalUtil.run() rc = generalUtil.get_results().rc if rc != 0: raise Exception("psql gptest -c failed with rc: (%d)" % (rc)) data = generalUtil.get_results().stdout #segmentInvalidCount = data[0].strip() segmentInvalidCount = data.strip() return rc, segmentInvalidCount ### def GetSegmentInSync(self, sleepTime=60, repeatCnt=120, greenplum_path=""): """ @param sleepTime: Number of seconds to sleep before retry @param repeatCnt: Number of times to repeat retry. Default is 2 hours @return: Return True when the number of segment servers that are in resync is 0 rows """ inSync = "" for cnt in range(repeatCnt): data = "" try: cmd = "psql gptest -c \"SELECT dbid, content, role, preferred_role, status, mode, address, fselocation, port, replication_port FROM gp_segment_configuration, pg_filespace_entry where dbid = fsedbid and mode = 'r'\"" if greenplum_path: cmd = "%s %s" % (greenplum_path, cmd) # use Command instead of ShellCommand #rc, data = self.generalUtil.ShellCommand(cmd) generalUtil = Command(name='psql gptest -c',cmdStr=cmd) generalUtil.run() rc = generalUtil.get_results().rc data = generalUtil.get_results().stdout if rc == 0: if True in ['(0 rows)' in x for x in data]: return rc, True time.sleep(sleepTime) except Exception, e: traceback.print_exc() print "ERRORFOUND GetSegmentInSync %s" % (str(e)) #PrettyPrint('ERRORFOUND GetSegmentInSync', data) TODO print 'ERRORFOUND GetSegmentInSync', data return 0, False ### def GetServerList(self, role='p', status='u'): """ @param role: Supported role are 'p' and 'm' @param status: Supported status are 'u' and 'd' @return: list of hostname """ cmd = "SELECT hostname FROM gp_segment_configuration WHERE content != -1 AND role = '%s' AND status = '%s'" % (role, status) (rc, data) = self.GetSqlData(cmd) return rc, data ### def GetMasterHost(self, role='p', status='u'): """ @param role: Supported role are 'p' and 'm' @param status: Supported status are 'u' and 'd' @return: master hostname """ cmd = "SELECT hostname FROM gp_segment_configuration WHERE content = -1 AND role = '%s' AND status = '%s'" % (role, status) (rc, data) = self.GetSqlData(cmd) if data: data = data[0] data = data.strip() else: data = None return rc, data ### def GetMasterStandbyHost(self, status='u'): """ @param status: Supported status are 'u' and 'd' @return: Master-standby hostname """ rc, data = self.GetMasterHost('m', status) return rc, data ### def GetUpServerList(self, role='p'): """ @param role: Supported role are 'p' and 'm' @return: list of segment server that are up """ serverList = self.GetServerList(role, "u") return serverList ### def GetDownServerList(self, role='m'): """ @param role: Supported role are 'p' and 'm' @return: list of segment server that are down """ rc, serverList = self.GetServerList(role, "d") return rc, serverList ### def GetSegmentServerCount(self, role='p', status='u'): """ @param role: Supported role are 'p' and 'm' @param status: Supported status are 'u' and 'd' @return: Segment server count """ rc, serverList = self.GetServerList(role, status) return rc, len(serverList) ### def GetHostAndPort(self, content, role='p', status='u'): """ Returns the list of segment server that are up or down depending on mode @param role: Supported role are 'p' and 'm' @param status: Supported status are 'u' and 'd' @return: hostname and port """ cmd = "SELECT hostname, port FROM gp_segment_configuration WHERE content = %s AND role = '%s' AND status = '%s'" % (content, role, status) (rc, data) = self.GetSqlData(cmd) if data: host, port = data[0].split('|') return rc, host.strip(), port.strip() else: return rc, "", "" ### def GetContentIdList(self, role='p', status='u'): """ Returns the list of segment server content ID for the primary or mirror depending on role in content assending order @param role: Supported role are 'p' and 'm' @return: content list """ contentList = [] cmd = "SELECT content FROM gp_segment_configuration WHERE content != -1 AND role = '%s' AND status = '%s' ORDER BY content" % (role, status) out = self.psql.run_sql_command(sql_cmd='%s' % (cmd), dbname='gptest',out_file='-', flags='-q -t') #TODO for line in out: line = line.strip() if line: contentList.append(line) return contentList ### def GetPrimaryContentIdList(self, status): """ Returns the list of primary segment server content ID that are up or down depending on mode in assending order @param status: Supported mode are 'u' and 'd' @return: content list of primary segment server """ rc, contentList = self.GetContentIdList("p", status) return rc, contentList ### def GetMirrorContentIdList(self, status): """ Returns the list of mirror segment server content ID that are up or down depending on mode in assending order @param status: Supported status are 'u' and 'd' @return: content list of mirror segment server """ rc, contentList = self.GetContentIdList("m", status) return rc, contentList ### def GetMasterDataDirectory(self): """ @return: master data directory """ cmd = "SELECT fselocation as datadir FROM gp_segment_configuration, pg_filespace_entry, pg_catalog.pg_filespace fs WHERE fsefsoid = fs.oid and fsname='pg_system' and gp_segment_configuration.dbid=pg_filespace_entry.fsedbid AND content = -1 AND role = 'p' ORDER BY content, preferred_role" out = self.psql.run_sql_command(sql_cmd='%s' % (cmd),dbname='gptest', out_file='-', flags='-q -t') datadir = out datadir = datadir.strip() return datadir ### def GetSegmentData(self, myContentId, myRole='p', myStatus='u'): """ Returns the list of segment information that matches the content id, role and status @param myContentId: @param myRole: Either 'p' or 'm' @param myStatus: Either 'u' or 'd' @return: hostname, port, datadir address and status """ segmentData = [] cmd = "SELECT dbid, content, role, preferred_role, mode, status, hostname, address, port, fselocation as datadir, replication_port FROM gp_segment_configuration, pg_filespace_entry, pg_catalog.pg_filespace fs WHERE fsefsoid = fs.oid and fsname='pg_system' and gp_segment_configuration.dbid=pg_filespace_entry.fsedbid ORDER BY content, preferred_role" #(rc, out) = psql.run(dbname='gptest', cmd='%s' % (cmd), ofile='-', flag='-q -t') out = self.psql.run_sql_command(sql_cmd='%s' % (cmd),dbname='gptest',out_file='-', flags='-t -q') for line in out: if line: data = {} # Check for valid data if len(line) > 10: (dbid, content, role, preferred_role, mode, status, hostname, address, port, datadir, replication_port) = line.split('|') content = content.strip() role = role.strip() status = status.strip() if int(content) == int(myContentId) and role == myRole and status == myStatus: data['content'] = content data['hostname'] = hostname.strip() data['port'] = port.strip() data['datadir'] = datadir.strip() data['status'] = status.strip() data['role'] = role.strip() data['preferred_role'] = preferred_role.strip() data['address'] = address.strip() segmentData.append(data) return segmentData if __name__ == '__main__': gpdbSegmentConfig = GpdbSegmentConfig() gpdbSegmentConfig.GetSegmentInvalidCount() x, y = gpdbSegmentConfig.GetSegmentInSync() print "x %s y %s" % (x, y)
40.896875
358
0.593184
#!/usr/bin/env python # Line too long - pylint: disable=C0301 # Invalid name - pylint: disable=C0103 """ Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the 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. Capture the information regarding gpdb """ try: import sys, time import traceback #from generalUtil import GeneralUtil from gppylib.commands.base import Command from PSQL import PSQL #from cdbfastUtil import PrettyPrint from datetime import datetime except Exception, e: sys.exit('Cannot import modules GpdbSegmentConfig. Please check that you have sourced greenplum_path.sh. Detail: ' + str(e)) ##### class GpdbSegmentConfig: """ Capture the information regarding Gpdb Segment Configuration @class GpdbSegmentConfig @organization: DCD Partner Engineering @contact: Kenneth Wong """ ### def __init__(self): """ Constructor for GpdbSegmentConfig """ #self.generalUtil = GeneralUtil() self.psql = PSQL ### def GetSqlData(self, sql): """ Execute the sql statement and returns the data @param sql: The sql command to execute @return: data """ data = [] # use run_sql_command in SQL instead of run #(rc, out) = psql.run(dbname='gptest', cmd='%s' % (sql), ofile='-', flag='-q -t') out = self.psql.run_sql_command(sql_cmd='%s' % (sql), dbname='gptest', out_file='-', flags='-q -t') for line in out: line = line.strip() if line: data.append(line) return 0, data def hasStandbyMaster( self ): ''' check if a greenplum database has standby master configured @return: True or False which indicates whether or not the gpdb has standby master configured ''' cmd = 'SELECT CASE WHEN count(*) > 0 THEN \'True\' ELSE \'False\' END AS hasstandby FROM pg_catalog.gp_segment_configuration WHERE content = -1 AND role = \'m\';' # use run_sql_command in SQL instead of runcmd #( ok, out ) = psql.runcmd( cmd ) out = self.psql.run_sql_command(sql_cmd='%s' % (cmd), out_file='-', flags='-t -q') #if not ok: if out and out[0].strip() == 'True': return True else: return False def hasMirrors( self ): ''' check if a greenplum database has mirrors configured @return: True or False which indicates whether or not the gpdb has mirrors configured ''' cmd = 'SELECT CASE WHEN count(*) > 0 THEN \'True\' ELSE \'False\' END AS hasstandby FROM pg_catalog.gp_segment_configuration WHERE content > -1 AND role = \'m\';' # use run_sql_command in SQL instead of runcmd #( ok, out ) = psql.runcmd( cmd ) out = self.psql.run_sql_command(sql_cmd='%s' % (cmd), out_file='-', flags='-t -q') if out.strip() == 'True': return True else: return False ### def GetSegmentInvalidCount(self): """ @return: Number of invalid segment servers """ """ """ cmd = "psql gptest -c 'SET search_path To public,gp_toolkit; SELECT COUNT(*) as invalid FROM gp_pgdatabase_invalid' | sed -n '3,3 s/^[ ]*//p'" # use Command instead of ShellCommand #rc, data = self.generalUtil.ShellCommand("psql gptest -c 'SET search_path To public,gp_toolkit; SELECT COUNT(*) as invalid FROM gp_pgdatabase_invalid' | sed -n '3,3 s/^[ ]*//p'") generalUtil = Command(name='psql gptest -c',cmdStr=cmd) generalUtil.run() rc = generalUtil.get_results().rc if rc != 0: raise Exception("psql gptest -c failed with rc: (%d)" % (rc)) data = generalUtil.get_results().stdout #segmentInvalidCount = data[0].strip() segmentInvalidCount = data.strip() return rc, segmentInvalidCount ### def GetSegmentInSync(self, sleepTime=60, repeatCnt=120, greenplum_path=""): """ @param sleepTime: Number of seconds to sleep before retry @param repeatCnt: Number of times to repeat retry. Default is 2 hours @return: Return True when the number of segment servers that are in resync is 0 rows """ inSync = "" for cnt in range(repeatCnt): data = "" try: cmd = "psql gptest -c \"SELECT dbid, content, role, preferred_role, status, mode, address, fselocation, port, replication_port FROM gp_segment_configuration, pg_filespace_entry where dbid = fsedbid and mode = 'r'\"" if greenplum_path: cmd = "%s %s" % (greenplum_path, cmd) # use Command instead of ShellCommand #rc, data = self.generalUtil.ShellCommand(cmd) generalUtil = Command(name='psql gptest -c',cmdStr=cmd) generalUtil.run() rc = generalUtil.get_results().rc data = generalUtil.get_results().stdout if rc == 0: if True in ['(0 rows)' in x for x in data]: return rc, True time.sleep(sleepTime) except Exception, e: traceback.print_exc() print "ERRORFOUND GetSegmentInSync %s" % (str(e)) #PrettyPrint('ERRORFOUND GetSegmentInSync', data) TODO print 'ERRORFOUND GetSegmentInSync', data return 0, False ### def GetServerList(self, role='p', status='u'): """ @param role: Supported role are 'p' and 'm' @param status: Supported status are 'u' and 'd' @return: list of hostname """ cmd = "SELECT hostname FROM gp_segment_configuration WHERE content != -1 AND role = '%s' AND status = '%s'" % (role, status) (rc, data) = self.GetSqlData(cmd) return rc, data ### def GetMasterHost(self, role='p', status='u'): """ @param role: Supported role are 'p' and 'm' @param status: Supported status are 'u' and 'd' @return: master hostname """ cmd = "SELECT hostname FROM gp_segment_configuration WHERE content = -1 AND role = '%s' AND status = '%s'" % (role, status) (rc, data) = self.GetSqlData(cmd) if data: data = data[0] data = data.strip() else: data = None return rc, data ### def GetMasterStandbyHost(self, status='u'): """ @param status: Supported status are 'u' and 'd' @return: Master-standby hostname """ rc, data = self.GetMasterHost('m', status) return rc, data ### def GetUpServerList(self, role='p'): """ @param role: Supported role are 'p' and 'm' @return: list of segment server that are up """ serverList = self.GetServerList(role, "u") return serverList ### def GetDownServerList(self, role='m'): """ @param role: Supported role are 'p' and 'm' @return: list of segment server that are down """ rc, serverList = self.GetServerList(role, "d") return rc, serverList ### def GetSegmentServerCount(self, role='p', status='u'): """ @param role: Supported role are 'p' and 'm' @param status: Supported status are 'u' and 'd' @return: Segment server count """ rc, serverList = self.GetServerList(role, status) return rc, len(serverList) ### def GetHostAndPort(self, content, role='p', status='u'): """ Returns the list of segment server that are up or down depending on mode @param role: Supported role are 'p' and 'm' @param status: Supported status are 'u' and 'd' @return: hostname and port """ cmd = "SELECT hostname, port FROM gp_segment_configuration WHERE content = %s AND role = '%s' AND status = '%s'" % (content, role, status) (rc, data) = self.GetSqlData(cmd) if data: host, port = data[0].split('|') return rc, host.strip(), port.strip() else: return rc, "", "" ### def GetContentIdList(self, role='p', status='u'): """ Returns the list of segment server content ID for the primary or mirror depending on role in content assending order @param role: Supported role are 'p' and 'm' @return: content list """ contentList = [] cmd = "SELECT content FROM gp_segment_configuration WHERE content != -1 AND role = '%s' AND status = '%s' ORDER BY content" % (role, status) out = self.psql.run_sql_command(sql_cmd='%s' % (cmd), dbname='gptest',out_file='-', flags='-q -t') #TODO for line in out: line = line.strip() if line: contentList.append(line) return contentList ### def GetPrimaryContentIdList(self, status): """ Returns the list of primary segment server content ID that are up or down depending on mode in assending order @param status: Supported mode are 'u' and 'd' @return: content list of primary segment server """ rc, contentList = self.GetContentIdList("p", status) return rc, contentList ### def GetMirrorContentIdList(self, status): """ Returns the list of mirror segment server content ID that are up or down depending on mode in assending order @param status: Supported status are 'u' and 'd' @return: content list of mirror segment server """ rc, contentList = self.GetContentIdList("m", status) return rc, contentList ### def GetMasterDataDirectory(self): """ @return: master data directory """ cmd = "SELECT fselocation as datadir FROM gp_segment_configuration, pg_filespace_entry, pg_catalog.pg_filespace fs WHERE fsefsoid = fs.oid and fsname='pg_system' and gp_segment_configuration.dbid=pg_filespace_entry.fsedbid AND content = -1 AND role = 'p' ORDER BY content, preferred_role" out = self.psql.run_sql_command(sql_cmd='%s' % (cmd),dbname='gptest', out_file='-', flags='-q -t') datadir = out datadir = datadir.strip() return datadir ### def GetSegmentData(self, myContentId, myRole='p', myStatus='u'): """ Returns the list of segment information that matches the content id, role and status @param myContentId: @param myRole: Either 'p' or 'm' @param myStatus: Either 'u' or 'd' @return: hostname, port, datadir address and status """ segmentData = [] cmd = "SELECT dbid, content, role, preferred_role, mode, status, hostname, address, port, fselocation as datadir, replication_port FROM gp_segment_configuration, pg_filespace_entry, pg_catalog.pg_filespace fs WHERE fsefsoid = fs.oid and fsname='pg_system' and gp_segment_configuration.dbid=pg_filespace_entry.fsedbid ORDER BY content, preferred_role" #(rc, out) = psql.run(dbname='gptest', cmd='%s' % (cmd), ofile='-', flag='-q -t') out = self.psql.run_sql_command(sql_cmd='%s' % (cmd),dbname='gptest',out_file='-', flags='-t -q') for line in out: if line: data = {} # Check for valid data if len(line) > 10: (dbid, content, role, preferred_role, mode, status, hostname, address, port, datadir, replication_port) = line.split('|') content = content.strip() role = role.strip() status = status.strip() if int(content) == int(myContentId) and role == myRole and status == myStatus: data['content'] = content data['hostname'] = hostname.strip() data['port'] = port.strip() data['datadir'] = datadir.strip() data['status'] = status.strip() data['role'] = role.strip() data['preferred_role'] = preferred_role.strip() data['address'] = address.strip() segmentData.append(data) return segmentData if __name__ == '__main__': gpdbSegmentConfig = GpdbSegmentConfig() gpdbSegmentConfig.GetSegmentInvalidCount() x, y = gpdbSegmentConfig.GetSegmentInSync() print "x %s y %s" % (x, y)
0
0
0
e8e874d1ba46c6302dbad010c653ee72b994c3aa
1,851
py
Python
main_PyBank.py
akshitarora19/Python
b097585bc075a693e159490bf1061f4efe36bc3f
[ "ADSL" ]
null
null
null
main_PyBank.py
akshitarora19/Python
b097585bc075a693e159490bf1061f4efe36bc3f
[ "ADSL" ]
null
null
null
main_PyBank.py
akshitarora19/Python
b097585bc075a693e159490bf1061f4efe36bc3f
[ "ADSL" ]
null
null
null
import os import csv total_months=0 total=0 last_pl=0 average_change=0 change_in_pl=0 total_change=0 ginc_profits=0 gdec_profits=0 prev_change_in_pl=0 ginc_profits_month="" gdec_profits_month="" csvpath=os.path.join("..", "Resources", "budget_data.csv") with open (csvpath, newline="") as csvfile: csvreader=csv.reader(csvfile, delimiter=",") csv_header=next(csvreader) print("csv_header", csv_header) for row in csvreader: month=row[0] total_months=total_months+1 total = total + int(row[1]) if total_months >1: change_in_pl=int(row[1])-last_pl total_change+=change_in_pl average_change=total_change/(total_months-1) last_pl=int(row[1]) if change_in_pl>ginc_profits: ginc_profits=change_in_pl ginc_profits_month=month elif change_in_pl<gdec_profits: gdec_profits=change_in_pl gdec_profits_month=month print ("Financial Analysis") print ("-------------------------------------") print(f'Total Months: {total_months}') print(f'Total: ${total}') print(f'Average Change: ${average_change}') print(f'Greatest Increase in Profits: {ginc_profits_month} ($ {ginc_profits})') print(f'Greatest Decrease in Profits: {gdec_profits_month} ($ {gdec_profits})') output= open("budget_data_output.txt","w+") output.write("Financial Analysis \n") output.write("------------------------------------- \n") output.write(f'Total Months: {total_months}' + "\n") output.write(f'Total: ${total}'+ "\n") output.write(f'Average Change: ${average_change}'+ "\n") output.write(f'Greatest Increase in Profits: {ginc_profits_month} ($ {ginc_profits})'+ "\n") output.write(f'Greatest Decrease in Profits: {gdec_profits_month} ($ {gdec_profits})'+ "\n") output.close()
30.85
92
0.647218
import os import csv total_months=0 total=0 last_pl=0 average_change=0 change_in_pl=0 total_change=0 ginc_profits=0 gdec_profits=0 prev_change_in_pl=0 ginc_profits_month="" gdec_profits_month="" csvpath=os.path.join("..", "Resources", "budget_data.csv") with open (csvpath, newline="") as csvfile: csvreader=csv.reader(csvfile, delimiter=",") csv_header=next(csvreader) print("csv_header", csv_header) for row in csvreader: month=row[0] total_months=total_months+1 total = total + int(row[1]) if total_months >1: change_in_pl=int(row[1])-last_pl total_change+=change_in_pl average_change=total_change/(total_months-1) last_pl=int(row[1]) if change_in_pl>ginc_profits: ginc_profits=change_in_pl ginc_profits_month=month elif change_in_pl<gdec_profits: gdec_profits=change_in_pl gdec_profits_month=month print ("Financial Analysis") print ("-------------------------------------") print(f'Total Months: {total_months}') print(f'Total: ${total}') print(f'Average Change: ${average_change}') print(f'Greatest Increase in Profits: {ginc_profits_month} ($ {ginc_profits})') print(f'Greatest Decrease in Profits: {gdec_profits_month} ($ {gdec_profits})') output= open("budget_data_output.txt","w+") output.write("Financial Analysis \n") output.write("------------------------------------- \n") output.write(f'Total Months: {total_months}' + "\n") output.write(f'Total: ${total}'+ "\n") output.write(f'Average Change: ${average_change}'+ "\n") output.write(f'Greatest Increase in Profits: {ginc_profits_month} ($ {ginc_profits})'+ "\n") output.write(f'Greatest Decrease in Profits: {gdec_profits_month} ($ {gdec_profits})'+ "\n") output.close()
0
0
0
3c0c1510131fc8b90f5bc9b912db6614a61a3882
3,250
py
Python
network/basher.py
voelkerb/pythonNetwork
4483fb5ec6071aabaa65d81c6aa5a05aee5641b7
[ "CC0-1.0" ]
null
null
null
network/basher.py
voelkerb/pythonNetwork
4483fb5ec6071aabaa65d81c6aa5a05aee5641b7
[ "CC0-1.0" ]
null
null
null
network/basher.py
voelkerb/pythonNetwork
4483fb5ec6071aabaa65d81c6aa5a05aee5641b7
[ "CC0-1.0" ]
null
null
null
import sys import threading import os import subprocess import time import signal class Basher(): """ Class to execute any command given as a subprocess in a new thread. You can wait for execution to finish or execute in the background and check the output frequently. """ # Init function def __init__(self, command, lineCb=None, echo=False, waittime=1.0): """ Init the Basher NOTE + TODO: CODE INJECTION is currently possible using Basher! :param command: The command to execute in string format. :type command: str :param lineCB: An optional callback which is called for each line output of the command. :type lineCB: function(str, Basher), default: ``None`` :param echo: If output should be echoed to standard out :type echo: bool, default: ``False`` :param waittime: Time to wait for execution to finish. This only works if :func:`run<terminal.basher.Basher.run> is called with ``wait=True`` :type waittime: float, default: 1.0 """ self.command = command self.lineCb = lineCb self.output = [] self.echo = echo self.waittime = waittime self.startTime = None self.__process = None self.running = False def run(self, wait=True): """ Run the specified command. :param wait: If we shoul wait for execution to finish. :type wait: bool, default: True :return: List of output lines. :rtype: list(str) """ self.__process = subprocess.Popen(self.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid) self.__thread = threading.Thread(target=self.__output_reader) self.__thread2 = threading.Thread(target=self.__error_reader) self.__thread.daemon = True self.__thread2.daemon = True self.__thread.start() self.__thread2.start() self.startTime = time.time() self.running=True if wait: while self.running and time.time()-self.startTime < self.waittime: time.sleep(0.01) self.stop() return self.output def stop(self): """Stop the execution of the command.""" self.__process.terminate() self.__process.send_signal(signal.SIGTERM) # self.__thread.join() self.running=False def __output_reader(self): """Read output in thread.""" for plain_line in iter(self.__process.stdout.readline, b''): line = plain_line.decode('utf-8') self.output.append(line) if self.echo: print('#BASHER: {0}'.format(line), end='') if self.lineCb is not None: self.lineCb(line, self) self.running=False def __error_reader(self): """Read error output in thread.""" for plain_line in iter(self.__process.stderr.readline, b''): line = plain_line.decode('utf-8') self.output.append(line) if self.echo: print('#BASHER: {0}'.format(line), end='') if self.lineCb is not None: self.lineCb(line, self)
35.326087
137
0.602769
import sys import threading import os import subprocess import time import signal class Basher(): """ Class to execute any command given as a subprocess in a new thread. You can wait for execution to finish or execute in the background and check the output frequently. """ # Init function def __init__(self, command, lineCb=None, echo=False, waittime=1.0): """ Init the Basher NOTE + TODO: CODE INJECTION is currently possible using Basher! :param command: The command to execute in string format. :type command: str :param lineCB: An optional callback which is called for each line output of the command. :type lineCB: function(str, Basher), default: ``None`` :param echo: If output should be echoed to standard out :type echo: bool, default: ``False`` :param waittime: Time to wait for execution to finish. This only works if :func:`run<terminal.basher.Basher.run> is called with ``wait=True`` :type waittime: float, default: 1.0 """ self.command = command self.lineCb = lineCb self.output = [] self.echo = echo self.waittime = waittime self.startTime = None self.__process = None self.running = False def run(self, wait=True): """ Run the specified command. :param wait: If we shoul wait for execution to finish. :type wait: bool, default: True :return: List of output lines. :rtype: list(str) """ self.__process = subprocess.Popen(self.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid) self.__thread = threading.Thread(target=self.__output_reader) self.__thread2 = threading.Thread(target=self.__error_reader) self.__thread.daemon = True self.__thread2.daemon = True self.__thread.start() self.__thread2.start() self.startTime = time.time() self.running=True if wait: while self.running and time.time()-self.startTime < self.waittime: time.sleep(0.01) self.stop() return self.output def stop(self): """Stop the execution of the command.""" self.__process.terminate() self.__process.send_signal(signal.SIGTERM) # self.__thread.join() self.running=False def __output_reader(self): """Read output in thread.""" for plain_line in iter(self.__process.stdout.readline, b''): line = plain_line.decode('utf-8') self.output.append(line) if self.echo: print('#BASHER: {0}'.format(line), end='') if self.lineCb is not None: self.lineCb(line, self) self.running=False def __error_reader(self): """Read error output in thread.""" for plain_line in iter(self.__process.stderr.readline, b''): line = plain_line.decode('utf-8') self.output.append(line) if self.echo: print('#BASHER: {0}'.format(line), end='') if self.lineCb is not None: self.lineCb(line, self)
0
0
0
124e9b1791f943c162075aa54d54f6b877b4680c
15,562
py
Python
applications/ATOM/utils/gather_atom_metrics.py
jonesholger/lbann
3214f189a1438565d695542e076c4fa8e7332d34
[ "Apache-2.0" ]
194
2016-07-19T15:40:21.000Z
2022-03-19T08:06:10.000Z
applications/ATOM/utils/gather_atom_metrics.py
jonesholger/lbann
3214f189a1438565d695542e076c4fa8e7332d34
[ "Apache-2.0" ]
1,021
2016-07-19T12:56:31.000Z
2022-03-29T00:41:47.000Z
applications/ATOM/utils/gather_atom_metrics.py
jonesholger/lbann
3214f189a1438565d695542e076c4fa8e7332d34
[ "Apache-2.0" ]
74
2016-07-28T18:24:00.000Z
2022-01-24T19:41:04.000Z
import sys import numpy as np import re #tag = sys.argv[len(sys.argv)-1] #for each log file for num in range(len(sys.argv)-1): inp = sys.argv[num+1] print('################################################################################') print("File#", num , " ", inp) print('################################################################################') run_stats = dict() trainer_metrics = dict() current_epoch = {} # Dict for each trainer to track the current epoch ds_times = {} active_ds_mode = '' sync_time = 0 # Patterns for key metrics p_trainers = re.compile('\s+Trainers\s+: ([0-9.]+)') p_ppt = re.compile('\s+Processes per trainer\s+: ([0-9.]+)') p_ppn = re.compile('\s+Processes on node\s+: ([0-9.]+)') p_procs = re.compile('\s+Total number of processes\s+: ([0-9.]+)') p_omp = re.compile('\s+OpenMP threads per process\s+: ([0-9.]+)') p_mb = re.compile('\s+mini_batch_size:\s+([0-9.]+)') # Patterns for key metrics p_train_time = re.compile('\w+\s+\(instance ([0-9]*)\) training epoch ([0-9]*) run time : ([0-9.]+)') p_test_time = re.compile('\w+\s+\(instance ([0-9]*)\) test run time : ([0-9.]+)') p_test_recon = re.compile('\w+\s+\(instance ([0-9]*)\) test recon : ([0-9.]+)') # Patterns for secondary metrics p_train_mb_time = re.compile('\w+\s+\(instance ([0-9]*)\) training epoch ([0-9]*) mini-batch time statistics : ([0-9.]+)s mean') # p_train_recon = re.compile('\w+\s+\(instance ([0-9]*)\) training epoch ([0-9]*) recon : ([0-9.]+)') # Capture the time required to load the data p_preload_data_store_mode = re.compile('starting do_preload_data_store.*num indices:\s+([0-9,]+) for role: (\w+)') p_preload_data_store_time = re.compile('\s+do_preload_data_store time:\s+([0-9.]+)') # Find the line with time to synchronize trainers p_sync_time = re.compile('synchronizing trainers... ([0-9.]+)s') with open(inp) as ifile1: for line in ifile1: m_trainers = p_trainers.match(line) if (m_trainers): run_stats['num_trainers'] = m_trainers.group(1) m_ppt = p_ppt.match(line) if (m_ppt): run_stats['procs_per_trainer'] = m_ppt.group(1) m_ppn = p_ppn.match(line) if (m_ppn): run_stats['procs_per_node'] = m_ppn.group(1) m_procs = p_procs.match(line) if (m_procs): run_stats['num_processes'] = m_procs.group(1) m_omp = p_omp.match(line) if (m_omp): run_stats['num_omp_threads'] = m_omp.group(1) m_mb = p_mb.match(line) if (m_mb): run_stats['minibatch_size'] = m_mb.group(1) m_time = p_train_time.match(line) if (m_time): tid = m_time.group(1) e = m_time.group(2) current_epoch[tid] = e # track the current epoch for each trainer t = m_time.group(3) if not trainer_metrics : trainer_metrics = { e : { tid : { 'train_time' : t } } } else: if e in trainer_metrics : if tid in trainer_metrics[e]: trainer_metrics[e][tid]['train_time'] = t else: trainer_metrics[e][tid] = { 'train_time' : t } else: trainer_metrics[e] = { tid : { 'train_time' : t } } m_test_recon = p_test_recon.match(line) if (m_test_recon): tid = m_test_recon.group(1) e = current_epoch[tid] r = m_test_recon.group(2) if not 'test_recon' in trainer_metrics[e][tid].keys(): trainer_metrics[e][tid]['test_recon'] = r else: print('@epoch ' + e + ' - duplicate test reconstruction metric found - existing = ' + trainer_metrics[e][tid]['test_recon'] + ' discarding ' + r + ' (ran test twice???)') m_test_time = p_test_time.match(line) if (m_test_time): tid = m_test_time.group(1) e = current_epoch[tid] r = m_test_time.group(2) if not 'test_time' in trainer_metrics[e][tid].keys(): trainer_metrics[e][tid]['test_time'] = r else: print('@epoch ' + e + ' - duplicate test time found - existing = ' + trainer_metrics[e][tid]['test_time'] + ' discarding ' + r + ' (ran test twice???)') m_train_mb_time = p_train_mb_time.match(line) if (m_train_mb_time): tid = m_train_mb_time.group(1) e = current_epoch[tid] if not e == m_train_mb_time.group(2): assert('Epoch mismatch') r = m_train_mb_time.group(3) if not 'train_mb_time' in trainer_metrics[e][tid].keys(): trainer_metrics[e][tid]['train_mb_time'] = r else: print('@epoch ' + e + ' - duplicate train mb time found - existing = ' + trainer_metrics[e][tid]['train_mb_time'] + ' discarding ' + r + ' (abort)') exit(-1) m_ds_mode = p_preload_data_store_mode.match(line) if (m_ds_mode): active_mode = m_ds_mode.group(2) samples = int(m_ds_mode.group(1).replace(',', '')) ds_times[active_mode] = {'samples' : samples } m_ds_time = p_preload_data_store_time.match(line) if (m_ds_time): time = float(m_ds_time.group(1)) ds_times[active_mode]['load_time'] = time m_sync_time = p_sync_time.match(line) if (m_sync_time): sync_time = float(m_sync_time.group(1)) # m_train_recon = p_train_recon.match(line) # if (m_train_recon): # tid = m_train_recon.group(1) # e = current_epoch[tid] # if not e == m_train_recon.group(2): # assert('Epoch mismatch') # r = m_train_recon.group(3) # trainer_metrics[e][tid]['train_recon'] = r print(f"Trainers : {run_stats['num_trainers']}") print(f"Procs per trainer : {run_stats['procs_per_trainer']}") print(f"Procs per node : {run_stats['procs_per_node']}") print(f"Total num. Processes : {run_stats['num_processes']}") print(f"Num. OpenMP Threads : {run_stats['num_omp_threads']}") print(f"Mini-batch Size : {run_stats['minibatch_size']}") results, partial_results, total_train_times, total_train_times_not_first_epoch = summarize_metrics(trainer_metrics) print_results(results, partial_results, total_train_times, total_train_times_not_first_epoch) ifile1.close() #table = pd.DataFrame(results) #table = pd.DataFrame(all_metrics) #met_file = "gb_metrics" +str(datetime.date.today())+'.csv' #print("Saving computed metrics to ", met_file) #table.to_csv(met_file, index=False)
48.479751
133
0.569528
import sys import numpy as np import re #tag = sys.argv[len(sys.argv)-1] def summarize_metrics(trainer_metrics): total_time = 0 total_train_time = 0 results = {} partial_results = {} total_train_times = [] total_train_times_not_first_epoch = [] # For each epoch, gather data from all trainers for e, data in trainer_metrics.items(): train_times = [] test_recons = [] test_times = [] train_mb_times = [] # train_recon = [] num_trainers = len(data) # For each trainer in the epoch for k, v in data.items(): # Make sure that it has at least pairs of keys to ensure that we don't grab # partial results if 'train_time' in v and 'train_mb_time' in v: train_times.append(float(v['train_time'])) train_mb_times.append(float(v['train_mb_time'])) if 'test_recon' in v and 'test_time' in v: test_recons.append(float(v['test_recon'])) test_times.append(float(v['test_time'])) if num_trainers != len(train_times): if np.array(train_times): partial_mean_epoch_train_time = np.mean(np.array(train_times)) else: partial_mean_epoch_train_time = 0 if np.array(test_times): partial_mean_epoch_test_time = np.mean(np.array(test_times)) else: partial_mean_epoch_test_time = 0 partial_total_time = (partial_mean_epoch_train_time + partial_mean_epoch_test_time) partial_results[e] = { 'epoch' : e, 'total_time' : total_time + partial_total_time, 'total_train_time' : total_train_time, 'num_trainers': len(train_times)} if np.array(train_times): partial_results[e].update({ 'mean_train_time' : partial_mean_epoch_train_time, 'std_train_time' : np.std(np.array(train_times)), 'min_train_time' : np.amin(np.array(train_times)), 'max_train_time' : np.amax(np.array(train_times)), 'mean_train_mb_time' : np.mean(np.array(train_mb_times)), 'std_train_mb_time' : np.std(np.array(train_mb_times))}) if np.array(test_recons): partial_results[e].update({ 'recon_min' : np.amin(np.array(test_recons)), 'recon_max' : np.amax(np.array(test_recons)), 'recon_mean' : np.mean(np.array(test_recons)), 'recon_std' : np.std(np.array(test_recons)), 'mean_test_time' : partial_mean_epoch_test_time, 'std_test_time' : np.std(np.array(test_times))}) # 'train_recon_min' : np.amin(np.array(train_recons)), # 'train_recon_max' : np.amax(np.array(train_recons)), # 'train_recon_mean' : np.mean(np.array(train_recons)), # 'train_recon_std' : np.std(np.array(train_recons)) continue else: total_train_times.append(train_times) if e != '0': total_train_times_not_first_epoch.append(train_times) if np.array(train_times): mean_epoch_train_time = np.mean(np.array(train_times)) else: mean_epoch_train_time = 0 if np.array(test_times): mean_epoch_test_time = np.mean(np.array(test_times)) else: mean_epoch_test_time = 0 total_time += (mean_epoch_train_time + mean_epoch_test_time) total_train_time += mean_epoch_train_time results[e] = { 'epoch' : e, 'total_time' : total_time, 'total_train_time' : total_train_time, 'num_trainers': len(train_times)} # 'train_recon_min' : np.amin(np.array(train_recons)), # 'train_recon_max' : np.amax(np.array(train_recons)), # 'train_recon_mean' : np.mean(np.array(train_recons)), # 'train_recon_std' : np.std(np.array(train_recons)) if np.array(train_times): results[e].update({ 'mean_train_time' : mean_epoch_train_time, 'std_train_time' : np.std(np.array(train_times)), 'min_train_time' : np.amin(np.array(train_times)), 'max_train_time' : np.amax(np.array(train_times)), 'mean_train_mb_time' : np.mean(np.array(train_mb_times)), 'std_train_mb_time' : np.std(np.array(train_mb_times))}) if np.array(test_recons): results[e].update({ 'recon_min' : np.amin(np.array(test_recons)), 'recon_max' : np.amax(np.array(test_recons)), 'recon_mean' : np.mean(np.array(test_recons)), 'recon_std' : np.std(np.array(test_recons)), 'mean_test_time' : mean_epoch_test_time, 'std_test_time' : np.std(np.array(test_times))}) return results, partial_results, total_train_times, total_train_times_not_first_epoch def print_results(results, partial_results, total_train_times, total_train_times_not_first_epoch): for e in sorted(results.keys()): r = results[e] msg = 'Epoch ' + r['epoch'] msg += ' {:7.1f}s'.format(r['total_time']) msg += ' / {:7.1f}s'.format(r['total_train_time']) if 'mean_train_time' in r and 'std_train_time' in r and 'min_train_time' in r and 'max_train_time' in r: msg += ' training = {:6.2f}s +- {:3.2f} / min = {:6.3f} / max = {:6.3f}'.format( r['mean_train_time'], r['std_train_time'], r['min_train_time'], r['max_train_time']) if 'recon_min' in r and 'recon_max' in r and 'recon_mean' in r and 'recon_std' in r: msg += ' :: reconstruction min = {:6.3f} / max = {:6.3f} / avg = {:6.3f} +- {:3.2f}'.format( r['recon_min'], r['recon_max'], r['recon_mean'], r['recon_std']) if 'mean_test_time' in r: msg += ' :: test time = {:6.3f}s +- {:3.2f}'.format(r['mean_test_time'], r['std_test_time']) msg += ' :: train MB time = {:5.3f}s +- {:3.2f}'.format(r['mean_train_mb_time'], r['std_train_mb_time']) msg += ' :: ' + str(r['num_trainers']) + ' trainers' # + ' :: train reconstruction min = {:6.3f} / max = {:6.3f} / avg = {:6.3f} +- {:3.2f}'. # format(r['train_recon_min'], r['train_recon_max'], r['train_recon_mean'], r['train_recon_std'])) print(msg) if len(total_train_times) != 0: print("All epochs (including 0) epoch time : mean=" + '{:7.2f}s'.format(np.mean(np.array(total_train_times))) + ' +- {:3.2f}'.format(np.std(np.array(total_train_times))) + ' min={:6.2f}s'.format(np.amin(np.array(total_train_times))) + ' max={:6.2f}s'.format(np.amax(np.array(total_train_times)))) if len(total_train_times_not_first_epoch) != 0: print("All epochs (except 0) epoch time : mean=" + '{:7.2f}s'.format(np.mean(np.array(total_train_times_not_first_epoch))) + ' +- {:3.2f}'.format(np.std(np.array(total_train_times_not_first_epoch))) + ' min={:6.2f}s'.format(np.amin(np.array(total_train_times_not_first_epoch))) + ' max={:6.2f}s'.format(np.amax(np.array(total_train_times_not_first_epoch)))) else: print("WARNING: Training failed - No epochs completed") print('--------------------------------------------------------------------------------') print('Time to load data:') for k,v in ds_times.items(): print('Loading {:12s}'.format(k) + ' data set with {:9d} samples'.format(v['samples']) + ' took {:6.2f}s'.format(v['load_time'])) print('Time to synchronize the trainers: {:12.6f}s'.format(sync_time)) for e in sorted(partial_results.keys()): r = partial_results[e] print('--------------------------------------------------------------------------------') print('Results for epochs with only some trainers reporting') print('Epoch ' + r['epoch'] + ' {:7.1f}s'.format(r['total_time']) + ' training = {:6.2f}s +- {:3.2f} / min = {:6.3f} / max = {:6.3f}'.format( r['mean_train_time'], r['std_train_time'], r['min_train_time'], r['max_train_time']) + ' :: reconstruction min = {:6.3f} / max = {:6.3f} / avg = {:6.3f} +- {:3.2f}'.format( r['recon_min'], r['recon_max'], r['recon_mean'], r['recon_std']) + ' :: test time = {:6.3f}s +- {:3.2f}'.format(r['mean_test_time'], r['std_test_time']) + ' :: train MB time = {:5.3f}s +- {:3.2f}'.format(r['mean_train_mb_time'], r['std_train_mb_time']) + ' :: ' + str(r['num_trainers']) + ' trainers') # + ' :: train reconstruction min = {:6.3f} / max = {:6.3f} / avg = {:6.3f} +- {:3.2f}'. # format(r['train_recon_min'], r['train_recon_max'], r['train_recon_mean'], r['train_recon_std'])) #for each log file for num in range(len(sys.argv)-1): inp = sys.argv[num+1] print('################################################################################') print("File#", num , " ", inp) print('################################################################################') run_stats = dict() trainer_metrics = dict() current_epoch = {} # Dict for each trainer to track the current epoch ds_times = {} active_ds_mode = '' sync_time = 0 # Patterns for key metrics p_trainers = re.compile('\s+Trainers\s+: ([0-9.]+)') p_ppt = re.compile('\s+Processes per trainer\s+: ([0-9.]+)') p_ppn = re.compile('\s+Processes on node\s+: ([0-9.]+)') p_procs = re.compile('\s+Total number of processes\s+: ([0-9.]+)') p_omp = re.compile('\s+OpenMP threads per process\s+: ([0-9.]+)') p_mb = re.compile('\s+mini_batch_size:\s+([0-9.]+)') # Patterns for key metrics p_train_time = re.compile('\w+\s+\(instance ([0-9]*)\) training epoch ([0-9]*) run time : ([0-9.]+)') p_test_time = re.compile('\w+\s+\(instance ([0-9]*)\) test run time : ([0-9.]+)') p_test_recon = re.compile('\w+\s+\(instance ([0-9]*)\) test recon : ([0-9.]+)') # Patterns for secondary metrics p_train_mb_time = re.compile('\w+\s+\(instance ([0-9]*)\) training epoch ([0-9]*) mini-batch time statistics : ([0-9.]+)s mean') # p_train_recon = re.compile('\w+\s+\(instance ([0-9]*)\) training epoch ([0-9]*) recon : ([0-9.]+)') # Capture the time required to load the data p_preload_data_store_mode = re.compile('starting do_preload_data_store.*num indices:\s+([0-9,]+) for role: (\w+)') p_preload_data_store_time = re.compile('\s+do_preload_data_store time:\s+([0-9.]+)') # Find the line with time to synchronize trainers p_sync_time = re.compile('synchronizing trainers... ([0-9.]+)s') with open(inp) as ifile1: for line in ifile1: m_trainers = p_trainers.match(line) if (m_trainers): run_stats['num_trainers'] = m_trainers.group(1) m_ppt = p_ppt.match(line) if (m_ppt): run_stats['procs_per_trainer'] = m_ppt.group(1) m_ppn = p_ppn.match(line) if (m_ppn): run_stats['procs_per_node'] = m_ppn.group(1) m_procs = p_procs.match(line) if (m_procs): run_stats['num_processes'] = m_procs.group(1) m_omp = p_omp.match(line) if (m_omp): run_stats['num_omp_threads'] = m_omp.group(1) m_mb = p_mb.match(line) if (m_mb): run_stats['minibatch_size'] = m_mb.group(1) m_time = p_train_time.match(line) if (m_time): tid = m_time.group(1) e = m_time.group(2) current_epoch[tid] = e # track the current epoch for each trainer t = m_time.group(3) if not trainer_metrics : trainer_metrics = { e : { tid : { 'train_time' : t } } } else: if e in trainer_metrics : if tid in trainer_metrics[e]: trainer_metrics[e][tid]['train_time'] = t else: trainer_metrics[e][tid] = { 'train_time' : t } else: trainer_metrics[e] = { tid : { 'train_time' : t } } m_test_recon = p_test_recon.match(line) if (m_test_recon): tid = m_test_recon.group(1) e = current_epoch[tid] r = m_test_recon.group(2) if not 'test_recon' in trainer_metrics[e][tid].keys(): trainer_metrics[e][tid]['test_recon'] = r else: print('@epoch ' + e + ' - duplicate test reconstruction metric found - existing = ' + trainer_metrics[e][tid]['test_recon'] + ' discarding ' + r + ' (ran test twice???)') m_test_time = p_test_time.match(line) if (m_test_time): tid = m_test_time.group(1) e = current_epoch[tid] r = m_test_time.group(2) if not 'test_time' in trainer_metrics[e][tid].keys(): trainer_metrics[e][tid]['test_time'] = r else: print('@epoch ' + e + ' - duplicate test time found - existing = ' + trainer_metrics[e][tid]['test_time'] + ' discarding ' + r + ' (ran test twice???)') m_train_mb_time = p_train_mb_time.match(line) if (m_train_mb_time): tid = m_train_mb_time.group(1) e = current_epoch[tid] if not e == m_train_mb_time.group(2): assert('Epoch mismatch') r = m_train_mb_time.group(3) if not 'train_mb_time' in trainer_metrics[e][tid].keys(): trainer_metrics[e][tid]['train_mb_time'] = r else: print('@epoch ' + e + ' - duplicate train mb time found - existing = ' + trainer_metrics[e][tid]['train_mb_time'] + ' discarding ' + r + ' (abort)') exit(-1) m_ds_mode = p_preload_data_store_mode.match(line) if (m_ds_mode): active_mode = m_ds_mode.group(2) samples = int(m_ds_mode.group(1).replace(',', '')) ds_times[active_mode] = {'samples' : samples } m_ds_time = p_preload_data_store_time.match(line) if (m_ds_time): time = float(m_ds_time.group(1)) ds_times[active_mode]['load_time'] = time m_sync_time = p_sync_time.match(line) if (m_sync_time): sync_time = float(m_sync_time.group(1)) # m_train_recon = p_train_recon.match(line) # if (m_train_recon): # tid = m_train_recon.group(1) # e = current_epoch[tid] # if not e == m_train_recon.group(2): # assert('Epoch mismatch') # r = m_train_recon.group(3) # trainer_metrics[e][tid]['train_recon'] = r print(f"Trainers : {run_stats['num_trainers']}") print(f"Procs per trainer : {run_stats['procs_per_trainer']}") print(f"Procs per node : {run_stats['procs_per_node']}") print(f"Total num. Processes : {run_stats['num_processes']}") print(f"Num. OpenMP Threads : {run_stats['num_omp_threads']}") print(f"Mini-batch Size : {run_stats['minibatch_size']}") results, partial_results, total_train_times, total_train_times_not_first_epoch = summarize_metrics(trainer_metrics) print_results(results, partial_results, total_train_times, total_train_times_not_first_epoch) ifile1.close() #table = pd.DataFrame(results) #table = pd.DataFrame(all_metrics) #met_file = "gb_metrics" +str(datetime.date.today())+'.csv' #print("Saving computed metrics to ", met_file) #table.to_csv(met_file, index=False)
8,844
0
46
988a098972dbe06fa08dd88ea86938c07dd60dfc
1,167
py
Python
scripts/compare_stemmers.py
tklovett/MaudeMiner
ba73f5dd99331c233fede9ccab1a2b1d5b430324
[ "MIT" ]
3
2015-09-10T09:07:36.000Z
2020-12-01T22:17:06.000Z
scripts/compare_stemmers.py
tklovett/MaudeMiner
ba73f5dd99331c233fede9ccab1a2b1d5b430324
[ "MIT" ]
null
null
null
scripts/compare_stemmers.py
tklovett/MaudeMiner
ba73f5dd99331c233fede9ccab1a2b1d5b430324
[ "MIT" ]
null
null
null
import nltk lines = [] with open("foitext.txt", 'r') as f: for line in f: lines.append(strip_non_ascii(line)) narratives = [x[x.rfind('|')+1:].strip() for x in lines] tokens_list = [nltk.wordpunct_tokenize(x) for x in narratives] # pos_list = [nltk.pos_tag(x) for x in tokens_list] tokens = [] for x in tokens_list: for y in x: tokens.append(y) tokens = list(set(tokens)) tokens.sort() stem_functions = { "snwbl_eng": nltk.stem.snowball.EnglishStemmer().stem, "snwbl_snwbl": nltk.stem.snowball.SnowballStemmer("english").stem, "snwbl_prtr": nltk.stem.snowball.PorterStemmer().stem, "prtr": nltk.stem.porter.PorterStemmer().stem, "wordnet": nltk.stem.wordnet.WordNetLemmatizer().lemmatize, "lancaster": nltk.stem.lancaster.LancasterStemmer().stem } stems = {} # Make stems for name, func in stem_functions.items(): this_stem = [func(x) for x in tokens] this_stem = list(set(this_stem)) this_stem.sort() stems[name] = this_stem # Print results result = "Results:\n" for name, stem_list in stems.items(): result += name + ":\t" + str(len(stem_list)) + "\n" print result
23.34
67
0.700943
import nltk def strip_non_ascii(s): return "".join(i for i in s if ord(i) < 128) lines = [] with open("foitext.txt", 'r') as f: for line in f: lines.append(strip_non_ascii(line)) narratives = [x[x.rfind('|')+1:].strip() for x in lines] tokens_list = [nltk.wordpunct_tokenize(x) for x in narratives] # pos_list = [nltk.pos_tag(x) for x in tokens_list] tokens = [] for x in tokens_list: for y in x: tokens.append(y) tokens = list(set(tokens)) tokens.sort() stem_functions = { "snwbl_eng": nltk.stem.snowball.EnglishStemmer().stem, "snwbl_snwbl": nltk.stem.snowball.SnowballStemmer("english").stem, "snwbl_prtr": nltk.stem.snowball.PorterStemmer().stem, "prtr": nltk.stem.porter.PorterStemmer().stem, "wordnet": nltk.stem.wordnet.WordNetLemmatizer().lemmatize, "lancaster": nltk.stem.lancaster.LancasterStemmer().stem } stems = {} # Make stems for name, func in stem_functions.items(): this_stem = [func(x) for x in tokens] this_stem = list(set(this_stem)) this_stem.sort() stems[name] = this_stem # Print results result = "Results:\n" for name, stem_list in stems.items(): result += name + ":\t" + str(len(stem_list)) + "\n" print result
48
0
23
b48daa89ced5699a98cab00df5229ec5b86c586c
6,083
py
Python
neuralnetworks/classifiers/las_model.py
v0lta/tfkaldi
4772e881cc168439723c19f69a2425588f661060
[ "MIT" ]
57
2017-01-19T15:58:46.000Z
2021-01-12T17:57:31.000Z
neuralnetworks/classifiers/las_model.py
v0lta/tfkaldi
4772e881cc168439723c19f69a2425588f661060
[ "MIT" ]
null
null
null
neuralnetworks/classifiers/las_model.py
v0lta/tfkaldi
4772e881cc168439723c19f69a2425588f661060
[ "MIT" ]
15
2017-02-25T17:44:35.000Z
2019-09-23T14:03:18.000Z
''' This module implements a listen attend and spell classifier. ''' from __future__ import absolute_import, division, print_function import tensorflow as tf from neuralnetworks.classifiers.classifier import Classifier from neuralnetworks.las_elements import Listener from neuralnetworks.beam_search_speller import BeamSearchSpeller from IPython.core.debugger import Tracer; debug_here = Tracer(); class LasModel(Classifier): """ A neural end to end network based speech model.""" def __init__(self, general_settings, listener_settings, attend_and_spell_settings): """ Create a listen attend and Spell model. As described in, Chan, Jaitly, Le et al. Listen, attend and spell Params: mel_feature_no: The length of the mel-featrue vectors at each time step. batch_size: The number of utterances in each (mini)-batch. target_label_no: The number of letters or phonemes in the training data set. decoding: Boolean flag indicating if this graph is going to be used for decoding purposes. """ super(LasModel, self).__init__(general_settings.target_label_no) self.gen_set = general_settings self.lst_set = listener_settings self.as_set = attend_and_spell_settings self.dtype = tf.float32 self.mel_feature_no = self.gen_set.mel_feature_no self.batch_size = self.gen_set.batch_size self.target_label_no = self.gen_set.target_label_no #decoding constants self.max_decoding_steps = 100 #self.max_decoding_steps = 44 #store the two model parts. self.listener = Listener(general_settings, listener_settings) #create a greedy speller. #self.speller = Speller(attend_and_spell_settings, # self.batch_size, # self.dtype, # self.target_label_no, # self.max_decoding_steps) #create a beam search speller. self.speller = BeamSearchSpeller(attend_and_spell_settings, self.batch_size, self.dtype, self.target_label_no, self.max_decoding_steps, beam_width=self.gen_set.beam_width, dropout_settings=self.gen_set.dropout_settings) def encode_targets_one_hot(self, targets): """ Transforn the targets into one hot encoded targets. Args: targets: Tensor of shape [batch_size, max_target_time, 1] Returns: one_hot_targets: [batch_size, max_target_time, label_no] """ with tf.variable_scope("one_hot_encoding"): target_one_hot = tf.one_hot(targets, self.target_label_no, axis=2) #one hot encoding adds an extra dimension we don't want. #squeeze it out. target_one_hot = tf.squeeze(target_one_hot, squeeze_dims=[3]) print("train targets shape: ", tf.Tensor.get_shape(target_one_hot)) return target_one_hot @staticmethod def add_input_noise(inputs, stddev=0.65): """ Add noise with a given standart deviation to the inputs Args: inputs: the noise free input-features. stddev: The standart deviation of the noise. returns: Input features plus noise. """ if stddev != 0: with tf.variable_scope("input_noise"): #add input noise with a standart deviation of stddev. inputs = tf.random_normal(tf.shape(inputs), 0.0, stddev) + inputs else: print("stddev is zero no input noise added.") return inputs
41.380952
88
0.595594
''' This module implements a listen attend and spell classifier. ''' from __future__ import absolute_import, division, print_function import tensorflow as tf from neuralnetworks.classifiers.classifier import Classifier from neuralnetworks.las_elements import Listener from neuralnetworks.beam_search_speller import BeamSearchSpeller from IPython.core.debugger import Tracer; debug_here = Tracer(); class LasModel(Classifier): """ A neural end to end network based speech model.""" def __init__(self, general_settings, listener_settings, attend_and_spell_settings): """ Create a listen attend and Spell model. As described in, Chan, Jaitly, Le et al. Listen, attend and spell Params: mel_feature_no: The length of the mel-featrue vectors at each time step. batch_size: The number of utterances in each (mini)-batch. target_label_no: The number of letters or phonemes in the training data set. decoding: Boolean flag indicating if this graph is going to be used for decoding purposes. """ super(LasModel, self).__init__(general_settings.target_label_no) self.gen_set = general_settings self.lst_set = listener_settings self.as_set = attend_and_spell_settings self.dtype = tf.float32 self.mel_feature_no = self.gen_set.mel_feature_no self.batch_size = self.gen_set.batch_size self.target_label_no = self.gen_set.target_label_no #decoding constants self.max_decoding_steps = 100 #self.max_decoding_steps = 44 #store the two model parts. self.listener = Listener(general_settings, listener_settings) #create a greedy speller. #self.speller = Speller(attend_and_spell_settings, # self.batch_size, # self.dtype, # self.target_label_no, # self.max_decoding_steps) #create a beam search speller. self.speller = BeamSearchSpeller(attend_and_spell_settings, self.batch_size, self.dtype, self.target_label_no, self.max_decoding_steps, beam_width=self.gen_set.beam_width, dropout_settings=self.gen_set.dropout_settings) def encode_targets_one_hot(self, targets): """ Transforn the targets into one hot encoded targets. Args: targets: Tensor of shape [batch_size, max_target_time, 1] Returns: one_hot_targets: [batch_size, max_target_time, label_no] """ with tf.variable_scope("one_hot_encoding"): target_one_hot = tf.one_hot(targets, self.target_label_no, axis=2) #one hot encoding adds an extra dimension we don't want. #squeeze it out. target_one_hot = tf.squeeze(target_one_hot, squeeze_dims=[3]) print("train targets shape: ", tf.Tensor.get_shape(target_one_hot)) return target_one_hot @staticmethod def add_input_noise(inputs, stddev=0.65): """ Add noise with a given standart deviation to the inputs Args: inputs: the noise free input-features. stddev: The standart deviation of the noise. returns: Input features plus noise. """ if stddev != 0: with tf.variable_scope("input_noise"): #add input noise with a standart deviation of stddev. inputs = tf.random_normal(tf.shape(inputs), 0.0, stddev) + inputs else: print("stddev is zero no input noise added.") return inputs def __call__(self, inputs, seq_length, is_training=False, decoding=False, reuse=True, scope=None, targets=None, target_seq_length=None): print('\x1b[01;32m' + "Adding LAS computations:") print(" training_graph:", is_training) print(" decoding_graph:", decoding) print('\x1b[0m') if is_training is True: inputs = self.add_input_noise(inputs, self.gen_set.input_noise_std) #check if the targets are available for training. assert targets is not None #inputs = tf.cast(inputs, self.dtype) if targets is not None: #remove the <sos> token, because training starts at t=1. targets = targets[:, 1:, :] target_seq_length = target_seq_length-1 #one hot encode the targets targets = self.encode_targets_one_hot(targets) else: assert decoding is True, "No targets found. \ Did you mean to create a decoding graph?" input_shape = tf.Tensor.get_shape(inputs) print("las input shape:", input_shape) with tf.variable_scope(scope or type(self).__name__, reuse=reuse): print('adding listen computations to the graph...') high_level_features, feature_seq_length \ = self.listener(inputs, seq_length, is_training, reuse) output, output_sequence_length = self.speller( high_level_features, feature_seq_length, targets, target_seq_length, is_training, decoding) # The saver can be used to restore the variables in the graph # from file later. if (is_training is True) or (decoding is True): saver = tf.train.Saver() else: saver = None print("output tensor shape:", tf.Tensor.get_shape(output)) #None is returned as no control ops are defined yet. return output, output_sequence_length, saver, None
1,985
0
27
997f596b808ddac161e32183631001799a8088e5
1,127
py
Python
basketball_reference_web_scraper/parsers/players_season_totals.py
sheagk/basketball_reference_web_scraper
820ff9760f91bffc3efd770d91547f3213f42ec8
[ "MIT" ]
null
null
null
basketball_reference_web_scraper/parsers/players_season_totals.py
sheagk/basketball_reference_web_scraper
820ff9760f91bffc3efd770d91547f3213f42ec8
[ "MIT" ]
null
null
null
basketball_reference_web_scraper/parsers/players_season_totals.py
sheagk/basketball_reference_web_scraper
820ff9760f91bffc3efd770d91547f3213f42ec8
[ "MIT" ]
null
null
null
from basketball_reference_web_scraper.data import TEAM_ABBREVIATIONS_TO_TEAM, POSITION_ABBREVIATIONS_TO_POSITION from basketball_reference_web_scraper.parsers.common import COLUMN_RENAMER, COLUMN_PARSER, \ find_team_column, parse_souped_row_given_header_columns, split_header_columns, get_all_tables_with_soup __totals_stats_by_year_header_string = "Player,Pos,Age,Tm,G,GS,MP,FG,FGA,FG%,3P,3PA,3P%,2P,2PA,2P%,eFG%,FT,FTA,FT%,ORB,DRB,TRB,AST,STL,BLK,TOV,PF,PTS" _totals_stats_by_year_header_columns = split_header_columns(__totals_stats_by_year_header_string)
53.666667
150
0.795918
from basketball_reference_web_scraper.data import TEAM_ABBREVIATIONS_TO_TEAM, POSITION_ABBREVIATIONS_TO_POSITION from basketball_reference_web_scraper.parsers.common import COLUMN_RENAMER, COLUMN_PARSER, \ find_team_column, parse_souped_row_given_header_columns, split_header_columns, get_all_tables_with_soup __totals_stats_by_year_header_string = "Player,Pos,Age,Tm,G,GS,MP,FG,FGA,FG%,3P,3PA,3P%,2P,2PA,2P%,eFG%,FT,FTA,FT%,ORB,DRB,TRB,AST,STL,BLK,TOV,PF,PTS" _totals_stats_by_year_header_columns = split_header_columns(__totals_stats_by_year_header_string) def parse_players_season_totals(page, skip_totals=False): all_tables = get_all_tables_with_soup(page) rows = all_tables['PLAYER TOTALS TABLE'] header_columns = _totals_stats_by_year_header_columns if skip_totals: team_column = find_team_column(header_columns) return [parse_souped_row_given_header_columns(row, header_columns) for row in rows if (row[team_column].text != "TOT" and len(row[0].text))] else: return [parse_souped_row_given_header_columns(row, header_columns) for row in rows]
540
0
23
1351df6d8950944565fc29066b395b8fc367a49c
13,279
py
Python
implementation/h2o-benchmarker/metaopt.py
kordikp/AutoMLprediction
6f87bd0b95ce78103c9f4f83ee85d831ab60a0a6
[ "Apache-2.0" ]
1
2018-03-22T12:45:32.000Z
2018-03-22T12:45:32.000Z
implementation/h2o-benchmarker/metaopt.py
kordikp/AutoMLprediction
6f87bd0b95ce78103c9f4f83ee85d831ab60a0a6
[ "Apache-2.0" ]
null
null
null
implementation/h2o-benchmarker/metaopt.py
kordikp/AutoMLprediction
6f87bd0b95ce78103c9f4f83ee85d831ab60a0a6
[ "Apache-2.0" ]
null
null
null
import h2o from Benchmarker.experiment import Experiment import Benchmarker.config as config import Benchmarker.utils as utils import warnings from optparse import OptionParser from Benchmarker.utils import init_journal, close_journal import numbers import Benchmarker.metaopt.fakegame as fg import Benchmarker.metaopt.params as p from Benchmarker.utils import persist import datetime import re import numpy as np from numpy.random import rand, randint import sys import pysmac dt = datetime.datetime ## Settings experiment_name = "" x_cols = [] y_col = None data_file = "" steps = int(sys.argv[1]) experiment_name = "Airlines 10k" x_cols = ["Year", "Month", "DayofMonth", "DayOfWeek", "DepTime", "CRSDepTime", "ArrTime", "CRSArrTime", "UniqueCarrier", "FlightNum", "TailNum", "Origin", "Dest", "Distance", "TaxiIn"] y_col = "IsDepDelayed" data_file = "/home/frydatom/Sync/School/Vylet_2016/data/airlines_imputed_10k.csv" # data_file = "/home/ubuntu/frydatom-vylet-2016/data/airlines_imputed_10k.csv" ## ================================================== Script =========================================================== keep_files = None optStart = dt.now() experimentName = experiment_name ## =================================================== Trainers ======================================================== trdata = None vadata = None tedata = None keep_files = None algs = [(GLMtrainer, p.glm_params),(CCtrainer, p.fakegame_cascadeCorrelation_params), (DRFtrainer, p.drf_params),(GBMtrainer, p.gbm_params), (BPtrainer, p.fakegame_backprop_params),(DLtrainer, p.dl_params), (QPtrainer, p.fakegame_quickprop_params), (RPtrainer, p.fakegame_rprop_params)] ##################################################### Run ############################################################## if __name__ == '__main__': opt = OptionParser() opt.add_option("-n", "--nthreads", dest="nthreads", help="number of threads used by h2o") opt.add_option("-c", "--cluster", dest="cluster", help="cluster name used by h2o to establish connection") opt.add_option("-j", "--journal-file", dest="journal", help="filename of a journal, i.e., file that gets" "appended by each result in case something goes wrong") (options, args) = opt.parse_args() if options.journal: utils.journal_file = options.journal init_journal() # Sanity checks try: f = open(utils.journal_file, "a") f.close() except: warnings.warn("An error occurred during opening the journal file. Have you set it properly? (-j)") exit(1) config.hostname = "127.0.0.1" config.port = 54321 config.nthreads = int(options.nthreads) if int(options.nthreads) >= 1 or options.nthreads is None else 4 config.cluster = "one" if options.cluster == "" or options.cluster is None else options.cluster # Actual code to run h2o.init(config.hostname, config.port, nthreads=config.nthreads, cluster_name=config.cluster) h2o.remove_all() data = h2o.import_file(data_file) r = data.runif() trdata = data[r < 0.5] vadata = data[(r >= 0.5) & (r < 0.75)] tedata = data[r >= 0.75] keep_frames = re.compile("|".join([trdata.frame_id, vadata.frame_id, tedata.frame_id]) + "|.*\\.hex|py_.*") for (tr, par) in algs: print("random search") randomSearch(tr, par, steps) print("smac") smac(tr, par, steps)
36.084239
150
0.590858
import h2o from Benchmarker.experiment import Experiment import Benchmarker.config as config import Benchmarker.utils as utils import warnings from optparse import OptionParser from Benchmarker.utils import init_journal, close_journal import numbers import Benchmarker.metaopt.fakegame as fg import Benchmarker.metaopt.params as p from Benchmarker.utils import persist import datetime import re import numpy as np from numpy.random import rand, randint import sys import pysmac dt = datetime.datetime ## Settings experiment_name = "" x_cols = [] y_col = None data_file = "" steps = int(sys.argv[1]) experiment_name = "Airlines 10k" x_cols = ["Year", "Month", "DayofMonth", "DayOfWeek", "DepTime", "CRSDepTime", "ArrTime", "CRSArrTime", "UniqueCarrier", "FlightNum", "TailNum", "Origin", "Dest", "Distance", "TaxiIn"] y_col = "IsDepDelayed" data_file = "/home/frydatom/Sync/School/Vylet_2016/data/airlines_imputed_10k.csv" # data_file = "/home/ubuntu/frydatom-vylet-2016/data/airlines_imputed_10k.csv" ## ================================================== Script =========================================================== keep_files = None optStart = dt.now() experimentName = experiment_name def appendVal(row, lmbda): try: res = lmbda() if hasattr(res, '__contains__'): print("{} has more than one value: {}".format(config.Names[len(row)], res)) res = res[0][1] row.append(res) except: row.append(None) return row def get_classification_error(mod): err = None cm = mod.confusion_matrix() try: err = float(cm.as_data_frame()['Error'].tail(1)) except: acc = mod.accuracy() if hasattr(acc, '__contains__'): err = 1.0 - acc[0][1] else: err = 1.0 - acc return err def benchmark(model, model_name, params, initTime, trainTime): row = [config.cluster, config.nthreads, experimentName, -1, model_name, str(params), initTime.total_seconds(), trainTime.total_seconds(), 0,0] metricsIdx = len(row) - 2 metricsTime = dt.now() for data in [trdata, vadata, tedata]: metrics = model.model_performance(test_data=data) err = get_classification_error(metrics) appendVal(row, lambda: 1 - err) appendVal(row, lambda: err) appendVal(row, lambda: metrics.F1()) appendVal(row, lambda: metrics.fnr()) appendVal(row, lambda: metrics.fpr()) appendVal(row, lambda: metrics.tnr()) appendVal(row, lambda: metrics.tpr()) appendVal(row, lambda: metrics.precision()) appendVal(row, lambda: metrics.recall()) appendVal(row, lambda: metrics.sensitivity()) appendVal(row, lambda: metrics.specificity()) appendVal(row, lambda: metrics.aic()) appendVal(row, lambda: metrics.auc()) appendVal(row, lambda: metrics.logloss()) appendVal(row, lambda: metrics.mean_residual_deviance()) appendVal(row, lambda: metrics.mse()) appendVal(row, lambda: metrics.null_degrees_of_freedom()) appendVal(row, lambda: metrics.null_deviance()) appendVal(row, lambda: metrics.r2()) appendVal(row, lambda: metrics.residual_degrees_of_freedom()) appendVal(row, lambda: metrics.residual_deviance()) metricsTime = dt.now() - metricsTime row[metricsIdx] = metricsTime.total_seconds() row[metricsIdx+1] = (initTime + trainTime + metricsTime).total_seconds() row = map(lambda x: None if isinstance(x, numbers.Number) and (x is None or np.isnan(x)) or x == u"NaN" or x == "NaN" else x, row) persist(row) for [frame] in h2o.ls().as_matrix(): if not keep_frames.match(frame): h2o.remove(frame) ## =================================================== Trainers ======================================================== trdata = None vadata = None tedata = None keep_files = None def GBMtrainer(**params): import h2o h2o.init() try: model = h2o.H2OGradientBoostingEstimator(**params) model_name = "Gradient Boosting" trainTime = dt.now() model.train(x=x_cols, y=y_col, training_frame=trdata, validation_frame=vadata) initTime = dt.now() - optStart trainTime = dt.now() - trainTime mse = model.mse(valid=True) benchmark(model, model_name, params, initTime, trainTime) return mse except: print("Error in {} with params {}".format(model_name, str(params))) return 10e15 def GLMtrainer(**params): import h2o h2o.init() try: model = h2o.H2OGeneralizedLinearEstimator(**params) model_name = "Generalized Linear Model" trainTime = dt.now() model.train(x=x_cols, y=y_col, training_frame=trdata, validation_frame=vadata) initTime = dt.now() - optStart trainTime = dt.now() - trainTime mse = model.mse(valid=True) benchmark(model, model_name, params, initTime, trainTime) return mse except: print("Error in {} with params {}".format(model_name, str(params))) return 10e15 def DRFtrainer(**params): import h2o h2o.init() try: model = h2o.H2ORandomForestEstimator(**params) model_name = "Distributed Random Forest" trainTime = dt.now() model.train(x=x_cols, y=y_col, training_frame=trdata, validation_frame=vadata) initTime = dt.now() - optStart trainTime = dt.now() - trainTime mse = model.mse(valid=True) benchmark(model, model_name, params, initTime, trainTime) return mse except: print("Error in {} with params {}".format(model_name, str(params))) return 10e15 def DLtrainer(**params): import h2o h2o.init() layers = ["hidden_l{}".format(x) for x in range(1, 5)] params["hidden"] = [params[x] for x in layers if params.get(x, 0) > 0] for x in layers: try: del params[x] except: pass try: model = h2o.H2ODeepLearningEstimator(**params) model_name = "Deep Learning" trainTime = dt.now() model.train(x=x_cols, y=y_col, training_frame=trdata, validation_frame=vadata) initTime = dt.now() - optStart trainTime = dt.now() - trainTime mse = model.mse(valid=True) benchmark(model, model_name, params, initTime, trainTime) return mse except: print("Error in {} with params {}".format(model_name, str(params))) return 10e15 def BPtrainer(**params): import h2o h2o.init() try: model = h2o.H2OFakeGameEstimator(model_config=fg.backPropagation(**params)) model_name = "Fakegame - Backpropagation" trainTime = dt.now() model.train(x=x_cols, y=y_col, training_frame=trdata, validation_frame=vadata) initTime = dt.now() - optStart trainTime = dt.now() - trainTime mse = model.mse(valid=True) benchmark(model, model_name, params, initTime, trainTime) return mse except: print("Error in {} with params {}".format(model_name, str(params))) return 10e15 def CCtrainer(**params): import h2o h2o.init() try: model = h2o.H2OFakeGameEstimator(model_config=fg.cascadeCorrelation(**params)) model_name = "Fakegame - Cascade Correlation" trainTime = dt.now() model.train(x=x_cols, y=y_col, training_frame=trdata, validation_frame=vadata) initTime = dt.now() - optStart trainTime = dt.now() - trainTime mse = model.mse(valid=True) benchmark(model, model_name, params, initTime, trainTime) return mse except: print("Error in {} with params {}".format(model_name, str(params))) return 10e15 def QPtrainer(**params): import h2o h2o.init() try: model = h2o.H2OFakeGameEstimator(model_config=fg.quickProp(**params)) model_name = "Fakegame - QuickProp" trainTime = dt.now() model.train(x=x_cols, y=y_col, training_frame=trdata, validation_frame=vadata) initTime = dt.now() - optStart trainTime = dt.now() - trainTime mse = model.mse(valid=True) benchmark(model, model_name, params, initTime, trainTime) return mse except: print("Error in {} with params {}".format(model_name, str(params))) return 10e15 def RPtrainer(**params): import h2o h2o.init() try: model = h2o.H2OFakeGameEstimator(model_config=fg.rProp(**params)) model_name = "Fakegame - RProp" trainTime = dt.now() model.train(x=x_cols, y=y_col, training_frame=trdata, validation_frame=vadata) initTime = dt.now() - optStart trainTime = dt.now() - trainTime mse = model.mse(valid=True) benchmark(model, model_name, params, initTime, trainTime) return mse except: print("Error in {} with params {}".format(model_name, str(params))) return 10e15 def sampleFrom(dictionary): res = {} for k, (typ, vals, default) in dictionary.iteritems(): if typ == "categorical": res[k] = vals[randint(0, len(vals))] elif typ == "integer": res[k] = randint(vals[0], vals[1]) elif typ == "real": scale = (min(10e300, vals[1]) - max(-10e300, vals[0])) if default == -1 and vals[0] > -1: if abs(rand()) < 1.0 / (scale + 1): res[k] = -1 continue res[k] = rand() * scale + max(vals[0], -10e300) return res def parse_params(params): par = {} forb = [] for k,(typ, interval, default) in params.iteritems(): if typ == "integer" or typ == "real": (lo, hi) = interval if lo > default: par[k] = (typ, [default, hi], default) forb.append("{"+"{k} > {default} && {k} < {lo}".format(k=k, default=default, lo=lo)+"}") continue par[k] = (typ, interval, default) print(forb) print(par) return par, forb def randomSearch(trainer, params, steps): global experimentName, optStart optStart = dt.now() experimentName = experiment_name + " - Random Search" for i in range(steps): cur_conf = sampleFrom(params) try: trainer(**cur_conf) except: print(cur_conf) import traceback traceback.print_tb(sys.exc_traceback) def smac(trainer, params, steps): global experimentName, optStart optStart = dt.now() experimentName = experiment_name + " - SMAC" opt = pysmac.SMAC_optimizer() parms, forbidden = parse_params(params) opt.minimize(trainer, steps, parms, forbidden_clauses = forbidden) algs = [(GLMtrainer, p.glm_params),(CCtrainer, p.fakegame_cascadeCorrelation_params), (DRFtrainer, p.drf_params),(GBMtrainer, p.gbm_params), (BPtrainer, p.fakegame_backprop_params),(DLtrainer, p.dl_params), (QPtrainer, p.fakegame_quickprop_params), (RPtrainer, p.fakegame_rprop_params)] ##################################################### Run ############################################################## if __name__ == '__main__': opt = OptionParser() opt.add_option("-n", "--nthreads", dest="nthreads", help="number of threads used by h2o") opt.add_option("-c", "--cluster", dest="cluster", help="cluster name used by h2o to establish connection") opt.add_option("-j", "--journal-file", dest="journal", help="filename of a journal, i.e., file that gets" "appended by each result in case something goes wrong") (options, args) = opt.parse_args() if options.journal: utils.journal_file = options.journal init_journal() # Sanity checks try: f = open(utils.journal_file, "a") f.close() except: warnings.warn("An error occurred during opening the journal file. Have you set it properly? (-j)") exit(1) config.hostname = "127.0.0.1" config.port = 54321 config.nthreads = int(options.nthreads) if int(options.nthreads) >= 1 or options.nthreads is None else 4 config.cluster = "one" if options.cluster == "" or options.cluster is None else options.cluster # Actual code to run h2o.init(config.hostname, config.port, nthreads=config.nthreads, cluster_name=config.cluster) h2o.remove_all() data = h2o.import_file(data_file) r = data.runif() trdata = data[r < 0.5] vadata = data[(r >= 0.5) & (r < 0.75)] tedata = data[r >= 0.75] keep_frames = re.compile("|".join([trdata.frame_id, vadata.frame_id, tedata.frame_id]) + "|.*\\.hex|py_.*") for (tr, par) in algs: print("random search") randomSearch(tr, par, steps) print("smac") smac(tr, par, steps)
9,301
0
375
56d63ba86ae10523e85c0d58aef43b02420340ec
6,669
py
Python
partymode.py
aruether/partymode
c16599c4d7ad4c3fcc76cf0ce4e8f332feba4c02
[ "MIT" ]
1
2022-03-09T15:52:42.000Z
2022-03-09T15:52:42.000Z
partymode.py
aruether/partymode
c16599c4d7ad4c3fcc76cf0ce4e8f332feba4c02
[ "MIT" ]
null
null
null
partymode.py
aruether/partymode
c16599c4d7ad4c3fcc76cf0ce4e8f332feba4c02
[ "MIT" ]
null
null
null
#!/usr/bin/env python import RPi.GPIO as gpio import os import time import subprocess import sys import signal import threading import datetime # Volume controls day_volume = 70 night_volume = 100 # Control box IO key_channel = 22 button_channel = 7 armed_indicator_channel = 18 activated_indicator_channel = 29 # Motor IO motor1_channel = 35 motor2_channel = 32 top_limit_channel = 33 # Wacky Wavy Guy Fan fan_channel = 40 # System control reboot_channel = 37 shutdown_channel = 38 # Set up GPIO gpio.setmode(gpio.BOARD) gpio.setup(button_channel, gpio.IN, pull_up_down=gpio.PUD_UP) gpio.setup(key_channel, gpio.IN, pull_up_down=gpio.PUD_UP) gpio.setup(armed_indicator_channel, gpio.OUT) gpio.setup(activated_indicator_channel, gpio.OUT) gpio.setup(motor1_channel, gpio.OUT) gpio.setup(motor2_channel, gpio.OUT) gpio.setup(top_limit_channel, gpio.IN, pull_up_down=gpio.PUD_UP) gpio.setup(fan_channel, gpio.OUT) gpio.setup(reboot_channel, gpio.IN, pull_up_down=gpio.PUD_UP) gpio.setup(shutdown_channel, gpio.IN, pull_up_down=gpio.PUD_UP) # Handle keyboard break # Stop light display # Check on the state of the key # Lower platform using motors # Setup to handle keyboard interrupts (control-C) signal.signal(signal.SIGINT, signal_handler) # Initial state lights = False raising_platform = False armed = gpio.input(key_channel) gpio.output(armed_indicator_channel, gpio.input(key_channel)) gpio.output(activated_indicator_channel, gpio.LOW) stop_motors() stop_fan() gpio.add_event_detect(key_channel, gpio.BOTH, callback=check_event, bouncetime=400) gpio.add_event_detect(button_channel, gpio.RISING, callback=check_event, bouncetime=300) gpio.add_event_detect(top_limit_channel, gpio.FALLING, callback=check_event, bouncetime=100) gpio.add_event_detect(reboot_channel, gpio.FALLING, callback=check_event, bouncetime=300) gpio.add_event_detect(shutdown_channel, gpio.FALLING, callback=check_event, bouncetime=300) print("Make sure everything is reset at start") stop_party() while True: # trying not to waste cycles on the pi time.sleep(2)
25.65
114
0.708202
#!/usr/bin/env python import RPi.GPIO as gpio import os import time import subprocess import sys import signal import threading import datetime # Volume controls day_volume = 70 night_volume = 100 # Control box IO key_channel = 22 button_channel = 7 armed_indicator_channel = 18 activated_indicator_channel = 29 # Motor IO motor1_channel = 35 motor2_channel = 32 top_limit_channel = 33 # Wacky Wavy Guy Fan fan_channel = 40 # System control reboot_channel = 37 shutdown_channel = 38 # Set up GPIO gpio.setmode(gpio.BOARD) gpio.setup(button_channel, gpio.IN, pull_up_down=gpio.PUD_UP) gpio.setup(key_channel, gpio.IN, pull_up_down=gpio.PUD_UP) gpio.setup(armed_indicator_channel, gpio.OUT) gpio.setup(activated_indicator_channel, gpio.OUT) gpio.setup(motor1_channel, gpio.OUT) gpio.setup(motor2_channel, gpio.OUT) gpio.setup(top_limit_channel, gpio.IN, pull_up_down=gpio.PUD_UP) gpio.setup(fan_channel, gpio.OUT) gpio.setup(reboot_channel, gpio.IN, pull_up_down=gpio.PUD_UP) gpio.setup(shutdown_channel, gpio.IN, pull_up_down=gpio.PUD_UP) # Handle keyboard break def signal_handler(signal, frame): print("Cleaning up") gpio.cleanup() sys.exit(0) # Stop light display def stop_party(): global lights print("Stop the party!") lights = False gpio.output(activated_indicator_channel, gpio.LOW) ret = subprocess.check_output(["stop_music_and_lights"], stderr=subprocess.STDOUT) print(ret) raise_platform() return # Check on the state of the key def check_event(channel): print("Event triggered on channel " + str(channel)) if channel==key_channel: check_key() elif channel==button_channel: check_button() elif channel==top_limit_channel: # If the platform is being raised, stop the motors. # Only check when the platform is being raised, because debounce problems # can trigger limit switch output when turning off print("Top limit switch activated") if platform_rising(): stop_motors() elif channel==reboot_channel: reboot_os() elif channel==shutdown_channel: shutdown_os() return def platform_rising(): # Return true if the platform is being raised return (gpio.input(motor1_channel) and not gpio.input(motor2_channel)) def check_key(): global lights global armed # Give key extra time to settle time.sleep(0.2) armed = gpio.input(key_channel) if armed: print("Armed") gpio.output(armed_indicator_channel, gpio.HIGH) else: print("Disarmed") gpio.output(armed_indicator_channel, gpio.LOW) if lights: stop_party() return def check_button(): global lights global armed global raising_platform # Short debounce time.sleep(0.1) # Check to see if button is pressed and system is armed if (not gpio.input(button_channel)) and armed and not raising_platform: if not lights: start_party() else: stop_party() # Give some time for debouncing time.sleep(0.1) return def start_party(): global lights print("Starting the party") gpio.output(activated_indicator_channel, gpio.HIGH) lights = True # Set volume based on day/time volume = night_volume # Assume night volume currentDateTime = datetime.datetime.now() if currentDateTime.weekday()<5: # It is a weekday. Check to see if the time is 9-5 if currentDateTime.time() > datetime.time(9,0,0,0) and currentDateTime.time() < datetime.time(17,0,0,0): volume = day_volume print("Setting volume command: 'amixer -q -M sset PCM {}%'".format(volume)) os.system("amixer -c 1 -q sset Speaker {}%".format(volume)) threading.Timer(2, lower_platform).start() # https://stackoverflow.com/a/2581943 # Runs the musicshowpi call in a subprocess.Popen, and then raises the platform when the subprocess completes. def runInThread(): global lights print("Starting a thread to lightshowpi") command = "sudo python /home/pi/lightshowpi/py/synchronized_lights.py".split() proc = subprocess.Popen(command, stdin=subprocess.PIPE) proc.wait() lights = False gpio.output(activated_indicator_channel, gpio.LOW) raise_platform() return thread = threading.Thread(target=runInThread) thread.start() # returns immediately after the thread starts return thread # Lower platform using motors def lower_platform(): print("Lowering platform") gpio.output(motor1_channel, gpio.LOW) gpio.output(motor2_channel, gpio.HIGH) threading.Timer(15, stop_motors).start() def stop_motors(): global raising_platform print("Stopping motors") gpio.output(motor1_channel, gpio.LOW) gpio.output(motor2_channel, gpio.LOW) raising_platform=False def raise_platform(): global raising_platform # Raise the platform print("Raising platform") # Make sure top limit switch isn't already activated # Interrupt will handle end turning off lift motor if gpio.input(top_limit_channel): gpio.output(motor1_channel, gpio.HIGH) gpio.output(motor2_channel, gpio.LOW) raising_platform=True else: print("Platform already at top") def stop_fan(): print("Stopping fan") gpio.output(fan_channel, gpio.LOW) def start_fan(): print("Starting fan") gpio.output(fan_channel, gpio.HIGH) def reboot_os(): # Reboot the operating system print("Rebooting") os.system("sudo reboot now") def shutdown_os(): # Reboot the operating system print("Shutting down") os.system("sudo shutdown now") # Setup to handle keyboard interrupts (control-C) signal.signal(signal.SIGINT, signal_handler) # Initial state lights = False raising_platform = False armed = gpio.input(key_channel) gpio.output(armed_indicator_channel, gpio.input(key_channel)) gpio.output(activated_indicator_channel, gpio.LOW) stop_motors() stop_fan() gpio.add_event_detect(key_channel, gpio.BOTH, callback=check_event, bouncetime=400) gpio.add_event_detect(button_channel, gpio.RISING, callback=check_event, bouncetime=300) gpio.add_event_detect(top_limit_channel, gpio.FALLING, callback=check_event, bouncetime=100) gpio.add_event_detect(reboot_channel, gpio.FALLING, callback=check_event, bouncetime=300) gpio.add_event_detect(shutdown_channel, gpio.FALLING, callback=check_event, bouncetime=300) print("Make sure everything is reset at start") stop_party() while True: # trying not to waste cycles on the pi time.sleep(2)
4,265
0
319
345b571a44ba28aa19a909ee3ef31505cd612587
457
py
Python
alpacka/agents/callbacks/__init__.py
shoot-tree-search/sts
2d9f19a40c7fb1c637dd3bd230942c01f14927e1
[ "MIT" ]
2
2021-01-03T04:21:56.000Z
2021-02-12T12:54:58.000Z
alpacka/agents/callbacks/__init__.py
shoot-tree-search/sts
2d9f19a40c7fb1c637dd3bd230942c01f14927e1
[ "MIT" ]
null
null
null
alpacka/agents/callbacks/__init__.py
shoot-tree-search/sts
2d9f19a40c7fb1c637dd3bd230942c01f14927e1
[ "MIT" ]
null
null
null
"""Callbacks.""" import gin from alpacka.agents.callbacks import graph_size_callback # Configure callbacks in this module to ensure they're accessible via the # alpacka.agents.callbacks.* namespace. GraphSizeCallback = configure_callback(graph_size_callback.GraphSizeCallback) # pylint: disable=invalid-name
26.882353
109
0.792123
"""Callbacks.""" import gin from alpacka.agents.callbacks import graph_size_callback # Configure callbacks in this module to ensure they're accessible via the # alpacka.agents.callbacks.* namespace. def configure_callback(callback_class): return gin.external_configurable( callback_class, module='alpacka.agents.callbacks' ) GraphSizeCallback = configure_callback(graph_size_callback.GraphSizeCallback) # pylint: disable=invalid-name
120
0
22
4265a2a6ddbbcec2469a3d81b4e651385adf2254
10,653
py
Python
distributed/dist_fleet/dist_fleet_ctr.py
zjjlivein/continuous_integration
c8825f32136fdd425389702c37ded08d6fd28a26
[ "Apache-2.0" ]
14
2020-03-04T07:52:07.000Z
2022-02-14T01:39:14.000Z
distributed/dist_fleet/dist_fleet_ctr.py
zjjlivein/continuous_integration
c8825f32136fdd425389702c37ded08d6fd28a26
[ "Apache-2.0" ]
19
2020-03-04T03:52:10.000Z
2021-12-23T07:02:07.000Z
distributed/dist_fleet/dist_fleet_ctr.py
zjjlivein/continuous_integration
c8825f32136fdd425389702c37ded08d6fd28a26
[ "Apache-2.0" ]
26
2020-03-04T05:39:09.000Z
2022-02-14T01:43:28.000Z
#!/bin/env python # -*- coding: utf-8 -*- # encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python #====================================================================== # # Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved # #====================================================================== """ @Desc: dist_base_fleet module @File: dist_base_fleet.py @Author: liangjinhua @Date: 2019/8/26 19:21 """ from __future__ import print_function import paddle import math import time import numpy as np import paddle.fluid as fluid import os import sys sys.path.append('./thirdparty/ctr') import py_reader_generator as py_reader1 # from cts_test.dist_fleet.reader_generator import ctr_py_reader_generator as py_reader1 from dist_base_fleet import runtime_main from dist_base_fleet import FleetDistRunnerBase params = { "is_first_trainer": True, "model_path": "dist_model_ctr", "is_pyreader_train": True, "is_dataset_train": False } # Fix seed for test fluid.default_startup_program().random_seed = 1 fluid.default_main_program().random_seed = 1 np.random.seed(1) DATA_PATH = 'thirdparty/data/dist_data/ctr_data/part-100' class TestDistCTR(FleetDistRunnerBase): """distCTR model.""" def input_data(self): """ def input data for ctr. Returns: list: The return value contains dense_input,sparse_input, label. """ dense_feature_dim = 13 self.dense_input = fluid.layers.data( name="dense_input", shape=[dense_feature_dim], dtype='float32') self.sparse_input_ids = [ fluid.layers.data( name="C" + str(i), shape=[1], lod_level=1, dtype='int64') for i in range(1, 27) ] self.label = fluid.layers.data(name='label', shape=[1], dtype='int64') self._words = [self.dense_input] + self.sparse_input_ids + [self.label] return self._words def py_reader(self): """get py_reader.""" py_reader = fluid.layers.create_py_reader_by_data( capacity=64, feed_list=self._words, name='py_reader', use_double_buffer=False) return py_reader def dataset_reader(self): """get dataset_reader.""" dataset = fluid.DatasetFactory().create_dataset() dataset.set_use_var([self.dense_input] + self.sparse_input_ids + [self.label]) pipe_command = "python ./thirdparty/ctr/dataset_generator.py" dataset.set_pipe_command(pipe_command) dataset.set_batch_size(4) thread_num = int(2) dataset.set_thread(thread_num) return dataset def net(self, args=None): """ ctr net struct. Args: args (ArgumentParser): run args to config dist fleet. Returns: A Variable holding Tensor representing the cross entropy, whose data type is the same with input. """ self.inputs = self.input_data() if not args.run_params.get("run_from_dataset", False): self.pyreader = self.py_reader() self.inputs = fluid.layers.read_file(self.pyreader) sparse_feature_dim = 1000001 embedding_size = 10 words = self.inputs sparse_embed_seq = list(map(embedding_layer, words[1:-1])) concated = fluid.layers.concat(sparse_embed_seq + words[0:1], axis=1) fc1 = fluid.layers.fc(input=concated, size=400, act='relu', param_attr=fluid.ParamAttr( initializer=fluid.initializer.Normal( scale=1 / math.sqrt(concated.shape[1])))) fc2 = fluid.layers.fc(input=fc1, size=400, act='relu', param_attr=fluid.ParamAttr( initializer=fluid.initializer.Normal( scale=1 / math.sqrt(fc1.shape[1])))) fc3 = fluid.layers.fc(input=fc2, size=400, act='relu', param_attr=fluid.ParamAttr( initializer=fluid.initializer.Normal( scale=1 / math.sqrt(fc2.shape[1])))) predict = fluid.layers.fc(input=fc3, size=2, act='softmax', param_attr=fluid.ParamAttr( initializer=fluid.initializer.Normal( scale=1 / math.sqrt(fc3.shape[1])))) cost = fluid.layers.cross_entropy(input=predict, label=words[-1]) self.avg_cost = fluid.layers.reduce_sum(cost) accuracy = fluid.layers.accuracy(input=predict, label=words[-1]) auc_var, batch_auc_var, auc_states = \ fluid.layers.auc(input=predict, label=words[-1], num_thresholds=2 ** 12, slide_steps=20) return self.avg_cost def check_model_right(self, dirname): """ check model right. Args: dirname(str): model save dir """ model_filename = os.path.join(dirname, "__model__") with open(model_filename, "rb") as f: program_desc_str = f.read() program = fluid.Program.parse_from_string(program_desc_str) with open(os.path.join(dirname, "__model__.proto"), "w") as wn: wn.write(str(program)) def do_training(self, fleet, args): """ training_from_pyreader Args: fleet (DistributedTranspiler): DistributedTranspiler inherited base class Fleet args (ArgumentParser): run args to config dist fleet. Returns: list """ exe = fluid.Executor(fluid.CPUPlace()) fleet.init_worker() exe.run(fleet.startup_program) train_generator = py_reader1.CriteoDataset(1000001) file_list = [str(DATA_PATH)] * 2 train_reader = paddle.batch( train_generator.train(file_list, args.trainers, args.current_id), batch_size=4) self.pyreader.decorate_paddle_reader(train_reader) if os.getenv("PADDLE_COMPATIBILITY_CHECK", False): exec_strategy = fluid.ExecutionStrategy() exec_strategy.num_threads = int(2) build_strategy = fluid.BuildStrategy() build_strategy.async_mode = self.async_mode if args.run_params["sync_mode"] == "async": build_strategy.memory_optimize = False if args.run_params['cpu_num'] > 1: build_strategy.reduce_strategy = fluid.BuildStrategy.ReduceStrategy.Reduce else: build_strategy = self.strategy.get_build_strategy() if args.run_params["sync_mode"] == "async": build_strategy.memory_optimize = False self.strategy.set_build_strategy(build_strategy) exec_strategy = self.strategy.get_execute_strategy() compiled_prog = fluid.compiler.CompiledProgram( fleet.main_program).with_data_parallel( loss_name=self.avg_cost.name, build_strategy=build_strategy, exec_strategy=exec_strategy) # Notice: py_reader should use try & catch EOFException method to enter the dataset # reader.start() must declare in advance self.pyreader.start() train_info = [] batch_id = 0 try: while True: avg_cost = exe.run(program=compiled_prog, fetch_list=[self.avg_cost.name]) avg_cost = np.mean(avg_cost) train_info.append(avg_cost) batch_id += 1 if params["is_first_trainer"]: if params["is_pyreader_train"]: model_path = str(params["model_path"] + "/final" + "_pyreader") fleet.save_persistables( executor=fluid.Executor(fluid.CPUPlace()), dirname=model_path) elif params["is_dataset_train"]: model_path = str(params["model_path"] + '/final' + "_dataset") fleet.save_persistables( executor=fluid.Executor(fluid.CPUPlace()), dirname=model_path) else: raise ValueError( "Program must has Date feed method: is_pyreader_train / is_dataset_train" ) if batch_id == 5: break except fluid.core.EOFException: self.pyreader.reset() fleet.stop_worker() return train_info def do_training_from_dataset(self, fleet, args): """ training_from_dataset Args: fleet (DistributedTranspiler): args (ArgumentParser): run args to config dist fleet. Returns: list """ exe = fluid.Executor(fluid.CPUPlace()) fleet.init_worker() exe.run(fleet.startup_program) dataset = self.dataset_reader() file_list = [str(DATA_PATH)] * 2 for epoch in range(1): dataset.set_filelist(file_list) var_dict = {"loss": self.avg_cost} train_info = [] exe.train_from_dataset( program=fleet.main_program, dataset=dataset, fetch_handler=FetchVars(var_dict)) return train_info if __name__ == "__main__": runtime_main(TestDistCTR)
37.776596
101
0.552708
#!/bin/env python # -*- coding: utf-8 -*- # encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python #====================================================================== # # Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved # #====================================================================== """ @Desc: dist_base_fleet module @File: dist_base_fleet.py @Author: liangjinhua @Date: 2019/8/26 19:21 """ from __future__ import print_function import paddle import math import time import numpy as np import paddle.fluid as fluid import os import sys sys.path.append('./thirdparty/ctr') import py_reader_generator as py_reader1 # from cts_test.dist_fleet.reader_generator import ctr_py_reader_generator as py_reader1 from dist_base_fleet import runtime_main from dist_base_fleet import FleetDistRunnerBase params = { "is_first_trainer": True, "model_path": "dist_model_ctr", "is_pyreader_train": True, "is_dataset_train": False } # Fix seed for test fluid.default_startup_program().random_seed = 1 fluid.default_main_program().random_seed = 1 np.random.seed(1) DATA_PATH = 'thirdparty/data/dist_data/ctr_data/part-100' class TestDistCTR(FleetDistRunnerBase): """distCTR model.""" def input_data(self): """ def input data for ctr. Returns: list: The return value contains dense_input,sparse_input, label. """ dense_feature_dim = 13 self.dense_input = fluid.layers.data( name="dense_input", shape=[dense_feature_dim], dtype='float32') self.sparse_input_ids = [ fluid.layers.data( name="C" + str(i), shape=[1], lod_level=1, dtype='int64') for i in range(1, 27) ] self.label = fluid.layers.data(name='label', shape=[1], dtype='int64') self._words = [self.dense_input] + self.sparse_input_ids + [self.label] return self._words def py_reader(self): """get py_reader.""" py_reader = fluid.layers.create_py_reader_by_data( capacity=64, feed_list=self._words, name='py_reader', use_double_buffer=False) return py_reader def dataset_reader(self): """get dataset_reader.""" dataset = fluid.DatasetFactory().create_dataset() dataset.set_use_var([self.dense_input] + self.sparse_input_ids + [self.label]) pipe_command = "python ./thirdparty/ctr/dataset_generator.py" dataset.set_pipe_command(pipe_command) dataset.set_batch_size(4) thread_num = int(2) dataset.set_thread(thread_num) return dataset def net(self, args=None): """ ctr net struct. Args: args (ArgumentParser): run args to config dist fleet. Returns: A Variable holding Tensor representing the cross entropy, whose data type is the same with input. """ self.inputs = self.input_data() if not args.run_params.get("run_from_dataset", False): self.pyreader = self.py_reader() self.inputs = fluid.layers.read_file(self.pyreader) sparse_feature_dim = 1000001 embedding_size = 10 words = self.inputs def embedding_layer(input): return fluid.layers.embedding( input=input, is_sparse=True, is_distributed=False, size=[sparse_feature_dim, embedding_size], param_attr=fluid.ParamAttr( name="SparseFeatFactors", initializer=fluid.initializer.Uniform())) sparse_embed_seq = list(map(embedding_layer, words[1:-1])) concated = fluid.layers.concat(sparse_embed_seq + words[0:1], axis=1) fc1 = fluid.layers.fc(input=concated, size=400, act='relu', param_attr=fluid.ParamAttr( initializer=fluid.initializer.Normal( scale=1 / math.sqrt(concated.shape[1])))) fc2 = fluid.layers.fc(input=fc1, size=400, act='relu', param_attr=fluid.ParamAttr( initializer=fluid.initializer.Normal( scale=1 / math.sqrt(fc1.shape[1])))) fc3 = fluid.layers.fc(input=fc2, size=400, act='relu', param_attr=fluid.ParamAttr( initializer=fluid.initializer.Normal( scale=1 / math.sqrt(fc2.shape[1])))) predict = fluid.layers.fc(input=fc3, size=2, act='softmax', param_attr=fluid.ParamAttr( initializer=fluid.initializer.Normal( scale=1 / math.sqrt(fc3.shape[1])))) cost = fluid.layers.cross_entropy(input=predict, label=words[-1]) self.avg_cost = fluid.layers.reduce_sum(cost) accuracy = fluid.layers.accuracy(input=predict, label=words[-1]) auc_var, batch_auc_var, auc_states = \ fluid.layers.auc(input=predict, label=words[-1], num_thresholds=2 ** 12, slide_steps=20) return self.avg_cost def check_model_right(self, dirname): """ check model right. Args: dirname(str): model save dir """ model_filename = os.path.join(dirname, "__model__") with open(model_filename, "rb") as f: program_desc_str = f.read() program = fluid.Program.parse_from_string(program_desc_str) with open(os.path.join(dirname, "__model__.proto"), "w") as wn: wn.write(str(program)) def do_training(self, fleet, args): """ training_from_pyreader Args: fleet (DistributedTranspiler): DistributedTranspiler inherited base class Fleet args (ArgumentParser): run args to config dist fleet. Returns: list """ exe = fluid.Executor(fluid.CPUPlace()) fleet.init_worker() exe.run(fleet.startup_program) train_generator = py_reader1.CriteoDataset(1000001) file_list = [str(DATA_PATH)] * 2 train_reader = paddle.batch( train_generator.train(file_list, args.trainers, args.current_id), batch_size=4) self.pyreader.decorate_paddle_reader(train_reader) if os.getenv("PADDLE_COMPATIBILITY_CHECK", False): exec_strategy = fluid.ExecutionStrategy() exec_strategy.num_threads = int(2) build_strategy = fluid.BuildStrategy() build_strategy.async_mode = self.async_mode if args.run_params["sync_mode"] == "async": build_strategy.memory_optimize = False if args.run_params['cpu_num'] > 1: build_strategy.reduce_strategy = fluid.BuildStrategy.ReduceStrategy.Reduce else: build_strategy = self.strategy.get_build_strategy() if args.run_params["sync_mode"] == "async": build_strategy.memory_optimize = False self.strategy.set_build_strategy(build_strategy) exec_strategy = self.strategy.get_execute_strategy() compiled_prog = fluid.compiler.CompiledProgram( fleet.main_program).with_data_parallel( loss_name=self.avg_cost.name, build_strategy=build_strategy, exec_strategy=exec_strategy) # Notice: py_reader should use try & catch EOFException method to enter the dataset # reader.start() must declare in advance self.pyreader.start() train_info = [] batch_id = 0 try: while True: avg_cost = exe.run(program=compiled_prog, fetch_list=[self.avg_cost.name]) avg_cost = np.mean(avg_cost) train_info.append(avg_cost) batch_id += 1 if params["is_first_trainer"]: if params["is_pyreader_train"]: model_path = str(params["model_path"] + "/final" + "_pyreader") fleet.save_persistables( executor=fluid.Executor(fluid.CPUPlace()), dirname=model_path) elif params["is_dataset_train"]: model_path = str(params["model_path"] + '/final' + "_dataset") fleet.save_persistables( executor=fluid.Executor(fluid.CPUPlace()), dirname=model_path) else: raise ValueError( "Program must has Date feed method: is_pyreader_train / is_dataset_train" ) if batch_id == 5: break except fluid.core.EOFException: self.pyreader.reset() fleet.stop_worker() return train_info def do_training_from_dataset(self, fleet, args): """ training_from_dataset Args: fleet (DistributedTranspiler): args (ArgumentParser): run args to config dist fleet. Returns: list """ exe = fluid.Executor(fluid.CPUPlace()) fleet.init_worker() exe.run(fleet.startup_program) dataset = self.dataset_reader() file_list = [str(DATA_PATH)] * 2 for epoch in range(1): dataset.set_filelist(file_list) var_dict = {"loss": self.avg_cost} train_info = [] class FetchVars(fluid.executor.FetchHandler): def __init__(self, var_dict=None, period_secs=5): super(FetchVars, self).__init__(var_dict, period_secs=5) def handler(self, res_dict): if len(train_info) < 6: train_info.extend(res_dict['loss'].tolist()) exe.train_from_dataset( program=fleet.main_program, dataset=dataset, fetch_handler=FetchVars(var_dict)) return train_info if __name__ == "__main__": runtime_main(TestDistCTR)
584
24
143
47044f1000f098378c2891a015792409afffcd37
2,235
py
Python
azure-iot-common/tests/test_sastoken.py
olivakar/azure-iot-sdk-python-preview
636855716a362bad1623983026666b5f91c22825
[ "MIT" ]
null
null
null
azure-iot-common/tests/test_sastoken.py
olivakar/azure-iot-sdk-python-preview
636855716a362bad1623983026666b5f91c22825
[ "MIT" ]
null
null
null
azure-iot-common/tests/test_sastoken.py
olivakar/azure-iot-sdk-python-preview
636855716a362bad1623983026666b5f91c22825
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import pytest import time from azure.iot.common.sastoken import SasToken, SasTokenError
31.041667
94
0.561969
# -*- coding: utf-8 -*- # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import pytest import time from azure.iot.common.sastoken import SasToken, SasTokenError class TestCreateSasToken(object): def test_create_default_ttl(self): uri = "my.host.name" key_name = "mykeyname" key = "Zm9vYmFy" s = SasToken(uri, key, key_name) assert s._uri == uri assert s._key_name == key_name assert s._key == key assert s.ttl == 3600 def test_create_custom_ttl(self): uri = "my.host.name" key_name = "mykeyname" key = "Zm9vYmFy" s = SasToken(uri, key, key_name, 9000) assert s._uri == uri assert s._key_name == key_name assert s._key == key assert s.ttl == 9000 def test_uri_with_special_chars(self): uri = "my châteu.host.name" key_name = "mykeyname" key = "Zm9vYmFy" s = SasToken(uri, key, key_name) expected_uri = "my+ch%C3%A2teu.host.name" assert s._uri == expected_uri def test_key_not_base_64(self): with pytest.raises(SasTokenError): uri = "my.host.name" key_name = "mykeyname" key = "this is not base64" SasToken(uri, key, key_name) class TestsOnValidSasToken(object): def test_refresh(self): # Move this setup block to fixtures when understood uri = "my.host.name" key_name = "mykeyname" key = "Zm9vYmFy" sastoken = SasToken(uri, key, key_name) # Actual test old_expiry = sastoken.expiry_time time.sleep(1) sastoken.refresh() new_expiry = sastoken.expiry_time assert new_expiry > old_expiry def test_refresh_time_mock(self): # To be implemented (need mock framework knowledge) pass def test___repr_(self): # To be implemented (need regex knowledge) pass
1,517
26
233
a93a345092e0fef48e929c091a6827fefb7df8be
2,891
py
Python
scripts/graphicslib.py
nash169/graphics-lib
a71dd2e27ac64ccccd8f55f1dd87863404789959
[ "MIT" ]
null
null
null
scripts/graphicslib.py
nash169/graphics-lib
a71dd2e27ac64ccccd8f55f1dd87863404789959
[ "MIT" ]
null
null
null
scripts/graphicslib.py
nash169/graphics-lib
a71dd2e27ac64ccccd8f55f1dd87863404789959
[ "MIT" ]
null
null
null
#!/usr/bin/env python # encoding: utf-8 # # This file is part of graphics-lib. # # Copyright (c) 2020, 2021, 2022 Bernardo Fichera <bernardo.fichera@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from waflib.Configure import conf from utils import check_include, check_lib @conf
34.831325
89
0.682463
#!/usr/bin/env python # encoding: utf-8 # # This file is part of graphics-lib. # # Copyright (c) 2020, 2021, 2022 Bernardo Fichera <bernardo.fichera@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from waflib.Configure import conf from utils import check_include, check_lib def options(opt): # Required package options opt.load("eigen magnum", tooldir="waf_tools") # Options opt.add_option( "--graphicslib-path", type="string", help="path to graphics-lib", dest="graphicslib_path", ) @conf def check_graphicslib(ctx): # Set the search path if ctx.options.graphicslib_path is None: path_check = ["/usr/local", "/usr"] else: path_check = [ctx.options.graphicslib_path] # graphics-lib includes check_include( ctx, "GRAPHICSLIB", [""], [ "graphics_lib/Graphics.hpp"], path_check ) # graphics-lib libs check_lib(ctx, "GRAPHICSLIB", "", ["libGraphics"], path_check) if ctx.env.LIB_GRAPHICSLIB or ctx.env.STLIB_GRAPHICSLIB: # Add dependencies to require libraries ctx.get_env()["requires"] = ctx.get_env()[ "requires"] + ["EIGEN", "MAGNUM"] # Check for dependencies ctx.options.magnum_components = ( "Sdl2Application,Primitives,Shaders,MeshTools,SceneGraph,Trade,GL,DebugTools" ) ctx.options.magnum_integrations = "Eigen,Bullet" ctx.load("eigen magnum", tooldir="waf_tools") # Add useful define to dynamically activate the graphics ctx.env.DEFINES_GRAPHICSLIB += ["GRAPHICS"] # Add library ctx.get_env()["libs"] = ctx.get_env()["libs"] + ["GRAPHICSLIB"] def configure(cfg): if not cfg.env.LIB_GRAPHICSLIB and not cfg.env.STLIB_GRAPHICSLIB: cfg.check_graphicslib()
1,467
0
68
52aab517e0bb1695d7a351f3c996f23cfccf95ac
4,387
py
Python
stonesoup/models/measurement/tests/test_combined.py
Red-Portal/Stone-Soup-1
267621c86161a839da9b144c2745d28d9166d903
[ "MIT" ]
157
2019-04-14T20:43:11.000Z
2022-03-30T08:30:33.000Z
stonesoup/models/measurement/tests/test_combined.py
Red-Portal/Stone-Soup-1
267621c86161a839da9b144c2745d28d9166d903
[ "MIT" ]
364
2019-04-18T15:54:49.000Z
2022-03-31T09:50:02.000Z
stonesoup/models/measurement/tests/test_combined.py
Red-Portal/Stone-Soup-1
267621c86161a839da9b144c2745d28d9166d903
[ "MIT" ]
86
2019-04-20T02:01:18.000Z
2022-03-28T01:03:11.000Z
# coding: utf-8 import pytest from pytest import approx import numpy as np from ....types.angle import Bearing from ....types.array import StateVector, CovarianceMatrix from ....types.detection import Detection from ....types.state import State from ..linear import LinearGaussian from ..nonlinear import ( CombinedReversibleGaussianMeasurementModel, CartesianToBearingRange) @pytest.fixture(scope="module")
35.379032
90
0.63483
# coding: utf-8 import pytest from pytest import approx import numpy as np from ....types.angle import Bearing from ....types.array import StateVector, CovarianceMatrix from ....types.detection import Detection from ....types.state import State from ..linear import LinearGaussian from ..nonlinear import ( CombinedReversibleGaussianMeasurementModel, CartesianToBearingRange) @pytest.fixture(scope="module") def model(): return CombinedReversibleGaussianMeasurementModel([ CartesianToBearingRange(5, [0, 1], np.diag([1, 10])), CartesianToBearingRange(5, [3, 4], np.diag([2, 20])), ]) def test_non_linear(model): assert model.ndim_meas == 4 assert model.ndim_state == 5 meas_vector = model.function( Detection(StateVector([[0], [10], [10], [0], [-10]]))) assert isinstance(meas_vector[0, 0], Bearing) assert not isinstance(meas_vector[1, 0], Bearing) assert isinstance(meas_vector[2, 0], Bearing) assert not isinstance(meas_vector[3, 0], Bearing) assert isinstance(meas_vector, StateVector) assert np.array_equal(meas_vector, np.array([[np.pi/2], [10], [-np.pi/2], [10]])) assert model.mapping == [0, 1, 3, 4] def test_jacobian(model): state = State(StateVector([[10.0], [10.0], [0.0], [10.0], [0.0]])) jacobian = model.jacobian(state) assert jacobian == approx(np.array([[-0.05, 0.05, 0, 0, 0], [0.70710678, 0.70710678, 0, 0, 0], [0, 0, 0, 0, 0.1], [0, 0, 0, 1, 0]])) def test_covar(model): covar = model.covar() assert covar == approx(np.diag([1, 10, 2, 20])) assert isinstance(covar, CovarianceMatrix) def test_inverse(model): state = State(StateVector([[0.1], [10], [0], [0.2], [20]])) meas_state = model.function(state) assert model.inverse_function(State(meas_state)) == approx(state.state_vector) def test_rvs(model): rvs_state = model.rvs() assert isinstance(rvs_state[0, 0], Bearing) assert not isinstance(rvs_state[1, 0], Bearing) assert isinstance(rvs_state[2, 0], Bearing) assert not isinstance(rvs_state[3, 0], Bearing) assert rvs_state.shape == (4, 1) assert isinstance(rvs_state, StateVector) rvs_state = model.rvs(10) assert rvs_state.shape == (4, 10) assert all(isinstance(state, Bearing) for state in rvs_state[0]) assert all(not isinstance(state, Bearing) for state in rvs_state[1]) assert all(isinstance(state, Bearing) for state in rvs_state[2]) assert all(not isinstance(state, Bearing) for state in rvs_state[3]) def test_pdf(model): pdf = model.pdf(State(StateVector([[0], [10], [0], [10]])), State(StateVector([[10], [0], [0], [10], [0]]))) assert float(pdf) == approx(0.0012665, rel=1e-3) def test_non_linear_and_linear(): model = CombinedReversibleGaussianMeasurementModel([ CartesianToBearingRange(3, [0, 1], np.diag([1, 10])), LinearGaussian(3, [2], np.array([[20]])), ]) state = State(StateVector([[0], [10], [20]])) meas_vector = model.function(state) assert isinstance(meas_vector[0, 0], Bearing) assert not isinstance(meas_vector[1, 0], Bearing) assert not isinstance(meas_vector[2, 0], Bearing) assert isinstance(meas_vector, StateVector) assert np.array_equal(meas_vector, np.array([[np.pi/2], [10], [20]])) assert model.inverse_function(State(meas_vector)) == approx(state.state_vector) assert model.covar() == approx(np.diag([1, 10, 20])) def test_mismatch_ndim_state(): with pytest.raises(ValueError): CombinedReversibleGaussianMeasurementModel([ CartesianToBearingRange(3, [0, 1], np.diag([1, 10])), CartesianToBearingRange(4, [0, 1], np.diag([1, 10])), ]) def test_none_covar(): new_model = CombinedReversibleGaussianMeasurementModel([ CartesianToBearingRange(4, [0, 1], None), CartesianToBearingRange(4, [0, 1], np.diag([1, 10])) ]) with pytest.raises(ValueError, match="Cannot generate rvs from None-type covariance"): new_model.rvs() with pytest.raises(ValueError, match="Cannot generate pdf from None-type covariance"): new_model.pdf(State([0, 0, 0, 0]), State([0, 0, 0, 0]))
3,734
0
229
3a91273c8d7483c5d7b396705caa5c2cf20b08b5
824
py
Python
ms_flask_app/app.py
royxss/Project_Risk_Assessment_Deploy
931dc91caca120aa86eddfaf0c8fba49867c64fc
[ "Apache-2.0" ]
null
null
null
ms_flask_app/app.py
royxss/Project_Risk_Assessment_Deploy
931dc91caca120aa86eddfaf0c8fba49867c64fc
[ "Apache-2.0" ]
null
null
null
ms_flask_app/app.py
royxss/Project_Risk_Assessment_Deploy
931dc91caca120aa86eddfaf0c8fba49867c64fc
[ "Apache-2.0" ]
null
null
null
from flask import Flask,render_template,url_for,request import pandas as pd import pickle import traceback import ast import sklearn import xgboost pickledModel = pickle.load(open('../app/public/latePaymentsModel.pkl','rb')) app = Flask(__name__) @app.route('/') @app.route('/process',methods=["POST"]) if __name__ == '__main__': app.run(debug=True)
26.580645
96
0.743932
from flask import Flask,render_template,url_for,request import pandas as pd import pickle import traceback import ast import sklearn import xgboost pickledModel = pickle.load(open('../app/public/latePaymentsModel.pkl','rb')) app = Flask(__name__) @app.route('/') def index(): return render_template("index.html") @app.route('/process',methods=["POST"]) def process(): if request.method == 'POST': payLatePrediction = ast.literal_eval(request.form['rawtext']) try: payLatePredictionDf = pd.DataFrame.from_dict(payLatePrediction) result = pickledModel.predict_proba(payLatePredictionDf) except: traceback.print_exc() result = "Oops! Something went wrong" return render_template("index.html",result='Approved!' if result[0][0] >= 0.5 else 'Rejected!') if __name__ == '__main__': app.run(debug=True)
425
0
44
7a641e5f90766451959de7a519933e97339c5c6a
6,814
py
Python
app.py
snarfed/ownyourresponses
52e2db2d1b7cae9bb2f9e0d320411627ea195f81
[ "CC0-1.0" ]
33
2015-02-12T22:19:23.000Z
2022-01-19T11:02:43.000Z
app.py
snarfed/ownyourresponses
52e2db2d1b7cae9bb2f9e0d320411627ea195f81
[ "CC0-1.0" ]
1
2015-10-07T05:53:57.000Z
2016-02-16T15:21:04.000Z
app.py
snarfed/ownyourresponses
52e2db2d1b7cae9bb2f9e0d320411627ea195f81
[ "CC0-1.0" ]
1
2015-10-04T17:32:59.000Z
2015-10-04T17:32:59.000Z
"""OwnYourResponses: turns likes, replies, etc. into posts on your web site. Polls your social network activity and creates new posts on your web site (via Micropub) for public Facebook comments and likes, Instagram likes, and Twitter @-replies, retweets, and favorites. """ import logging import json import urllib.error, urllib.parse, urllib.request from flask import Flask from google.cloud import ndb from granary import ( facebook, instagram, microformats2, source as gr_source, twitter, ) from oauth_dropins.webutil import ( appengine_info, appengine_config, flask_util, util, ) from oauth_dropins.webutil.util import json_loads # Change this to your web site's Micropub endpoint. # https://indiewebcamp.com/micropub if appengine_config.DEBUG: MICROPUB_ENDPOINT = 'http://localhost/wp-json/micropub/1.0/endpoint' MICROPUB_ACCESS_TOKEN = util.read('micropub_access_token_local') else: MICROPUB_ENDPOINT = 'https://snarfed.org/wp-json/micropub/1.0/endpoint' MICROPUB_ACCESS_TOKEN = util.read('micropub_access_token') # ActivityStreams objectTypes and verbs to create posts for. You can add or # remove types here to control what gets posted to your site. TYPES = ('like', 'comment', 'share', 'rsvp-yes', 'rsvp-no', 'rsvp-maybe') # The category to include with each response type. If you don't want categories # for any (or all) types, just remove them. CATEGORIES = { 'like': 'like', 'comment': 'reply', 'share': 'repost', 'rsvp-yes': 'rsvp', 'rsvp-no': 'rsvp', 'rsvp-maybe': 'rsvp', } FACEBOOK_ACCESS_TOKEN = util.read('facebook_access_token') INSTAGRAM_ACCESS_TOKEN = util.read('instagram_access_token') TWITTER_ACCESS_TOKEN = util.read('twitter_access_token') TWITTER_ACCESS_TOKEN_SECRET = util.read('twitter_access_token_secret') TWITTER_SCRAPE_HEADERS = json_loads(util.read('twitter_scrape_headers.schnarfed.json')) # Flask app app = Flask('bridgy-fed') app.template_folder = './templates' app.config.from_mapping( ENV='development' if appengine_info.DEBUG else 'PRODUCTION', CACHE_TYPE='SimpleCache', SECRET_KEY=util.read('flask_secret_key'), JSONIFY_PRETTYPRINT_REGULAR=True, ) app.register_error_handler(Exception, flask_util.handle_exception) app.wsgi_app = flask_util.ndb_context_middleware( app.wsgi_app, client=appengine_config.ndb_client) class Response(ndb.Model): """Key name is ActivityStreams activity id.""" activity_json = ndb.TextProperty(required=True) post_url = ndb.TextProperty() response_body = ndb.TextProperty() status = ndb.StringProperty(choices=('started', 'complete'), default='started') created = ndb.DateTimeProperty(auto_now_add=True) updated = ndb.DateTimeProperty(auto_now=True) @app.route('/cron/poll') def poll(): """Poll handler for cron job.""" # if FACEBOOK_ACCESS_TOKEN: # sources.append(facebook.Facebook(FACEBOOK_ACCESS_TOKEN)) # if INSTAGRAM_ACCESS_TOKEN: # sources.append(instagram.Instagram(INSTAGRAM_ACCESS_TOKEN)) source = twitter.Twitter(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET, scrape_headers=TWITTER_SCRAPE_HEADERS) activities = source.get_activities(group_id=gr_source.SELF, fetch_likes=True) resps = ndb.get_multi(ndb.Key('Response', util.trim_nulls(a['id'])) for a in activities) resps = {r.key.id(): r for r in resps if r} exception = None for activity in activities: obj = activity.get('object', {}) # have we already posted or started on this response? resp = resps.get(activity['id']) mf2 = microformats2.object_to_json(activity) mf2_props = microformats2.first_props(mf2.get('properties', {})) type = gr_source.object_type(activity) if mf2_props.get('in-reply-to'): type = 'comment' # twitter reply if type not in TYPES or (resp and resp.status == 'complete'): continue elif resp: logging.info('Retrying %s', resp) else: resp = Response.get_or_insert(activity['id'], activity_json=json.dumps(activity)) logging.info('Created new Response: %s', resp) base_id = source.base_object(activity)['id'] base = source.get_activities(activity_id=base_id)[0] # logging.info(json.dumps(base, indent=2)) # make micropub call to create post # http://indiewebcamp.com/micropub # # include access token in both header and post body for compatibility # with servers that only support one or the other (for whatever reason). headers = {'Authorization': 'Bearer ' + MICROPUB_ACCESS_TOKEN} data = { 'access_token': MICROPUB_ACCESS_TOKEN, 'h': 'entry', 'category[]': CATEGORIES.get(type), 'content[html]': render(source, activity, base), 'name': base.get('content') or base.get('object', {}).get('content'), } for key in 'in-reply-to', 'like-of', 'repost-of', 'published', 'updated': val = mf2_props.get(key) if val: data[key] = microformats2.get_string_urls([val])[0] try: result = urlopen(MICROPUB_ENDPOINT, util.trim_nulls(data), headers=headers) except urllib.error.HTTPError as exception: logging.exception('%s %s', exception.reason, exception.read()) continue except urllib.error.URLError as exception: logging.exception(exception.reason) continue resp.post_url = result.info().get('Location') logging.info('Created new post: %s', resp.post_url) resp.response_body = result.read() logging.info('Response body: %s', resp.response_body) resp.status = 'complete' resp.put() # uncomment for testing # return # end loop over activities return ('Failed, see logs', 500) if exception else 'OK'
34.588832
87
0.695627
"""OwnYourResponses: turns likes, replies, etc. into posts on your web site. Polls your social network activity and creates new posts on your web site (via Micropub) for public Facebook comments and likes, Instagram likes, and Twitter @-replies, retweets, and favorites. """ import logging import json import urllib.error, urllib.parse, urllib.request from flask import Flask from google.cloud import ndb from granary import ( facebook, instagram, microformats2, source as gr_source, twitter, ) from oauth_dropins.webutil import ( appengine_info, appengine_config, flask_util, util, ) from oauth_dropins.webutil.util import json_loads # Change this to your web site's Micropub endpoint. # https://indiewebcamp.com/micropub if appengine_config.DEBUG: MICROPUB_ENDPOINT = 'http://localhost/wp-json/micropub/1.0/endpoint' MICROPUB_ACCESS_TOKEN = util.read('micropub_access_token_local') else: MICROPUB_ENDPOINT = 'https://snarfed.org/wp-json/micropub/1.0/endpoint' MICROPUB_ACCESS_TOKEN = util.read('micropub_access_token') # ActivityStreams objectTypes and verbs to create posts for. You can add or # remove types here to control what gets posted to your site. TYPES = ('like', 'comment', 'share', 'rsvp-yes', 'rsvp-no', 'rsvp-maybe') # The category to include with each response type. If you don't want categories # for any (or all) types, just remove them. CATEGORIES = { 'like': 'like', 'comment': 'reply', 'share': 'repost', 'rsvp-yes': 'rsvp', 'rsvp-no': 'rsvp', 'rsvp-maybe': 'rsvp', } FACEBOOK_ACCESS_TOKEN = util.read('facebook_access_token') INSTAGRAM_ACCESS_TOKEN = util.read('instagram_access_token') TWITTER_ACCESS_TOKEN = util.read('twitter_access_token') TWITTER_ACCESS_TOKEN_SECRET = util.read('twitter_access_token_secret') TWITTER_SCRAPE_HEADERS = json_loads(util.read('twitter_scrape_headers.schnarfed.json')) # Flask app app = Flask('bridgy-fed') app.template_folder = './templates' app.config.from_mapping( ENV='development' if appengine_info.DEBUG else 'PRODUCTION', CACHE_TYPE='SimpleCache', SECRET_KEY=util.read('flask_secret_key'), JSONIFY_PRETTYPRINT_REGULAR=True, ) app.register_error_handler(Exception, flask_util.handle_exception) app.wsgi_app = flask_util.ndb_context_middleware( app.wsgi_app, client=appengine_config.ndb_client) class Response(ndb.Model): """Key name is ActivityStreams activity id.""" activity_json = ndb.TextProperty(required=True) post_url = ndb.TextProperty() response_body = ndb.TextProperty() status = ndb.StringProperty(choices=('started', 'complete'), default='started') created = ndb.DateTimeProperty(auto_now_add=True) updated = ndb.DateTimeProperty(auto_now=True) @app.route('/cron/poll') def poll(): """Poll handler for cron job.""" # if FACEBOOK_ACCESS_TOKEN: # sources.append(facebook.Facebook(FACEBOOK_ACCESS_TOKEN)) # if INSTAGRAM_ACCESS_TOKEN: # sources.append(instagram.Instagram(INSTAGRAM_ACCESS_TOKEN)) source = twitter.Twitter(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET, scrape_headers=TWITTER_SCRAPE_HEADERS) activities = source.get_activities(group_id=gr_source.SELF, fetch_likes=True) resps = ndb.get_multi(ndb.Key('Response', util.trim_nulls(a['id'])) for a in activities) resps = {r.key.id(): r for r in resps if r} exception = None for activity in activities: obj = activity.get('object', {}) # have we already posted or started on this response? resp = resps.get(activity['id']) mf2 = microformats2.object_to_json(activity) mf2_props = microformats2.first_props(mf2.get('properties', {})) type = gr_source.object_type(activity) if mf2_props.get('in-reply-to'): type = 'comment' # twitter reply if type not in TYPES or (resp and resp.status == 'complete'): continue elif resp: logging.info('Retrying %s', resp) else: resp = Response.get_or_insert(activity['id'], activity_json=json.dumps(activity)) logging.info('Created new Response: %s', resp) base_id = source.base_object(activity)['id'] base = source.get_activities(activity_id=base_id)[0] # logging.info(json.dumps(base, indent=2)) # make micropub call to create post # http://indiewebcamp.com/micropub # # include access token in both header and post body for compatibility # with servers that only support one or the other (for whatever reason). headers = {'Authorization': 'Bearer ' + MICROPUB_ACCESS_TOKEN} data = { 'access_token': MICROPUB_ACCESS_TOKEN, 'h': 'entry', 'category[]': CATEGORIES.get(type), 'content[html]': render(source, activity, base), 'name': base.get('content') or base.get('object', {}).get('content'), } for key in 'in-reply-to', 'like-of', 'repost-of', 'published', 'updated': val = mf2_props.get(key) if val: data[key] = microformats2.get_string_urls([val])[0] try: result = urlopen(MICROPUB_ENDPOINT, util.trim_nulls(data), headers=headers) except urllib.error.HTTPError as exception: logging.exception('%s %s', exception.reason, exception.read()) continue except urllib.error.URLError as exception: logging.exception(exception.reason) continue resp.post_url = result.info().get('Location') logging.info('Created new post: %s', resp.post_url) resp.response_body = result.read() logging.info('Response body: %s', resp.response_body) resp.status = 'complete' resp.put() # uncomment for testing # return # end loop over activities return ('Failed, see logs', 500) if exception else 'OK' def render(source, activity, base): obj = activity.get('object') or activity content = microformats2.render_content(obj) embed = source.embed_post(base) type = gr_source.object_type(activity) content = activity.get('content', '') if type == 'share' and not content: content = 'retweeted this.' rendered = embed + content if type == 'comment' else content + embed mf2_class = {'like': 'u-like-of', 'share': 'u-repost-of', }.get(type, 'in-reply-to') url = (obj.get('inReplyTo') or [{}])[0].get('url') or base.get('url') rendered += """ <a class="%s" href="%s"></a> <a class="u-syndication" href="%s"></a> """ % (mf2_class, url, activity.get('url')) return rendered def urlopen(url, data, headers=None): data = {key: val for key, val in data.items()} data = urllib.parse.urlencode(data).encode() logging.info('Fetching %s with headers %s, data %s', url, headers, data) if headers: url = urllib.request.Request(url, data=data, headers=headers) return urllib.request.urlopen(url, timeout=600, data=data)
1,030
0
46
dbc24dbe997b9424f4f5edfed6b8616411c81386
7,267
py
Python
ImageNet/train.py
mbodenham/Pytorch-XNOR-Net
aad9b68a522026a4a7ebbdf1b9ea82230e2edf24
[ "BSD-3-Clause" ]
null
null
null
ImageNet/train.py
mbodenham/Pytorch-XNOR-Net
aad9b68a522026a4a7ebbdf1b9ea82230e2edf24
[ "BSD-3-Clause" ]
null
null
null
ImageNet/train.py
mbodenham/Pytorch-XNOR-Net
aad9b68a522026a4a7ebbdf1b9ea82230e2edf24
[ "BSD-3-Clause" ]
null
null
null
## ssh -L 16006:127.0.0.1:16006 mb2775@ogg.cs.bath.ac.uk import torch from models import XNOR_VGG import torchvision from torchvision import transforms import argparse import binop import torch.utils.tensorboard as tensorboard import os from datetime import datetime import time def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res class AverageMeter(object): """Computes and stores the average and current value""" parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='./ImageNet', help='path to dataset, default = ./ImageNet') parser.add_argument('--attention', action='store_true', help='use attention branch model') parser.add_argument('--imgres', type=int, default=224, help='image input and output resolution, default = 352') parser.add_argument('--epoch', type=int, default=100, help='number of epochs, default = 100') parser.add_argument('--lr', type=float, default=1e-2, help='learning rate, default = 0.01') parser.add_argument('--momentum', type=float, default=0.9, help='momentum, default = 0.9') parser.add_argument('--weight_decay', type=float, default=5e-4, help='weight_decay, default = 0.0005') parser.add_argument('--batch_size', type=int, default=16, help='training batch size, default = 10') parser.add_argument('--clip', type=float, default=0.5, help='gradient clipping margin, default = 0.5') parser.add_argument('--decay_rate', type=float, default=0.1, help='decay rate of learning rate, default = 0.1') parser.add_argument('--decay_epoch', type=int, default=30, help='every n epochs decay learning rate, default = 50') args = parser.parse_args() # if torch.cuda.is_available(): # device = torch.device('cuda') # else: # device = torch.device('cpu') device = torch.device('cpu') model = XNOR_VGG().to(device) # model = torchvision.models.vgg16(pretrained=True).to(device) print('Model loaded') b_model = XNOR_VGG(state_dict=model.features.state_dict()).to(device) save_path = 'ckpts/{}/'.format(model.name) torch.save(b_model.state_dict(), '{}{}.pth'.format(save_path, 'bin')) model.eval() with torch.no_grad(): n = 100 input = torch.rand([n, 1, 3, args.imgres, args.imgres]).to(device) t0 = time.time() for i in input: pred = model(i) avg_t = (time.time() - t0) / n print('Inference time', avg_t) print('FPS', 1/avg_t) b_model.eval() with torch.no_grad(): n = 100 input = torch.rand([n, 1, 3, args.imgres, args.imgres]).to(device) t0 = time.time() for i in input: pred = b_model(i) avg_t = (time.time() - t0) / n print('Inference time', avg_t) print('FPS', 1/avg_t) transform = transforms.Compose([ transforms.Resize((256, 256)), transforms.RandomCrop((args.imgres, args.imgres)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) dataset = torchvision.datasets.ImageNet(args.dataset, split='train', transform=transform) dataset_val = torchvision.datasets.ImageNet(args.dataset, split='val', transform=transform) loader = torch.utils.data.DataLoader(dataset, batch_size=args.batch_size, shuffle=True) loader_val = torch.utils.data.DataLoader(dataset_val, batch_size=args.batch_size, shuffle=True) total_steps = len(loader) print('Dataset loaded') optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) bin_op = binop.BinOp(model) writer = tensorboard.SummaryWriter(os.path.join('logs', datetime.now().strftime('%Y%m%d-%H%M%S'))) criterion = torch.nn.CrossEntropyLoss().to(device) for epoch in range(args.epoch): lr_lambda = lambda epoch: args.decay_rate ** (epoch // args.decay_epoch) scheduler = torch.optim.lr_scheduler.MultiplicativeLR(optimizer, lr_lambda=lr_lambda) validate(loader_val, model, criterion) for step, sample in enumerate(loader, start=1): global_step = epoch * total_steps + step input, target = sample target_var = torch.autograd.Variable(target).to(device) input = input.to(device) target = input.to(device) bin_op.binarization() output = model(input) loss = criterion(output, target_var) optimizer.zero_grad() loss.backward() bin_op.restore() bin_op.updateBinaryGradWeight() optimizer.step() writer.add_scalar('Loss/Total Loss', float(loss), global_step) if step % 100 == 0 or step == total_steps: print('{} Epoch [{:03d}/{:03d}], Step [{:04d}/{:04d}], Loss: {:.4f}'. format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), epoch+1, args.epoch, step, total_steps, loss.data)) if epoch % 5 == 0: save_path = 'ckpts/{}/'.format(model.name) if not os.path.exists(save_path): os.makedirs(save_path) torch.save(model.state_dict(), '{}{}.pth.{:03d}'.format(save_path, model.name, epoch))
36.335
122
0.638916
## ssh -L 16006:127.0.0.1:16006 mb2775@ogg.cs.bath.ac.uk import torch from models import XNOR_VGG import torchvision from torchvision import transforms import argparse import binop import torch.utils.tensorboard as tensorboard import os from datetime import datetime import time def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res def validate(val_loader, model, criterion): batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() # switch to evaluate mode model.eval() # end = time.time() bin_op.binarization() for i, (input, target) in enumerate(val_loader): target = target.to(device) input = input.to(device) with torch.no_grad(): input_var = torch.autograd.Variable(input) target_var = torch.autograd.Variable(target) # compute output t0 = time.time() output = model(input_var) batch_time.update(time.time() - t0) loss = criterion(output, target_var) # measure accuracy and record loss prec1, prec5 = accuracy(output.data, target, topk=(1, 5)) losses.update(loss.data.item(), input.size(0)) top1.update(prec1[0], input.size(0)) top5.update(prec5[0], input.size(0)) # measure elapsed time # batch_time.update(time.time() - end) # end = time.time() if i % 100 == 0: print('Test: [{0}/{1}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format( i, len(val_loader), batch_time=batch_time, loss=losses, top1=top1, top5=top5)) bin_op.restore() print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}' .format(top1=top1, top5=top5)) return top1.avg class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='./ImageNet', help='path to dataset, default = ./ImageNet') parser.add_argument('--attention', action='store_true', help='use attention branch model') parser.add_argument('--imgres', type=int, default=224, help='image input and output resolution, default = 352') parser.add_argument('--epoch', type=int, default=100, help='number of epochs, default = 100') parser.add_argument('--lr', type=float, default=1e-2, help='learning rate, default = 0.01') parser.add_argument('--momentum', type=float, default=0.9, help='momentum, default = 0.9') parser.add_argument('--weight_decay', type=float, default=5e-4, help='weight_decay, default = 0.0005') parser.add_argument('--batch_size', type=int, default=16, help='training batch size, default = 10') parser.add_argument('--clip', type=float, default=0.5, help='gradient clipping margin, default = 0.5') parser.add_argument('--decay_rate', type=float, default=0.1, help='decay rate of learning rate, default = 0.1') parser.add_argument('--decay_epoch', type=int, default=30, help='every n epochs decay learning rate, default = 50') args = parser.parse_args() # if torch.cuda.is_available(): # device = torch.device('cuda') # else: # device = torch.device('cpu') device = torch.device('cpu') model = XNOR_VGG().to(device) # model = torchvision.models.vgg16(pretrained=True).to(device) print('Model loaded') b_model = XNOR_VGG(state_dict=model.features.state_dict()).to(device) save_path = 'ckpts/{}/'.format(model.name) torch.save(b_model.state_dict(), '{}{}.pth'.format(save_path, 'bin')) model.eval() with torch.no_grad(): n = 100 input = torch.rand([n, 1, 3, args.imgres, args.imgres]).to(device) t0 = time.time() for i in input: pred = model(i) avg_t = (time.time() - t0) / n print('Inference time', avg_t) print('FPS', 1/avg_t) b_model.eval() with torch.no_grad(): n = 100 input = torch.rand([n, 1, 3, args.imgres, args.imgres]).to(device) t0 = time.time() for i in input: pred = b_model(i) avg_t = (time.time() - t0) / n print('Inference time', avg_t) print('FPS', 1/avg_t) transform = transforms.Compose([ transforms.Resize((256, 256)), transforms.RandomCrop((args.imgres, args.imgres)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) dataset = torchvision.datasets.ImageNet(args.dataset, split='train', transform=transform) dataset_val = torchvision.datasets.ImageNet(args.dataset, split='val', transform=transform) loader = torch.utils.data.DataLoader(dataset, batch_size=args.batch_size, shuffle=True) loader_val = torch.utils.data.DataLoader(dataset_val, batch_size=args.batch_size, shuffle=True) total_steps = len(loader) print('Dataset loaded') optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) bin_op = binop.BinOp(model) writer = tensorboard.SummaryWriter(os.path.join('logs', datetime.now().strftime('%Y%m%d-%H%M%S'))) criterion = torch.nn.CrossEntropyLoss().to(device) for epoch in range(args.epoch): lr_lambda = lambda epoch: args.decay_rate ** (epoch // args.decay_epoch) scheduler = torch.optim.lr_scheduler.MultiplicativeLR(optimizer, lr_lambda=lr_lambda) validate(loader_val, model, criterion) for step, sample in enumerate(loader, start=1): global_step = epoch * total_steps + step input, target = sample target_var = torch.autograd.Variable(target).to(device) input = input.to(device) target = input.to(device) bin_op.binarization() output = model(input) loss = criterion(output, target_var) optimizer.zero_grad() loss.backward() bin_op.restore() bin_op.updateBinaryGradWeight() optimizer.step() writer.add_scalar('Loss/Total Loss', float(loss), global_step) if step % 100 == 0 or step == total_steps: print('{} Epoch [{:03d}/{:03d}], Step [{:04d}/{:04d}], Loss: {:.4f}'. format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), epoch+1, args.epoch, step, total_steps, loss.data)) if epoch % 5 == 0: save_path = 'ckpts/{}/'.format(model.name) if not os.path.exists(save_path): os.makedirs(save_path) torch.save(model.state_dict(), '{}{}.pth.{:03d}'.format(save_path, model.name, epoch))
1,836
0
103
441f712583f6078e0ab5cdb4e58a31c9252a5c74
12,506
py
Python
matsubara/heom.py
pyquantum/matsubara
c8f540a54fe3eadd2ceb8158b69d650f9cc93133
[ "MIT" ]
3
2020-04-02T09:28:44.000Z
2021-01-28T12:19:29.000Z
matsubara/heom.py
Ydeh22/matsubara
c8f540a54fe3eadd2ceb8158b69d650f9cc93133
[ "MIT" ]
2
2019-07-04T10:09:14.000Z
2019-07-12T15:04:02.000Z
matsubara/heom.py
Ydeh22/matsubara
c8f540a54fe3eadd2ceb8158b69d650f9cc93133
[ "MIT" ]
3
2019-04-02T07:59:54.000Z
2022-03-23T23:49:27.000Z
""" This module provides a solver for the spin-boson model at zero temperature using the hierarchy equations of motion (HEOM) method. """ # Authors: Shahnawaz Ahmed, Neill Lambert # Contact: shahnawaz.ahmed95@gmail.com import numpy as np from copy import copy from qutip import Qobj, qeye from qutip.states import enr_state_dictionaries from qutip.superoperator import liouvillian, spre, spost from qutip import liouvillian, mat2vec, state_number_enumerate from qutip.cy.spmatfuncs import cy_ode_rhs from qutip.solver import Options, Result, Stats from scipy.special import factorial from scipy.sparse import lil_matrix from scipy.integrate import ode def add_at_idx(seq, k, val): """ Add (subtract) a value in the tuple at position k """ lst = list(seq) lst[k] += val return tuple(lst) def prevhe(current_he, k, ncut): """ Calculate the previous heirarchy index for the current index `n`. """ nprev = add_at_idx(current_he, k, -1) if nprev[k] < 0: return False return nprev def nexthe(current_he, k, ncut): """ Calculate the next heirarchy index for the current index `n`. """ nnext = add_at_idx(current_he, k, 1) if sum(nnext) > ncut: return False return nnext def num_hierarchy(ncut, kcut): """ Get the total number of auxiliary density matrices in the hierarchy. Parameters ========== ncut: int The Heirarchy cutoff kcut: int The cutoff in the correlation frequencies, i.e., how many total exponents are used. Returns ======= num_hierarchy: int The total number of auxiliary density matrices in the hierarchy. """ return int(factorial(ncut + kcut) / (factorial(ncut) * factorial(kcut))) def _heom_state_dictionaries(dims, excitations): """ Return the number of states, and lookup-dictionaries for translating a state tuple to a state index, and vice versa, for a system with a given number of components and maximum number of excitations. Parameters ---------- dims: list A list with the number of states in each sub-system. excitations : integer The maximum numbers of dimension Returns ------- nstates, state2idx, idx2state: integer, dict, dict The number of states `nstates`, a dictionary for looking up state indices from a state tuple, and a dictionary for looking up state state tuples from state indices. """ nstates = 0 state2idx = {} idx2state = {} for state in state_number_enumerate(dims, excitations): state2idx[state] = nstates idx2state[nstates] = state nstates += 1 return nstates, state2idx, idx2state def _heom_number_enumerate(dims, excitations=None, state=None, idx=0): """ An iterator that enumerate all the state number arrays (quantum numbers on the form [n1, n2, n3, ...]) for a system with dimensions given by dims. Example: >>> for state in state_number_enumerate([2,2]): >>> print(state) [ 0. 0.] [ 0. 1.] [ 1. 0.] [ 1. 1.] Parameters ---------- dims : list or array The quantum state dimensions array, as it would appear in a Qobj. state : list Current state in the iteration. Used internally. excitations : integer (None) Restrict state space to states with excitation numbers below or equal to this value. idx : integer Current index in the iteration. Used internally. Returns ------- state_number : list Successive state number arrays that can be used in loops and other iterations, using standard state enumeration *by definition*. """ if state is None: state = np.zeros(len(dims)) if excitations and sum(state[0:idx]) > excitations: pass elif idx == len(dims): if excitations is None: yield np.array(state) else: yield tuple(state) else: for n in range(dims[idx]): state[idx] = n for s in state_number_enumerate(dims, excitations, state, idx + 1): yield s def get_aux_matrices(full, level, Nc, Nk): """ Extracts the auxiliary matrices at a particular level from the full hierarchy ADOs. Parameters ---------- full: ndarray A 2D array of the time evolution of the ADOs. level: int The level of the hierarchy to get the ADOs. Nc: int The hierarchy cutoff. k: int The total number of exponentials used to express the correlation. """ nstates, state2idx, idx2state = _heom_state_dictionaries([Nc + 1] * (Nk), Nc) aux_indices = [] aux_heom_indices = [] for stateid in state2idx: if np.sum(stateid) == level: aux_indices.append(state2idx[stateid]) aux_heom_indices.append(stateid) full = np.array(full) aux = [] for i in aux_indices: qlist = [Qobj(full[k, i, :].reshape(2, 2).T) for k in range(len(full))] aux.append(qlist) return aux, aux_heom_indices class HeomUB: """ The Heom class to tackle Heirarchy using the underdamped Brownian motion Parameters ---------- hamiltonian: :class:`qutip.Qobj` The system Hamiltonian coupling: :class:`qutip.Qobj` The coupling operator coup_strength: float The coupling strength. ck: list The list of amplitudes in the expansion of the correlation function vk: list The list of frequencies in the expansion of the correlation function ncut: int The hierarchy cutoff beta: float Inverse temperature, 1/kT. At zero temperature, beta is inf and we use an optimization for the non Matsubara terms """ def populate(self, heidx_list): """ Given a Hierarchy index list, populate the graph of next and previous elements """ ncut = self.ncut kcut = self.kcut he2idx = self.he2idx idx2he = self.idx2he for heidx in heidx_list: for k in range(self.kcut): he_current = idx2he[heidx] he_next = nexthe(he_current, k, ncut) he_prev = prevhe(he_current, k, ncut) if he_next and (he_next not in he2idx): he2idx[he_next] = self.nhe idx2he[self.nhe] = he_next self.nhe += 1 if he_prev and (he_prev not in he2idx): he2idx[he_prev] = self.nhe idx2he[self.nhe] = he_prev self.nhe += 1 def grad_n(self, he_n): """ Get the gradient term for the Hierarchy ADM at level n """ c = self.ck nu = self.vk L = self.L.copy() gradient_sum = -np.sum(np.multiply(he_n, nu)) sum_op = gradient_sum * np.eye(L.shape[0]) L += sum_op # Fill in larger L nidx = self.he2idx[he_n] block = self.N ** 2 pos = int(nidx * (block)) self.L_helems[pos : pos + block, pos : pos + block] = L def grad_prev(self, he_n, k, prev_he): """ Get prev gradient """ c = self.ck nu = self.vk spreQ = self.spreQ spostQ = self.spostQ nk = he_n[k] norm_prev = nk # Non Matsubara terms if k == 0: norm_prev = np.sqrt(float(nk) / abs(self.lam)) op1 = -1j * norm_prev * (-self.lam * spostQ) elif k == 1: norm_prev = np.sqrt(float(nk) / abs(self.lam)) op1 = -1j * norm_prev * (self.lam * spreQ) # Matsubara terms else: norm_prev = np.sqrt(float(nk) / abs(c[k])) op1 = -1j * norm_prev * (c[k] * (spreQ - spostQ)) # Fill in larger L rowidx = self.he2idx[he_n] colidx = self.he2idx[prev_he] block = self.N ** 2 rowpos = int(rowidx * (block)) colpos = int(colidx * (block)) self.L_helems[rowpos : rowpos + block, colpos : colpos + block] = op1 def rhs(self, progress=None): """ Make the RHS """ while self.nhe < self.total_nhe: heidxlist = copy(list(self.idx2he.keys())) self.populate(heidxlist) if progress is not None: bar = progress(total=self.nhe * self.kcut) for n in self.idx2he: he_n = self.idx2he[n] self.grad_n(he_n) for k in range(self.kcut): next_he = nexthe(he_n, k, self.ncut) prev_he = prevhe(he_n, k, self.ncut) if next_he and (next_he in self.he2idx): self.grad_next(he_n, k, next_he) if prev_he and (prev_he in self.he2idx): self.grad_prev(he_n, k, prev_he) def solve(self, rho0, tlist, options=None, progress=None): """ Solve the Hierarchy equations of motion for the given initial density matrix and time. """ if options is None: options = Options() output = Result() output.solver = "hsolve" output.times = tlist output.states = [] output.states.append(Qobj(rho0)) dt = np.diff(tlist) rho_he = np.zeros(self.hshape, dtype=np.complex) rho_he[0] = rho0.full().ravel("F") rho_he = rho_he.flatten() self.rhs() L_helems = self.L_helems.asformat("csr") r = ode(cy_ode_rhs) r.set_f_params(L_helems.data, L_helems.indices, L_helems.indptr) r.set_integrator( "zvode", method=options.method, order=options.order, atol=options.atol, rtol=options.rtol, nsteps=options.nsteps, first_step=options.first_step, min_step=options.min_step, max_step=options.max_step, ) r.set_initial_value(rho_he, tlist[0]) dt = np.diff(tlist) n_tsteps = len(tlist) if progress: bar = progress(total=n_tsteps - 1) for t_idx, t in enumerate(tlist): if t_idx < n_tsteps - 1: r.integrate(r.t + dt[t_idx]) r1 = r.y.reshape(self.hshape) r0 = r1[0].reshape(self.N, self.N).T output.states.append(Qobj(r0)) r_heom = r.y.reshape(self.hshape) self.full_hierarchy.append(r_heom) if progress: bar.update() return output
29.705463
88
0.574124
""" This module provides a solver for the spin-boson model at zero temperature using the hierarchy equations of motion (HEOM) method. """ # Authors: Shahnawaz Ahmed, Neill Lambert # Contact: shahnawaz.ahmed95@gmail.com import numpy as np from copy import copy from qutip import Qobj, qeye from qutip.states import enr_state_dictionaries from qutip.superoperator import liouvillian, spre, spost from qutip import liouvillian, mat2vec, state_number_enumerate from qutip.cy.spmatfuncs import cy_ode_rhs from qutip.solver import Options, Result, Stats from scipy.special import factorial from scipy.sparse import lil_matrix from scipy.integrate import ode def add_at_idx(seq, k, val): """ Add (subtract) a value in the tuple at position k """ lst = list(seq) lst[k] += val return tuple(lst) def prevhe(current_he, k, ncut): """ Calculate the previous heirarchy index for the current index `n`. """ nprev = add_at_idx(current_he, k, -1) if nprev[k] < 0: return False return nprev def nexthe(current_he, k, ncut): """ Calculate the next heirarchy index for the current index `n`. """ nnext = add_at_idx(current_he, k, 1) if sum(nnext) > ncut: return False return nnext def num_hierarchy(ncut, kcut): """ Get the total number of auxiliary density matrices in the hierarchy. Parameters ========== ncut: int The Heirarchy cutoff kcut: int The cutoff in the correlation frequencies, i.e., how many total exponents are used. Returns ======= num_hierarchy: int The total number of auxiliary density matrices in the hierarchy. """ return int(factorial(ncut + kcut) / (factorial(ncut) * factorial(kcut))) def _heom_state_dictionaries(dims, excitations): """ Return the number of states, and lookup-dictionaries for translating a state tuple to a state index, and vice versa, for a system with a given number of components and maximum number of excitations. Parameters ---------- dims: list A list with the number of states in each sub-system. excitations : integer The maximum numbers of dimension Returns ------- nstates, state2idx, idx2state: integer, dict, dict The number of states `nstates`, a dictionary for looking up state indices from a state tuple, and a dictionary for looking up state state tuples from state indices. """ nstates = 0 state2idx = {} idx2state = {} for state in state_number_enumerate(dims, excitations): state2idx[state] = nstates idx2state[nstates] = state nstates += 1 return nstates, state2idx, idx2state def _heom_number_enumerate(dims, excitations=None, state=None, idx=0): """ An iterator that enumerate all the state number arrays (quantum numbers on the form [n1, n2, n3, ...]) for a system with dimensions given by dims. Example: >>> for state in state_number_enumerate([2,2]): >>> print(state) [ 0. 0.] [ 0. 1.] [ 1. 0.] [ 1. 1.] Parameters ---------- dims : list or array The quantum state dimensions array, as it would appear in a Qobj. state : list Current state in the iteration. Used internally. excitations : integer (None) Restrict state space to states with excitation numbers below or equal to this value. idx : integer Current index in the iteration. Used internally. Returns ------- state_number : list Successive state number arrays that can be used in loops and other iterations, using standard state enumeration *by definition*. """ if state is None: state = np.zeros(len(dims)) if excitations and sum(state[0:idx]) > excitations: pass elif idx == len(dims): if excitations is None: yield np.array(state) else: yield tuple(state) else: for n in range(dims[idx]): state[idx] = n for s in state_number_enumerate(dims, excitations, state, idx + 1): yield s def get_aux_matrices(full, level, Nc, Nk): """ Extracts the auxiliary matrices at a particular level from the full hierarchy ADOs. Parameters ---------- full: ndarray A 2D array of the time evolution of the ADOs. level: int The level of the hierarchy to get the ADOs. Nc: int The hierarchy cutoff. k: int The total number of exponentials used to express the correlation. """ nstates, state2idx, idx2state = _heom_state_dictionaries([Nc + 1] * (Nk), Nc) aux_indices = [] aux_heom_indices = [] for stateid in state2idx: if np.sum(stateid) == level: aux_indices.append(state2idx[stateid]) aux_heom_indices.append(stateid) full = np.array(full) aux = [] for i in aux_indices: qlist = [Qobj(full[k, i, :].reshape(2, 2).T) for k in range(len(full))] aux.append(qlist) return aux, aux_heom_indices class HeomUB: """ The Heom class to tackle Heirarchy using the underdamped Brownian motion Parameters ---------- hamiltonian: :class:`qutip.Qobj` The system Hamiltonian coupling: :class:`qutip.Qobj` The coupling operator coup_strength: float The coupling strength. ck: list The list of amplitudes in the expansion of the correlation function vk: list The list of frequencies in the expansion of the correlation function ncut: int The hierarchy cutoff beta: float Inverse temperature, 1/kT. At zero temperature, beta is inf and we use an optimization for the non Matsubara terms """ def __init__(self, hamiltonian, coupling, coup_strength, ck, vk, ncut, beta=np.inf): self.hamiltonian = hamiltonian self.coupling = coupling self.ck, self.vk = ck, vk self.ncut = ncut self.kcut = len(ck) nhe, he2idx, idx2he = _heom_state_dictionaries([ncut + 1] * (len(ck)), ncut) self.nhe = nhe self.he2idx = he2idx self.idx2he = idx2he self.N = self.hamiltonian.shape[0] total_nhe = int( factorial(self.ncut + self.kcut) / (factorial(self.ncut) * factorial(self.kcut)) ) self.total_nhe = total_nhe self.hshape = (total_nhe, self.N ** 2) self.L = liouvillian(self.hamiltonian, []).data self.grad_shape = (self.N ** 2, self.N ** 2) self.spreQ = spre(coupling).data self.spostQ = spost(coupling).data self.L_helems = lil_matrix( (total_nhe * self.N ** 2, total_nhe * self.N ** 2), dtype=np.complex ) self.lam = coup_strength self.full_hierarchy = [] def populate(self, heidx_list): """ Given a Hierarchy index list, populate the graph of next and previous elements """ ncut = self.ncut kcut = self.kcut he2idx = self.he2idx idx2he = self.idx2he for heidx in heidx_list: for k in range(self.kcut): he_current = idx2he[heidx] he_next = nexthe(he_current, k, ncut) he_prev = prevhe(he_current, k, ncut) if he_next and (he_next not in he2idx): he2idx[he_next] = self.nhe idx2he[self.nhe] = he_next self.nhe += 1 if he_prev and (he_prev not in he2idx): he2idx[he_prev] = self.nhe idx2he[self.nhe] = he_prev self.nhe += 1 def grad_n(self, he_n): """ Get the gradient term for the Hierarchy ADM at level n """ c = self.ck nu = self.vk L = self.L.copy() gradient_sum = -np.sum(np.multiply(he_n, nu)) sum_op = gradient_sum * np.eye(L.shape[0]) L += sum_op # Fill in larger L nidx = self.he2idx[he_n] block = self.N ** 2 pos = int(nidx * (block)) self.L_helems[pos : pos + block, pos : pos + block] = L def grad_prev(self, he_n, k, prev_he): """ Get prev gradient """ c = self.ck nu = self.vk spreQ = self.spreQ spostQ = self.spostQ nk = he_n[k] norm_prev = nk # Non Matsubara terms if k == 0: norm_prev = np.sqrt(float(nk) / abs(self.lam)) op1 = -1j * norm_prev * (-self.lam * spostQ) elif k == 1: norm_prev = np.sqrt(float(nk) / abs(self.lam)) op1 = -1j * norm_prev * (self.lam * spreQ) # Matsubara terms else: norm_prev = np.sqrt(float(nk) / abs(c[k])) op1 = -1j * norm_prev * (c[k] * (spreQ - spostQ)) # Fill in larger L rowidx = self.he2idx[he_n] colidx = self.he2idx[prev_he] block = self.N ** 2 rowpos = int(rowidx * (block)) colpos = int(colidx * (block)) self.L_helems[rowpos : rowpos + block, colpos : colpos + block] = op1 def grad_next(self, he_n, k, next_he): c = self.ck nu = self.vk spreQ = self.spreQ spostQ = self.spostQ nk = he_n[k] # Non Matsubara terms if k < 2: norm_next = np.sqrt(self.lam * (nk + 1)) op2 = -1j * norm_next * (spreQ - spostQ) # Non Matsubara terms else: norm_next = np.sqrt(abs(c[k]) * (nk + 1)) op2 = -1j * norm_next * (spreQ - spostQ) # Fill in larger L rowidx = self.he2idx[he_n] colidx = self.he2idx[next_he] block = self.N ** 2 rowpos = int(rowidx * (block)) colpos = int(colidx * (block)) self.L_helems[rowpos : rowpos + block, colpos : colpos + block] = op2 def rhs(self, progress=None): """ Make the RHS """ while self.nhe < self.total_nhe: heidxlist = copy(list(self.idx2he.keys())) self.populate(heidxlist) if progress is not None: bar = progress(total=self.nhe * self.kcut) for n in self.idx2he: he_n = self.idx2he[n] self.grad_n(he_n) for k in range(self.kcut): next_he = nexthe(he_n, k, self.ncut) prev_he = prevhe(he_n, k, self.ncut) if next_he and (next_he in self.he2idx): self.grad_next(he_n, k, next_he) if prev_he and (prev_he in self.he2idx): self.grad_prev(he_n, k, prev_he) def solve(self, rho0, tlist, options=None, progress=None): """ Solve the Hierarchy equations of motion for the given initial density matrix and time. """ if options is None: options = Options() output = Result() output.solver = "hsolve" output.times = tlist output.states = [] output.states.append(Qobj(rho0)) dt = np.diff(tlist) rho_he = np.zeros(self.hshape, dtype=np.complex) rho_he[0] = rho0.full().ravel("F") rho_he = rho_he.flatten() self.rhs() L_helems = self.L_helems.asformat("csr") r = ode(cy_ode_rhs) r.set_f_params(L_helems.data, L_helems.indices, L_helems.indptr) r.set_integrator( "zvode", method=options.method, order=options.order, atol=options.atol, rtol=options.rtol, nsteps=options.nsteps, first_step=options.first_step, min_step=options.min_step, max_step=options.max_step, ) r.set_initial_value(rho_he, tlist[0]) dt = np.diff(tlist) n_tsteps = len(tlist) if progress: bar = progress(total=n_tsteps - 1) for t_idx, t in enumerate(tlist): if t_idx < n_tsteps - 1: r.integrate(r.t + dt[t_idx]) r1 = r.y.reshape(self.hshape) r0 = r1[0].reshape(self.N, self.N).T output.states.append(Qobj(r0)) r_heom = r.y.reshape(self.hshape) self.full_hierarchy.append(r_heom) if progress: bar.update() return output
1,768
0
54
23d4b9e441abbd42ced42cd4096380d4ab596e69
3,225
py
Python
tools/pycozmo_replay.py
gimait/pycozmo
601d9c09903b9300e8990723cae95974212afb09
[ "MIT" ]
123
2019-08-25T21:28:23.000Z
2022-03-12T13:54:59.000Z
tools/pycozmo_replay.py
solosito/pycozmo
5d28118eb8f7a625ae4a66054dabf19b4fe27483
[ "MIT" ]
41
2019-08-25T21:21:37.000Z
2022-02-09T14:20:54.000Z
tools/pycozmo_replay.py
solosito/pycozmo
5d28118eb8f7a625ae4a66054dabf19b4fe27483
[ "MIT" ]
51
2019-09-04T13:30:02.000Z
2022-01-09T01:20:24.000Z
#!/usr/bin/env python from typing import Optional import sys import time import dpkt import pycozmo if __name__ == '__main__': main()
32.908163
100
0.537364
#!/usr/bin/env python from typing import Optional import sys import time import dpkt import pycozmo class ReplayApp(object): def __init__(self, log_messages: Optional[list] = None, replay_messages: Optional[list] = None): self.log_messages = log_messages self.frame_count = 0 self.pkts = [] self.first_ts = None self.packet_id_filter = pycozmo.filter.Filter() if replay_messages: for i in replay_messages: self.packet_id_filter.deny_ids(pycozmo.protocol_encoder.PACKETS_BY_GROUP[i]) def load_engine_pkts(self, fspec): self.pkts = [] self.frame_count = 0 with open(fspec, "rb") as f: self.first_ts = None for ts, frame in dpkt.pcap.Reader(f): if self.first_ts is None: self.first_ts = ts eth = dpkt.ethernet.Ethernet(frame) if eth.type != dpkt.ethernet.ETH_TYPE_IP: # Skip non-IP frames continue ip = eth.data if ip.p != dpkt.ip.IP_PROTO_UDP: # Skip non-UDP frames continue udp = ip.data if udp.data[:7] != pycozmo.protocol_declaration.FRAME_ID: # Skip non-Cozmo frames continue frame = pycozmo.Frame.from_bytes(udp.data) if frame.type not in (pycozmo.protocol_declaration.FrameType.ENGINE, pycozmo.protocol_declaration.FrameType.ENGINE_ACT): # Skip non-engine frames continue for pkt in frame.pkts: if pkt.type not in [pycozmo.protocol_declaration.PacketType.COMMAND, pycozmo.protocol_declaration.PacketType.KEYFRAME]: # Skip non-command packets continue self.pkts.append((ts, pkt)) self.frame_count += 1 print("Loaded {} engine packets from {} frames.".format( len(self.pkts), self.frame_count)) def replay(self, fspec): self.load_engine_pkts(fspec) pycozmo.setup_basic_logging(log_level="DEBUG", protocol_log_level="DEBUG") cli = pycozmo.Client(protocol_log_messages=self.log_messages) cli.start() cli.connect() cli.wait_for_robot() try: for i, v in enumerate(self.pkts): # if i < 1113: # continue ts, pkt = v if self.packet_id_filter.filter(pkt.id): continue input() print("{}, time={:.06f}".format(i, ts - self.first_ts)) cli.conn.send(pkt) except KeyboardInterrupt: pass cli.disconnect() time.sleep(1) def main(): fspec = sys.argv[1] log_messages = [] # "objects", "audio", "state"] replay_messages = [] # "lights", "objects"] app = ReplayApp(log_messages=log_messages, replay_messages=replay_messages) app.replay(fspec) if __name__ == '__main__': main()
2,950
3
127
4724c3f8a6a2a060f1395a3f8e0e389b1091ba8a
7,944
py
Python
opfython/core/opf.py
gugarosa/opfython
19b467a92d85c7c26d231efec770645096827b4e
[ "Apache-2.0" ]
26
2018-04-24T20:16:18.000Z
2022-03-09T14:03:28.000Z
opfython/core/opf.py
gugarosa/opfython
19b467a92d85c7c26d231efec770645096827b4e
[ "Apache-2.0" ]
4
2020-12-26T14:57:18.000Z
2022-03-30T02:34:18.000Z
opfython/core/opf.py
gugarosa/opfython
19b467a92d85c7c26d231efec770645096827b4e
[ "Apache-2.0" ]
16
2019-05-20T15:41:56.000Z
2022-03-23T17:59:53.000Z
"""Optimum-Path Forest standard definitions. """ import pickle import numpy as np import opfython.math.distance as d import opfython.stream.loader as loader import opfython.utils.exception as e import opfython.utils.logging as l from opfython.core import Subgraph logger = l.get_logger(__name__) class OPF: """A basic class to define all common OPF-related methods. References: J. P. Papa, A. X. Falcão and C. T. N. Suzuki. LibOPF: A library for the design of optimum-path forest classifiers (2015). """ def __init__(self, distance='log_squared_euclidean', pre_computed_distance=None): """Initialization method. Args: distance (str): An indicator of the distance metric to be used. pre_computed_distance (str): A pre-computed distance file for feeding into OPF. """ logger.info('Creating class: OPF.') # Initializing an empty subgraph self.subgraph = None # An indicator of the distance metric to be used self.distance = distance # Gathers the distance function as a property self.distance_fn = d.DISTANCES[distance] # If OPF should use a pre-computed distance if pre_computed_distance: # Marks the boolean indicator as True self.pre_computed_distance = True # Apply the distances matrix self._read_distances(pre_computed_distance) else: # Marks the boolean indicator as False self.pre_computed_distance = False # Marks the pre-distances property as None self.pre_distances = None logger.debug('Distance: %s | Pre-computed distance: %s.', self.distance, self.pre_computed_distance) logger.info('Class created.') @property def subgraph(self): """Subgraph: Subgraph's instance. """ return self._subgraph @subgraph.setter @property def distance(self): """str: Distance metric to be used. """ return self._distance @distance.setter @property def distance_fn(self): """callable: Distance function to be used. """ return self._distance_fn @distance_fn.setter @property def pre_computed_distance(self): """bool: Whether OPF should use a pre-computed distance or not. """ return self._pre_computed_distance @pre_computed_distance.setter @property def pre_distances(self): """np.array: Pre-computed distance matrix. """ return self._pre_distances @pre_distances.setter def _read_distances(self, file_name): """Reads the distance between nodes from a pre-defined file. Args: file_name (str): File to be loaded. """ logger.debug('Running private method: read_distances().') # Getting file extension extension = file_name.split('.')[-1] if extension == 'csv': distances = loader.load_csv(file_name) elif extension == 'txt': distances = loader.load_txt(file_name) else: # Raises an ArgumentError exception raise e.ArgumentError('File extension not recognized. It should be either `.csv` or .txt`') # Check if distances have been properly loaded if distances is None: raise e.ValueError('Pre-computed distances could not been properly loaded') # Apply the distances matrix to the property self.pre_distances = distances def load(self, file_name): """Loads the object from a pickle encoding. Args: file_name (str): Pickle's file path to be loaded. """ logger.info('Loading model from file: %s ...', file_name) with open(file_name, 'rb') as origin_file: opf = pickle.load(origin_file) self.__dict__.update(opf.__dict__) logger.info('Model loaded.') def save(self, file_name): """Saves the object to a pickle encoding. Args: file_name (str): File's name to be saved. """ logger.info('Saving model to file: %s ...', file_name) with open(file_name, 'wb') as dest_file: pickle.dump(self, dest_file) logger.info('Model saved.') def fit(self, X, Y): """Fits data in the classifier. It should be directly implemented in OPF child classes. Args: X (np.array): Array of features. Y (np.array): Array of labels. """ raise NotImplementedError def predict(self, X): """Predicts new data using the pre-trained classifier. It should be directly implemented in OPF child classes. Args: X (np.array): Array of features. Returns: A list of predictions for each record of the data. """ raise NotImplementedError
32.292683
124
0.601586
"""Optimum-Path Forest standard definitions. """ import pickle import numpy as np import opfython.math.distance as d import opfython.stream.loader as loader import opfython.utils.exception as e import opfython.utils.logging as l from opfython.core import Subgraph logger = l.get_logger(__name__) class OPF: """A basic class to define all common OPF-related methods. References: J. P. Papa, A. X. Falcão and C. T. N. Suzuki. LibOPF: A library for the design of optimum-path forest classifiers (2015). """ def __init__(self, distance='log_squared_euclidean', pre_computed_distance=None): """Initialization method. Args: distance (str): An indicator of the distance metric to be used. pre_computed_distance (str): A pre-computed distance file for feeding into OPF. """ logger.info('Creating class: OPF.') # Initializing an empty subgraph self.subgraph = None # An indicator of the distance metric to be used self.distance = distance # Gathers the distance function as a property self.distance_fn = d.DISTANCES[distance] # If OPF should use a pre-computed distance if pre_computed_distance: # Marks the boolean indicator as True self.pre_computed_distance = True # Apply the distances matrix self._read_distances(pre_computed_distance) else: # Marks the boolean indicator as False self.pre_computed_distance = False # Marks the pre-distances property as None self.pre_distances = None logger.debug('Distance: %s | Pre-computed distance: %s.', self.distance, self.pre_computed_distance) logger.info('Class created.') @property def subgraph(self): """Subgraph: Subgraph's instance. """ return self._subgraph @subgraph.setter def subgraph(self, subgraph): if subgraph is not None: if not isinstance(subgraph, Subgraph): raise e.TypeError('`subgraph` should be a subgraph') self._subgraph = subgraph @property def distance(self): """str: Distance metric to be used. """ return self._distance @distance.setter def distance(self, distance): if distance not in ['additive_symmetric', 'average_euclidean', 'bhattacharyya', 'bray_curtis', 'canberra', 'chebyshev', 'chi_squared', 'chord', 'clark', 'cosine', 'dice', 'divergence', 'euclidean', 'gaussian', 'gower', 'hamming', 'hassanat', 'hellinger', 'jaccard', 'jeffreys', 'jensen', 'jensen_shannon', 'k_divergence', 'kulczynski', 'kullback_leibler', 'log_euclidean', 'log_squared_euclidean', 'lorentzian', 'manhattan', 'matusita', 'max_symmetric', 'mean_censored_euclidean', 'min_symmetric', 'neyman', 'non_intersection', 'pearson', 'sangvi', 'soergel', 'squared', 'squared_chord', 'squared_euclidean', 'statistic', 'topsoe', 'vicis_symmetric1', 'vicis_symmetric2', 'vicis_symmetric3', 'vicis_wave_hedges']: raise e.TypeError('`distance` should be `additive_symmetric`, `average_euclidean`, `bhattacharyya`, ' '`bray_curtis`, `canberra`, `chebyshev`, `chi_squared`, `chord`, `clark`, `cosine`, ' '`dice`, `divergence`, `euclidean`, `gaussian`, `gower`, `hamming`, `hassanat`, `hellinger`, ' '`jaccard`, `jeffreys`, `jensen`, `jensen_shannon`, `k_divergence`, `kulczynski`, ' '`kullback_leibler`, `log_euclidean`, `log_squared_euclidean`, `lorentzian`, `manhattan`, ' '`matusita`, `max_symmetric`, `mean_censored_euclidean`, `min_symmetric`, `neyman`, ' '`non_intersection`, `pearson`, `sangvi`, `soergel`, `squared`, `squared_chord`, ' '`squared_euclidean`, `statistic`, `topsoe`, `vicis_symmetric1`, `vicis_symmetric2`, ' '`vicis_symmetric3` or `vicis_wave_hedges`') self._distance = distance @property def distance_fn(self): """callable: Distance function to be used. """ return self._distance_fn @distance_fn.setter def distance_fn(self, distance_fn): if not callable(distance_fn): raise e.TypeError('`distance_fn` should be a callable') self._distance_fn = distance_fn @property def pre_computed_distance(self): """bool: Whether OPF should use a pre-computed distance or not. """ return self._pre_computed_distance @pre_computed_distance.setter def pre_computed_distance(self, pre_computed_distance): if not isinstance(pre_computed_distance, bool): raise e.TypeError('`pre_computed_distance` should be a boolean') self._pre_computed_distance = pre_computed_distance @property def pre_distances(self): """np.array: Pre-computed distance matrix. """ return self._pre_distances @pre_distances.setter def pre_distances(self, pre_distances): if pre_distances is not None: if not isinstance(pre_distances, np.ndarray): raise e.TypeError('`pre_distances` should be a numpy array') self._pre_distances = pre_distances def _read_distances(self, file_name): """Reads the distance between nodes from a pre-defined file. Args: file_name (str): File to be loaded. """ logger.debug('Running private method: read_distances().') # Getting file extension extension = file_name.split('.')[-1] if extension == 'csv': distances = loader.load_csv(file_name) elif extension == 'txt': distances = loader.load_txt(file_name) else: # Raises an ArgumentError exception raise e.ArgumentError('File extension not recognized. It should be either `.csv` or .txt`') # Check if distances have been properly loaded if distances is None: raise e.ValueError('Pre-computed distances could not been properly loaded') # Apply the distances matrix to the property self.pre_distances = distances def load(self, file_name): """Loads the object from a pickle encoding. Args: file_name (str): Pickle's file path to be loaded. """ logger.info('Loading model from file: %s ...', file_name) with open(file_name, 'rb') as origin_file: opf = pickle.load(origin_file) self.__dict__.update(opf.__dict__) logger.info('Model loaded.') def save(self, file_name): """Saves the object to a pickle encoding. Args: file_name (str): File's name to be saved. """ logger.info('Saving model to file: %s ...', file_name) with open(file_name, 'wb') as dest_file: pickle.dump(self, dest_file) logger.info('Model saved.') def fit(self, X, Y): """Fits data in the classifier. It should be directly implemented in OPF child classes. Args: X (np.array): Array of features. Y (np.array): Array of labels. """ raise NotImplementedError def predict(self, X): """Predicts new data using the pre-trained classifier. It should be directly implemented in OPF child classes. Args: X (np.array): Array of features. Returns: A list of predictions for each record of the data. """ raise NotImplementedError
2,822
0
130
8f421a457cb054f46d0d551c64aeebdaf5a52b6e
2,093
py
Python
record_shortcuts.py
elyssac02/grass-gis-on-hpc-henry2
68262c3687f967760b1c8cee0fff1a29e45a7698
[ "CC0-1.0" ]
1
2021-09-30T14:50:00.000Z
2021-09-30T14:50:00.000Z
record_shortcuts.py
elyssac02/grass-gis-on-hpc-henry2
68262c3687f967760b1c8cee0fff1a29e45a7698
[ "CC0-1.0" ]
54
2020-05-12T01:58:04.000Z
2022-03-11T15:39:49.000Z
record_shortcuts.py
elyssac02/grass-gis-on-hpc-henry2
68262c3687f967760b1c8cee0fff1a29e45a7698
[ "CC0-1.0" ]
3
2020-07-14T20:43:13.000Z
2021-09-23T14:45:05.000Z
#!/usr/bin/env python """Record default module version and symlinks as shortcuts""" import os import re import sys from datetime import datetime from pathlib import Path def read_and_record_shortcuts(path, filename): """Read content of the directory, check validity, record to YAML file""" path = Path(path) symlinks = sorted([x for x in path.iterdir() if x.is_symlink()]) default_version = None version_file = path / ".version" if version_file.exists(): version_content = version_file.read_text() match = re.search( "^set ModulesVersion (.+)$", version_content, flags=re.MULTILINE ) if match: default_version = match.group(1) else: sys.exit( "Module .version file exists, but ModulesVersion seems to be missing" ) if not (path / default_version).exists(): sys.exit( f"Module .version file exists, but version '{default_version}' does not" ) with open(filename, "w") as record: date = datetime.today().strftime("%Y-%m-%d") record.write(f"date: {date}\n") if default_version: record.write(f'default: "{default_version}"\n') if symlinks: record.write("symbolic_links:\n") for symlink in symlinks: target = os.readlink(symlink) if not symlink.exists(): sys.exit( f"Symlink '{symlink}' exists," f" but the target '{target}' does not" ) record.write(f' - name: "{symlink.name}"\n') record.write(f' points_to: "{target}"\n') def main(): """Check parameters, make sure output directory exists, record shortcuts""" if len(sys.argv) != 2: sys.exit(f"Usage: {sys.argv[0]} MODULE_DIR") metadata_dir = Path("available") metadata_dir.mkdir(exist_ok=True) read_and_record_shortcuts(sys.argv[1], metadata_dir / "shortcuts.yml") if __name__ == "__main__": main()
32.703125
88
0.580029
#!/usr/bin/env python """Record default module version and symlinks as shortcuts""" import os import re import sys from datetime import datetime from pathlib import Path def read_and_record_shortcuts(path, filename): """Read content of the directory, check validity, record to YAML file""" path = Path(path) symlinks = sorted([x for x in path.iterdir() if x.is_symlink()]) default_version = None version_file = path / ".version" if version_file.exists(): version_content = version_file.read_text() match = re.search( "^set ModulesVersion (.+)$", version_content, flags=re.MULTILINE ) if match: default_version = match.group(1) else: sys.exit( "Module .version file exists, but ModulesVersion seems to be missing" ) if not (path / default_version).exists(): sys.exit( f"Module .version file exists, but version '{default_version}' does not" ) with open(filename, "w") as record: date = datetime.today().strftime("%Y-%m-%d") record.write(f"date: {date}\n") if default_version: record.write(f'default: "{default_version}"\n') if symlinks: record.write("symbolic_links:\n") for symlink in symlinks: target = os.readlink(symlink) if not symlink.exists(): sys.exit( f"Symlink '{symlink}' exists," f" but the target '{target}' does not" ) record.write(f' - name: "{symlink.name}"\n') record.write(f' points_to: "{target}"\n') def main(): """Check parameters, make sure output directory exists, record shortcuts""" if len(sys.argv) != 2: sys.exit(f"Usage: {sys.argv[0]} MODULE_DIR") metadata_dir = Path("available") metadata_dir.mkdir(exist_ok=True) read_and_record_shortcuts(sys.argv[1], metadata_dir / "shortcuts.yml") if __name__ == "__main__": main()
0
0
0
2973f68aa295f821c1ca6e62f4b29b4927cb92eb
1,926
py
Python
country_named_entity_recognition/tests/test_georgia_country_vs_state.py
fastdatascience/countryfinder
174bd34a658c8f01563494e51c1d285c3095f1ff
[ "MIT" ]
null
null
null
country_named_entity_recognition/tests/test_georgia_country_vs_state.py
fastdatascience/countryfinder
174bd34a658c8f01563494e51c1d285c3095f1ff
[ "MIT" ]
null
null
null
country_named_entity_recognition/tests/test_georgia_country_vs_state.py
fastdatascience/countryfinder
174bd34a658c8f01563494e51c1d285c3095f1ff
[ "MIT" ]
null
null
null
import unittest from countryfinder.country_finder import find_countries
44.790698
159
0.695223
import unittest from countryfinder.country_finder import find_countries class TestSynonymsForUSA(unittest.TestCase): def test_american_address(self): countries = find_countries("8757 Georgia Avenue, 12th Floor") self.assertEqual(0, len(countries)) def test_other_eastern_european_countries(self): countries = find_countries("countries including Poland, Hungary, Czech republic, Slovakia, Georgia, Russia, Ukraine, Bulgaria and Latvia", True) self.assertEqual(9, len(countries)) self.assertEqual("PL", countries[0][0].alpha_2) self.assertEqual("HU", countries[1][0].alpha_2) self.assertEqual("CZ", countries[2][0].alpha_2) self.assertEqual("SK", countries[3][0].alpha_2) self.assertEqual("GE", countries[4][0].alpha_2) self.assertEqual("RU", countries[5][0].alpha_2) self.assertEqual("UA", countries[6][0].alpha_2) self.assertEqual("BG", countries[7][0].alpha_2) self.assertEqual("LV", countries[8][0].alpha_2) def test_georgian_address(self): countries = find_countries("""2. Dr. Avtandil Abramashvili Kristine Sharashidze Street #19 Tbilisi, Georgia 0131""") self.assertEqual(1, len(countries)) self.assertEqual("GE", countries[0][0].alpha_2) def test_georgia_country(self): countries = find_countries("Georgia (საქართველო, Sakartvelo; IPA: [sɑkʰɑrtʰvɛlɔ]), officially the Republic of Georgia from 1990 to 1995,") self.assertEqual(2, len(countries)) self.assertEqual("GE", countries[0][0].alpha_2) self.assertEqual("GE", countries[1][0].alpha_2) def test_georgia_state(self): countries = find_countries("Georgia is a state in the Southeastern region of the United States, bordered to the north by Tennessee and North Carolina") self.assertEqual(1, len(countries)) self.assertEqual("US", countries[0][0].alpha_2)
1,696
23
158
2e1292230597d1078b8609ca622f2f6e67696ad3
2,494
py
Python
carver/ole/ole/ole.py
maydewd/stoq-plugins-public
8b2877b5091ae731437ef35a95d4debdbf0a19f3
[ "Apache-2.0" ]
null
null
null
carver/ole/ole/ole.py
maydewd/stoq-plugins-public
8b2877b5091ae731437ef35a95d4debdbf0a19f3
[ "Apache-2.0" ]
null
null
null
carver/ole/ole/ole.py
maydewd/stoq-plugins-public
8b2877b5091ae731437ef35a95d4debdbf0a19f3
[ "Apache-2.0" ]
null
null
null
# Copyright 2014-2015 PUNCH Cyber Analytics Group # # 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. """ Overview ======== Carve OLE streams within Microsoft Office Documents """ import olefile from io import BytesIO from stoq.plugins import StoqCarverPlugin
29.341176
94
0.54571
# Copyright 2014-2015 PUNCH Cyber Analytics Group # # 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. """ Overview ======== Carve OLE streams within Microsoft Office Documents """ import olefile from io import BytesIO from stoq.plugins import StoqCarverPlugin class OLECarver(StoqCarverPlugin): def __init__(self): super().__init__() def activate(self, stoq): self.stoq = stoq super().activate() def carve(self, payload, **kwargs): """ Carve OLE streams :param bytes payload: OLE Payload to be parsed :param **kwargs kwargs: Additional attributes (unused) :returns: Carved OLE streams :rtype: list of tuples """ results = None file_object = BytesIO(payload) try: ole_object = olefile.OleFileIO(file_object) except OSError: return results streams = ole_object.listdir() for stream in streams: try: stream_buffer = ole_object.openstream(stream).read() # Check to see if we have a buffer if stream_buffer: # Looks like our first stream identified, let's make sure # the results are in a list if not results: results = [] # Save the results as a set() within a list meta = {'stream': streams.index(stream), 'name': stream[0], 'size': len(stream_buffer)} results.append((meta, stream_buffer)) self.log.info("Carved OLE stream {}[{}] ({} bytes)".format(meta['name'], meta['stream'], meta['size'])) except: pass return results
82
1,608
23
54ddfcbec622cddc0ff5caa8d2af77d5e8895d40
2,017
py
Python
main.py
ArtDevRodrigues/game-basePython
e150e592a03c5b37aa20c1fdbb047e11aec2f56d
[ "MIT" ]
null
null
null
main.py
ArtDevRodrigues/game-basePython
e150e592a03c5b37aa20c1fdbb047e11aec2f56d
[ "MIT" ]
null
null
null
main.py
ArtDevRodrigues/game-basePython
e150e592a03c5b37aa20c1fdbb047e11aec2f56d
[ "MIT" ]
null
null
null
from game import * from random import * # elementos e seus ids # 1-fogo # 2-agua # 3-terra # 4-ar p1 = Player("P1","Guerreiro","Masculino","Indiano") ws1 = [ #Weapon(id ,element ,price ,rarity ,strength ,speed), Weapon( 1 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"espada"), Weapon( 2 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"machado"), Weapon( 3 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"clava"), Weapon( 4 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"massa"), Weapon( 5 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"adaga") ] p2 = Player("P2","Guerreiro","Masculino","Australiano") ws2 = [ #Weapon(id ,element ,price ,rarity ,strength ,speed), Weapon( 6 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"espada"), Weapon( 7 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"machado"), Weapon( 8 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"clava"), Weapon( 9 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"massa"), Weapon(10 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"adaga") ] p1.setItensInventory(ws1) p1.equip() p2.setItensInventory(ws2) p2.equip() print(p1) print(p2) print("="*100) bf = BattleField(p1,p2) print(bf.fight()) print(bf.showPlayersStatus()) time = 0 while(not bf.end() and p1.isEquipped() and p2.isEquipped()): time += 1 if time >= 60: print("apos uma luta epica os combatentes se cansaram e ambos cairam exaltos no chao e assim o campeao menos machucado foi escolhido") print(("O "+bf.champion()+" Ganhou a luta") if bf.champion() != 0 else "Deu Empate ninguem ganhou, Droga tudo isso para nada -_-") break print(bf.fight()) print(bf.showPlayersStatus())
37.351852
142
0.646009
from game import * from random import * # elementos e seus ids # 1-fogo # 2-agua # 3-terra # 4-ar p1 = Player("P1","Guerreiro","Masculino","Indiano") ws1 = [ #Weapon(id ,element ,price ,rarity ,strength ,speed), Weapon( 1 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"espada"), Weapon( 2 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"machado"), Weapon( 3 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"clava"), Weapon( 4 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"massa"), Weapon( 5 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"adaga") ] p2 = Player("P2","Guerreiro","Masculino","Australiano") ws2 = [ #Weapon(id ,element ,price ,rarity ,strength ,speed), Weapon( 6 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"espada"), Weapon( 7 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"machado"), Weapon( 8 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"clava"), Weapon( 9 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"massa"), Weapon(10 ,randint(1,4),randint(10,200),randint(1,5),randint(10,100),randint(2,10),"adaga") ] p1.setItensInventory(ws1) p1.equip() p2.setItensInventory(ws2) p2.equip() print(p1) print(p2) print("="*100) bf = BattleField(p1,p2) print(bf.fight()) print(bf.showPlayersStatus()) time = 0 while(not bf.end() and p1.isEquipped() and p2.isEquipped()): time += 1 if time >= 60: print("apos uma luta epica os combatentes se cansaram e ambos cairam exaltos no chao e assim o campeao menos machucado foi escolhido") print(("O "+bf.champion()+" Ganhou a luta") if bf.champion() != 0 else "Deu Empate ninguem ganhou, Droga tudo isso para nada -_-") break print(bf.fight()) print(bf.showPlayersStatus())
0
0
0
fc1262d2e00618c8f06ef4ca02d3e3ab4748a18c
4,997
py
Python
Lib/site-packages/tensorboard/plugins/scalar/scalars_plugin.py
caiyongji/tf2.3.1-py3.7.9-full-built
ace4efcbf05b2b494388739718a18c13eab83c71
[ "CNRI-Python-GPL-Compatible" ]
4
2020-09-02T16:13:51.000Z
2021-06-05T08:45:59.000Z
Lib/site-packages/tensorboard/plugins/scalar/scalars_plugin.py
caiyongji/tf2.3.1-py3.7.9-full-built
ace4efcbf05b2b494388739718a18c13eab83c71
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
Lib/site-packages/tensorboard/plugins/scalar/scalars_plugin.py
caiyongji/tf2.3.1-py3.7.9-full-built
ace4efcbf05b2b494388739718a18c13eab83c71
[ "CNRI-Python-GPL-Compatible" ]
1
2020-09-17T13:16:30.000Z
2020-09-17T13:16:30.000Z
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """The TensorBoard Scalars plugin. See `http_api.md` in this directory for specifications of the routes for this plugin. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import csv import six from six import StringIO from werkzeug import wrappers import numpy as np from tensorboard import errors from tensorboard import plugin_util from tensorboard.backend import http_util from tensorboard.data import provider from tensorboard.plugins import base_plugin from tensorboard.plugins.scalar import metadata from tensorboard.util import tensor_util _DEFAULT_DOWNSAMPLING = 1000 # scalars per time series class OutputFormat(object): """An enum used to list the valid output formats for API calls.""" JSON = "json" CSV = "csv" class ScalarsPlugin(base_plugin.TBPlugin): """Scalars Plugin for TensorBoard.""" plugin_name = metadata.PLUGIN_NAME def __init__(self, context): """Instantiates ScalarsPlugin via TensorBoard core. Args: context: A base_plugin.TBContext instance. """ self._downsample_to = (context.sampling_hints or {}).get( self.plugin_name, _DEFAULT_DOWNSAMPLING ) self._data_provider = context.data_provider def index_impl(self, ctx, experiment=None): """Return {runName: {tagName: {displayName: ..., description: ...}}}.""" mapping = self._data_provider.list_scalars( ctx, experiment_id=experiment, plugin_name=metadata.PLUGIN_NAME, ) result = {run: {} for run in mapping} for (run, tag_to_content) in six.iteritems(mapping): for (tag, metadatum) in six.iteritems(tag_to_content): description = plugin_util.markdown_to_safe_html( metadatum.description ) result[run][tag] = { "displayName": metadatum.display_name, "description": description, } return result def scalars_impl(self, ctx, tag, run, experiment, output_format): """Result of the form `(body, mime_type)`.""" all_scalars = self._data_provider.read_scalars( ctx, experiment_id=experiment, plugin_name=metadata.PLUGIN_NAME, downsample=self._downsample_to, run_tag_filter=provider.RunTagFilter(runs=[run], tags=[tag]), ) scalars = all_scalars.get(run, {}).get(tag, None) if scalars is None: raise errors.NotFoundError( "No scalar data for run=%r, tag=%r" % (run, tag) ) values = [(x.wall_time, x.step, x.value) for x in scalars] if output_format == OutputFormat.CSV: string_io = StringIO() writer = csv.writer(string_io) writer.writerow(["Wall time", "Step", "Value"]) writer.writerows(values) return (string_io.getvalue(), "text/csv") else: return (values, "application/json") @wrappers.Request.application @wrappers.Request.application def scalars_route(self, request): """Given a tag and single run, return array of ScalarEvents.""" tag = request.args.get("tag") run = request.args.get("run") ctx = plugin_util.context(request.environ) experiment = plugin_util.experiment_id(request.environ) output_format = request.args.get("format") (body, mime_type) = self.scalars_impl( ctx, tag, run, experiment, output_format ) return http_util.Respond(request, body, mime_type)
35.439716
80
0.64959
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """The TensorBoard Scalars plugin. See `http_api.md` in this directory for specifications of the routes for this plugin. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import csv import six from six import StringIO from werkzeug import wrappers import numpy as np from tensorboard import errors from tensorboard import plugin_util from tensorboard.backend import http_util from tensorboard.data import provider from tensorboard.plugins import base_plugin from tensorboard.plugins.scalar import metadata from tensorboard.util import tensor_util _DEFAULT_DOWNSAMPLING = 1000 # scalars per time series class OutputFormat(object): """An enum used to list the valid output formats for API calls.""" JSON = "json" CSV = "csv" class ScalarsPlugin(base_plugin.TBPlugin): """Scalars Plugin for TensorBoard.""" plugin_name = metadata.PLUGIN_NAME def __init__(self, context): """Instantiates ScalarsPlugin via TensorBoard core. Args: context: A base_plugin.TBContext instance. """ self._downsample_to = (context.sampling_hints or {}).get( self.plugin_name, _DEFAULT_DOWNSAMPLING ) self._data_provider = context.data_provider def get_plugin_apps(self): return { "/scalars": self.scalars_route, "/tags": self.tags_route, } def is_active(self): return False # `list_plugins` as called by TB core suffices def frontend_metadata(self): return base_plugin.FrontendMetadata(element_name="tf-scalar-dashboard") def index_impl(self, ctx, experiment=None): """Return {runName: {tagName: {displayName: ..., description: ...}}}.""" mapping = self._data_provider.list_scalars( ctx, experiment_id=experiment, plugin_name=metadata.PLUGIN_NAME, ) result = {run: {} for run in mapping} for (run, tag_to_content) in six.iteritems(mapping): for (tag, metadatum) in six.iteritems(tag_to_content): description = plugin_util.markdown_to_safe_html( metadatum.description ) result[run][tag] = { "displayName": metadatum.display_name, "description": description, } return result def scalars_impl(self, ctx, tag, run, experiment, output_format): """Result of the form `(body, mime_type)`.""" all_scalars = self._data_provider.read_scalars( ctx, experiment_id=experiment, plugin_name=metadata.PLUGIN_NAME, downsample=self._downsample_to, run_tag_filter=provider.RunTagFilter(runs=[run], tags=[tag]), ) scalars = all_scalars.get(run, {}).get(tag, None) if scalars is None: raise errors.NotFoundError( "No scalar data for run=%r, tag=%r" % (run, tag) ) values = [(x.wall_time, x.step, x.value) for x in scalars] if output_format == OutputFormat.CSV: string_io = StringIO() writer = csv.writer(string_io) writer.writerow(["Wall time", "Step", "Value"]) writer.writerows(values) return (string_io.getvalue(), "text/csv") else: return (values, "application/json") @wrappers.Request.application def tags_route(self, request): ctx = plugin_util.context(request.environ) experiment = plugin_util.experiment_id(request.environ) index = self.index_impl(ctx, experiment=experiment) return http_util.Respond(request, index, "application/json") @wrappers.Request.application def scalars_route(self, request): """Given a tag and single run, return array of ScalarEvents.""" tag = request.args.get("tag") run = request.args.get("run") ctx = plugin_util.context(request.environ) experiment = plugin_util.experiment_id(request.environ) output_format = request.args.get("format") (body, mime_type) = self.scalars_impl( ctx, tag, run, experiment, output_format ) return http_util.Respond(request, body, mime_type)
522
0
107
8788365c9cd1db6b69140f3e164a309b5cbc16ec
929
py
Python
backend/surveybackend/djangobasic/urls.py
huarngpa/huarngpa_norc_challenge
58dc0d47b9149a8081f6ba81facb27bf5aefe8bb
[ "MIT" ]
null
null
null
backend/surveybackend/djangobasic/urls.py
huarngpa/huarngpa_norc_challenge
58dc0d47b9149a8081f6ba81facb27bf5aefe8bb
[ "MIT" ]
7
2020-02-11T23:07:58.000Z
2022-02-10T16:34:54.000Z
backend/surveybackend/djangobasic/urls.py
huarngpa/huarngpa_norc_challenge
58dc0d47b9149a8081f6ba81facb27bf5aefe8bb
[ "MIT" ]
null
null
null
from django.conf.urls import url, include from django.contrib.auth.decorators import login_required from django.urls import path from . import views from rest_framework.routers import DefaultRouter app_name = 'djangobasic' # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r'survey', views.SurveyViewSet) router.register(r'question', views.QuestionViewSet) router.register(r'choice', views.ChoiceViewSet) router.register(r'respond', views.ResponseViewSet) router.register(r'user', views.UserViewSet) urlpatterns = [ path('', login_required(views.IndexView.as_view()), name='index'), path('<int:pk>/', login_required(views.DetailView.as_view()), name='detail'), path('<int:pk>/results/', login_required(views.ResultsView.as_view()), name='results'), path('<int:question_id>/respond/', views.respond, name='respond'), url(r'^api/', include(router.urls)), ]
29.967742
91
0.748116
from django.conf.urls import url, include from django.contrib.auth.decorators import login_required from django.urls import path from . import views from rest_framework.routers import DefaultRouter app_name = 'djangobasic' # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r'survey', views.SurveyViewSet) router.register(r'question', views.QuestionViewSet) router.register(r'choice', views.ChoiceViewSet) router.register(r'respond', views.ResponseViewSet) router.register(r'user', views.UserViewSet) urlpatterns = [ path('', login_required(views.IndexView.as_view()), name='index'), path('<int:pk>/', login_required(views.DetailView.as_view()), name='detail'), path('<int:pk>/results/', login_required(views.ResultsView.as_view()), name='results'), path('<int:question_id>/respond/', views.respond, name='respond'), url(r'^api/', include(router.urls)), ]
0
0
0
7d17b72b36a89362f6e2c9c098373876069e693b
7,354
py
Python
python/paddle/fluid/tests/unittests/test_beam_search_op.py
jinyuKING/Paddle
1f4d46fa885448af4ce45827eae3c609280d4e34
[ "Apache-2.0" ]
null
null
null
python/paddle/fluid/tests/unittests/test_beam_search_op.py
jinyuKING/Paddle
1f4d46fa885448af4ce45827eae3c609280d4e34
[ "Apache-2.0" ]
null
null
null
python/paddle/fluid/tests/unittests/test_beam_search_op.py
jinyuKING/Paddle
1f4d46fa885448af4ce45827eae3c609280d4e34
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # 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 print_function import logging from paddle.fluid.op import Operator, DynamicRecurrentOp import paddle.fluid.core as core import unittest import numpy as np import paddle.fluid as fluid from paddle.fluid.framework import Program, program_guard class BeamSearchOpTester(unittest.TestCase): """unittest of beam_search_op""" if __name__ == '__main__': unittest.main()
36.77
79
0.549905
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # 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 print_function import logging from paddle.fluid.op import Operator, DynamicRecurrentOp import paddle.fluid.core as core import unittest import numpy as np import paddle.fluid as fluid from paddle.fluid.framework import Program, program_guard def create_tensor(scope, name, np_data): tensor = scope.var(name).get_tensor() tensor.set(np_data, core.CPUPlace()) return tensor class BeamSearchOpTester(unittest.TestCase): """unittest of beam_search_op""" def setUp(self): self.scope = core.Scope() self._create_ids() self._create_pre_scores() self._create_scores() self._create_pre_ids() self.scope.var('selected_ids') self.scope.var('selected_scores') self.scope.var('parent_idx') def test_run(self): op = Operator( 'beam_search', pre_ids='pre_ids', pre_scores='pre_scores', ids='ids', scores='scores', selected_ids='selected_ids', selected_scores='selected_scores', parent_idx='parent_idx', level=0, beam_size=2, end_id=0, ) op.run(self.scope, core.CPUPlace()) selected_ids = self.scope.find_var("selected_ids").get_tensor() selected_scores = self.scope.find_var("selected_scores").get_tensor() parent_idx = self.scope.find_var("parent_idx").get_tensor() self.assertTrue( np.allclose( np.array(selected_ids), np.array([4, 2, 3, 8])[:, np.newaxis])) self.assertTrue( np.allclose( np.array(selected_scores), np.array([0.5, 0.6, 0.9, 0.7])[:, np.newaxis])) self.assertEqual(selected_ids.lod(), [[0, 2, 4], [0, 1, 2, 3, 4]]) self.assertTrue( np.allclose(np.array(parent_idx), np.array([0, 1, 2, 3]))) def _create_pre_ids(self): np_data = np.array([[1, 2, 3, 4]], dtype='int64') tensor = create_tensor(self.scope, 'pre_ids', np_data) def _create_pre_scores(self): np_data = np.array([[0.1, 0.2, 0.3, 0.4]], dtype='float32') tensor = create_tensor(self.scope, 'pre_scores', np_data) def _create_ids(self): self.lod = [[0, 2, 4], [0, 1, 2, 3, 4]] np_data = np.array( [[4, 2, 5], [2, 1, 3], [3, 5, 2], [8, 2, 1]], dtype='int64') tensor = create_tensor(self.scope, "ids", np_data) tensor.set_lod(self.lod) def _create_scores(self): np_data = np.array( [ [0.5, 0.3, 0.2], [0.6, 0.3, 0.1], [0.9, 0.5, 0.1], [0.7, 0.5, 0.1], ], dtype='float32') tensor = create_tensor(self.scope, "scores", np_data) tensor.set_lod(self.lod) class TestBeamSearchOpError(unittest.TestCase): def test_errors(self): with program_guard(Program(), Program()): pre_ids = fluid.layers.data( name='pre_id', shape=[1], lod_level=2, dtype='int64') pre_scores = fluid.layers.data( name='pre_scores', shape=[1], lod_level=2, dtype='float32') probs = fluid.layers.data( name='probs', shape=[10000], dtype='float32') topk_scores, topk_indices = fluid.layers.topk(probs, k=4) accu_scores = fluid.layers.elementwise_add( x=fluid.layers.log(x=topk_scores), y=fluid.layers.reshape( pre_scores, shape=[-1]), axis=0) def test_preids_Variable(): # the input pre_ids must be Variable input_data = np.random.randint(1, 5, [5, 1]).astype("int64") fluid.layers.beam_search( pre_ids=input_data, pre_scores=pre_scores, ids=topk_indices, scores=accu_scores, beam_size=4, end_id=1) self.assertRaises(TypeError, test_preids_Variable) def test_prescores_Variable(): # the input pre_scores must be Variable input_data = np.random.uniform(1, 5, [5, 1]).astype("float32") fluid.layers.beam_search( pre_ids=pre_ids, pre_scores=input_data, ids=topk_indices, scores=accu_scores, beam_size=4, end_id=1) self.assertRaises(TypeError, test_prescores_Variable) def test_ids_Variable(): # the input ids must be Variable or None input_data = np.random.randint(1, 5, [5, 1]).astype("int64") fluid.layers.beam_search( pre_ids=pre_ids, pre_scores=pre_scores, ids=input_data, scores=accu_scores, beam_size=4, end_id=1) self.assertRaises(TypeError, test_ids_Variable) def test_scores_Variable(): # the input scores must be Variable input_data = np.random.randint(1, 5, [5, 1]).astype("float32") fluid.layers.beam_search( pre_ids=pre_ids, pre_scores=pre_scores, ids=topk_indices, scores=input_data, beam_size=4, end_id=1) self.assertRaises(TypeError, test_scores_Variable) def test_preids_dtype(): # the dtype of input pre_ids must be int64 input_data = fluid.layers.data( name='input_data', shape=[1], lod_level=2, dtype='float32') fluid.layers.beam_search( pre_ids=input_data, pre_scores=pre_scores, ids=topk_indices, scores=accu_scores, beam_size=4, end_id=1) self.assertRaises(TypeError, test_preids_dtype) def test_prescores_dtype(): # the dtype of input pre_scores must be float32 input_data = fluid.layers.data( name='input_data', shape=[1], lod_level=2, dtype='int64') fluid.layers.beam_search( pre_ids=pre_ids, pre_scores=input_data, ids=topk_indices, scores=accu_scores, beam_size=4, end_id=1) self.assertRaises(TypeError, test_prescores_dtype) if __name__ == '__main__': unittest.main()
6,080
26
234
94fe63f2bb4e1cc66bec275d7ad54bdb798933b1
45
py
Python
apps/utils/images/__init__.py
jorgesaw/oclock
2a78bd4d1ab40eaa65ea346cf8c37556fcbbeca5
[ "MIT" ]
null
null
null
apps/utils/images/__init__.py
jorgesaw/oclock
2a78bd4d1ab40eaa65ea346cf8c37556fcbbeca5
[ "MIT" ]
5
2021-03-19T10:16:00.000Z
2022-02-10T09:16:32.000Z
apps/utils/images/__init__.py
jorgesaw/oclock
2a78bd4d1ab40eaa65ea346cf8c37556fcbbeca5
[ "MIT" ]
null
null
null
from .uploads_images import custom_upload_to
22.5
44
0.888889
from .uploads_images import custom_upload_to
0
0
0
d8536b2cabc7f5bc241592886b848784c96f50cc
1,019
py
Python
results/baseline/parse_baseline.py
XiaoSanchez/autophase
3d8d173ad27b9786e36efd22d0ceacbcf1cb1dfb
[ "BSD-3-Clause" ]
14
2020-04-03T12:41:50.000Z
2022-02-04T00:05:01.000Z
results/baseline/parse_baseline.py
XiaoSanchez/autophase
3d8d173ad27b9786e36efd22d0ceacbcf1cb1dfb
[ "BSD-3-Clause" ]
2
2020-03-02T04:32:58.000Z
2021-09-15T20:02:25.000Z
results/baseline/parse_baseline.py
XiaoSanchez/autophase
3d8d173ad27b9786e36efd22d0ceacbcf1cb1dfb
[ "BSD-3-Clause" ]
8
2020-03-02T10:30:36.000Z
2021-08-03T02:29:38.000Z
import pickle get_random_pgm_groups()
25.475
84
0.584887
import pickle def get_random_pgm_groups(): interval = [0, 1000, 5000, 10000, 50000, 100000] buckets = {} for i in range(len(interval)-1): buckets[i] = [] valid_count = 0 with open('baseline.txt') as f: lines = f.readlines() print("Ignore Header Line: {}".format(lines[0])) lines = lines[1:] for line in lines: data = line.split('|') bm = data[0] o0_cycle = int(data[1]) o3_cycle = int(data[2]) if o0_cycle == 10000000: #print("{}".format(bm)) continue valid_count += 1 for i in range(len(interval)-1): if o0_cycle >= interval[i] and o0_cycle < interval[i+1]: buckets[i].append(data) break print("Total {} valid programs".format(valid_count)) for i in range(len(interval)-1): print("Interval {} ~ {}: {}".format(interval[i], interval[i+1],len(buckets[i]))) output = open('random_pgms.pkl', 'wb') pickle.dump(buckets, output) output.close() get_random_pgm_groups()
957
0
23
a0d5b28ad7f528382bfd88d685d4abe641a9bb60
395
py
Python
hads_adad.py
rezasf/hads-adad
c6183c8a84ceb526242822c49ba7ad8bc71287a3
[ "Unlicense" ]
null
null
null
hads_adad.py
rezasf/hads-adad
c6183c8a84ceb526242822c49ba7ad8bc71287a3
[ "Unlicense" ]
null
null
null
hads_adad.py
rezasf/hads-adad
c6183c8a84ceb526242822c49ba7ad8bc71287a3
[ "Unlicense" ]
null
null
null
# Copyright (C) 2021 rezasf - All Rights Reserved import random res = random.randint(0,40) count = 1 while True: daf =int(input("ye adad vared kon: ")) if daf == res : print("bad az "+ str(count) +" bar talash"+" shoma bordid") break elif daf > res : print("bro pain") count += 1 elif daf < res : print("bro bala") count += 1
23.235294
67
0.544304
# Copyright (C) 2021 rezasf - All Rights Reserved import random res = random.randint(0,40) count = 1 while True: daf =int(input("ye adad vared kon: ")) if daf == res : print("bad az "+ str(count) +" bar talash"+" shoma bordid") break elif daf > res : print("bro pain") count += 1 elif daf < res : print("bro bala") count += 1
0
0
0
a8d084e6f1b2eaabb108d7dc5fb8eaa0ab99eec6
789
py
Python
dipole_test.py
rweigel/magnetovis
2f466df4e29c2bb71c3d92294efea7f9eb036cec
[ "BSD-2-Clause" ]
null
null
null
dipole_test.py
rweigel/magnetovis
2f466df4e29c2bb71c3d92294efea7f9eb036cec
[ "BSD-2-Clause" ]
2
2020-11-06T10:20:08.000Z
2021-01-25T17:44:48.000Z
dipole_test.py
rweigel/magnetovis
2f466df4e29c2bb71c3d92294efea7f9eb036cec
[ "BSD-2-Clause" ]
1
2021-05-22T11:35:18.000Z
2021-05-22T11:35:18.000Z
import magnetovis as mvs import paraview.simple as pvs time = [2015,3,20,0,0,0] # time not used if coord_sys = GSM coord_sys = 'GSM' M=7.788E22 dipoleFieldSourceDisplay, renderView, dipoleFieldSource = mvs.dipole_field(time, M, coord_sys) # create a new 'Glyph' glyph = pvs.Glyph(registrationName='-- Glyph', Input=dipoleFieldSource, GlyphType='Arrow') glyph.OrientationArray = ['POINTS', 'B_field'] glyph.ScaleArray = ['POINTS', 'No scale array'] # show data in view glyphDisplay = pvs.Show(glyph, renderView, 'GeometryRepresentation') glyphDisplay.Opacity = 0.72 # center and position camera renderView.CameraPosition = [0, -120, 0] renderView.CameraFocalPoint = [0, 0.0, 0] renderView.CameraViewUp = [0.0, 0.0, 1.0] pvs.Hide(dipoleFieldSource, renderView) renderView.Update()
30.346154
95
0.746515
import magnetovis as mvs import paraview.simple as pvs time = [2015,3,20,0,0,0] # time not used if coord_sys = GSM coord_sys = 'GSM' M=7.788E22 dipoleFieldSourceDisplay, renderView, dipoleFieldSource = mvs.dipole_field(time, M, coord_sys) # create a new 'Glyph' glyph = pvs.Glyph(registrationName='-- Glyph', Input=dipoleFieldSource, GlyphType='Arrow') glyph.OrientationArray = ['POINTS', 'B_field'] glyph.ScaleArray = ['POINTS', 'No scale array'] # show data in view glyphDisplay = pvs.Show(glyph, renderView, 'GeometryRepresentation') glyphDisplay.Opacity = 0.72 # center and position camera renderView.CameraPosition = [0, -120, 0] renderView.CameraFocalPoint = [0, 0.0, 0] renderView.CameraViewUp = [0.0, 0.0, 1.0] pvs.Hide(dipoleFieldSource, renderView) renderView.Update()
0
0
0
fc3ec0b8abfc036829de0eac8883435ae2262c58
2,443
py
Python
main.py
heylakshya/youtubeRabbitHole
c1a45479429cc68f36ac8586cc54755cc119141b
[ "MIT" ]
1
2020-11-26T13:49:42.000Z
2020-11-26T13:49:42.000Z
main.py
heylakshya/youtubeRabbitHole
c1a45479429cc68f36ac8586cc54755cc119141b
[ "MIT" ]
null
null
null
main.py
heylakshya/youtubeRabbitHole
c1a45479429cc68f36ac8586cc54755cc119141b
[ "MIT" ]
1
2021-03-02T05:00:57.000Z
2021-03-02T05:00:57.000Z
import functions as f import random import numpy as np import matplotlib.pyplot as plt import json def crawl2(url, depth, first_call = 0, home_tags = None): ''' Crawl the yt web graph and return relevance index upto defined depth. ''' print("---\tat depth = {}".format(depth)) if depth == 0: return [] tags = home_tags links = None attempt=5 while (tags==None or links==None) and attempt>0: attempt -= 1 tags, links = f.getDataFromUrl(url) if tags == None or links == None: print("---\t---\tpage issues...retrying") continue if attempt==0: print("---\t---\tran out of attempts") return [] temp_tags = None attempt = 10 while temp_tags==None and attempt>0: attempt -= 1 link = random.choice(links) temp_tags, _ = f.getDataFromUrl(link) if temp_tags == None: print("---\t---\tpage issues...skipping page") continue if attempt==0: print("---\t---\tran out of attempts") return [] relevance_list = [] relevance = 0 if first_call==0: tags = home_tags relevance = f.getRelevance(tags, temp_tags) relevance_list.append(relevance) return_list = crawl2(link, depth-1, 0, tags) relevance_list = relevance_list + return_list return relevance_list # Start URLs urls = [] with open("links.txt","r") as file: urls = file.readlines() urls = list(set(urls)) # Each item in this list is a list with relevance # at different depths signified by their indices results_for_urls = [] depth_range = 16 num_links = len(urls) lim_urls = random.sample(urls,num_links) results_for_json = {} for index, url in enumerate(lim_urls): print("FOR \turl#{}/{}".format(index + 1, len(lim_urls))) try: result = crawl2(url, depth_range, 1) except: continue if len(result)==depth_range: # Save result in json results_for_json[url] = result with open("results_appended_new.json","w") as file: file.write(json.dumps(results_for_json)) # links_done.add(url) results_for_urls.append(result) visualize_results(results_for_urls)
25.715789
61
0.6623
import functions as f import random import numpy as np import matplotlib.pyplot as plt import json def crawl2(url, depth, first_call = 0, home_tags = None): ''' Crawl the yt web graph and return relevance index upto defined depth. ''' print("---\tat depth = {}".format(depth)) if depth == 0: return [] tags = home_tags links = None attempt=5 while (tags==None or links==None) and attempt>0: attempt -= 1 tags, links = f.getDataFromUrl(url) if tags == None or links == None: print("---\t---\tpage issues...retrying") continue if attempt==0: print("---\t---\tran out of attempts") return [] temp_tags = None attempt = 10 while temp_tags==None and attempt>0: attempt -= 1 link = random.choice(links) temp_tags, _ = f.getDataFromUrl(link) if temp_tags == None: print("---\t---\tpage issues...skipping page") continue if attempt==0: print("---\t---\tran out of attempts") return [] relevance_list = [] relevance = 0 if first_call==0: tags = home_tags relevance = f.getRelevance(tags, temp_tags) relevance_list.append(relevance) return_list = crawl2(link, depth-1, 0, tags) relevance_list = relevance_list + return_list return relevance_list def visualize_results(results): y = np.array([np.array(x) for x in results]) y_avg = np.average(y, axis=0) for i in range(y.shape[0]): plt.plot(y[i], marker='o', color='b', alpha=0.2) plt.plot(y_avg, marker='o', color='r') plt.xlabel("Depth of rabbit hole") plt.ylabel("Relevance to root video") fig = plt.gcf() fig.set_size_inches(10, 7) plt.show() # Start URLs urls = [] with open("links.txt","r") as file: urls = file.readlines() urls = list(set(urls)) # Each item in this list is a list with relevance # at different depths signified by their indices results_for_urls = [] depth_range = 16 num_links = len(urls) lim_urls = random.sample(urls,num_links) results_for_json = {} for index, url in enumerate(lim_urls): print("FOR \turl#{}/{}".format(index + 1, len(lim_urls))) try: result = crawl2(url, depth_range, 1) except: continue if len(result)==depth_range: # Save result in json results_for_json[url] = result with open("results_appended_new.json","w") as file: file.write(json.dumps(results_for_json)) # links_done.add(url) results_for_urls.append(result) visualize_results(results_for_urls)
372
0
23
3591c896cf2d3754b91b4056684ed9d3359d0500
765
py
Python
lib/innvestigate/examples/utils_imagenet.py
vwesselkamp/deepfake-fingerprint-atacks
0befc913b081913255399d4264f09bce0d39cbcb
[ "MIT" ]
null
null
null
lib/innvestigate/examples/utils_imagenet.py
vwesselkamp/deepfake-fingerprint-atacks
0befc913b081913255399d4264f09bce0d39cbcb
[ "MIT" ]
null
null
null
lib/innvestigate/examples/utils_imagenet.py
vwesselkamp/deepfake-fingerprint-atacks
0befc913b081913255399d4264f09bce0d39cbcb
[ "MIT" ]
null
null
null
import numpy as np import innvestigate import innvestigate.utils as iutils import innvestigate.utils.visualizations as ivis
19.615385
71
0.688889
import numpy as np import innvestigate import innvestigate.utils as iutils import innvestigate.utils.visualizations as ivis def preprocess(X, net): X = X.copy() X = net["preprocess_f"](X) return X def postprocess(X, color_conversion, channels_first): X = X.copy() X = iutils.postprocess_images( X, color_coding=color_conversion, channels_first=channels_first ) return X def image(X): X = X.copy() return ivis.project(X, absmax=255.0, input_is_positive_only=True) def bk_proj(X): X = ivis.clip_quantile(X, 1) return ivis.project(X) def heatmap(X): # X = ivis.gamma(X, minamp=0, gamma=0.95) return ivis.heatmap(X) def graymap(X): return ivis.graymap(np.abs(X), input_is_positive_only=True)
496
0
138
0db5529ac93de1b8d3df8ca691845c4c56323a28
2,844
py
Python
oidc/models.py
didx-xyz/yoma-oidc-bridge
7e3ff6ab3ea4fed01cd7d4c113c7c3b3244356eb
[ "Apache-2.0" ]
4
2020-10-08T07:36:22.000Z
2022-02-04T12:31:31.000Z
oidc/models.py
didx-xyz/yoma-oidc-bridge
7e3ff6ab3ea4fed01cd7d4c113c7c3b3244356eb
[ "Apache-2.0" ]
1
2021-04-10T08:32:42.000Z
2021-04-10T08:32:42.000Z
oidc/models.py
didx-xyz/yoma-oidc-bridge
7e3ff6ab3ea4fed01cd7d4c113c7c3b3244356eb
[ "Apache-2.0" ]
7
2021-02-10T16:04:29.000Z
2022-03-16T08:04:48.000Z
from django.db import models import uuid from model_utils.models import TimeStampedModel from django.conf import settings # Create your models here.
34.26506
84
0.678973
from django.db import models import uuid from model_utils.models import TimeStampedModel from django.conf import settings def disambiguate_referent(referent: str) -> str: ref_idx = 1 ref_split = referent.split("~") if len(ref_split) > 1: old_idx = int(ref_split[-1]) ref_idx += old_idx return f"{ref_split[0]}~{ref_idx}" # Create your models here. class PresentationConfigurations(models.Model): id = models.CharField(primary_key=True, max_length=255) subject_identifier = models.CharField(max_length=255) configuration = models.JSONField() def __str__(self): return f"{self.id}" def to_json(self): presentation_request = { "name": self.configuration.get("name", ""), "version": self.configuration.get("version", ""), "requested_attributes": {}, "requested_predicates": {}, } for attr in self.configuration.get("requested_attributes", []): label = attr.get("label", str(uuid.uuid4())) if label in presentation_request.get("requested_attributes", {}).keys(): label = disambiguate_referent(label) presentation_request["requested_attributes"].update({label: attr}) for attr in self.configuration.get("requested_predicates", []): label = attr.get("label", str(uuid.uuid4())) if label in presentation_request.get("requested_predicates", {}).keys(): label = disambiguate_referent(label) presentation_request["requested_predicates"].update({label: attr}) return {"proof_request": presentation_request} class AuthSession(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) presentation_record_id = models.CharField(max_length=255) presentation_request_id = models.CharField(max_length=255) presentation_request = models.JSONField() presentation_request_satisfied = models.BooleanField(default=False) expired_timestamp = models.DateTimeField(blank=True, null=True) request_parameters = models.JSONField() presentation = models.JSONField(null=True, blank=True) def __str__(self): return f"{self.presentation_record_id} - {self.presentation_request_id}" def satisfy_session(self, presentation): self.presentation_request_satisfied = True self.presentation = presentation self.save() class MappedUrl(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) url = models.TextField() session = models.ForeignKey( AuthSession, on_delete=models.CASCADE, blank=True, null=True ) def __str__(self): return f"{self.id}" def get_short_url(self): return f"{settings.SITE_URL}/url/{self.id}"
1,513
1,084
92
93d40edf5cdacd5bd4debc10d624462c580a5df1
613
py
Python
tests/packages/PlatformDependentCode/plugin.py
Thom1729/st_package_reviewer
71e4eaad60fe3391b0a4d39405b784ec84ea58bc
[ "MIT" ]
8
2017-06-07T07:52:32.000Z
2021-04-26T23:46:36.000Z
tests/packages/PlatformDependentCode/plugin.py
Thom1729/st_package_reviewer
71e4eaad60fe3391b0a4d39405b784ec84ea58bc
[ "MIT" ]
26
2017-05-29T21:11:10.000Z
2021-05-16T20:58:23.000Z
tests/packages/PlatformDependentCode/plugin.py
Thom1729/st_package_reviewer
71e4eaad60fe3391b0a4d39405b784ec84ea58bc
[ "MIT" ]
8
2017-05-31T21:16:49.000Z
2021-03-20T16:43:26.000Z
import platform, sublime, sublime_plugin
25.541667
59
0.575856
import platform, sublime, sublime_plugin class AwesomeFooCommand(sublime_plugin.ApplicationCommand): def run(self): if "Darwin" in platform.platform(): print("Darwin") else: print("not supported") class AwesomeBarCommand(sublime_plugin.ApplicationCommand): def run(self): if sublime.platform() == "linux": print("linux") elif sublime.platform() == "osx": print("osx") elif sublime.platform() == "windows": print("windows") else: print("unknown: %s" % sublime.platform())
386
76
108
7b7dfdca5cb46e7b8e6460d7345da616a31b7001
9,426
py
Python
scripts/automation/trex_control_plane/interactive/trex/astf/ignored_ips_macs.py
GabrielGanne/trex-core
688a0fe0adb890964691473723d70ffa98e00dd3
[ "Apache-2.0" ]
null
null
null
scripts/automation/trex_control_plane/interactive/trex/astf/ignored_ips_macs.py
GabrielGanne/trex-core
688a0fe0adb890964691473723d70ffa98e00dd3
[ "Apache-2.0" ]
null
null
null
scripts/automation/trex_control_plane/interactive/trex/astf/ignored_ips_macs.py
GabrielGanne/trex-core
688a0fe0adb890964691473723d70ffa98e00dd3
[ "Apache-2.0" ]
null
null
null
from ..common.trex_exceptions import * from ..utils.common import * from ..utils.text_tables import TRexTextTable, print_table_with_header from ..utils import parsing_opts
33.30742
120
0.579355
from ..common.trex_exceptions import * from ..utils.common import * from ..utils.text_tables import TRexTextTable, print_table_with_header from ..utils import parsing_opts class MacsIpsMngr(object): def __init__(self, client, macs = None, ips = None): self.client = client self.black_list_macs = macs or set() self.black_list_ip = ips or set() self.max_size = 1000 def add_macs_list(self, mac_list, is_str=True): if len(self.black_list_macs) + len(mac_list) > 1000: raise TRexError("The maximum size of mac's black list is: %s" % (self.max_size)) for mac in mac_list: if is_str: mac_str = mac if ":" in mac: mac_str = mac2str(mac_str) mac_addr = mac_str_to_num(mac_str) else: if type(mac) != int: raise TRexError("The Mac type is not int") mac_addr = mac self.black_list_macs.add(mac_addr) def _remove_mac_list(self, mac_list, is_str=True): for mac in mac_list: mac_addr = mac if is_str: if ":" in mac: mac_addr = mac2str(mac) mac_addr = mac_str_to_num(mac_addr) if mac_addr not in self.black_list_macs: raise TRexError("The list does not contain MAC address: %s" % (int2mac(mac_addr))) self.black_list_macs.remove(mac_addr) def _clear_mac_str_list(self): self.black_list_macs.clear() def _upload_mac_list(self): json_macs = [] for mac in self.black_list_macs: json_macs.append({'mac_addr' : mac}) params = {'mac_list' : json_macs} self.client.ctx.logger.pre_cmd("setting ignored mac list" + '.\n') rc = self.client._transmit("set_ignored_macs", params = params) self.client.ctx.logger.post_cmd(rc) if not rc: raise TRexError(rc.err()) return rc def _mac_list_to_str(self, mac_list): str_mac_list = [] for mac in mac_list: str_mac_list.append(int2mac(mac)) return str_mac_list def _get_mac_list_from_server(self): rc = self.client._transmit("get_ignored_macs") self.client.ctx.logger.post_cmd(rc) if not rc: raise TRexError(rc.err()) data = rc.data() mac_list = [] for mac_dict in data: for _ , mac in mac_dict.items(): mac_list.append(mac) return mac_list def get_mac_list(self, from_server=True, to_str=True): if from_server: mac_list = self._get_mac_list_from_server() else: mac_list = list(self.black_list_macs) if to_str: mac_list = self._mac_list_to_str(mac_list) return mac_list def add_ips_list(self, ips_list, is_str=True): if len(self.black_list_ip) + len(ips_list) > 1000: raise TRexError("The maximum size of IP addresses black list is: %s" % (self.max_size)) for ip in ips_list: ip_addr = ip if is_str: ip_addr = ip2int(ip) else: if type(ip) != int: raise TRexError("The IP type is not int") self.black_list_ip.add(ip_addr) def _remove_ip_list(self, ip_list, is_str=True): for ip in ip_list: if is_str: ip_addr = ip2int(ip) else: ip_addr = ip if ip_addr not in self.black_list_ip: raise TRexError("The list does not contain IPv4 address: %s" % (int2ip(ip_addr))) self.black_list_ip.remove(ip_addr) def _clear_ips_list(self): self.black_list_ip.clear() def _upload_ips_list(self): json_ips = [] for ip in self.black_list_ip: json_ips.append({'ip' : ip}) params = {'ip_list' : json_ips} self.client.ctx.logger.pre_cmd("setting ignored ip list" + '.\n') rc = self.client._transmit("set_ignored_ips", params = params) self.client.ctx.logger.post_cmd(rc) if not rc: raise TRexError(rc.err()) return rc def _ip_list_to_str(self, ip_list): str_ip_list = [] for ip in ip_list: str_ip_list.append(int2ip(ip)) return str_ip_list def _get_ips_list_from_server(self): rc = self.client._transmit("get_ignored_ips") if not rc: raise TRexError(rc.err()) data = rc.data() ip_list = [] for ip_dict in data: for _ , ip in ip_dict.items(): ip_list.append(ip) return ip_list def get_ips_list(self, from_server=True, to_str=True): if from_server: ip_list = self._get_ips_list_from_server() else: ip_list = list(self.black_list_ip) if to_str: ip_list = self._ip_list_to_str(ip_list) return ip_list def _flush_all(self): self._upload_mac_list() self._upload_ips_list() def _clear_all(self): self._clear_mac_str_list() self._clear_ips_list() def set_ignored_macs_ips(self, mac_list = None, ip_list=None, upload_to_server=True, is_str=True, to_override=True): if to_override: self._clear_all() rc = True if mac_list: self.add_macs_list(mac_list, is_str=is_str) if ip_list: self.add_ips_list(ip_list, is_str=is_str) if upload_to_server: rc = self._flush_all() return rc def _remove_ignored_macs_ips(self, mac_list = None, ip_list=None, upload_to_server=False, is_str=True): rc = True if mac_list: self._remove_mac_list(mac_list, is_str=is_str) if ip_list: self._remove_ip_list(ip_list, is_str=is_str) if upload_to_server: rc = self._flush_all() return rc def _show_macs_table(self): server_mac_set = set(self._get_mac_list_from_server()) table_name = "Mac's black list" if server_mac_set != self.black_list_macs: table_name += " (Not sync with server)" else: table_name += " (Sync with server)" macs_table = TRexTextTable(table_name) macs_table.set_cols_align(['c'] * 3) macs_table.set_cols_dtype(['t'] * 3) macs_table.header(['Mac_start', 'Mac_end', 'Is-Sync']) sorted_mac_list = sorted(self.black_list_macs) start_mac = None end_mac = None is_mac_sync = True max_len = len("Mac_start") length = len(sorted_mac_list) for idx, mac in enumerate(sorted_mac_list): if mac not in server_mac_set: is_mac_sync = False if not start_mac: start_mac = mac if idx != length - 1: next_mac = sorted_mac_list[idx + 1] else: next_mac = mac + 2 if next_mac - mac > 1: end_mac = mac start_mac_str = int2mac(start_mac) end_mac_str = int2mac(end_mac) macs_table.add_row([start_mac_str, end_mac_str, is_mac_sync]) max_len = max (max_len, max(len(start_mac_str), len(end_mac_str))) is_mac_sync = True start_mac = None macs_table.set_cols_width([max_len, max_len, 7]) print_table_with_header(macs_table, untouched_header = macs_table.title, buffer = sys.stdout) def _show_ips_table(self): server_ip_set = set(self._get_ips_list_from_server()) table_name = "IP's black list" if server_ip_set != self.black_list_ip: table_name += " (Not sync with server)" else: table_name += " (Sync with server)" ips_table = TRexTextTable(table_name) ips_table.set_cols_align(['c'] * 3) ips_table.set_cols_dtype(['t'] * 3) ips_table.header(['IP_start', 'IP_end', 'Is-Sync']) sorted_ip_list = sorted(self.black_list_ip) start_ip = None end_ip = None is_ip_sync = True max_len = len("IP_start") length = len(sorted_ip_list) for idx, ip in enumerate(sorted_ip_list): if ip not in server_ip_set: is_ip_sync = False if not start_ip: start_ip = ip if idx != length - 1: next_ip = sorted_ip_list[idx + 1] else: next_ip = ip + 2 if next_ip - ip > 1: end_ip = ip start_ip_str = int2ip(start_ip) end_ip_str = int2ip(end_ip) ips_table.add_row([start_ip_str, end_ip_str, is_ip_sync]) max_len = max (max_len, max(len(start_ip_str), len(end_ip_str))) is_ip_sync = True start_ip = None ips_table.set_cols_width([max_len, max_len, 7]) print_table_with_header(ips_table, untouched_header = ips_table.title, buffer = sys.stdout) def sync_with_server(self): self._clear_all() self.black_list_ip.update(self._get_ips_list_from_server()) self.black_list_macs.update(self._get_mac_list_from_server()) def _show(self): self._show_macs_table() self._show_ips_table()
8,583
5
643
44d826263dd166b68c14221609b4bc0ae344851f
3,578
py
Python
Zero_to_Google_SDE/LeetCodeHelper.py
NihalAgarwal/My-coding-DSA-Template
db872f6f72609f1d6ce7fb8e388dcbeca8337ffb
[ "MIT" ]
null
null
null
Zero_to_Google_SDE/LeetCodeHelper.py
NihalAgarwal/My-coding-DSA-Template
db872f6f72609f1d6ce7fb8e388dcbeca8337ffb
[ "MIT" ]
null
null
null
Zero_to_Google_SDE/LeetCodeHelper.py
NihalAgarwal/My-coding-DSA-Template
db872f6f72609f1d6ce7fb8e388dcbeca8337ffb
[ "MIT" ]
null
null
null
import turtle import pyperclip as pc class TreeBuild: """ Display how our tree looks like. """ @staticmethod @staticmethod class SquareBracketToCurlyBracket: """ [[ ]] -> {{}} or [] -> {} or [[...[]...]] -> {{..{}..}} """ if __name__ == "__main__": rep = "y" while rep == "y" or rep == "Y": print("*" * 10 + " ~~HELPER MENU~~ " + "*" * 10 + "\n") print("1. Draw Tree (press 1) ") print("2. Convert [] to {} (press 2) ") print("3. String to CharArray e.g., \"add\" -> \"{'a','d','d'}\" (press 3)") inp = int(input("\nPress enter your choice : ")) print() if inp == 1: t = TreeBuild() elif inp == 2: t = SquareBracketToCurlyBracket() elif inp == 3: t = ToCharArray() else: exit() rep = input( "\nDo you want to see 'HELPER MENU', if true 'y' else 'n' : " ).strip()
27.953125
84
0.439072
import turtle import pyperclip as pc class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): return "TreeNode({})".format(self.val) class TreeBuild: """ Display how our tree looks like. """ def __init__(self): repeat = "y" while repeat == "y" or repeat == "Y": ar = input("Enter the tree info in form '[...]': \n").strip() print(ar) self.drawtree(self.deserialize(ar)) repeat = input("Display another tree, if true 'y' else 'n' : ").strip() @staticmethod def deserialize(string): if string == "{}": return None nodes = [ None if val == "null" else TreeNode(int(val)) for val in string.strip("[]{}").split(",") ] kids = nodes[::-1] root = kids.pop() for node in nodes: if node: if kids: node.left = kids.pop() if kids: node.right = kids.pop() return root @staticmethod def drawtree(root): def height(root): return 1 + max(height(root.left), height(root.right)) if root else -1 def jumpto(x, y): t.penup() t.goto(x, y) t.pendown() def draw(node, x, y, dx): if node: t.goto(x, y) jumpto(x, y - 20) t.write(node.val, align="center", font=("Arial", 12, "normal")) draw(node.left, x - dx, y - 60, dx / 2) jumpto(x, y - 20) draw(node.right, x + dx, y - 60, dx / 2) t = turtle.Turtle() t.speed(0) turtle.delay(0) h = height(root) jumpto(0, 30 * h) draw(root, 0, 30 * h, 40 * h) t.hideturtle() turtle.mainloop() class SquareBracketToCurlyBracket: """ [[ ]] -> {{}} or [] -> {} or [[...[]...]] -> {{..{}..}} """ def __init__(self): flag = True while flag: s = input( "Enter input in valid form (e.g., [a, b, c, ...]): \n" ).strip() pc.copy(s.replace("[", "{").replace("]", "}")) pc.paste() class ToCharArray: def stringToCharArray(self, s): if s.startswith('"'): s = s[1:] if s.endswith('"'): s = s[:-1] str = "{" for i in s: str += "'" + i + "'" + ", " str = str[:-2] + "}" print(str) return str def __init__(self): a = "y" while a == "y": s = input("print string to char array: \n").strip() pc.copy(self.stringToCharArray(s)) pc.paste() a = input("Coninue, if true 'y' else 'n': ") if __name__ == "__main__": rep = "y" while rep == "y" or rep == "Y": print("*" * 10 + " ~~HELPER MENU~~ " + "*" * 10 + "\n") print("1. Draw Tree (press 1) ") print("2. Convert [] to {} (press 2) ") print("3. String to CharArray e.g., \"add\" -> \"{'a','d','d'}\" (press 3)") inp = int(input("\nPress enter your choice : ")) print() if inp == 1: t = TreeBuild() elif inp == 2: t = SquareBracketToCurlyBracket() elif inp == 3: t = ToCharArray() else: exit() rep = input( "\nDo you want to see 'HELPER MENU', if true 'y' else 'n' : " ).strip()
2,376
-9
258
7c37e7c4e9abf74a7fe46b2d7f2c93f45ecdf0a0
2,089
py
Python
pre_save_embedding.py
jstzwj/NatsuBot
ceb22a67f9c3779bea44a56209d7b3174c34d480
[ "MIT" ]
4
2020-08-07T10:28:04.000Z
2020-08-09T04:12:28.000Z
pre_save_embedding.py
jstzwj/NatsuBot
ceb22a67f9c3779bea44a56209d7b3174c34d480
[ "MIT" ]
null
null
null
pre_save_embedding.py
jstzwj/NatsuBot
ceb22a67f9c3779bea44a56209d7b3174c34d480
[ "MIT" ]
null
null
null
import pickle import os import json from sentence_transformers import SentenceTransformer if __name__ == "__main__": model = SentenceTransformer('distiluse-base-multilingual-cased', device='cuda') # path = ['./chat_text/poetry.txt', './chat_text/chat_text.txt'] # path = ['./chat_text/chat_text.txt', './chat_text/ownthink_v2.txt'] path = ['./chat_text/basic_settings.jsonl', './chat_text/natsu_chat.jsonl'] limit = 300000 count = 0 if os.path.isfile('embeddings.pickle'): with open('embeddings.pickle', 'rb') as file: embedding_cache = pickle.load(file) else: embedding_cache = {} for each_path in path: print(each_path) with open(each_path, 'r', encoding='utf-8') as f: questions = [] for each_line in f: obj = json.loads(each_line) question, answer = obj['question'], obj['answer'] if 'context' in obj: context = obj['context'] for each_context in context: if each_context not in embedding_cache: questions.append(each_context) if question not in embedding_cache: questions.append(question) if len(questions) > 4096 * 10: out = model.encode(questions, batch_size=512, show_progress_bar=True) for i, each_out in enumerate(out): embedding_cache[questions[i]] = each_out questions.clear() count += 1 if count > limit: break # 把剩余question全部处理完 if len(questions) != 0: out = model.encode(questions, show_progress_bar=True) for i, each_out in enumerate(out): embedding_cache[questions[i]] = each_out questions.clear() if count > limit: break with open('embeddings.pickle', 'wb') as file: pickle.dump(embedding_cache, file)
41.78
89
0.549545
import pickle import os import json from sentence_transformers import SentenceTransformer if __name__ == "__main__": model = SentenceTransformer('distiluse-base-multilingual-cased', device='cuda') # path = ['./chat_text/poetry.txt', './chat_text/chat_text.txt'] # path = ['./chat_text/chat_text.txt', './chat_text/ownthink_v2.txt'] path = ['./chat_text/basic_settings.jsonl', './chat_text/natsu_chat.jsonl'] limit = 300000 count = 0 if os.path.isfile('embeddings.pickle'): with open('embeddings.pickle', 'rb') as file: embedding_cache = pickle.load(file) else: embedding_cache = {} for each_path in path: print(each_path) with open(each_path, 'r', encoding='utf-8') as f: questions = [] for each_line in f: obj = json.loads(each_line) question, answer = obj['question'], obj['answer'] if 'context' in obj: context = obj['context'] for each_context in context: if each_context not in embedding_cache: questions.append(each_context) if question not in embedding_cache: questions.append(question) if len(questions) > 4096 * 10: out = model.encode(questions, batch_size=512, show_progress_bar=True) for i, each_out in enumerate(out): embedding_cache[questions[i]] = each_out questions.clear() count += 1 if count > limit: break # 把剩余question全部处理完 if len(questions) != 0: out = model.encode(questions, show_progress_bar=True) for i, each_out in enumerate(out): embedding_cache[questions[i]] = each_out questions.clear() if count > limit: break with open('embeddings.pickle', 'wb') as file: pickle.dump(embedding_cache, file)
0
0
0
714a8bdf932506bb3237e597634c7ccafc4f7c25
1,147
py
Python
asym_rlpo/utils/debugging.py
abaisero/asym-porl
8a76d920e51d783bbeeeea3cd2b02efffbb33c72
[ "MIT" ]
2
2021-08-24T22:41:36.000Z
2021-10-31T01:55:37.000Z
asym_rlpo/utils/debugging.py
abaisero/asym-porl
8a76d920e51d783bbeeeea3cd2b02efffbb33c72
[ "MIT" ]
null
null
null
asym_rlpo/utils/debugging.py
abaisero/asym-porl
8a76d920e51d783bbeeeea3cd2b02efffbb33c72
[ "MIT" ]
1
2021-10-13T12:27:40.000Z
2021-10-13T12:27:40.000Z
from numbers import Number from typing import Type import numpy as np import torch # taken from https://stackoverflow.com/questions/18376935/best-practice-for-equality-in-python def nested_equal(a, b): """ Compare two objects recursively by element, handling numpy objects. Assumes hashable items are not mutable in a way that affects equality. """ if type(a) is not type(b): return False if isinstance(a, str): return a == b if isinstance(a, Number): return a == b if isinstance(a, np.ndarray): return np.all(a == b) if isinstance(a, torch.Tensor): return torch.equal(a, b) if isinstance(a, list): return all(nested_equal(x, y) for x, y in zip(a, b)) if isinstance(a, dict): if set(a.keys()) != set(b.keys()): return False return all(nested_equal(a[k], b[k]) for k in a.keys()) return a == b
22.057692
94
0.625981
from numbers import Number from typing import Type import numpy as np import torch def checkraise( condition: bool, error_type: Type[Exception], error_message_fmt: str, *args, **kwargs ): if not condition: raise error_type(error_message_fmt.format(*args, **kwargs)) # taken from https://stackoverflow.com/questions/18376935/best-practice-for-equality-in-python def nested_equal(a, b): """ Compare two objects recursively by element, handling numpy objects. Assumes hashable items are not mutable in a way that affects equality. """ if type(a) is not type(b): return False if isinstance(a, str): return a == b if isinstance(a, Number): return a == b if isinstance(a, np.ndarray): return np.all(a == b) if isinstance(a, torch.Tensor): return torch.equal(a, b) if isinstance(a, list): return all(nested_equal(x, y) for x, y in zip(a, b)) if isinstance(a, dict): if set(a.keys()) != set(b.keys()): return False return all(nested_equal(a[k], b[k]) for k in a.keys()) return a == b
193
0
23
36b1e4beb8447b7b4673bba514a248d10b86f37c
1,542
py
Python
flask_vgavro_utils/config.py
vgavro/flask-vgavro-utils
01b7caa0241a6b606c228081eea169e51a0d1337
[ "BSD-2-Clause" ]
null
null
null
flask_vgavro_utils/config.py
vgavro/flask-vgavro-utils
01b7caa0241a6b606c228081eea169e51a0d1337
[ "BSD-2-Clause" ]
null
null
null
flask_vgavro_utils/config.py
vgavro/flask-vgavro-utils
01b7caa0241a6b606c228081eea169e51a0d1337
[ "BSD-2-Clause" ]
null
null
null
from werkzeug.utils import ImportStringError from flask.config import Config class LazyValue(object): """ This class may be used to lazy resolve config after importing local overrides. For example: REDIS_URL = "redis://localhost:6379/0" CELERY_BROKER_URL = LazyValue(lambda conf: conf['REDIS_URL']) After running Config.resolve_lazy_values() CELERY_BROKER_URL will be resolved to REDIS_URL, even if REDIS_URL were redefined later. """ _counter = 0
33.521739
92
0.628405
from werkzeug.utils import ImportStringError from flask.config import Config class LazyValue(object): """ This class may be used to lazy resolve config after importing local overrides. For example: REDIS_URL = "redis://localhost:6379/0" CELERY_BROKER_URL = LazyValue(lambda conf: conf['REDIS_URL']) After running Config.resolve_lazy_values() CELERY_BROKER_URL will be resolved to REDIS_URL, even if REDIS_URL were redefined later. """ _counter = 0 def __init__(self, callback): self.callback = callback self.__class__._counter += 1 def resolve(self, config): return self.callback(config) class Config(Config): def from_object(self, obj, raise_no_module=True): if isinstance(obj, str) and not raise_no_module: try: super().from_object(obj) except ImportStringError as exc: exc = exc.exception if not (exc.args[0] and exc.args[0].startswith('No module named') and obj in exc.args[0]): # skip if override module not exist, raise otherwise raise else: super().from_object(obj) def resolve_lazy_values(self): for k in sorted([k for k in self if isinstance(self[k], LazyValue)], key=lambda k: self[k]._counter): self[k] = self[k].resolve(self) def update_from_namespace(self, namespace): self.update(self.get_namespace(namespace, lowercase=False))
897
0
157
968587f9776b6ebff30c84ba1c209150fc2ef151
2,827
py
Python
reagent/optimizer/uninferrable_schedulers.py
alexnikulkov/ReAgent
e404c5772ea4118105c2eb136ca96ad5ca8e01db
[ "BSD-3-Clause" ]
1
2021-01-15T01:55:47.000Z
2021-01-15T01:55:47.000Z
reagent/optimizer/uninferrable_schedulers.py
alexnikulkov/ReAgent
e404c5772ea4118105c2eb136ca96ad5ca8e01db
[ "BSD-3-Clause" ]
null
null
null
reagent/optimizer/uninferrable_schedulers.py
alexnikulkov/ReAgent
e404c5772ea4118105c2eb136ca96ad5ca8e01db
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python3 """ This file contains configs that could not be inferred from the default values provided by PyTorch. If PyTorch optimizers and lr_schedulers had type annotations then we could infer everything. default values that cannot be inferred: - tuple - None - required parameters (no default value) Sometimes there are no defaults to infer from, so we got to include those here. TODO: remove this file once we can infer everything. """ from typing import List, Optional, Union from reagent.core.dataclasses import dataclass from .scheduler import LearningRateSchedulerConfig @dataclass(frozen=True) @dataclass(frozen=True) @dataclass(frozen=True) @dataclass(frozen=True) @dataclass(frozen=True) @dataclass(frozen=True) @dataclass(frozen=True) @dataclass(frozen=True) @dataclass(frozen=True)
27.182692
81
0.719844
#!/usr/bin/env python3 """ This file contains configs that could not be inferred from the default values provided by PyTorch. If PyTorch optimizers and lr_schedulers had type annotations then we could infer everything. default values that cannot be inferred: - tuple - None - required parameters (no default value) Sometimes there are no defaults to infer from, so we got to include those here. TODO: remove this file once we can infer everything. """ from typing import List, Optional, Union from reagent.core.dataclasses import dataclass from .scheduler import LearningRateSchedulerConfig @dataclass(frozen=True) class LambdaLR(LearningRateSchedulerConfig): # lr_lambda is Callable, FBL doesn't support # TODO(T67530507) Add function factory (FBL doesn't allow callables) pass @dataclass(frozen=True) class MultiplicativeLR(LearningRateSchedulerConfig): # lr_lambda is Callable, FBL doesn't support # TODO(T67530507) Add function factory (FBL doesn't allow callables) pass @dataclass(frozen=True) class StepLR(LearningRateSchedulerConfig): step_size: int gamma: float = 0.1 last_epoch: int = -1 @dataclass(frozen=True) class MultiStepLR(LearningRateSchedulerConfig): milestones: List[int] gamma: float = 0.1 last_epoch: int = -1 @dataclass(frozen=True) class ExponentialLR(LearningRateSchedulerConfig): gamma: float last_epoch: int = -1 @dataclass(frozen=True) class CosineAnnealingLR(LearningRateSchedulerConfig): T_max: int eta_min: float = 0 last_epoch: int = -1 @dataclass(frozen=True) class CyclicLR(LearningRateSchedulerConfig): # scale_fn is Callable, which FBL doesn't support. # TODO(T67530507) Add function factory (FBL doesn't allow callables) pass # base_lr: Union[float, List[float]] # max_lr: Union[float, List[float]] # step_size_up: int = 2000 # step_size_down: Optional[int] = None # mode: str = "triangular" # gamma: float = 1.0 # scale_fn: Optional[Callable[[int], float]] = None # scale_mode: str = "cycle" # cycle_momentum: bool = True # base_momentum: float = 0.8 # max_momentum: float = 0.9 # last_epoch: int = -1 @dataclass(frozen=True) class OneCycleLR(LearningRateSchedulerConfig): max_lr: Union[float, List[float]] total_steps: Optional[int] = None epochs: Optional[int] = None steps_per_epoch: Optional[int] = None pct_start: float = 0.3 anneal_strategy: str = "cos" cycle_momentum: bool = True base_momentum: float = 0.85 max_momentum: float = 0.95 div_factor: float = 25.0 final_div_factor: float = 10000.0 last_epoch: int = -1 @dataclass(frozen=True) class CosineAnnealingWarmRestarts(LearningRateSchedulerConfig): T_0: int T_mult: int = 1 eta_min: float = 0 last_epoch: int = -1
0
1,800
198
5d61cc68d241fb00cfc9760d6e7c86d5bee99a1f
9,173
py
Python
src/diffupath/utils.py
multipaths/DiffuPath
80da8f23754169e1f670a2f93aa6e605d84ab7e8
[ "Apache-2.0" ]
5
2019-07-08T13:39:05.000Z
2021-06-21T02:11:39.000Z
src/diffupath/utils.py
multipaths/DiffuPath
80da8f23754169e1f670a2f93aa6e605d84ab7e8
[ "Apache-2.0" ]
5
2019-12-16T07:51:16.000Z
2020-12-24T16:50:14.000Z
src/diffupath/utils.py
multipaths/DiffuPath
80da8f23754169e1f670a2f93aa6e605d84ab7e8
[ "Apache-2.0" ]
1
2020-08-13T12:23:08.000Z
2020-08-13T12:23:08.000Z
# -*- coding: utf-8 -*- """Miscellaneous utils of the package.""" import copy import inspect import itertools import logging import os import pickle import random from collections import defaultdict from glob import glob from statistics import mean from typing import List import numpy as np log = logging.getLogger(__name__) def from_pickle(input_path): """Read network from pickle.""" with open(input_path, 'rb') as f: unpickler = pickle.Unpickler(f) background_mat = unpickler.load() return background_mat def to_pickle(to_pickle, output): """Write pickle.""" with open(output, 'wb') as file: pickle.dump(to_pickle, file) def get_or_create_dir(path, basename=True) -> List[str]: """If a folder in path exist retrieve list of files, else create folder.""" if not os.path.exists(path): os.makedirs(path) return [] else: return get_files_list(path, basename) def get_dir_list(path, basename=False): """Get list of directories in path.""" if basename: return [os.path.basename(os.path.normpath(f)) for f in glob(os.path.join(path, "*")) if os.path.isdir(f)] else: return [f for f in glob(os.path.join(path, "*")) if os.path.isdir(f)] def get_files_list(path, basename=False): """Get list of files in path.""" if basename: return [os.path.basename(os.path.normpath(f)) for f in glob(os.path.join(path, "*")) if os.path.isfile(f)] else: return [f for f in glob(os.path.join(path, "*")) if os.path.isfile(f)] def get_last_file(path): """Get last file.""" list_of_files = glob(os.path.join(path, '*')) return max(list_of_files, key=os.path.getctime) def get_kernel_from_graph(graph, kernel_method, normalized=False): """Get kernel from graph given a kernel method.""" if 'normalized' in inspect.getfullargspec(kernel_method).args: return kernel_method(graph, normalized=normalized) else: return kernel_method(graph) def print_dict_dimensions(entities_db, title='', message='Total number of '): """Print dimension of the dictionary.""" total = set() m = f'{title}\n' for k1, v1 in entities_db.items(): m = '' if isinstance(v1, dict): for k2, v2 in v1.items(): m += f'{k2}({len(v2)}), ' total.update(v2) else: m += f'{len(v1)} ' total.update(v1) print(f'{message} {k1}: {m} ') print(f'Total: {len(total)} ') def print_dict(dict_to_print, message=''): """Print dimension of the dictionary.""" for k1, v1 in dict_to_print.items(): print(f'{message} {k1}: {len(v1)} ') def get_labels_set_from_dict(entities): """Return label set from entity dict values.""" if isinstance(list(entities.values())[0], dict): # TODO: Check return set(itertools.chain.from_iterable(itertools.chain.from_iterable(entities.values()))) else: return set(itertools.chain.from_iterable(entities.values())) def reverse_twodim_dict(input_d: dict): """Revert key-value dictionary.""" dict1 = copy.deepcopy(input_d) d = defaultdict(lambda: defaultdict(lambda: list)) for k1, entities1 in dict1.items(): for k2, entities2 in entities1.items(): d[k2][k1] = entities2 d[k2] = dict(d[k2]) return dict(d) def reduce_dict_dimension(d: dict): """Reduce dictionary dimension.""" reduced_dict = {} dict1 = copy.deepcopy(d) for k1, entities1 in dict1.items(): for k2, entities2 in entities1.items(): if k1 in reduced_dict.keys(): reduced_dict[k1].update(entities2) else: reduced_dict[k1] = entities2 return reduced_dict def reduce_dict_two_dimensional(d1: dict): """Reduce dictionary two dimension.""" d2 = reduce_dict_dimension(d1) return {entity: entity_value for entity_type, entity_set in d2.items() for entity, entity_value in entity_set.items() } def split_random_two_subsets(to_split): """Split random two subsets.""" if isinstance(to_split, dict): to_split_labels = list(to_split.keys()) else: to_split_labels = to_split half_1 = random.sample(population=list(to_split_labels), k=int(len(to_split_labels) / 2)) half_2 = list(set(to_split_labels) - set(half_1)) if isinstance(to_split, dict): return {entity_label: to_split[entity_label] for entity_label in half_1}, \ {entity_label: to_split[entity_label] for entity_label in half_2} else: return half_1, half_2 def hide_true_positives(to_split, k=0.5): """Hide relative number of labels.""" if isinstance(to_split, set): to_split = list(to_split) new_labels = to_split[:] # Check for -1 if -1 in new_labels: new_labels = [0 if label == -1 else label for label in new_labels] indices = [index for index, label in enumerate(new_labels) if label != 0] for index in random.choices(indices, k=int(k * len(indices))): new_labels[index] = 0 return new_labels def split_random_three_subsets(to_split): """Split proportionally random-chosen a given set in three subsets.""" half_1 = random.sample(population=list(to_split), k=int(len(to_split) / 3)) half_2, half_3 = split_random_two_subsets(list(set(to_split) - set(half_1))) return half_1, half_2, half_3 def get_three_venn_intersections(set1, set2, set3): """Get the intersection and disjunction sets from three given subsets.""" set1, set2, set3 = set(set1), set(set2), set(set3) set1_set2 = set1.intersection(set2) set1_set3 = set1.intersection(set3) core = set1_set3.intersection(set1_set2) set1_set2 = set1_set2 - core set1_set3 = set1_set3 - core set2_set3 = set2.intersection(set3) - core return {'unique_set1': set1 - set1_set2 - set1_set3 - core, 'unique_set2': set2 - set1_set2 - set2_set3 - core, 'set1_set2': set1_set2, 'unique_set3': set3 - set1_set3 - set2_set3 - core, 'set1_set3': set1_set3, 'set2_set3': set2_set3, 'core': core, } def random_disjoint_intersection_two_subsets(unique_set1, unique_set2, intersection): """Split proportionaly random-chosen the intersection of two subsets and concatenate it to the disjoint part.""" set1, set2 = split_random_two_subsets(intersection) return unique_set1 | set(set1), unique_set2 | set(set2) def random_disjoint_intersection_three_subsets(sets_dict): """Split proportionally random-chosen the intersections of three subsets and concatenate it to the disjoint part.""" set_labels = list(sets_dict.keys()) set_values = list(sets_dict.values()) set1, set2, set3 = set_values[0][0], set_values[1][0], set_values[2][0] intersections = get_three_venn_intersections(set1, set2, set3) set1, set2 = random_disjoint_intersection_two_subsets( intersections['unique_set1'], intersections['unique_set2'], intersections['set1_set2'] ) set1, set3 = random_disjoint_intersection_two_subsets(set1, intersections['unique_set3'], intersections['set1_set3'] ) set2, set3 = random_disjoint_intersection_two_subsets(set2, set3, intersections['set2_set3'] ) set1_core, set2_core, set3_core = split_random_three_subsets(intersections['core']) return {set_labels[0]: set1 | set(set1_core), set_labels[1]: set2 | set(set2_core), set_labels[2]: set3 | set(set3_core) } def get_count_and_labels_from_two_dim_dict(mapping_by_database_and_entity): """Get count and raw labels from two dimensional dict.""" db_labels = [] types_labels = [] all_count = [] all_percentage = [] # entity_type_map = {'metabolite_nodes': 'metabolite', 'mirna_nodes': 'micrornas', 'gene_nodes': 'genes', 'bp_nodes': 'bps'} for type_label, entities in mapping_by_database_and_entity.items(): db_count = [] db_percentage = [] db_labels.append(type_label) if types_labels == []: types_labels = list(entities.keys()) for entity_type, entities_tupple in entities.items(): db_count.append(entities_tupple[1]) db_percentage.append(entities_tupple[0]) all_count.append(db_count) all_percentage.append(db_percentage) return np.array(all_count), np.array(all_percentage), db_labels, types_labels def get_mean_from_two_dim_dict(d): """Get a dict with the partial means of a two dimensional dict for each subset.""" for k1, v1 in d.items(): for k2, v2 in v1.items(): if v2: d[k1][k2] = [mean(v2)] return d
31.414384
128
0.631963
# -*- coding: utf-8 -*- """Miscellaneous utils of the package.""" import copy import inspect import itertools import logging import os import pickle import random from collections import defaultdict from glob import glob from statistics import mean from typing import List import numpy as np log = logging.getLogger(__name__) def from_pickle(input_path): """Read network from pickle.""" with open(input_path, 'rb') as f: unpickler = pickle.Unpickler(f) background_mat = unpickler.load() return background_mat def to_pickle(to_pickle, output): """Write pickle.""" with open(output, 'wb') as file: pickle.dump(to_pickle, file) def get_or_create_dir(path, basename=True) -> List[str]: """If a folder in path exist retrieve list of files, else create folder.""" if not os.path.exists(path): os.makedirs(path) return [] else: return get_files_list(path, basename) def get_dir_list(path, basename=False): """Get list of directories in path.""" if basename: return [os.path.basename(os.path.normpath(f)) for f in glob(os.path.join(path, "*")) if os.path.isdir(f)] else: return [f for f in glob(os.path.join(path, "*")) if os.path.isdir(f)] def get_files_list(path, basename=False): """Get list of files in path.""" if basename: return [os.path.basename(os.path.normpath(f)) for f in glob(os.path.join(path, "*")) if os.path.isfile(f)] else: return [f for f in glob(os.path.join(path, "*")) if os.path.isfile(f)] def get_last_file(path): """Get last file.""" list_of_files = glob(os.path.join(path, '*')) return max(list_of_files, key=os.path.getctime) def get_kernel_from_graph(graph, kernel_method, normalized=False): """Get kernel from graph given a kernel method.""" if 'normalized' in inspect.getfullargspec(kernel_method).args: return kernel_method(graph, normalized=normalized) else: return kernel_method(graph) def print_dict_dimensions(entities_db, title='', message='Total number of '): """Print dimension of the dictionary.""" total = set() m = f'{title}\n' for k1, v1 in entities_db.items(): m = '' if isinstance(v1, dict): for k2, v2 in v1.items(): m += f'{k2}({len(v2)}), ' total.update(v2) else: m += f'{len(v1)} ' total.update(v1) print(f'{message} {k1}: {m} ') print(f'Total: {len(total)} ') def print_dict(dict_to_print, message=''): """Print dimension of the dictionary.""" for k1, v1 in dict_to_print.items(): print(f'{message} {k1}: {len(v1)} ') def get_labels_set_from_dict(entities): """Return label set from entity dict values.""" if isinstance(list(entities.values())[0], dict): # TODO: Check return set(itertools.chain.from_iterable(itertools.chain.from_iterable(entities.values()))) else: return set(itertools.chain.from_iterable(entities.values())) def reverse_twodim_dict(input_d: dict): """Revert key-value dictionary.""" dict1 = copy.deepcopy(input_d) d = defaultdict(lambda: defaultdict(lambda: list)) for k1, entities1 in dict1.items(): for k2, entities2 in entities1.items(): d[k2][k1] = entities2 d[k2] = dict(d[k2]) return dict(d) def reduce_dict_dimension(d: dict): """Reduce dictionary dimension.""" reduced_dict = {} dict1 = copy.deepcopy(d) for k1, entities1 in dict1.items(): for k2, entities2 in entities1.items(): if k1 in reduced_dict.keys(): reduced_dict[k1].update(entities2) else: reduced_dict[k1] = entities2 return reduced_dict def reduce_dict_two_dimensional(d1: dict): """Reduce dictionary two dimension.""" d2 = reduce_dict_dimension(d1) return {entity: entity_value for entity_type, entity_set in d2.items() for entity, entity_value in entity_set.items() } def split_random_two_subsets(to_split): """Split random two subsets.""" if isinstance(to_split, dict): to_split_labels = list(to_split.keys()) else: to_split_labels = to_split half_1 = random.sample(population=list(to_split_labels), k=int(len(to_split_labels) / 2)) half_2 = list(set(to_split_labels) - set(half_1)) if isinstance(to_split, dict): return {entity_label: to_split[entity_label] for entity_label in half_1}, \ {entity_label: to_split[entity_label] for entity_label in half_2} else: return half_1, half_2 def hide_true_positives(to_split, k=0.5): """Hide relative number of labels.""" if isinstance(to_split, set): to_split = list(to_split) new_labels = to_split[:] # Check for -1 if -1 in new_labels: new_labels = [0 if label == -1 else label for label in new_labels] indices = [index for index, label in enumerate(new_labels) if label != 0] for index in random.choices(indices, k=int(k * len(indices))): new_labels[index] = 0 return new_labels def split_random_three_subsets(to_split): """Split proportionally random-chosen a given set in three subsets.""" half_1 = random.sample(population=list(to_split), k=int(len(to_split) / 3)) half_2, half_3 = split_random_two_subsets(list(set(to_split) - set(half_1))) return half_1, half_2, half_3 def get_three_venn_intersections(set1, set2, set3): """Get the intersection and disjunction sets from three given subsets.""" set1, set2, set3 = set(set1), set(set2), set(set3) set1_set2 = set1.intersection(set2) set1_set3 = set1.intersection(set3) core = set1_set3.intersection(set1_set2) set1_set2 = set1_set2 - core set1_set3 = set1_set3 - core set2_set3 = set2.intersection(set3) - core return {'unique_set1': set1 - set1_set2 - set1_set3 - core, 'unique_set2': set2 - set1_set2 - set2_set3 - core, 'set1_set2': set1_set2, 'unique_set3': set3 - set1_set3 - set2_set3 - core, 'set1_set3': set1_set3, 'set2_set3': set2_set3, 'core': core, } def random_disjoint_intersection_two_subsets(unique_set1, unique_set2, intersection): """Split proportionaly random-chosen the intersection of two subsets and concatenate it to the disjoint part.""" set1, set2 = split_random_two_subsets(intersection) return unique_set1 | set(set1), unique_set2 | set(set2) def random_disjoint_intersection_three_subsets(sets_dict): """Split proportionally random-chosen the intersections of three subsets and concatenate it to the disjoint part.""" set_labels = list(sets_dict.keys()) set_values = list(sets_dict.values()) set1, set2, set3 = set_values[0][0], set_values[1][0], set_values[2][0] intersections = get_three_venn_intersections(set1, set2, set3) set1, set2 = random_disjoint_intersection_two_subsets( intersections['unique_set1'], intersections['unique_set2'], intersections['set1_set2'] ) set1, set3 = random_disjoint_intersection_two_subsets(set1, intersections['unique_set3'], intersections['set1_set3'] ) set2, set3 = random_disjoint_intersection_two_subsets(set2, set3, intersections['set2_set3'] ) set1_core, set2_core, set3_core = split_random_three_subsets(intersections['core']) return {set_labels[0]: set1 | set(set1_core), set_labels[1]: set2 | set(set2_core), set_labels[2]: set3 | set(set3_core) } def get_count_and_labels_from_two_dim_dict(mapping_by_database_and_entity): """Get count and raw labels from two dimensional dict.""" db_labels = [] types_labels = [] all_count = [] all_percentage = [] # entity_type_map = {'metabolite_nodes': 'metabolite', 'mirna_nodes': 'micrornas', 'gene_nodes': 'genes', 'bp_nodes': 'bps'} for type_label, entities in mapping_by_database_and_entity.items(): db_count = [] db_percentage = [] db_labels.append(type_label) if types_labels == []: types_labels = list(entities.keys()) for entity_type, entities_tupple in entities.items(): db_count.append(entities_tupple[1]) db_percentage.append(entities_tupple[0]) all_count.append(db_count) all_percentage.append(db_percentage) return np.array(all_count), np.array(all_percentage), db_labels, types_labels def get_mean_from_two_dim_dict(d): """Get a dict with the partial means of a two dimensional dict for each subset.""" for k1, v1 in d.items(): for k2, v2 in v1.items(): if v2: d[k1][k2] = [mean(v2)] return d
0
0
0
774ef2745289a2cc5cdc3e604ab730eaef761c44
2,600
py
Python
src/features/word_count_analysis.py
Nazdarovja/Python_Semester_Project
de830060553c51389c3940e022ae038b41021455
[ "MIT" ]
null
null
null
src/features/word_count_analysis.py
Nazdarovja/Python_Semester_Project
de830060553c51389c3940e022ae038b41021455
[ "MIT" ]
null
null
null
src/features/word_count_analysis.py
Nazdarovja/Python_Semester_Project
de830060553c51389c3940e022ae038b41021455
[ "MIT" ]
null
null
null
import pandas as pd import collections import numpy as np def count_top_words_in_genre(genre, lyrics_df): """ Detect the language of the text. Parameters ---------- genre : str genre like 'Hip-Hop' or 'Pop' lyrics_df : pandas dataframe clean dataframe Returns return list of top words of genre """ lyrics_df['most_used_words'] = pd.Series(collections.Counter(lyrics.split()) .most_common(10) for _, lyrics in lyrics_df['lyrics'].iteritems()) arr = np.array(lyrics_df[lyrics_df['genre'] == genre]['most_used_words'].tolist()) # merges row's most_used_word column to list arr = arr[~pd.isna(arr)] # removing nans' flat_list = [item for sublist in arr for item in sublist] # converts array of arrays to one big array genre_dict = {} for tupl in flat_list: genre_dict[tupl[0]] = genre_dict.get(tupl[0], 0) + tupl[1] # sums up total occurances of each word top_words = collections.Counter(genre_dict) return top_words.most_common(10) def word_count(df, new_col_name, col_with_lyrics): """ Count the number of words in a dataframe lyrics column, given a column name, process it, and save as new_col_name Parameters ---------- df : dataframe new_col_name : name of new column col_with_lyric: column with lyrics Returns return dataframe with new column """ df[new_col_name] = df[col_with_lyrics].apply(lambda words: _count_words(words)) return df def _count_words(words): """ helper method for word_count() method, return length of given words """ try: return len(words.split()) except: return 0 #TODO: better error handling, maybe not return 0 def sentence_avg_word_length(df, new_col_name, col_with_lyrics): """ Count the average word length in a dataframe lyrics column, given a column name, process it, and save as new_col_name Parameters ---------- df : dataframe new_col_name : name of new column col_with_lyric: column with lyrics Returns return dataframe with new column """ df[new_col_name] = df[col_with_lyrics].apply(_sentence_avg_word_length) return df def _sentence_avg_word_length(sentence): """ helper method for sentence_avg_word_length() method, sum of len of words in sentence, divided by length of sentence ***3 (factorize) """ res = sum(len(word.split()) for word in sentence) / len(sentence.split())**3 return res
37.142857
136
0.653462
import pandas as pd import collections import numpy as np def count_top_words_in_genre(genre, lyrics_df): """ Detect the language of the text. Parameters ---------- genre : str genre like 'Hip-Hop' or 'Pop' lyrics_df : pandas dataframe clean dataframe Returns return list of top words of genre """ lyrics_df['most_used_words'] = pd.Series(collections.Counter(lyrics.split()) .most_common(10) for _, lyrics in lyrics_df['lyrics'].iteritems()) arr = np.array(lyrics_df[lyrics_df['genre'] == genre]['most_used_words'].tolist()) # merges row's most_used_word column to list arr = arr[~pd.isna(arr)] # removing nans' flat_list = [item for sublist in arr for item in sublist] # converts array of arrays to one big array genre_dict = {} for tupl in flat_list: genre_dict[tupl[0]] = genre_dict.get(tupl[0], 0) + tupl[1] # sums up total occurances of each word top_words = collections.Counter(genre_dict) return top_words.most_common(10) def word_count(df, new_col_name, col_with_lyrics): """ Count the number of words in a dataframe lyrics column, given a column name, process it, and save as new_col_name Parameters ---------- df : dataframe new_col_name : name of new column col_with_lyric: column with lyrics Returns return dataframe with new column """ df[new_col_name] = df[col_with_lyrics].apply(lambda words: _count_words(words)) return df def _count_words(words): """ helper method for word_count() method, return length of given words """ try: return len(words.split()) except: return 0 #TODO: better error handling, maybe not return 0 def sentence_avg_word_length(df, new_col_name, col_with_lyrics): """ Count the average word length in a dataframe lyrics column, given a column name, process it, and save as new_col_name Parameters ---------- df : dataframe new_col_name : name of new column col_with_lyric: column with lyrics Returns return dataframe with new column """ df[new_col_name] = df[col_with_lyrics].apply(_sentence_avg_word_length) return df def _sentence_avg_word_length(sentence): """ helper method for sentence_avg_word_length() method, sum of len of words in sentence, divided by length of sentence ***3 (factorize) """ res = sum(len(word.split()) for word in sentence) / len(sentence.split())**3 return res
0
0
0
f96ed070a5f96ae75dfd7a99c5dd448c88eb2e4c
9,423
py
Python
common/trainloop/loops.py
alainjungo/reliability-challenges-uncertainty
21e86f6e2a5d2520b5767dce48bbcf2b11773788
[ "MIT" ]
56
2019-07-10T06:02:11.000Z
2021-12-21T08:11:22.000Z
common/trainloop/loops.py
alainjungo/reliability-challenges-uncertainty
21e86f6e2a5d2520b5767dce48bbcf2b11773788
[ "MIT" ]
4
2019-09-26T08:51:58.000Z
2021-06-08T20:27:53.000Z
common/trainloop/loops.py
alainjungo/reliability-challenges-uncertainty
21e86f6e2a5d2520b5767dce48bbcf2b11773788
[ "MIT" ]
8
2019-10-21T12:43:08.000Z
2021-12-02T08:14:38.000Z
import logging import torch import numpy as np import common.utils.torchhelper as th import common.trainloop.context as ctx import common.trainloop.hooks as hooks import common.trainloop.data as data
39.759494
119
0.665818
import logging import torch import numpy as np import common.utils.torchhelper as th import common.trainloop.context as ctx import common.trainloop.hooks as hooks import common.trainloop.data as data class Validate: def __init__(self, steps: list) -> None: self.steps = steps self.score_aggregation_fn = np.mean def __call__(self, context: ctx.TrainContext, hook: hooks.TrainLoopHook, epoch: int): if not context.need_validation(epoch): return context.set_mode(is_train=False) task_context = context.get_task_context(epoch) hook.on_validation_start(task_context, context) for i, batch in enumerate(task_context.data.loader): batch_context = ctx.BatchContext(batch, i) hook.on_validation_batch_start(batch_context, task_context, context) self.validate_batch(batch_context, task_context, context, hook) hook.on_validation_batch_end(batch_context, task_context, context) score = self.score_aggregation_fn(task_context.scores) if context.best_score is None or score > context.best_score: context.best_score = score hook.on_validation_end(task_context, context) def validate_batch(self, batch_context: ctx.BatchContext, task_context: ctx.TaskContext, context: ctx.TrainContext, hook: hooks.TrainLoopHook): for step in self.steps: step(batch_context, task_context, context) if batch_context.metrics: task_context.history.add(batch_context.metrics, 'batch_metrics') if batch_context.score is None: raise ValueError('"score" must be set in BatchContext') task_context.scores.append(batch_context.score) def tensor_to_numpy(tensor: torch.Tensor): return tensor.cpu().numpy() class ValidateSubject(Validate): def __init__(self, steps: list, subject_steps: list, subject_assembler, entries: tuple = None, convert_fn=tensor_to_numpy, transform_fn=th.channel_to_end) -> None: super().__init__(steps) self.subject_steps = subject_steps self.subject_assembler = subject_assembler self.entries = entries self.convert_fn = convert_fn self.transform_fn = transform_fn def validate_batch(self, batch_context: ctx.BatchContext, task_context: ctx.TaskContext, context: ctx.TrainContext, hook: hooks.TrainLoopHook): for batch_step in self.steps: batch_step(batch_context, task_context, context) if batch_context.metrics: task_context.history.add(batch_context.metrics, 'batch_metrics') to_assemble = {} for key, value in batch_context.output.items(): if self.entries is None or key in self.entries: if self.transform_fn is not None: value = self.transform_fn(value) if self.convert_fn: value = self.convert_fn(value) to_assemble[key] = value is_last_batch = batch_context.batch_index == task_context.data.nb_batches - 1 self.subject_assembler.add_batch(to_assemble, batch_context.input, last_batch=is_last_batch) if self.subject_assembler.subjects_ready: for subject_index in list(self.subject_assembler.subjects_ready): subject_data = self.subject_assembler.get_assembled_subject(subject_index) subject_context = ctx.SubjectContext(subject_index, subject_data) hook.on_validation_subject_start(subject_context, task_context, context) for subject_step in self.subject_steps: subject_step(subject_context, task_context, context) if subject_context.metrics: task_context.history.add(subject_context.metrics, 'subject_metrics') if subject_context.score is None: raise ValueError('"score" must be set in SubjectContext') task_context.scores.append(subject_context.score) hook.on_validation_subject_end(subject_context, task_context, context) class Train: def __init__(self, steps: list, only_validate=False) -> None: self.steps = steps self.only_validate = only_validate def __call__(self, context: ctx.TrainContext, build_train: data.BuildData, build_valid: data.BuildData, validate: Validate, hook: hooks.TrainLoopHook = hooks.TrainLoopHook()): hook.on_startup() resume_at = context.get_resume_at() if resume_at is None: context.setup_directory() context.setup_logging() seed = context.get_seed() if seed is not None: context.do_seed(seed) context.load_train_and_valid_data(build_train, build_valid) if resume_at is None: logging.info('build new model') context.load_from_new() else: context.load_from_checkpoint(resume_at) hook.end_startup(context) first_epoch = 0 if resume_at is not None: first_epoch = resume_at + 1 for epoch in range(first_epoch, context.config.epochs): hook.on_epoch_start(context, epoch) if not self.only_validate: self._train(context, hook, epoch) validate(context, hook, epoch) hook.on_epoch_end(context, epoch) hook.on_termination(context) def _train(self, context: ctx.TrainContext, hook: hooks.TrainLoopHook, epoch: int): context.set_mode(is_train=True) seed = context.get_seed() if seed is not None and epoch != 0: # epoch 0 already seeded with startup context.do_seed(seed + epoch) task_context = context.get_task_context(epoch) hook.on_training_start(task_context, context) for i, batch in enumerate(task_context.data.loader): batch_context = ctx.BatchContext(batch, i) hook.on_training_batch_start(batch_context, task_context, context) for step in self.steps: step(batch_context, task_context, context) hook.on_training_batch_end(batch_context, task_context, context) hook.on_training_end(task_context, context) class Test: def __init__(self, steps: list, subject_steps: list = None, subject_assembler=None, entries: tuple = None, convert_fn=tensor_to_numpy) -> None: self.steps = steps self.subject_steps = subject_steps self.subject_assembler = subject_assembler self.entries = entries self.convert_fn = convert_fn self.channel_to_end_fn = th.channel_to_end def __call__(self, context: ctx.TestContext, build_test: data.BuildData, hook: hooks.TestLoopHook = hooks.TestLoopHook()): hook.on_startup() context.setup_directory() context.setup_logging() seed = context.get_seed() if seed is not None: context.do_seed(seed) context.load_test_data(build_test) context.load_from_checkpoint(context.get_test_at()) hook.end_startup(context) task_context = context.get_task_context() hook.on_test_start(task_context, context) for i, batch in enumerate(task_context.data.loader): batch_context = ctx.BatchContext(batch, i) hook.on_test_batch_start(batch_context, task_context, context) self._test_batch(batch_context, task_context, context, hook) hook.on_test_batch_end(batch_context, task_context, context) hook.on_test_end(task_context, context) hook.on_termination(context) def _test_batch(self, batch_context: ctx.BatchContext, task_context: ctx.TaskContext, context: ctx.TestContext, hook: hooks.TestLoopHook): for batch_step in self.steps: batch_step(batch_context, task_context, context) if batch_context.metrics: task_context.history.add(batch_context.metrics, 'batch_metrics') if self.subject_assembler is None: return to_assemble = {} for key, value in batch_context.output.items(): if self.entries is None or key in self.entries: value = self.channel_to_end_fn(value) if self.convert_fn: value = self.convert_fn(value) to_assemble[key] = value is_last_batch = batch_context.batch_index == task_context.data.nb_batches - 1 self.subject_assembler.add_batch(to_assemble, batch_context.input, last_batch=is_last_batch) if self.subject_assembler.subjects_ready: for subject_index in list(self.subject_assembler.subjects_ready): subject_data = self.subject_assembler.get_assembled_subject(subject_index) subject_context = ctx.SubjectContext(subject_index, subject_data) hook.on_test_subject_start(subject_context, task_context, context) for subject_step in self.subject_steps: subject_step(subject_context, task_context, context) if subject_context.metrics: task_context.history.add(subject_context.metrics, 'subject_metrics') hook.on_test_subject_end(subject_context, task_context, context)
8,817
-14
412
fb6e766a3aec86b5093d661ed727eae1c29acdee
2,286
py
Python
q2_types/per_sample_sequences/__init__.py
jakereps/q2-types
9942237a3d44e159e3617b836e48435a12842e3c
[ "BSD-3-Clause" ]
8
2016-06-26T20:35:52.000Z
2021-08-08T07:45:56.000Z
q2_types/per_sample_sequences/__init__.py
jakereps/q2-types
9942237a3d44e159e3617b836e48435a12842e3c
[ "BSD-3-Clause" ]
170
2016-05-10T19:27:56.000Z
2022-03-16T21:50:49.000Z
q2_types/per_sample_sequences/__init__.py
jakereps/q2-types
9942237a3d44e159e3617b836e48435a12842e3c
[ "BSD-3-Clause" ]
44
2016-05-09T20:56:06.000Z
2021-08-17T17:09:39.000Z
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2021, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import importlib from ._format import (CasavaOneEightSingleLanePerSampleDirFmt, CasavaOneEightLanelessPerSampleDirFmt, FastqGzFormat, YamlFormat, FastqManifestFormat, FastqAbsolutePathManifestFormat, SingleLanePerSampleSingleEndFastqDirFmt, SingleLanePerSamplePairedEndFastqDirFmt, SingleEndFastqManifestPhred33, SingleEndFastqManifestPhred64, PairedEndFastqManifestPhred33, PairedEndFastqManifestPhred64, SingleEndFastqManifestPhred33V2, SingleEndFastqManifestPhred64V2, PairedEndFastqManifestPhred33V2, PairedEndFastqManifestPhred64V2, QIIME1DemuxFormat, QIIME1DemuxDirFmt) from ._type import (Sequences, SequencesWithQuality, PairedEndSequencesWithQuality, JoinedSequencesWithQuality) __all__ = ['CasavaOneEightSingleLanePerSampleDirFmt', 'CasavaOneEightLanelessPerSampleDirFmt', 'FastqGzFormat', 'YamlFormat', 'FastqManifestFormat', 'FastqAbsolutePathManifestFormat', 'SingleLanePerSampleSingleEndFastqDirFmt', 'SingleLanePerSamplePairedEndFastqDirFmt', 'Sequences', 'SequencesWithQuality', 'PairedEndSequencesWithQuality', 'JoinedSequencesWithQuality', 'SingleEndFastqManifestPhred33', 'SingleEndFastqManifestPhred64', 'PairedEndFastqManifestPhred33', 'PairedEndFastqManifestPhred64', 'SingleEndFastqManifestPhred33V2', 'SingleEndFastqManifestPhred64V2', 'PairedEndFastqManifestPhred33V2', 'PairedEndFastqManifestPhred64V2', 'QIIME1DemuxFormat', 'QIIME1DemuxDirFmt'] importlib.import_module('q2_types.per_sample_sequences._transformer')
49.695652
78
0.625984
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2021, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import importlib from ._format import (CasavaOneEightSingleLanePerSampleDirFmt, CasavaOneEightLanelessPerSampleDirFmt, FastqGzFormat, YamlFormat, FastqManifestFormat, FastqAbsolutePathManifestFormat, SingleLanePerSampleSingleEndFastqDirFmt, SingleLanePerSamplePairedEndFastqDirFmt, SingleEndFastqManifestPhred33, SingleEndFastqManifestPhred64, PairedEndFastqManifestPhred33, PairedEndFastqManifestPhred64, SingleEndFastqManifestPhred33V2, SingleEndFastqManifestPhred64V2, PairedEndFastqManifestPhred33V2, PairedEndFastqManifestPhred64V2, QIIME1DemuxFormat, QIIME1DemuxDirFmt) from ._type import (Sequences, SequencesWithQuality, PairedEndSequencesWithQuality, JoinedSequencesWithQuality) __all__ = ['CasavaOneEightSingleLanePerSampleDirFmt', 'CasavaOneEightLanelessPerSampleDirFmt', 'FastqGzFormat', 'YamlFormat', 'FastqManifestFormat', 'FastqAbsolutePathManifestFormat', 'SingleLanePerSampleSingleEndFastqDirFmt', 'SingleLanePerSamplePairedEndFastqDirFmt', 'Sequences', 'SequencesWithQuality', 'PairedEndSequencesWithQuality', 'JoinedSequencesWithQuality', 'SingleEndFastqManifestPhred33', 'SingleEndFastqManifestPhred64', 'PairedEndFastqManifestPhred33', 'PairedEndFastqManifestPhred64', 'SingleEndFastqManifestPhred33V2', 'SingleEndFastqManifestPhred64V2', 'PairedEndFastqManifestPhred33V2', 'PairedEndFastqManifestPhred64V2', 'QIIME1DemuxFormat', 'QIIME1DemuxDirFmt'] importlib.import_module('q2_types.per_sample_sequences._transformer')
0
0
0
fdb74a7ca6bafb012f1c478a67adb445d25c46e4
5,744
py
Python
gpMgmt/bin/gpssh_modules/gppxssh_wrapper.py
wapache-org/greenplum-gpdb
79e2bd251c1d27054846f630acd52e7903854829
[ "PostgreSQL", "Apache-2.0" ]
5,535
2015-10-28T01:05:40.000Z
2022-03-30T13:46:53.000Z
gpMgmt/bin/gpssh_modules/gppxssh_wrapper.py
wapache-org/greenplum-gpdb
79e2bd251c1d27054846f630acd52e7903854829
[ "PostgreSQL", "Apache-2.0" ]
9,369
2015-10-28T07:48:01.000Z
2022-03-31T23:56:42.000Z
gpMgmt/bin/gpssh_modules/gppxssh_wrapper.py
wapache-org/greenplum-gpdb
79e2bd251c1d27054846f630acd52e7903854829
[ "PostgreSQL", "Apache-2.0" ]
1,800
2015-10-28T01:08:25.000Z
2022-03-29T13:29:36.000Z
from datetime import datetime import time import sys sys.path.insert(1, sys.path[0] + '/lib') from pexpect import pxssh, TIMEOUT CRNL = '\r\n' DEBUG_VERBOSE_PRINTING = False # experimentally derived that a sequence of tries with delays of # 1, 5, 25, 125 secs worked to surmount a 1-second delay (via `tc` test) RETRY_EXPONENT = 5
43.18797
116
0.621692
from datetime import datetime import time import sys sys.path.insert(1, sys.path[0] + '/lib') from pexpect import pxssh, TIMEOUT CRNL = '\r\n' DEBUG_VERBOSE_PRINTING = False # experimentally derived that a sequence of tries with delays of # 1, 5, 25, 125 secs worked to surmount a 1-second delay (via `tc` test) RETRY_EXPONENT = 5 class PxsshWrapper(pxssh.pxssh): def __init__(self, delaybeforesend, sync_retries, options): self.sync_retries = sync_retries super(PxsshWrapper, self).__init__(delaybeforesend=delaybeforesend, options=options) def sync_original_prompt(self, sync_multiplier=1.0): """ override the pxssh method to allow retries with extended timeout intervals """ # make two attempts to throw away, perhaps emptying any initial Message Of The Day. # In practice, the first request can take a huge amount of time, compared to subsequent requests, # so give it a 5-second max wait as a special case. self.sendline() self.wait_for_any_response(max_wait_secs=5) self.clear_response_channel() self.sendline() self.try_read_prompt(sync_multiplier) # Each retry should go more slowly to accommodate possible cpu load, network, # or other issues on the segment host that might delay when we receive the prompt. num_retries = self.sync_retries retry_attempt = 0 success = False while (not success) and retry_attempt <= num_retries: # each retry will get an exponentially longer timeout interval sync_multiplier_for_this_retry = sync_multiplier * (RETRY_EXPONENT ** retry_attempt) start = time.time() if DEBUG_VERBOSE_PRINTING: sys.stderr.write("\nUsing sync multiplier: %f\n" % sync_multiplier_for_this_retry) self.sendline() if DEBUG_VERBOSE_PRINTING: sys.stderr.write("\nstart try read: %s\n" % datetime.now()) first_prompt = self.try_read_prompt(sync_multiplier_for_this_retry) if DEBUG_VERBOSE_PRINTING: sys.stderr.write("\nend try read: %s\n" % datetime.now()) self.sendline() second_prompt = self.try_read_prompt(sync_multiplier_for_this_retry) success = self.are_prompts_similar(first_prompt, second_prompt) if not success: retry_attempt += 1 if retry_attempt <= num_retries: # This attempt has failed to allow enough time. # We want to "clear the runway" before another attempt. # The next attempt will have a wait that is exponent times as long. # To clear the runway, we sleep for about as long as this upcoming retry. # Thus, the overall duration of this retry cycle becomes # roughly equivalent to the timeout used by the next attempt time.sleep(RETRY_EXPONENT * sync_multiplier_for_this_retry) self.clear_response_channel() if DEBUG_VERBOSE_PRINTING: if not success: sys.stderr.write('\nAfter %d retries, prompts failed to be consistent.\n' % num_retries) elif retry_attempt > 0: sys.stderr.write('\nConsistent prompts after extending timeout, with %i retries.\n' % retry_attempt) sys.stderr.flush() return success def clear_response_channel(self): """remove any readily-available characters. stop as soon as even a little wait time is discovered""" if DEBUG_VERBOSE_PRINTING: sys.stderr.write('\nflushing:\n') prompt = "dummy non empty" while prompt: try: prompt = self.read_nonblocking(size=1, timeout=0.01) if DEBUG_VERBOSE_PRINTING: sys.stderr.write(prompt) except TIMEOUT: break if DEBUG_VERBOSE_PRINTING: sys.stderr.write('\n') def wait_for_any_response(self, max_wait_secs=5): if DEBUG_VERBOSE_PRINTING: sys.stderr.write('\nstart looking for a character at %s\n' % datetime.now()) duration = 0 while duration < max_wait_secs: start = time.time() try: prompt = self.read_nonblocking(size=1, timeout=0.01) if prompt: break except TIMEOUT: duration += time.time() - start if DEBUG_VERBOSE_PRINTING: sys.stderr.write('\nFinished wait_for_any_response() at %s\n' % datetime.now()) def is_prompt_bad(self, prompt_output): return len(prompt_output) == 0 or prompt_output == CRNL def are_prompts_similar(self, prompt_one, prompt_two): if self.is_prompt_bad(prompt_one) or self.is_prompt_bad(prompt_two): if DEBUG_VERBOSE_PRINTING: sys.stderr.write('\n[A prompt was bad: ]') sys.stderr.write('\n[first prompt: {0!r}]'.format(prompt_one)) sys.stderr.write('\n[second prompt: {0!r}]'.format(prompt_two)) return False if len(prompt_one) == 0: return False # it will be used as the denominator of a ratio lev_dist = self.levenshtein_distance(prompt_one, prompt_two) lev_ratio = float(lev_dist) / len(prompt_one) if lev_ratio < 0.4: return True else: if DEBUG_VERBOSE_PRINTING: sys.stderr.write('\n[! distance too far: \n{0!r}\n{1!r}]\n'.format(prompt_one, prompt_two)) sys.stderr.write('\n[val=%f, ld=%i]\n' % (lev_ratio, lev_dist)) return False
1,780
3,605
23
b95a7481c95d69db4af9c074180e78b47074a31c
4,486
py
Python
gpMgmt/test/behave/mgmt_utils/steps/gpstart.py
zhongyibill/gpdb
12cfded239d5da2ad102697c9d56efb5759807dd
[ "PostgreSQL", "Apache-2.0" ]
1
2021-01-03T17:55:43.000Z
2021-01-03T17:55:43.000Z
gpMgmt/test/behave/mgmt_utils/steps/gpstart.py
zhongyibill/gpdb
12cfded239d5da2ad102697c9d56efb5759807dd
[ "PostgreSQL", "Apache-2.0" ]
6
2019-11-04T17:12:13.000Z
2020-06-04T21:18:41.000Z
gpMgmt/test/behave/mgmt_utils/steps/gpstart.py
zhongyibill/gpdb
12cfded239d5da2ad102697c9d56efb5759807dd
[ "PostgreSQL", "Apache-2.0" ]
1
2020-03-26T02:47:22.000Z
2020-03-26T02:47:22.000Z
import os import signal import subprocess from behave import given, when, then from test.behave_utils import utils from gppylib.commands.base import Command @when('the standby host goes down') def _handle_sigpipe(): """ Work around https://bugs.python.org/issue1615376, which is not fixed until Python 3.2. This bug interferes with Bash pipelines that rely on SIGPIPE to exit cleanly. """ signal.signal(signal.SIGPIPE, signal.SIG_DFL) @when('gpstart is run with prompts accepted') def impl(context): """ Runs `yes | gpstart`. """ p = subprocess.Popen( [ "bash", "-c", "yes | gpstart" ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=_handle_sigpipe, ) context.stdout_message, context.stderr_message = p.communicate() context.ret_code = p.returncode @given('segment {dbid} goes down' ) @then('the status of segment {dbid} should be "{expected_status}"' ) @then('the status of segment {dbid} is changed to "{status}"' ) @then('the cluster is returned to a good state' )
34.507692
133
0.653143
import os import signal import subprocess from behave import given, when, then from test.behave_utils import utils from gppylib.commands.base import Command def _run_sql(sql, opts=None): env = None if opts is not None: env = os.environ.copy() options = '' for key, value in opts.items(): options += "-c {}={} ".format(key, value) env['PGOPTIONS'] = options subprocess.check_call([ "psql", "postgres", "-c", sql, ], env=env) def do_catalog_query(query): cmd = '''PGOPTIONS='-c gp_role=utility' psql -t -d template1 -c "SET allow_system_table_mods='true'; %s"''' % query cmd = Command(name="catalog query", cmdStr=cmd) cmd.run(validateAfter=True) return cmd def change_hostname(dbid, hostname): do_catalog_query("UPDATE gp_segment_configuration SET hostname = '{0}', address = '{0}' WHERE dbid = {1}".format(hostname, dbid)) def change_status(dbid, status): do_catalog_query("UPDATE gp_segment_configuration SET status = '%s' WHERE dbid = %s" % (status, dbid)) @when('the standby host goes down') def impl(context): result = do_catalog_query("SELECT dbid FROM gp_segment_configuration WHERE content = -1 AND role = 'm'") dbid = result.get_stdout().strip() change_hostname(dbid, 'invalid_host') def cleanup(context): """ Reverses the above SQL by starting up in master-only utility mode. Since the standby host is incorrect, a regular gpstart call won't work. """ utils.stop_database_if_started(context) subprocess.check_call(['gpstart', '-am']) _run_sql(""" SET allow_system_table_mods='true'; UPDATE gp_segment_configuration SET hostname = master.hostname, address = master.address FROM ( SELECT hostname, address FROM gp_segment_configuration WHERE content = -1 and role = 'p' ) master WHERE content = -1 AND role = 'm' """, {'gp_role': 'utility'}) subprocess.check_call(['gpstop', '-am']) context.add_cleanup(cleanup, context) def _handle_sigpipe(): """ Work around https://bugs.python.org/issue1615376, which is not fixed until Python 3.2. This bug interferes with Bash pipelines that rely on SIGPIPE to exit cleanly. """ signal.signal(signal.SIGPIPE, signal.SIG_DFL) @when('gpstart is run with prompts accepted') def impl(context): """ Runs `yes | gpstart`. """ p = subprocess.Popen( [ "bash", "-c", "yes | gpstart" ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=_handle_sigpipe, ) context.stdout_message, context.stderr_message = p.communicate() context.ret_code = p.returncode @given('segment {dbid} goes down' ) def impl(context, dbid): result = do_catalog_query("SELECT hostname FROM gp_segment_configuration WHERE dbid = %s" % dbid) if not hasattr(context, 'old_hostnames'): context.old_hostnames = {} context.old_hostnames[dbid] = result.get_stdout().strip() change_hostname(dbid, 'invalid_host') @then('the status of segment {dbid} should be "{expected_status}"' ) def impl(context, dbid, expected_status): result = do_catalog_query("SELECT status FROM gp_segment_configuration WHERE dbid = %s" % dbid) status = result .get_stdout().strip() if status != expected_status: raise Exception("Expected status to be %s, but it is %s" % (expected_status, status)) @then('the status of segment {dbid} is changed to "{status}"' ) def impl(context, dbid, status): do_catalog_query("UPDATE gp_segment_configuration SET status = '%s' WHERE dbid = %s" % (status, dbid)) @then('the cluster is returned to a good state' ) def impl(context): if not hasattr(context, 'old_hostnames'): raise Exception("Cannot reset segment hostnames: no hostnames are saved") for dbid, hostname in context.old_hostnames.items(): change_hostname(dbid, hostname) context.execute_steps(""" When the user runs "gprecoverseg -a" Then gprecoverseg should return a return code of 0 And all the segments are running And the segments are synchronized When the user runs "gprecoverseg -a -r" Then gprecoverseg should return a return code of 0 And all the segments are running And the segments are synchronized """)
3,209
0
202
caae85bacfe71629215a5620278cfc2abaed9bde
17,277
py
Python
groupon/extras/code.py
vikmeup/python-groupon
a7fc55c3b22d3031ac5abf3190ea2d8fcdcd4699
[ "Apache-2.0" ]
null
null
null
groupon/extras/code.py
vikmeup/python-groupon
a7fc55c3b22d3031ac5abf3190ea2d8fcdcd4699
[ "Apache-2.0" ]
null
null
null
groupon/extras/code.py
vikmeup/python-groupon
a7fc55c3b22d3031ac5abf3190ea2d8fcdcd4699
[ "Apache-2.0" ]
null
null
null
from groupon import Version __author__ = "Allan Bunch" __copyright__ = "Copyright (C) 2010 Webframeworks LLC" __license__ = """Copyright 2010 Webframeworks LLC 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.""" __version__ = Version __maintainer__ = "Allan Bunch" __status__ = "Beta" __credits__ = []
57.019802
179
0.472883
from groupon import Version __author__ = "Allan Bunch" __copyright__ = "Copyright (C) 2010 Webframeworks LLC" __license__ = """Copyright 2010 Webframeworks LLC 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.""" __version__ = Version __maintainer__ = "Allan Bunch" __status__ = "Beta" __credits__ = [] class Factory( object ): def buildObject( self, objectRef, properties = {} ): if type( objectRef ) == type: for key, value in properties.iteritems(): setattr( objectRef, key, value ) else: return type( '%s' % objectRef, ( object, ), properties ) def objectify( self, structure, apiVersionNumber ): if structure.has_key( 'deals' ): dealList = [] for deal in structure['deals']: Deal = self.buildObject( 'Deal', {'id':deal['id'] , 'uri':deal['deal_url' ] , 'status':deal['status'] } ) # Begin Groupon Deal titles object. dealTitles = [] DealTitle = self.buildObject( 'DealTitle', {'short':deal['short_title']} ) dealTitles.append( DealTitle ) if apiVersionNumber in [1]: DealTitle = self.buildObject( 'DealTitle', {'long':deal['title']} ) dealTitles.append( DealTitle ) self.buildObject( Deal, {'titles':dealTitles} ) # Begin Groupon Deal placement object. try: DealPlacement = self.buildObject( 'DealPlacement', {'priority':deal['placement_priority']} ) except: DealPlacement = DealPlacement = self.buildObject( 'DealPlacement', {'priority':None} ) Deal.placement = DealPlacement # Begin Groupon Deal media object. DealMedia = self.buildObject( 'DealMedia' ) self.buildObject( DealMedia, { 'images':[] } ) DealImage = self.buildObject( 'DealImage' ) self.buildObject( DealImage, { 'uri':deal['small_image_url'] } ) self.buildObject( DealImage, { 'size':'small' } ) DealMedia.images.append( DealImage ) DealImage = self.buildObject( 'DealImage' ) self.buildObject( DealImage, { 'uri':deal['medium_image_url'] } ) self.buildObject( DealImage, { 'size':'medium' } ) DealMedia.images.append( DealImage ) DealImage = self.buildObject( 'DealImage' ) self.buildObject( DealImage, { 'uri':deal['large_image_url'] } ) self.buildObject( DealImage, { 'size':'large' } ) DealMedia.images.append( DealImage ) self.buildObject( Deal, { 'media':DealMedia } ) # Begin Groupon Deal division object. DealDivision = self.buildObject( 'DealDivision', { 'id':deal['division_id'] , 'name':deal['division_name'] } ) DealDivisionCoordinates = self.buildObject( 'DealDivisionCoordinates', { 'lat':deal['division_lat'], 'lng':deal['division_lng'] } ) DealDivisionGeo = self.buildObject( 'DealDivisionGeo', { 'coordinates':DealDivisionCoordinates } ) self.buildObject( DealDivision, { 'geo':DealDivisionGeo } ) self.buildObject( Deal, { 'division':DealDivision } ) DealDivisionTime = self.buildObject( 'DealDivisionTime' ) DealDivisionTimeZone = self.buildObject( 'DealDivisionTimeZone', { 'name':deal['division_timezone'] , 'meridian':'gmt', 'offset':deal['division_offset_gmt'] } ) self.buildObject( DealDivisionTime, { 'zone':DealDivisionTimeZone } ) self.buildObject( DealDivision, {'time':DealDivisionTime } ) self.buildObject( Deal, { 'division':DealDivision } ) # Begin Groupon Deal areas object. dealAreas = [] if apiVersionNumber in [1]: _dealAreas = [] for area in deal['areas']: _dealArea = dict( id = area ) _dealAreas.append( _dealArea ) else: _dealAreas = deal['areas'] for area in _dealAreas: DealArea = self.buildObject( 'DealArea', area ) dealAreas.append( DealArea ) self.buildObject( Deal, { 'areas':dealAreas } ) # Begin Groupon Deal shipping object. DealShipping = self.buildObject( 'DealShipping', { 'requirements':[] } ) DealShippingAddress = self.buildObject( 'DealShippingAddress', { 'required':deal['shipping_address_required'] } ) DealShippingRequirement = self.buildObject( 'DealShippingRequirement', { 'address':DealShippingAddress } ) DealShipping.requirements.append( DealShippingRequirement ) self.buildObject( Deal, { 'shipping':DealShipping } ) if apiVersionNumber in [1]: # Begin Groupon Deal vendor object. DealVendor = self.buildObject( 'DealVendor', {'id':deal['vendor_id'], 'name':deal['vendor_name'], 'uri':deal['vendor_website_url'] } ) self.buildObject( Deal, {'vendor':DealVendor} ) else: # Begin Groupon Deal merchant object. DealMerchant = self.buildObject( 'DealMerchant', {'id':deal['merchant_id'], 'name':deal['merchant_name'], 'uri':deal['merchant_website_url'] } ) self.buildObject( Deal, { 'vendor':DealMerchant } ) # Begin Groupon Deal dates object. DealDates = self.buildObject( 'DealDates', {'start':deal['start_date'], 'end':deal['end_date'] } ) self.buildObject( Deal, {'dates':DealDates} ) # Begin Groupon Deal tip object. DealTip = self.buildObject( 'DealTip', { 'reached':deal['tipped'], 'point':deal['tipping_point'] } ) try: self.buildObject( DealTip, { 'date':deal['tipped_date'] } ) except: self.buildObject( DealTip, { 'date':None } ) self.buildObject( Deal, { 'tip':DealTip } ) # Begin Groupon Deal inventory object. try: dealInventoryTotal = deal['conditions']['initial_quantity'] except: dealInventoryTotal = 'unlimited' try: dealInventoryStock = deal['conditions']['quantity_remaining'] except: dealInventoryStock = 'unlimited' DealInventoryUnits = self.buildObject( 'DealInventoryUnits', {'total':dealInventoryTotal , 'sold':deal['quantity_sold'] , 'available':dealInventoryStock } ) DealInventory = self.buildObject( 'DealInventory', { 'available':not deal['sold_out'], 'units':DealInventoryUnits } ) if apiVersionNumber in [1]: # This looks like an API version < 2, so: self.buildObject( DealInventory, {'limited':deal['conditions']['limited_quantity'] } ) self.buildObject( Deal, {'inventory':DealInventory } ) # Begin Groupon Deal cost object. if apiVersionNumber in [1]: dealCosts = [] DealCost = self.buildObject( 'DealCost', { 'type':'value', 'amount':deal['value'][:-3], 'units':deal['value'][-3:] } ) dealCosts.append( DealCost ) DealCost = self.buildObject( 'DealCost', { 'type':'price', 'amount':deal['price'][:-3], 'units':deal['price'][-3:] } ) dealCosts.append( DealCost ) DealCost = self.buildObject( 'DealCost', { 'type':'discount', 'amount':deal['discount_amount'][:-3], 'units':deal['discount_amount'][-3:], 'factor':deal['discount_percent'] * float( .01 ) } ) dealCosts.append( DealCost ) self.buildObject( Deal, {'costs':dealCosts} ) if apiVersionNumber in [1]: dealConditionsDates = [] DealConditions = self.buildObject( 'DealConditions' ) DealConditionsDate = self.buildObject( 'DealConditionsDate', {'type':'expiration', 'value':deal['conditions']['expiration_date']} ) dealConditionsDates.append( DealConditionsDate ) self.buildObject( DealConditions, {'dates':dealConditionsDates} ) DealConditionsPurchase = self.buildObject( 'DealConditionsPurchase', {'minimum':deal['conditions']['minimum_purchase'], 'maximum':deal['conditions']['maximum_purchase']} ) self.buildObject( DealConditions, {'purchase':DealConditionsPurchase} ) self.buildObject( Deal, {'conditions':DealConditions} ) if deal.has_key( 'options' ): # Begin Groupon Deal variations object. dealVariations = [] for dealOption in deal['options']: DealVariation = self.buildObject( 'DealVariation', {'id':dealOption['id'], 'title':dealOption['title']} ) # Begin Groupon Deal Option inventory object. try: dealVariationTotalUnits = dealOption['conditions']['initial_quantity'] except: dealVariationTotalUnits = None try: dealVariationUnitsInStock = dealOption['conditions']['quantity_remaining'] except: dealVariationUnitsInStock = None DealVariationInventory = self.buildObject( 'DealVariationInventory', {'total':dealVariationTotalUnits, 'sold':dealOption['quantity_sold'], 'stock':dealVariationUnitsInStock, 'available':not dealOption['sold_out']} ) self.buildObject( DealVariation, {'inventory':DealVariationInventory} ) # Begin Groupon Deal Option cost object. dealVariationCosts = [] DealVariationCost = self.buildObject( 'DealVariationCost', { 'type':'value', 'amount':dealOption['value'][:-3], 'units':dealOption['value'][-3:] } ) dealVariationCosts.append( DealVariationCost ) DealVariationCost = self.buildObject( 'DealVariationCost', { 'type':'price', 'amount':dealOption['price'][:-3], 'units':dealOption['price'][-3:] } ) dealVariationCosts.append( DealVariationCost ) DealVariationCost = self.buildObject( 'DealVariationCost', { 'type':'discount', 'amount':dealOption['discount_amount'][:-3], 'units':dealOption['discount_amount'][-3:], 'factor':dealOption['discount_percent'] * float( .01 ) } ) dealVariationCosts.append( DealVariationCost ) self.buildObject( DealVariation, {'costs':dealVariationCosts} ) # Begin Groupon Deal Options conditions object. dealVariationConditionsDates = [] DealVariationConditions = self.buildObject( 'DealVariationConditions' ) DealVariationConditionsDate = self.buildObject( 'DealVariationConditionsDate', {'type':'expiration', 'value':dealOption['conditions']['expiration_date']} ) dealVariationConditionsDates.append( DealVariationConditionsDate ) self.buildObject( DealVariationConditions, {'dates':dealVariationConditionsDates} ) DealVariationConditionsPurchase = self.buildObject( 'DealVariationConditionsPurchase', {'minimum':dealOption['conditions']['minimum_purchase'], 'maximum':dealOption['conditions']['maximum_purchase']} ) self.buildObject( DealVariationConditions, {'purchase':DealVariationConditionsPurchase} ) self.buildObject( DealVariation, {'conditions':DealVariationConditions} ) dealVariations.append( DealVariation ) self.buildObject( Deal, {'variations':dealVariations} ) dealList.append( Deal ) return dealList elif structure.has_key( 'divisions' ): divisionList = [] for division in structure['divisions']: Division = self.buildObject( 'Division', {'id':division['id'], 'name':division['name']} ) DivisionGeo = self.buildObject( 'DivisionGeo' ) DivisionGeoCoordinates = self.buildObject( 'DivisionGeoCoordinate', {'lat':division['location']['latitude'], 'lng':division['location']['longitude']} ) self.buildObject( DivisionGeo, {'coordinates':DivisionGeoCoordinates} ) self.buildObject( Division, {'geo':DivisionGeo} ) class DivisionTime: pass DivisionTime = self.buildObject( 'DivisionTime' ) DivisionTimeZone = self.buildObject( 'DivisionTimeZone', {'name':division['location']['timezone'], 'meridian':'gmt', 'offset':division['location']['timezone_offset_gmt']} ) self.buildObject( DivisionTime, {'zone':DivisionTimeZone} ) self.buildObject( Division, {'time':DivisionTime} ) divisionList.append( Division ) return divisionList else: raise Exception( 1000, 'Invalid Groupon entity requested.' )
16,270
3
77
593e64885e5d572e4b146897a1f80d8ba96c976f
11,552
py
Python
app/utils/webstore.py
Timon0305/Auto_Checking
8bb8e1e7e4a4817ff6769db25ea4fe0d8e5d65bf
[ "MIT" ]
null
null
null
app/utils/webstore.py
Timon0305/Auto_Checking
8bb8e1e7e4a4817ff6769db25ea4fe0d8e5d65bf
[ "MIT" ]
1
2022-02-09T16:45:14.000Z
2022-02-09T16:45:14.000Z
app/utils/webstore.py
Timon0305/Auto_Checking
8bb8e1e7e4a4817ff6769db25ea4fe0d8e5d65bf
[ "MIT" ]
null
null
null
import json from time import sleep import requests from cloudaio import tlsexpert import uuid import random s = requests.session() stylecode = 'DB5074-101' stop = False storage = {} sizes = ['9'] cookie = '_abck=42D4E2E416589130C76B07375A19C056~-1~YAAQwArGF1ovWzJ1AQAAFVlARAS+j6F2rlSe4zrahotRz7GSQSWK5sEIKBw84/F206ZvoZUygpHQDG2YE7a/6qDtXywJFj1qo80QXunTlvRzSb9Ir3ImsuxW2d1aiy+bJXLo/yXYCOuetAXkjg2A5oCOke/NNXdy237kNClxK+sKyTBOKevR+D+E1/NGMYiEpaAzD16lT+2zRGyEuEbaP+zB3uPBJFhWZmoCmaqlwzO4DURy2G6ezrTVix6pnEtqBc8ZnwXDj9EbIet9NllmEsaBbg4J0KVTDZNrj8KC06X9kQY76KG7ySYQo76J/0q87+rdbNLPerfEMa6EEmEA1BALEvPu/QekZodLy4wSyk78/OshgKGI04hEw/A507k+jyvj2bMaRxMDZL6CBfvbNI0pLPWNBKdI38rytTrR7CmgFjb36bypW+EX9+K5CA99EYXszg==~-1~-1~-1;bm_sz=2B6D19B104CB409988B860E3EFE6EFEF~YAAQwArGFw8uWzJ1AQAAbkBARAmC3kWjspX7DFScuMysLDd9PdAF5cLWQ/pCFM4kl5WauGx51hwgvP51RoEjABxOcClhVbzjJkiRUM9nStEYbG44nHc0RZp+5JscnidJMcNh5Mtx/WKLVAI+ZFCcbqTdL/mb1bdGExlbiO11DWzzk6JVgeJMoDf4u4887uoocgyJjo+kwWkmHXUZpj4k5XfCr2IaEbQ+hLlCMOU+qWprIs8ZKdQiWEb8cKSjsfltIL2MUPanCcQIdnN8m/8F0FuevUIBGqN/FKg=;' region = 'SG' visitor = str(uuid.uuid4()) url = 'https://api.nike.com/buy/partner_cart_preorder/v1/' + str(uuid.uuid4()) proxy1 = '108.165.18.67:14025' proxy = {"http": "http://" + proxy1, "https": "https://" + proxy1} s.proxies.update(proxy) maxlimit = None print(json.dumps( { "status": "0", "message": "Starting..." } )) # Fetch Product details found = details() while not found: found = details() # Your monitor code status,size = monitor() while not status: status, size = monitor() # Later on you branch to ATC success = atc(size) if success: check_order() #Now tell the UI to show the success to the user
35.435583
851
0.512119
import json from time import sleep import requests from cloudaio import tlsexpert import uuid import random s = requests.session() stylecode = 'DB5074-101' stop = False storage = {} sizes = ['9'] cookie = '_abck=42D4E2E416589130C76B07375A19C056~-1~YAAQwArGF1ovWzJ1AQAAFVlARAS+j6F2rlSe4zrahotRz7GSQSWK5sEIKBw84/F206ZvoZUygpHQDG2YE7a/6qDtXywJFj1qo80QXunTlvRzSb9Ir3ImsuxW2d1aiy+bJXLo/yXYCOuetAXkjg2A5oCOke/NNXdy237kNClxK+sKyTBOKevR+D+E1/NGMYiEpaAzD16lT+2zRGyEuEbaP+zB3uPBJFhWZmoCmaqlwzO4DURy2G6ezrTVix6pnEtqBc8ZnwXDj9EbIet9NllmEsaBbg4J0KVTDZNrj8KC06X9kQY76KG7ySYQo76J/0q87+rdbNLPerfEMa6EEmEA1BALEvPu/QekZodLy4wSyk78/OshgKGI04hEw/A507k+jyvj2bMaRxMDZL6CBfvbNI0pLPWNBKdI38rytTrR7CmgFjb36bypW+EX9+K5CA99EYXszg==~-1~-1~-1;bm_sz=2B6D19B104CB409988B860E3EFE6EFEF~YAAQwArGFw8uWzJ1AQAAbkBARAmC3kWjspX7DFScuMysLDd9PdAF5cLWQ/pCFM4kl5WauGx51hwgvP51RoEjABxOcClhVbzjJkiRUM9nStEYbG44nHc0RZp+5JscnidJMcNh5Mtx/WKLVAI+ZFCcbqTdL/mb1bdGExlbiO11DWzzk6JVgeJMoDf4u4887uoocgyJjo+kwWkmHXUZpj4k5XfCr2IaEbQ+hLlCMOU+qWprIs8ZKdQiWEb8cKSjsfltIL2MUPanCcQIdnN8m/8F0FuevUIBGqN/FKg=;' region = 'SG' visitor = str(uuid.uuid4()) url = 'https://api.nike.com/buy/partner_cart_preorder/v1/' + str(uuid.uuid4()) proxy1 = '108.165.18.67:14025' proxy = {"http": "http://" + proxy1, "https": "https://" + proxy1} s.proxies.update(proxy) maxlimit = None def details(): global region,stylecode,maxlimit try: url = 'https://api.nike.com/product_feed/threads/v2?filter=marketplace({r})&filter=language(en-GB)&filter=channelId(d9a5bc42-4b9c-4976-858a-f159cf99c647)&filter=publishedContent.properties.products.styleColor({s})'.format( r=region, s=stylecode) y = s.get(url).json() try: # (y['objects'][0]["productInfo"][0]["merchProduct"]["status"],y['objects'][0]["productInfo"][0]["merchProduct"]["styleCode"],y['objects'][0]["productInfo"][0]["merchProduct"]["labelName"],) if y['objects'][0]["productInfo"][0]["merchProduct"]["status"] in ['CLOSEOUT', 'ACTIVE', 'INACTIVE', "HOLD"]: status = y['objects'][0]["productInfo"][0]["merchProduct"]["status"] #stylecode = y['objects'][0]["productInfo"][0]["merchProduct"]["styleColor"] name = y['objects'][0]["productInfo"][0]["merchProduct"]["labelName"] maxlimit = y['objects'][0]["productInfo"][0]["merchProduct"]["quantityLimit"] price = y['objects'][0]["productInfo"][0]["merchPrice"]["currentPrice"] for z in y['objects'][0]["productInfo"][0]["skus"]: storage[z["nikeSize"]] = z["id"] return True else: print(json.dumps( { "status": "0", "message": "Product is not live..." } )) return False except: print(json.dumps( { "status": "0", "message": "Product was not found..." } )) sleep(5) return False except: print(json.dumps( { "status": "0", "message": "Error fetching skus..." } )) def monitor(): url = 'https://api.nike.com/cic/grand/v1/graphql' headers = { 'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.5', 'appid': 'com.nike.commerce.nikedotcom.web', 'Cache-Control': 'no-cache', 'cloud_stack': 'cart_applause_test', 'Connection': 'keep-alive', 'Content-Length': '194', 'Content-Type': 'application/json; charset=UTF-8', 'Host': 'api.nike.com', 'nike-api-caller-id': 'com.nike.commerce.nikedotcom.web', 'Origin': 'https://www.nike.com', 'Pragma': 'no-cache', 'Referer': 'https://www.nike.com/ca/en/cart', 'TE': 'Trailers', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0', 'X-B3-SpanName': 'CiCCart', 'X-B3-TraceId': str(uuid.uuid4()), 'X-Nike-VisitId': '3', 'X-Nike-VisitorId': str(uuid.uuid4()), } skulist = [] key, value = random.choice(list(storage.items())) skulist.append(value) data = { "hash": "ef571ff0ac422b0de43ab798cc8ff25f", "variables": {"ids": skulist, "country": "CA", "language": "en-GB", "isSwoosh": False}} # print(x) try: x = s.post(url, headers=headers, json=data).json() print(json.dumps( { "status": "0", "message": "Monitoring..." } )) for y in x['data']['skus'][0]['product']['skus']: if y['availability']['level'] != 'OOS': if y['id'] in [storage[str(z)] for z in sizes if z in storage.keys()]: size = helper(y['id']) print(json.dumps( { "status": "0", "message": "Added to cart..." } )) return True, size except: try: if x['errors'] != []: # print(colored('[' + str(dt.datetime.now()) + '] [Task #' + str(instance) + '] {} {}!', 'yellow').format(name, x['errors'][0]['message'])) return False, None except: print(json.dumps( { "status": "0", "message": "Banned proxy..." } )) return False, None sleep(5) def atc(size): global url puthead = { 'Accept': 'application/json; charset=UTF-8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.5', 'appid': 'com.nike.commerce.nikedotcom.web', 'Cache-Control': 'no-cache', 'Cookie': cookie, 'cloud_stack': 'buy_domain', 'Connection': 'keep-alive', 'Content-Type': 'application/json; charset=UTF-8', 'Host': 'api.nike.com', 'Origin': 'https://www.nike.com', 'Pragma': 'no-cache', 'Referer': 'https://www.nike.com/ca/en/cart', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36', 'X-B3-SpanName': 'undefined', 'X-B3-TraceId': str(uuid.uuid4()), 'x-nike-visitid': '1', 'x-nike-visitorid': visitor, } cur = None if region == "SG": cur = "SGD" if region == "MY": cur = "MYR" senddata2 = { "country": region, "language": "en-GB", "channel": "NIKECOM", "cartId": str(uuid.uuid4()), "currency": cur, "paypalClicked": False, "items": [ {"id": str(uuid.uuid4()), "skuId": size, "quantity": maxlimit}]} good = False try: x = tlsexpert.request('sby5ayjfD5PxA36dN7Rr4smNmkqqKdyV3rxVaRCK4FZdcYHm', 'PUT', url, proxy["http"], puthead, json.dumps(senddata2)) x = json.loads(x) good = True except: print(json.dumps( { "status": "0", "message": "Timeout error..." } )) if good: if x['Status'] == 202: print(json.dumps( { "status": "1", "message": "Successfully added to cart..." } )) return True else: print(json.dumps( { "status": "0", "message": "Failed add to cart..." } )) return False def check_order(): global url puthead = { 'Accept': 'application/json; charset=UTF-8, application/json', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.5', 'appid': 'com.nike.commerce.nikedotcom.web', 'Cache-Control': 'no-cache', 'cloud_stack': 'buy_domain', 'Connection': 'keep-alive', 'Content-Type': 'application/json; charset=UTF-8', # 'Cookie': '_abck=D9DAD9645F0BD1A7620CFE347533A46D~-1~YAAQhwXGFwbuLr9xAQAA+O+kJgNuJz+bgXqTSxmJJRi6WnlLahkTaoPXo+fz0hIGw5RIkG3aECc348nnUFjZASY433FpeC6SAQDK93IRZTbfzqt++2k8gpMv/4vPoMB1k6xgZhrwEs+1tXGxmvRP8dPFvz2fSOGYnTJdK0lcbygjUYszsG7y/sedZBJ144RDB7eim3l+P0ooBslY5oFSgihLz5YjFeaVmmUApy2ES2hcufORPWkjCil/3LBBNQ/fZXWXHeznYqTBE/jEg6xylKpQ0aNVqRkVTloj5BhETT9GT0T+JMoyP3I08d+pOc9YjKwTMpbf3+YiyFI7jPomY4oIxA==~-1~-1~-1;', 'Host': 'api.nike.com', 'Origin': 'https://www.nike.com', 'Pragma': 'no-cache', 'Referer': 'https://www.nike.com/ca/en/cart', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36', 'X-B3-SpanName': 'CiCCart', 'X-B3-TraceId': '2a68677b-68b4-4781-a0b2-a71fdb9d5ee1', 'x-nike-visitid': '1', 'x-nike-visitorid': visitor, } good = False try: x = tlsexpert.request('sby5ayjfD5PxA36dN7Rr4smNmkqqKdyV3rxVaRCK4FZdcYHm', 'GET', url, proxy["http"], puthead) x = json.loads(x) good = True except: print('timeout error') if good: if x["Status"] == 200: x = json.loads(x['Body']) if x['status'] == 'IN_PROGRESS': print(json.dumps( { "status": "0", "message": "Order in progress..." } )) sleep(1) check_order() else: try: url = x["response"]["redirectUrl"] print(json.dumps( { "status": "1", "message": "Got Cart..." } )) print(url) url = url print(json.dumps( { "status": "2", "message": "Sent Cart Link!", "url": url, "productImage": 'https://secure-images.nike.com/is/image/DotCom/' + stylecode.replace("-", "_"), "size": str(sizes[0]), } )) except: print(json.dumps( { "status": "0", "message": "Out of stock..." } )) else: print(json.dumps( { "status": "0", "message": "Error getting cart..." } )) def helper(skuid): for y in storage: if skuid == storage[y]: return storage[y] print(json.dumps( { "status": "0", "message": "Starting..." } )) # Fetch Product details found = details() while not found: found = details() # Your monitor code status,size = monitor() while not status: status, size = monitor() # Later on you branch to ATC success = atc(size) if success: check_order() #Now tell the UI to show the success to the user
9,730
0
115
d0e3068f6158d62cc93b692a481748d81fc4828b
8,344
py
Python
apps/solar_savings_potential.py
annieco29/rooftop_solar_energy_app
11314d80f1b714d86090c90df7a63f78966107e0
[ "MIT" ]
null
null
null
apps/solar_savings_potential.py
annieco29/rooftop_solar_energy_app
11314d80f1b714d86090c90df7a63f78966107e0
[ "MIT" ]
null
null
null
apps/solar_savings_potential.py
annieco29/rooftop_solar_energy_app
11314d80f1b714d86090c90df7a63f78966107e0
[ "MIT" ]
null
null
null
import streamlit as st import pandas as pd import numpy as np import datetime import plotly.express as px import base64
46.355556
188
0.680609
import streamlit as st import pandas as pd import numpy as np import datetime import plotly.express as px import base64 def app(): LOGO_IMAGE_IBM = "apps/ibm.png" LOGO_IMAGE_U_OF_F = "apps/u_of_f.svg.png" LOGO_IMAGE_BRIGHTER = "apps/brighter_potential_logo.png" st.markdown( """ <style> .container { display: flex; } .logo-text { font-weight:700 !important; font-size:50px !important; color: #f9a01b !important; padding-top: 75px !important; } .logo-img { float: left; position: relative; margin-top: 600px; } #logo { position: absolute; float: right; } </style> """, unsafe_allow_html=True ) st.markdown( f""" <img class="logo-img" src="data:image/png;base64,{base64.b64encode(open(LOGO_IMAGE_IBM, "rb").read()).decode()}" width="100x`" height="40" style="border:20px;margin:0px" /> <img class="logo-img" src="data:image/png;base64,{base64.b64encode(open(LOGO_IMAGE_U_OF_F, "rb").read()).decode()}" width="200" height="40" style="border:20px;margin:0px"/> &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp; &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp; <img class="logo" src="data:image/png;base64,{base64.b64encode(open(LOGO_IMAGE_BRIGHTER, "rb").read()).decode()}" width="100" height="100" /> """, unsafe_allow_html=True ) st.markdown('---') st.header("Solar Rooftop Potential Prediction") # Sidebar st.sidebar.header('Choose Time Range to View:') min_date = st.sidebar.date_input('Min Date', datetime.datetime(2019, 1, 1)) min_date = min_date.strftime('%m/%d/%y') max_date = st.sidebar.date_input('Max Date', datetime.datetime(2019, 12, 31)) max_date = max_date.strftime('%m/%d/%y') st.sidebar.header('Choose Zipcode to View:') # Declare zipcode list zipcodes = [33131,33040,34112,33916,33407,33935,33471,33950, 34266,34994,34972,34236,34950,34205,33873,32960,33830,33606,33755,34741,33525,32806,34601, 32796,33513,32778,32771,34453,32720,34471,32621,32110,32601,32177,32456,32080,32091,32054, 32066,32347,32401,32327, 32025,32064,32063,32202,32502,32503,32424,32321,32304,32340,32344, 32351,32570,32034,32433,32536,32428,32448,32425,32602,32603,32604,32605,32606, 32607,32608,32609,32610,32611,32612,32614,32627,32641,32653,32402,32404,32405,32406, 32412,32073,32081,32099,32201,32203,32204,32205,32206,32207,32208,32209, 32210,32211,32212,32214,32216,32217,32218,32219,32220,32221,32222,32223,32224, 32225,32226,32227,32228,32229,32233,32234,32235,32236,32237,32238,32239, 32241,32244,32245,32246,32247,32250,32254,32255,32256,32257,32258,32266,32277, 32501,32504,32505,32514,32520,32522,32523,32524,32591,33601,33602,33603,33604, 33605,33607,33608,33609,33610,33611,33612,33613,33615,33616,33617,33619, 33620,33621,33622,33623,33629,33630,33631,33633,33634,33637,33646,33647,33650,33655,33660,33661, 33662,33664,33672,33673,33674,33675,33677,33679,33680,33681,33686,33901, 33902,33903,33905,33906,33907,33911,33912,33913,33917,33919,33966,33971,33990,32301,32302,32303,32305,32306, 32307,32308,32309,32310,32311,32312,32313,32314,32316,32317,32395,32399, 33101,33109,33111,33114,33125,33126,33127,33128,33129,33130,33132,33133,33134,33135,33136,33137,33138, 33139,33140,33142,33144,33145,33146,33147,33149,33150,33151,33159,33222,33233,33234, 33238,33242,33245,33255,32789,32801,32802,32803,32804,32805,32807,32808,32809, 32810,32811,32812,32814,32819,32822,32824,32827,32829,32832,32834, 32835,32839,32853,32854,32855,32856,32861,32862,32878,32885,32886, 32891,33401,33402,33403,33405,33409,33411,33412,33417,33756,33757,33758, 33759,33761,33763,33764,33765,33766,33767,33769,33302, 33303,33304,33305,33306,33307,33308,33309,33311,33312,33315,33316,33334,33338,33339,33348, 33394 ] # Put client and date options in the sidebar selected_zip = st.sidebar.selectbox( 'Choose Zipcode:', zipcodes, key='zipcodes' ) st.markdown(""" * Renewables currently account for roughly only 4% of energy production in Florida. * Stakeholders need to know how solar energy sources can supplement the power grid. * The sunburst chart below shows the daily potential of energy demand that could be supplied by rooftop solar energy for 2019. * This projection for 2019 is based on predictive modeling that predicts the daily rooftop solar energy potential and the energy demand based on the weather. """) # area_stats = pd.read_csv('data/RPMSZips.csv', dtype={'zip':str}) area_stats = pd.read_csv('apps/florida_weather_w_predictions_and_zip_codes.csv', dtype={'zipcode':str}) #st.write(area_stats.head()) st.markdown("""Energy Demand vs. Solar Production Potential for 62 most populated Florida zip codes for all of 2019:""") # get f'{value:,}' florida_predicted_demand = round(area_stats['real_pred_demand_mwh'].sum()) florida_predicted_solar = round(area_stats['solar_prod_mwh'].sum()) col1, col2 = st.columns(2) col1.metric(label="Predicted Demand (mwh)", value=f'{florida_predicted_demand:,}' #, delta=100 ) col2.metric(label = "Solar Rooftop Potential (mwh)", value = f'{florida_predicted_solar:,}', #delta = 50 ) # create a dataframe that gets masked based on min and max date selectors area_stats['date_time'] = pd.to_datetime(area_stats['date_time']) selected_zip = str(selected_zip) daily_mask = ((area_stats['date_time'] >= min_date) & (area_stats['date_time'] <= max_date) & (area_stats['zipcode']== selected_zip)) df_masked = area_stats.loc[daily_mask] change_details = df_masked[['date_time','zipcode','real_pred_demand_mwh','solar_prod_mwh','percentage_demand_covered']].copy() change_details['date_time'] = change_details['date_time'].dt.strftime('%m/%d/%Y') #st.write('df_masked shape = ') #st.write(change_details.shape) st.write("---") st.markdown("""Energy Demand vs. Solar Production Potential for Selected Zip Code:""") # get f'{value:,}' predicted_demand = round(change_details['real_pred_demand_mwh'].sum()) predicted_solar = round(change_details['solar_prod_mwh'].sum()) col1, col2= st.columns(2) col1.metric(label="Predicted Demand (mwh) for " f'{selected_zip}', value=f'{predicted_demand:,}' #, delta=100 ) col2.metric(label = "Solar Rooftop Potential (mwh) for " f'{selected_zip}', value = f'{predicted_solar:,}', #delta = 50 ) #get name of month for sunburst chart area_stats['month'] = area_stats['date_time'].dt.strftime("%B") area_stats['word_date'] = area_stats['date_time'].dt.strftime("%B %e, %Y") # create a dataframe that gets masked based on zipcode selected_zip = str(selected_zip) zip_mask = (area_stats['zipcode']== selected_zip) df_zip_masked = area_stats.loc[zip_mask] change_details_zip = df_zip_masked[['date_time','month','word_date','zipcode','real_pred_demand_mwh','solar_prod_mwh','percentage_demand_covered']].copy() #st.write('df_masked shape = ') #st.write(change_details.shape) #sunburst chart label dictionary label_dict = {'Percent Demand Covered': 'percentage_demand_covered','Month': 'month', 'Date':'word_date'} # st.write(area_stats['percentage_demand_covered'].dtype) fig = px.sunburst(change_details_zip, path=['month','word_date'], values= 'percentage_demand_covered', color='percentage_demand_covered', color_continuous_scale='RdBu') fig.update_layout(coloraxis_colorbar_title='Rooftop Solar Energy Potential') fig.update_layout(title='Click various months to view percentage of demand fulfilled by solar potential') fig.update_layout(width=800, height=600) #format label fig.update_traces(hovertemplate='<b>%{label} </b> <br>%{customdata[0]:,.3f}') # write to streamlit st.plotly_chart(fig)
8,202
0
23
72ebbb47f00a1f3815d46bfb5a0e5a0fd768886b
14,312
py
Python
src/guesswhat/train/train_oracle.py
ibrahimSouleiman/GuessWhat
60d140de1aae5ccda27e7d3eef2b9fb9548f0854
[ "Apache-2.0" ]
null
null
null
src/guesswhat/train/train_oracle.py
ibrahimSouleiman/GuessWhat
60d140de1aae5ccda27e7d3eef2b9fb9548f0854
[ "Apache-2.0" ]
null
null
null
src/guesswhat/train/train_oracle.py
ibrahimSouleiman/GuessWhat
60d140de1aae5ccda27e7d3eef2b9fb9548f0854
[ "Apache-2.0" ]
null
null
null
import argparse import logging import os from multiprocessing import Pool from distutils.util import strtobool import tensorflow as tf import numpy as np import json from pathlib import Path from generic.data_provider.iterator import Iterator from generic.tf_utils.evaluator import Evaluator from generic.tf_utils.optimizer import create_optimizer from generic.tf_utils.ckpt_loader import load_checkpoint, create_resnet_saver from generic.utils.config import load_config from generic.utils.file_handlers import pickle_dump from generic.data_provider.image_loader import get_img_builder from generic.data_provider.nlp_utils import Embeddings from generic.data_provider.nlp_utils import GloveEmbeddings from src.guesswhat.data_provider.guesswhat_dataset import OracleDataset from src.guesswhat.data_provider.oracle_batchifier import OracleBatchifier from src.guesswhat.data_provider.guesswhat_tokenizer import GWTokenizer from src.guesswhat.models.oracle.oracle_network import OracleNetwork import time if __name__ == '__main__': ############################# # LOAD CONFIG ############################# parser = argparse.ArgumentParser('Oracle network baseline!') parser.add_argument("-data_dir", type=str, help="Directory with data") parser.add_argument("-exp_dir", type=str, help="Directory in which experiments are stored") parser.add_argument("-config", type=str, help='Config file') parser.add_argument("-dict_file_question", type=str, default="dict.json", help="Dictionary file name")# default dict_pos_tag parser.add_argument("-dict_file_description", type=str, default="dict_Description.json", help="Dictionary file name") parser.add_argument("-all_dictfile", type=str, default="data/list_allquestion1.npy", help="Dictionary file name") parser.add_argument("-img_dir", type=str, help='Directory with images') parser.add_argument("-crop_dir", type=str, help='Directory with images') parser.add_argument("-load_checkpoint", type=str, help="Load model parameters from specified checkpoint") parser.add_argument("-continue_exp", type=lambda x: bool(strtobool(x)), default="False", help="Continue previously started experiment?") parser.add_argument("-gpu_ratio", type=float, default=0.50, help="How many GPU ram is required? (ratio)") parser.add_argument("-no_thread", type=int, default=4, help="No thread to load batch") parser.add_argument("-inference_mode", type=bool, default=False, help="inference mode True if you want to execute only test_dataset") args = parser.parse_args() config, exp_identifier, save_path = load_config(args.config, args.exp_dir) # logger.info("Save_path = ",save_path) # exit() logger = logging.getLogger() # Load config resnet_version = config['model']["image"].get('resnet_version', 50) finetune = config["model"]["image"].get('finetune', list()) batch_size = config['optimizer']['batch_size'] no_epoch = config["optimizer"]["no_epoch"] use_glove = config["model"]["glove"] # Inference True if want to test the dataset_test of the pre-trained Weigth inference = False wait_inference = 1 ############################# # LOAD DATA ############################# # Load image image_builder, crop_builder = None, None use_resnet = False logger.info("Loading ") t_begin = time.time() if config['inputs'].get('image', False): logger.info('Loading images..') image_builder = get_img_builder(config['model']['image'], args.img_dir) use_resnet = image_builder.is_raw_image() if config['inputs'].get('crop', False): logger.info('Loading crops..') crop_builder = get_img_builder(config['model']['crop'], args.crop_dir, is_crop=True) use_resnet = crop_builder.is_raw_image() # Load data logger.info('Loading data..') all_img_bbox = {} all_img_describtion = [] t1 = time.time() trainset = OracleDataset.load(args.data_dir, "train",image_builder = image_builder, crop_builder = crop_builder,all_img_bbox = all_img_bbox,all_img_describtion=all_img_describtion) validset = OracleDataset.load(args.data_dir, "valid", image_builder= image_builder, crop_builder = crop_builder,all_img_bbox = all_img_bbox,all_img_describtion=all_img_describtion) testset = OracleDataset.load(args.data_dir, "test",image_builder= image_builder, crop_builder = crop_builder,all_img_bbox = all_img_bbox,all_img_describtion=all_img_describtion) t2 = time.time() logger.info("Time to load data = {}".format(t2-t1)) # np.save("all_img_bbox.npy",all_img_bbox) # logger.info("Image_crop legnth= {}".format(len(all_img_describtion))) # logger.info("Image_crop = {}".format(all_img_describtion)) # with open('all_img_bbox.json', 'a') as file: # file.write(json.dumps(all_img_bbox,sort_keys=True, indent=4, separators=(',', ': '))) file_allquestion = Path("all_question_game.txt") # verify if file exist if not file_allquestion.is_file(): with open('all_question_game.txt', 'a') as file: for question in all_img_describtion: file.write(question+"\n") else: logger.info("all_question exist") # Load dictionary logger.info('Loading dictionary Question..') tokenizer = GWTokenizer(os.path.join(args.data_dir, args.dict_file_question),dic_all_question="data/dict_word_indice.pickle") # Load dictionary tokenizer_description = None if config["inputs"]["description"]: logger.info('Loading dictionary Description......') tokenizer_description = GWTokenizer(os.path.join(args.data_dir,args.dict_file_description),question=False) # Build Network logger.info('Building network..') if tokenizer_description != None: network = OracleNetwork(config, num_words_question=tokenizer.no_words,num_words_description=tokenizer_description.no_words) else: network = OracleNetwork(config, num_words_question=tokenizer.no_words,num_words_description=None) # Build Optimizer logger.info('Building optimizer..') optimizer, outputs = create_optimizer(network, config, finetune=finetune) best_param = network.get_predict() ############################## # START TRAINING ############################# logger.info("Start training .......") # create a saver to store/load checkpoint saver = tf.train.Saver() resnet_saver = None logger.info("saver done !") cpu_pool = Pool(args.no_thread, maxtasksperchild=5000) gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_ratio) logger.info("gpu_options done !") # Retrieve only resnet variabes if use_resnet: resnet_saver = create_resnet_saver([network]) # use_embedding = False # if config["embedding"] != "None": # use_embedding = True logger.info("resnet_saver done !") glove = None if use_glove: logger.info('Loading glove..') glove = GloveEmbeddings(os.path.join(args.data_dir, config["glove_name"]),glove_dim=300,type_data="common_crow") logger.info("glove done !") # embedding = None # if use_embedding: # logger.info('Loading embedding..') # embedding = Embeddings(args.all_dictfile,total_words=tokenizer.no_words,train=trainset,valid=validset,test=testset,dictionary_file_question=os.path.join(args.data_dir, args.dict_file_question),dictionary_file_description=os.path.join(args.data_dir, args.dict_file_description),description=config["inputs"]["description"],lemme=config["lemme"],pos=config["pos"]) # CPU/GPU option with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True)) as sess: sources = network.get_sources(sess) out_net = network.get_parameters()[-1] # logger.info("Sources: " + ', '.join(sources)) sess.run(tf.global_variables_initializer()) if use_resnet: resnet_saver.restore(sess, os.path.join(args.data_dir, 'resnet_v1_{}.ckpt'.format(resnet_version))) start_epoch = load_checkpoint(sess, saver, args, save_path) best_val_err = 0 # best_train_err = None # # create training tools evaluator = Evaluator(sources, network.scope_name,network=network,tokenizer=tokenizer) # train_evaluator = MultiGPUEvaluator(sources, scope_names, networks=networks, tokenizer=tokenizer) # train_evaluator = Evaluator(sources, scope_names[0], network=networks[0], tokenizer=tokenizer) # eval_evaluator = Evaluator(sources, scope_names[0], network=networks[0], tokenizer=tokenizer) batchifier = OracleBatchifier(tokenizer, sources, status=config['status'],glove=glove,tokenizer_description=tokenizer_description,args = args,config=config) stop_learning = False progress_compteur = 0 t = 0 if inference == False: while start_epoch < no_epoch and not stop_learning : # for t in range(start_epoch, no_epoch): logger.info('Epoch {}..'.format(t + 1)) # logger.info('Epoch {}..'.format(t + 1)) logger.info(" train_oracle | Iterator ...") t1 = time.time() train_iterator = Iterator(trainset, batch_size=batch_size, pool=cpu_pool, batchifier=batchifier, shuffle=True) t2 = time.time() logger.info(" train_oracle | Iterator...Total=".format(t2-t1)) t1 = time.time() train_loss, train_accuracy = evaluator.process(sess, train_iterator, outputs=outputs + [optimizer],out_net=best_param) t2 = time.time() logger.info(" train_oracle | evaluatorator...Total=".format(t2-t1)) t1 = time.time() valid_iterator = Iterator(validset, pool=cpu_pool, batch_size=batch_size*2, batchifier=batchifier, shuffle=False) t2 = time.time() logger.info(" train_oracle | Iterator validset...Total=".format(t2-t1)) t1 = time.time() # [network.get_emb_concat()] valid_loss, valid_accuracy = evaluator.process(sess, valid_iterator, outputs=outputs,type_data="Valid") t2 = time.time() logger.info(" train_oracle | evaluator ...Total=".format(t2-t1)) logger.info("Training loss: {}".format(train_loss)) logger.info("Training error: {}".format(1-train_accuracy)) logger.info("Validation loss: {}".format(valid_loss)) logger.info("Validation error: {}".format(1-valid_accuracy)) t1 = time.time() if valid_accuracy > best_val_err: best_train_err = train_accuracy best_val_err = valid_accuracy saver.save(sess, save_path.format('params.ckpt')) progress_compteur = 0 logger.info("Oracle checkpoint saved...") pickle_dump({'epoch': t}, save_path.format('status.pkl')) elif valid_accuracy < best_val_err: progress_compteur += 1 if int(progress_compteur) == int(wait_inference): stop_learning = True t2 = time.time() logger.info(" train_oracle | Condition ...Total=".format(t2-t1)) t += 1 start_epoch += 1 # Load early stopping t1 = time.time() if inference: # save_path = "out/oracle/46499510c2ab980278d91eeff89aa06f/{}" # # save_path = "out/oracle/9efb52e0bd872e1f4e64f66b35a2f092/{}" # question # save_path = "out/oracle/a9cc5b30b2024399c79b6997086c5265/{}" # question,category,spatial # save_path = "out/oracle/89570bad275ddde7b69a5c37659bd40e/{}" # question,category,spaticial,crop # save_path = "out/oracle/b158b76a46173ff33e4aec021e267e5a/{}" # question,category,spaticial,history # save_path = "out/oracle/30ef7335e38c93632b58e91fa732cf2d/{}" # question,category,spaticial,history,Images # save_path = "out/oracle/d9f1951536bbd147a3ea605bb3cbdde7/{}" # question,category,spaticial,history,Crop # question,category,spaticial,history,Crop # save_path = "out/oracle/4a9f62698e3304c4c2d733bff0b24ee2/{}" save_path = "out/oracle/a630385c990e5cc470c2488a244f18dc/{}" # out/oracle/ce02141129f6d87172cafc817c6d0b59/params.ckpt # save_path = save_path.format('params.ckpt') logger.info("***** save_path = ".format(save_path)) save_path = save_path.format('params.ckpt') saver.restore(sess, save_path) test_iterator = Iterator(testset, pool=cpu_pool, batch_size=batch_size*2, batchifier=batchifier, shuffle=True) logger.info("Output = {}".format(outputs[1])) logger.info("Best_param = {}".format(best_param)) test_loss, test_accuracy = evaluator.process(sess, test_iterator, outputs=outputs ,out_net=best_param,inference=inference,type_data="Test") t2 = time.time() logger.info(" train_oracle | Iterator testset ...Total=".format(t2-t1)) try: logger.info("Testing loss: {}".format(test_loss)) except Exception: logger.info("Erreur loss") try: logger.info("Testing error: {}".format(1-test_accuracy)) except Exception: logger.info("Erreur accuracy") t_end = time.time() logger.info("Time execution = {}".format(t_end - t_begin))
38.891304
371
0.638276
import argparse import logging import os from multiprocessing import Pool from distutils.util import strtobool import tensorflow as tf import numpy as np import json from pathlib import Path from generic.data_provider.iterator import Iterator from generic.tf_utils.evaluator import Evaluator from generic.tf_utils.optimizer import create_optimizer from generic.tf_utils.ckpt_loader import load_checkpoint, create_resnet_saver from generic.utils.config import load_config from generic.utils.file_handlers import pickle_dump from generic.data_provider.image_loader import get_img_builder from generic.data_provider.nlp_utils import Embeddings from generic.data_provider.nlp_utils import GloveEmbeddings from src.guesswhat.data_provider.guesswhat_dataset import OracleDataset from src.guesswhat.data_provider.oracle_batchifier import OracleBatchifier from src.guesswhat.data_provider.guesswhat_tokenizer import GWTokenizer from src.guesswhat.models.oracle.oracle_network import OracleNetwork import time if __name__ == '__main__': ############################# # LOAD CONFIG ############################# parser = argparse.ArgumentParser('Oracle network baseline!') parser.add_argument("-data_dir", type=str, help="Directory with data") parser.add_argument("-exp_dir", type=str, help="Directory in which experiments are stored") parser.add_argument("-config", type=str, help='Config file') parser.add_argument("-dict_file_question", type=str, default="dict.json", help="Dictionary file name")# default dict_pos_tag parser.add_argument("-dict_file_description", type=str, default="dict_Description.json", help="Dictionary file name") parser.add_argument("-all_dictfile", type=str, default="data/list_allquestion1.npy", help="Dictionary file name") parser.add_argument("-img_dir", type=str, help='Directory with images') parser.add_argument("-crop_dir", type=str, help='Directory with images') parser.add_argument("-load_checkpoint", type=str, help="Load model parameters from specified checkpoint") parser.add_argument("-continue_exp", type=lambda x: bool(strtobool(x)), default="False", help="Continue previously started experiment?") parser.add_argument("-gpu_ratio", type=float, default=0.50, help="How many GPU ram is required? (ratio)") parser.add_argument("-no_thread", type=int, default=4, help="No thread to load batch") parser.add_argument("-inference_mode", type=bool, default=False, help="inference mode True if you want to execute only test_dataset") args = parser.parse_args() config, exp_identifier, save_path = load_config(args.config, args.exp_dir) # logger.info("Save_path = ",save_path) # exit() logger = logging.getLogger() # Load config resnet_version = config['model']["image"].get('resnet_version', 50) finetune = config["model"]["image"].get('finetune', list()) batch_size = config['optimizer']['batch_size'] no_epoch = config["optimizer"]["no_epoch"] use_glove = config["model"]["glove"] # Inference True if want to test the dataset_test of the pre-trained Weigth inference = False wait_inference = 1 ############################# # LOAD DATA ############################# # Load image image_builder, crop_builder = None, None use_resnet = False logger.info("Loading ") t_begin = time.time() if config['inputs'].get('image', False): logger.info('Loading images..') image_builder = get_img_builder(config['model']['image'], args.img_dir) use_resnet = image_builder.is_raw_image() if config['inputs'].get('crop', False): logger.info('Loading crops..') crop_builder = get_img_builder(config['model']['crop'], args.crop_dir, is_crop=True) use_resnet = crop_builder.is_raw_image() # Load data logger.info('Loading data..') all_img_bbox = {} all_img_describtion = [] t1 = time.time() trainset = OracleDataset.load(args.data_dir, "train",image_builder = image_builder, crop_builder = crop_builder,all_img_bbox = all_img_bbox,all_img_describtion=all_img_describtion) validset = OracleDataset.load(args.data_dir, "valid", image_builder= image_builder, crop_builder = crop_builder,all_img_bbox = all_img_bbox,all_img_describtion=all_img_describtion) testset = OracleDataset.load(args.data_dir, "test",image_builder= image_builder, crop_builder = crop_builder,all_img_bbox = all_img_bbox,all_img_describtion=all_img_describtion) t2 = time.time() logger.info("Time to load data = {}".format(t2-t1)) # np.save("all_img_bbox.npy",all_img_bbox) # logger.info("Image_crop legnth= {}".format(len(all_img_describtion))) # logger.info("Image_crop = {}".format(all_img_describtion)) # with open('all_img_bbox.json', 'a') as file: # file.write(json.dumps(all_img_bbox,sort_keys=True, indent=4, separators=(',', ': '))) file_allquestion = Path("all_question_game.txt") # verify if file exist if not file_allquestion.is_file(): with open('all_question_game.txt', 'a') as file: for question in all_img_describtion: file.write(question+"\n") else: logger.info("all_question exist") # Load dictionary logger.info('Loading dictionary Question..') tokenizer = GWTokenizer(os.path.join(args.data_dir, args.dict_file_question),dic_all_question="data/dict_word_indice.pickle") # Load dictionary tokenizer_description = None if config["inputs"]["description"]: logger.info('Loading dictionary Description......') tokenizer_description = GWTokenizer(os.path.join(args.data_dir,args.dict_file_description),question=False) # Build Network logger.info('Building network..') if tokenizer_description != None: network = OracleNetwork(config, num_words_question=tokenizer.no_words,num_words_description=tokenizer_description.no_words) else: network = OracleNetwork(config, num_words_question=tokenizer.no_words,num_words_description=None) # Build Optimizer logger.info('Building optimizer..') optimizer, outputs = create_optimizer(network, config, finetune=finetune) best_param = network.get_predict() ############################## # START TRAINING ############################# logger.info("Start training .......") # create a saver to store/load checkpoint saver = tf.train.Saver() resnet_saver = None logger.info("saver done !") cpu_pool = Pool(args.no_thread, maxtasksperchild=5000) gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_ratio) logger.info("gpu_options done !") # Retrieve only resnet variabes if use_resnet: resnet_saver = create_resnet_saver([network]) # use_embedding = False # if config["embedding"] != "None": # use_embedding = True logger.info("resnet_saver done !") glove = None if use_glove: logger.info('Loading glove..') glove = GloveEmbeddings(os.path.join(args.data_dir, config["glove_name"]),glove_dim=300,type_data="common_crow") logger.info("glove done !") # embedding = None # if use_embedding: # logger.info('Loading embedding..') # embedding = Embeddings(args.all_dictfile,total_words=tokenizer.no_words,train=trainset,valid=validset,test=testset,dictionary_file_question=os.path.join(args.data_dir, args.dict_file_question),dictionary_file_description=os.path.join(args.data_dir, args.dict_file_description),description=config["inputs"]["description"],lemme=config["lemme"],pos=config["pos"]) # CPU/GPU option with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True)) as sess: sources = network.get_sources(sess) out_net = network.get_parameters()[-1] # logger.info("Sources: " + ', '.join(sources)) sess.run(tf.global_variables_initializer()) if use_resnet: resnet_saver.restore(sess, os.path.join(args.data_dir, 'resnet_v1_{}.ckpt'.format(resnet_version))) start_epoch = load_checkpoint(sess, saver, args, save_path) best_val_err = 0 # best_train_err = None # # create training tools evaluator = Evaluator(sources, network.scope_name,network=network,tokenizer=tokenizer) # train_evaluator = MultiGPUEvaluator(sources, scope_names, networks=networks, tokenizer=tokenizer) # train_evaluator = Evaluator(sources, scope_names[0], network=networks[0], tokenizer=tokenizer) # eval_evaluator = Evaluator(sources, scope_names[0], network=networks[0], tokenizer=tokenizer) batchifier = OracleBatchifier(tokenizer, sources, status=config['status'],glove=glove,tokenizer_description=tokenizer_description,args = args,config=config) stop_learning = False progress_compteur = 0 t = 0 if inference == False: while start_epoch < no_epoch and not stop_learning : # for t in range(start_epoch, no_epoch): logger.info('Epoch {}..'.format(t + 1)) # logger.info('Epoch {}..'.format(t + 1)) logger.info(" train_oracle | Iterator ...") t1 = time.time() train_iterator = Iterator(trainset, batch_size=batch_size, pool=cpu_pool, batchifier=batchifier, shuffle=True) t2 = time.time() logger.info(" train_oracle | Iterator...Total=".format(t2-t1)) t1 = time.time() train_loss, train_accuracy = evaluator.process(sess, train_iterator, outputs=outputs + [optimizer],out_net=best_param) t2 = time.time() logger.info(" train_oracle | evaluatorator...Total=".format(t2-t1)) t1 = time.time() valid_iterator = Iterator(validset, pool=cpu_pool, batch_size=batch_size*2, batchifier=batchifier, shuffle=False) t2 = time.time() logger.info(" train_oracle | Iterator validset...Total=".format(t2-t1)) t1 = time.time() # [network.get_emb_concat()] valid_loss, valid_accuracy = evaluator.process(sess, valid_iterator, outputs=outputs,type_data="Valid") t2 = time.time() logger.info(" train_oracle | evaluator ...Total=".format(t2-t1)) logger.info("Training loss: {}".format(train_loss)) logger.info("Training error: {}".format(1-train_accuracy)) logger.info("Validation loss: {}".format(valid_loss)) logger.info("Validation error: {}".format(1-valid_accuracy)) t1 = time.time() if valid_accuracy > best_val_err: best_train_err = train_accuracy best_val_err = valid_accuracy saver.save(sess, save_path.format('params.ckpt')) progress_compteur = 0 logger.info("Oracle checkpoint saved...") pickle_dump({'epoch': t}, save_path.format('status.pkl')) elif valid_accuracy < best_val_err: progress_compteur += 1 if int(progress_compteur) == int(wait_inference): stop_learning = True t2 = time.time() logger.info(" train_oracle | Condition ...Total=".format(t2-t1)) t += 1 start_epoch += 1 # Load early stopping t1 = time.time() if inference: # save_path = "out/oracle/46499510c2ab980278d91eeff89aa06f/{}" # # save_path = "out/oracle/9efb52e0bd872e1f4e64f66b35a2f092/{}" # question # save_path = "out/oracle/a9cc5b30b2024399c79b6997086c5265/{}" # question,category,spatial # save_path = "out/oracle/89570bad275ddde7b69a5c37659bd40e/{}" # question,category,spaticial,crop # save_path = "out/oracle/b158b76a46173ff33e4aec021e267e5a/{}" # question,category,spaticial,history # save_path = "out/oracle/30ef7335e38c93632b58e91fa732cf2d/{}" # question,category,spaticial,history,Images # save_path = "out/oracle/d9f1951536bbd147a3ea605bb3cbdde7/{}" # question,category,spaticial,history,Crop # question,category,spaticial,history,Crop # save_path = "out/oracle/4a9f62698e3304c4c2d733bff0b24ee2/{}" save_path = "out/oracle/a630385c990e5cc470c2488a244f18dc/{}" # out/oracle/ce02141129f6d87172cafc817c6d0b59/params.ckpt # save_path = save_path.format('params.ckpt') logger.info("***** save_path = ".format(save_path)) save_path = save_path.format('params.ckpt') saver.restore(sess, save_path) test_iterator = Iterator(testset, pool=cpu_pool, batch_size=batch_size*2, batchifier=batchifier, shuffle=True) logger.info("Output = {}".format(outputs[1])) logger.info("Best_param = {}".format(best_param)) test_loss, test_accuracy = evaluator.process(sess, test_iterator, outputs=outputs ,out_net=best_param,inference=inference,type_data="Test") t2 = time.time() logger.info(" train_oracle | Iterator testset ...Total=".format(t2-t1)) try: logger.info("Testing loss: {}".format(test_loss)) except Exception: logger.info("Erreur loss") try: logger.info("Testing error: {}".format(1-test_accuracy)) except Exception: logger.info("Erreur accuracy") t_end = time.time() logger.info("Time execution = {}".format(t_end - t_begin))
0
0
0
b17c0e29efe0a6120c90012157d73cbf64908685
8,202
py
Python
venv/lib/python2.7/site-packages/webassets/filter/compass.py
mutaihillary/mycalculator
55685dd7c968861f18ae0701129f5af2bc682d67
[ "MIT" ]
null
null
null
venv/lib/python2.7/site-packages/webassets/filter/compass.py
mutaihillary/mycalculator
55685dd7c968861f18ae0701129f5af2bc682d67
[ "MIT" ]
7
2021-02-08T20:22:15.000Z
2022-03-11T23:19:41.000Z
venv/lib/python2.7/site-packages/webassets/filter/compass.py
mutaihillary/mycalculator
55685dd7c968861f18ae0701129f5af2bc682d67
[ "MIT" ]
null
null
null
""" Generally speaking, compass provides a command line util that is used a) as a management script (like django-admin.py) doing for example setup work, adding plugins to a project etc), and b) can compile the sass source files into CSS. While generally project-based, starting with 0.10, compass supposedly supports compiling individual files, which is what we are using for implementing this filter. Supposedly, because there are numerous issues that require working around. See the comments in the actual filter code for the full story on all the hoops be have to jump through. An alternative option would be to use Sass to compile. Compass essentially adds two things on top of sass: A bunch of CSS frameworks, ported to Sass, and available for including. And various ruby helpers that these frameworks and custom Sass files can use. Apparently there is supposed to be a way to compile a compass project through sass, but so far, I haven't got it to work. The syntax is supposed to be one of: $ sass -r compass `compass imports` FILE $ sass --compass FILE See: http://groups.google.com/group/compass-users/browse_thread/thread/a476dfcd2b47653e http://groups.google.com/group/compass-users/browse_thread/thread/072bd8b51bec5f7c http://groups.google.com/group/compass-users/browse_thread/thread/daf55acda03656d1 """ import os, subprocess from os import path import tempfile import shutil from webassets.exceptions import FilterError from webassets.filter import Filter, option __all__ = ('CompassFilter',) class CompassFilter(Filter): """Converts `Compass <http://compass-style.org/>`_ .sass files to CSS. Requires at least version 0.10. To compile a standard Compass project, you only need to have to compile your main ``screen.sass``, ``print.sass`` and ``ie.sass`` files. All the partials that you include will be handled by Compass. If you want to combine the filter with other CSS filters, make sure this one runs first. Supported configuration options: COMPASS_BIN The path to the Compass binary. If not set, the filter will try to run ``compass`` as if it's in the system path. COMPASS_PLUGINS Compass plugins to use. This is equivalent to the ``--require`` command line option of the Compass. and expects a Python list object of Ruby libraries to load. """ name = 'compass' options = { 'compass': ('binary', 'COMPASS_BIN'), 'plugins': option('COMPASS_PLUGINS', type=list) } def open(self, out, source_path, **kw): """Compass currently doesn't take data from stdin, and doesn't allow us accessing the result from stdout either. Also, there's a bunch of other issues we need to work around: - compass doesn't support given an explict output file, only a "--css-dir" output directory. We have to "guess" the filename that will be created in that directory. - The output filename used is based on the input filename, and simply cutting of the length of the "sass_dir" (and changing the file extension). That is, compass expects the input filename to always be inside the "sass_dir" (which defaults to ./src), and if this is not the case, the output filename will be gibberish (missing characters in front). See: https://github.com/chriseppstein/compass/issues/304 We fix this by setting the proper --sass-dir option. - Compass insists on creating a .sass-cache folder in the current working directory, and unlike the sass executable, there doesn't seem to be a way to disable it. The workaround is to set the working directory to our temp directory, so that the cache folder will be deleted at the end. """ tempout = tempfile.mkdtemp() # Temporarily move to "tempout", so .sass-cache will be created there old_wd = os.getcwdu() os.chdir(tempout) try: # Make sure to use normpath() to not cause trouble with # compass' simplistic path handling, where it just assumes # source_path is within sassdir, and cuts off the length of # sassdir from the input file. sassdir = path.normpath(path.dirname(source_path)) source_path = path.normpath(source_path) # Compass offers some helpers like image-url(), which need # information about the urls under which media files will be # available. This is hard for two reasons: First, the options in # question aren't supported on the command line, so we need to write # a temporary config file. Secondly, the assume a defined and # separate directories for "images", "stylesheets" etc., something # webassets knows nothing of: we don't support the user defining # something such directories. Because we traditionally had this # filter point all type-specific directories to the root media # directory, we will define the paths to match this. In other # words, in Compass, both inline-image("img/test.png) and # image-url("img/test.png") will find the same file, and assume it # to be {env.directory}/img/test.png. # However, this partly negates the purpose of an utiility like # image-url() in the first place - you not having to hard code # the location of your images. So a possiblity for the future # might be adding options that allow changing this behavior (see # ticket #36). # # Note that is also the --relative-assets option, which we can't # use because it calculates an actual relative path between the # image and the css output file, the latter being in a temporary # directory in our case. config_file = path.join(tempout, '.config.rb') f = open(config_file, 'w') try: f.write(""" http_path = "%s" http_images_dir = "" http_stylesheets_dir = "" http_fonts_dir = "" http_javascripts_dir = "" """ % self.env.url) f.flush() finally: f.close() command = [self.compass or 'compass', 'compile'] for plugin in self.plugins or []: command.extend(('--require', plugin)) command.extend(['--sass-dir', sassdir, '--css-dir', tempout, '--image-dir', self.env.directory, '--config', config_file, '--quiet', '--boring', '--output-style', 'expanded', source_path]) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, # shell: necessary on windows to execute # ruby files, but doesn't work on linux. shell=(os.name == 'nt')) stdout, stderr = proc.communicate() # compass seems to always write a utf8 header? to stderr, so # make sure to not fail just because there's something there. if proc.returncode != 0: raise FilterError(('compass: subprocess had error: stderr=%s, '+ 'stdout=%s, returncode=%s') % ( stderr, stdout, proc.returncode)) guessed_outputfile = \ path.join(tempout, path.splitext(path.basename(source_path))[0]) f = open("%s.css" % guessed_outputfile) try: out.write(f.read()) finally: f.close() finally: # Restore previous working dir os.chdir(old_wd) # Clean up the temp dir shutil.rmtree(tempout)
42.942408
86
0.611558
""" Generally speaking, compass provides a command line util that is used a) as a management script (like django-admin.py) doing for example setup work, adding plugins to a project etc), and b) can compile the sass source files into CSS. While generally project-based, starting with 0.10, compass supposedly supports compiling individual files, which is what we are using for implementing this filter. Supposedly, because there are numerous issues that require working around. See the comments in the actual filter code for the full story on all the hoops be have to jump through. An alternative option would be to use Sass to compile. Compass essentially adds two things on top of sass: A bunch of CSS frameworks, ported to Sass, and available for including. And various ruby helpers that these frameworks and custom Sass files can use. Apparently there is supposed to be a way to compile a compass project through sass, but so far, I haven't got it to work. The syntax is supposed to be one of: $ sass -r compass `compass imports` FILE $ sass --compass FILE See: http://groups.google.com/group/compass-users/browse_thread/thread/a476dfcd2b47653e http://groups.google.com/group/compass-users/browse_thread/thread/072bd8b51bec5f7c http://groups.google.com/group/compass-users/browse_thread/thread/daf55acda03656d1 """ import os, subprocess from os import path import tempfile import shutil from webassets.exceptions import FilterError from webassets.filter import Filter, option __all__ = ('CompassFilter',) class CompassFilter(Filter): """Converts `Compass <http://compass-style.org/>`_ .sass files to CSS. Requires at least version 0.10. To compile a standard Compass project, you only need to have to compile your main ``screen.sass``, ``print.sass`` and ``ie.sass`` files. All the partials that you include will be handled by Compass. If you want to combine the filter with other CSS filters, make sure this one runs first. Supported configuration options: COMPASS_BIN The path to the Compass binary. If not set, the filter will try to run ``compass`` as if it's in the system path. COMPASS_PLUGINS Compass plugins to use. This is equivalent to the ``--require`` command line option of the Compass. and expects a Python list object of Ruby libraries to load. """ name = 'compass' options = { 'compass': ('binary', 'COMPASS_BIN'), 'plugins': option('COMPASS_PLUGINS', type=list) } def open(self, out, source_path, **kw): """Compass currently doesn't take data from stdin, and doesn't allow us accessing the result from stdout either. Also, there's a bunch of other issues we need to work around: - compass doesn't support given an explict output file, only a "--css-dir" output directory. We have to "guess" the filename that will be created in that directory. - The output filename used is based on the input filename, and simply cutting of the length of the "sass_dir" (and changing the file extension). That is, compass expects the input filename to always be inside the "sass_dir" (which defaults to ./src), and if this is not the case, the output filename will be gibberish (missing characters in front). See: https://github.com/chriseppstein/compass/issues/304 We fix this by setting the proper --sass-dir option. - Compass insists on creating a .sass-cache folder in the current working directory, and unlike the sass executable, there doesn't seem to be a way to disable it. The workaround is to set the working directory to our temp directory, so that the cache folder will be deleted at the end. """ tempout = tempfile.mkdtemp() # Temporarily move to "tempout", so .sass-cache will be created there old_wd = os.getcwdu() os.chdir(tempout) try: # Make sure to use normpath() to not cause trouble with # compass' simplistic path handling, where it just assumes # source_path is within sassdir, and cuts off the length of # sassdir from the input file. sassdir = path.normpath(path.dirname(source_path)) source_path = path.normpath(source_path) # Compass offers some helpers like image-url(), which need # information about the urls under which media files will be # available. This is hard for two reasons: First, the options in # question aren't supported on the command line, so we need to write # a temporary config file. Secondly, the assume a defined and # separate directories for "images", "stylesheets" etc., something # webassets knows nothing of: we don't support the user defining # something such directories. Because we traditionally had this # filter point all type-specific directories to the root media # directory, we will define the paths to match this. In other # words, in Compass, both inline-image("img/test.png) and # image-url("img/test.png") will find the same file, and assume it # to be {env.directory}/img/test.png. # However, this partly negates the purpose of an utiility like # image-url() in the first place - you not having to hard code # the location of your images. So a possiblity for the future # might be adding options that allow changing this behavior (see # ticket #36). # # Note that is also the --relative-assets option, which we can't # use because it calculates an actual relative path between the # image and the css output file, the latter being in a temporary # directory in our case. config_file = path.join(tempout, '.config.rb') f = open(config_file, 'w') try: f.write(""" http_path = "%s" http_images_dir = "" http_stylesheets_dir = "" http_fonts_dir = "" http_javascripts_dir = "" """ % self.env.url) f.flush() finally: f.close() command = [self.compass or 'compass', 'compile'] for plugin in self.plugins or []: command.extend(('--require', plugin)) command.extend(['--sass-dir', sassdir, '--css-dir', tempout, '--image-dir', self.env.directory, '--config', config_file, '--quiet', '--boring', '--output-style', 'expanded', source_path]) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, # shell: necessary on windows to execute # ruby files, but doesn't work on linux. shell=(os.name == 'nt')) stdout, stderr = proc.communicate() # compass seems to always write a utf8 header? to stderr, so # make sure to not fail just because there's something there. if proc.returncode != 0: raise FilterError(('compass: subprocess had error: stderr=%s, '+ 'stdout=%s, returncode=%s') % ( stderr, stdout, proc.returncode)) guessed_outputfile = \ path.join(tempout, path.splitext(path.basename(source_path))[0]) f = open("%s.css" % guessed_outputfile) try: out.write(f.read()) finally: f.close() finally: # Restore previous working dir os.chdir(old_wd) # Clean up the temp dir shutil.rmtree(tempout)
0
0
0
eb1606b89995448b7b26ebd06607561f33f3d993
789
py
Python
05_ventanas.py
dlunna/gob.selenium
9c663e78b880b3363731f6e6f5b6899a972ef7c0
[ "MIT" ]
null
null
null
05_ventanas.py
dlunna/gob.selenium
9c663e78b880b3363731f6e6f5b6899a972ef7c0
[ "MIT" ]
null
null
null
05_ventanas.py
dlunna/gob.selenium
9c663e78b880b3363731f6e6f5b6899a972ef7c0
[ "MIT" ]
null
null
null
import time import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys if __name__ == '__main__': unittest.main()
26.3
97
0.669202
import time import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys class usando_unittest(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path='/var/www/pyfy/gob.selenium/chromedriver') def test_cambiar_ventana(self): driver = self.driver driver.get("https://www.google.com") time.sleep(3) driver.execute_script("window.open('');") time.sleep(3) driver.switch_to.window(driver.window_handles[1]) driver.get("http://www.stackoverflow.com") time.sleep(3) driver.switch_to.window(driver.window_handles[0]) time.sleep(3) def tearDown(self): self.driver.close() if __name__ == '__main__': unittest.main()
511
20
104
adaef4a84bf0412b7f77103cd7fd303ee40f3c2f
7,367
py
Python
app/crud/job.py
meddler-io/secoflex
3a61b46ab03a25f6436d8e004a1d8ead46093272
[ "MIT" ]
null
null
null
app/crud/job.py
meddler-io/secoflex
3a61b46ab03a25f6436d8e004a1d8ead46093272
[ "MIT" ]
null
null
null
app/crud/job.py
meddler-io/secoflex
3a61b46ab03a25f6436d8e004a1d8ead46093272
[ "MIT" ]
null
null
null
from motor.frameworks.asyncio import pymongo_class_wrapper from app.api.api_v2.endpoints import job from typing import Any, List from app.models.tool.job import JobCompositeInResponse, JobInDb, JobInRequest, JobInResponse, JobProgressResponse, JobUpdateModel from app.models.mongo_id import ObjectIdInReq, ObjectIdInRes, BsonObjectId from app.models.tool.builds import BuildMessageSpec from app.models.tool.build.common import BaseBuildModel, BaseBuildModelInRequest, BaseBuildModelInResponse, BaseBuildWithToolModelInResponse, BuildType from app.models.tool.executor import BuildExecutorCompositeInResponse, BuildExecutorDeploymentStructure, BuildExecutorInDb, BuildExecutorInRequest, BuildExecutorInResponse, ExecutionStatus from ..db.mongodb import AsyncIOMotorClient from ..core.config import ( database_name, job_collection_name as coll_name, tools_collection_name, build_collection_name, build_executor_collection_name ) # JobInResponse # JobInResponse # JobInResponse
23.996743
188
0.467626
from motor.frameworks.asyncio import pymongo_class_wrapper from app.api.api_v2.endpoints import job from typing import Any, List from app.models.tool.job import JobCompositeInResponse, JobInDb, JobInRequest, JobInResponse, JobProgressResponse, JobUpdateModel from app.models.mongo_id import ObjectIdInReq, ObjectIdInRes, BsonObjectId from app.models.tool.builds import BuildMessageSpec from app.models.tool.build.common import BaseBuildModel, BaseBuildModelInRequest, BaseBuildModelInResponse, BaseBuildWithToolModelInResponse, BuildType from app.models.tool.executor import BuildExecutorCompositeInResponse, BuildExecutorDeploymentStructure, BuildExecutorInDb, BuildExecutorInRequest, BuildExecutorInResponse, ExecutionStatus from ..db.mongodb import AsyncIOMotorClient from ..core.config import ( database_name, job_collection_name as coll_name, tools_collection_name, build_collection_name, build_executor_collection_name ) async def create_job(client: AsyncIOMotorClient, job: JobInRequest) -> JobInResponse: collection = client[database_name][coll_name] data = job.dict() data = JobInDb(**data).dict() result = await collection.insert_one(data) result = await collection.find_one({"_id": result.inserted_id}) result = JobInResponse(**result) return result async def update_job(client: AsyncIOMotorClient, job_id: str, job: JobUpdateModel, exec_status: ExecutionStatus) -> JobInResponse: collection = client[database_name][coll_name] job_id = BsonObjectId(job_id) job.exec_status = exec_status result = await collection.update_one({"_id": job_id}, {"$set": job.dict()}) result = await collection.find_one({"_id": job_id}) result = JobInResponse(**result) return result # JobInResponse async def get_job_by_id(client: AsyncIOMotorClient, job_id: str) -> JobCompositeInResponse: collection = client[database_name][coll_name] rows = collection.aggregate( [ { "$match": { "_id": BsonObjectId(job_id) } }, { "$lookup": { "from": build_executor_collection_name, "localField": "refrence_id", "foreignField": "_id", "as": "tool" } }, { "$set": { "tool": {"$arrayElemAt": ["$tool", 0]} } }, { "$set": { "tool": "$tool.refrence_id", } }, # { "$lookup": { "from": build_collection_name, "localField": "tool", "foreignField": "_id", "as": "tool" } }, { "$set": { "tool": {"$arrayElemAt": ["$tool", 0]} } }, { "$lookup": { "from": tools_collection_name, "localField": "tool.refrence_id", "foreignField": "_id", "as": "tool" } }, { "$set": { "tool": {"$arrayElemAt": ["$tool", 0]} } }, {"$limit": 1} ]) async for row in rows: row = JobCompositeInResponse(**row) # row = str(row) # row["_id"] = str(row["_id"]) # row["refrence_id"] = str(row["refrence_id"]) return row raise Exception("Not found") # JobInResponse async def get_jobs(client: AsyncIOMotorClient, id: str) -> List[JobCompositeInResponse]: collection = client[database_name][build_collection_name] result: List[Any] = [] rows = collection.aggregate([ { "$match": { "refrence_id": BsonObjectId(id) } }, { "$lookup": { "from": build_executor_collection_name, "localField": "_id", "foreignField": "refrence_id", "as": "executors" } }, { "$unwind": "$executors" }, { "$project": { "_id": "$executors._id", "tool_ref_id": "$refrence_id", } }, { "$lookup": { "from": coll_name, "localField": "_id", "foreignField": "refrence_id", "as": "job" } }, { "$unwind": "$job" }, # { "$lookup": { "from": tools_collection_name, "localField": "tool_ref_id", "foreignField": "_id", "as": "tool" } }, { "$set": { "tool": {"$arrayElemAt": ["$tool", 0]} } }, # { "$set": { "job.tool": "$tool" } }, { "$replaceRoot": { "newRoot": "$job" } }, {"$sort": {"_id": -1}}, ]) async for row in rows: row = JobCompositeInResponse(**row) result.append(row) return result # JobInResponse async def get_al_jobs(client: AsyncIOMotorClient) -> List[JobCompositeInResponse]: collection = client[database_name][build_collection_name] result: List[Any] = [] rows = collection.aggregate([ { "$lookup": { "from": build_executor_collection_name, "localField": "_id", "foreignField": "refrence_id", "as": "executors" } }, { "$unwind": "$executors" }, { "$project": { "_id": "$executors._id", "tool_ref_id": "$refrence_id", } }, { "$lookup": { "from": coll_name, "localField": "_id", "foreignField": "refrence_id", "as": "job" } }, { "$unwind": "$job" }, # { "$lookup": { "from": tools_collection_name, "localField": "tool_ref_id", "foreignField": "_id", "as": "tool" } }, { "$set": { "tool": {"$arrayElemAt": ["$tool", 0]} } }, # { "$set": { "job.tool": "$tool" } }, { "$replaceRoot": { "newRoot": "$job" } }, {"$sort": {"_id": -1}} ]) async for row in rows: row = JobCompositeInResponse(**row) result.append(row) return result async def get_job_status(client: AsyncIOMotorClient, job_id: str) -> JobProgressResponse: job_id = BsonObjectId(job_id) collection = client[database_name][coll_name] result = await collection.find_one({"_id": job_id}) return JobProgressResponse(**result)
6,221
0
135
cb99d70f985f446d177e9d7d3af216fc3f222dc4
942
py
Python
article/migrations/0003_comments.py
hexa-yagnenok/myblog
ebba71516ce2ebb6b05fcb8c889a54924b9284c9
[ "MIT" ]
null
null
null
article/migrations/0003_comments.py
hexa-yagnenok/myblog
ebba71516ce2ebb6b05fcb8c889a54924b9284c9
[ "MIT" ]
null
null
null
article/migrations/0003_comments.py
hexa-yagnenok/myblog
ebba71516ce2ebb6b05fcb8c889a54924b9284c9
[ "MIT" ]
null
null
null
# Generated by Django 3.1.5 on 2021-02-08 11:06 from django.db import migrations, models import django.db.models.deletion
37.68
163
0.638004
# Generated by Django 3.1.5 on 2021-02-08 11:06 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('article', '0002_auto_20210207_1514'), ] operations = [ migrations.CreateModel( name='Comments', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('comment_author', models.CharField(max_length=50, verbose_name='Name')), ('comment_content', models.CharField(max_length=200, verbose_name='Comment')), ('comment_date', models.DateTimeField(auto_now_add=True, verbose_name='Created Date')), ('article', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='article.article', verbose_name='Article')), ], ), ]
0
795
23
74445ecadd16262701e1fb5d7152036f5118ee58
347
py
Python
src/scenarios/shared/postcommands.py
BruceForstall/performance
47524b9060aa7cb13205fa281a6be6e2d404995c
[ "MIT" ]
547
2018-11-06T21:14:57.000Z
2022-03-31T21:14:57.000Z
src/scenarios/shared/postcommands.py
BruceForstall/performance
47524b9060aa7cb13205fa281a6be6e2d404995c
[ "MIT" ]
1,572
2018-11-06T21:30:31.000Z
2022-03-31T23:31:25.000Z
src/scenarios/shared/postcommands.py
BruceForstall/performance
47524b9060aa7cb13205fa281a6be6e2d404995c
[ "MIT" ]
196
2018-11-06T20:58:21.000Z
2022-03-29T21:04:21.000Z
from shared.const import APPDIR, TMPDIR, TRACEDIR, PUBDIR, BINDIR, CROSSGENDIR from performance.common import remove_directory
43.375
80
0.731988
from shared.const import APPDIR, TMPDIR, TRACEDIR, PUBDIR, BINDIR, CROSSGENDIR from performance.common import remove_directory def clean_directories(): to_remove = (APPDIR, TMPDIR, TRACEDIR, PUBDIR, BINDIR, CROSSGENDIR, "emsdk") print(f"Removing {','.join(to_remove)} if exist ...") for dir in to_remove: remove_directory(dir)
198
0
23
ebadf0352571b46b1488b0e97b824910cb2a4fe5
3,718
py
Python
tests/chainer_tests/optimizer_hooks_tests/test_gradient_lars.py
dl4fugaku/chainer
34655eff5986522eae56f47fc82a8cc2b78e1617
[ "MIT" ]
2
2019-08-12T21:48:04.000Z
2020-08-27T18:04:20.000Z
tests/chainer_tests/optimizer_hooks_tests/test_gradient_lars.py
dl4fugaku/chainer
34655eff5986522eae56f47fc82a8cc2b78e1617
[ "MIT" ]
null
null
null
tests/chainer_tests/optimizer_hooks_tests/test_gradient_lars.py
dl4fugaku/chainer
34655eff5986522eae56f47fc82a8cc2b78e1617
[ "MIT" ]
null
null
null
import unittest import numpy as np import chainer from chainer import optimizer_hooks from chainer import optimizers from chainer import testing _backend_params = [ # NumPy {}, {'use_ideep': 'always'}, # CuPy {'use_cuda': True, 'cuda_device': 0}, {'use_cuda': True, 'cuda_device': 1}, # ChainerX {'use_chainerx': True, 'chainerx_device': 'native:0'}, {'use_chainerx': True, 'chainerx_device': 'cuda:0'}, {'use_chainerx': True, 'chainerx_device': 'cuda:1'}, ] @testing.backend.inject_backend_tests(None, _backend_params) @testing.backend.inject_backend_tests(None, _backend_params) @testing.backend.inject_backend_tests(None, _backend_params) testing.run_module(__name__, __file__)
33.495495
76
0.581495
import unittest import numpy as np import chainer from chainer import optimizer_hooks from chainer import optimizers from chainer import testing _backend_params = [ # NumPy {}, {'use_ideep': 'always'}, # CuPy {'use_cuda': True, 'cuda_device': 0}, {'use_cuda': True, 'cuda_device': 1}, # ChainerX {'use_chainerx': True, 'chainerx_device': 'native:0'}, {'use_chainerx': True, 'chainerx_device': 'cuda:0'}, {'use_chainerx': True, 'chainerx_device': 'cuda:1'}, ] class SimpleLink(chainer.Link): def __init__(self, params): super(SimpleLink, self).__init__() with self.init_scope(): for i, p in enumerate(params): setattr(self, 'p{}'.format(i), p) @testing.backend.inject_backend_tests(None, _backend_params) @testing.backend.inject_backend_tests(None, _backend_params) @testing.backend.inject_backend_tests(None, _backend_params) class TestGradientLARS(unittest.TestCase): def setUp(self): num_params = 3 arrs = [ np.random.uniform(-3, 3, (2, 3)).astype(np.float32) for _ in range(num_params)] grads = [ np.random.uniform(-3, 3, (2, 3)).astype(np.float32) for _ in range(num_params)] params_0 = [] for arr, grad in zip(arrs, grads): param = chainer.Parameter(arr) param.grad = grad params_0.append(param) arrs = [ np.random.uniform(-3, 3, (2, 3)).astype(np.float32) * 0.0001 for _ in range(num_params)] grads = [ np.random.uniform(-3, 3, (2, 3)).astype(np.float32) for _ in range(num_params)] params_1 = [] for arr, grad in zip(arrs, grads): param = chainer.Parameter(arr) param.grad = grad params_1.append(param) self.target = chainer.ChainList( SimpleLink(params_0), SimpleLink(params_1)) def check_LARS(self, backend_configs): target = self.target devices = [bc.device for bc in backend_configs] assert len(backend_configs) == len(list(target[0].params())) assert len(backend_configs) == len(list(target[1].params())) threshold = 1e-2 weight_decay = 0.2 eps = 1e-9 expects0 = [] expects1 = [] # Compute expected for param, device in zip(target[0].params(), devices): p0_norm = np.linalg.norm(param.array) g0_norm = np.linalg.norm(param.grad) clip_rate = p0_norm / (eps + g0_norm + weight_decay * p0_norm) expects0.append(param.array - clip_rate * (param.grad + weight_decay * param.array)) param.to_device(device) for param, device in zip(target[1].params(), devices): expects1.append(param.array - 1.0 * (param.grad + weight_decay * param.array)) opt = optimizers.SGD(lr=1) opt.setup(self.target) opt.add_hook(optimizer_hooks.GradientLARS(threshold=threshold, weight_decay=weight_decay, eps=eps)) opt.update() for expect, param in zip(expects0, target[0].params()): testing.assert_allclose(expect, param.array) for expect, param in zip(expects1, target[1].params()): testing.assert_allclose(expect, param.array) def test_LARS(self, backend_config0, backend_config1, backend_config2): self.check_LARS( [backend_config0, backend_config1, backend_config2]) testing.run_module(__name__, __file__)
2,804
31
153
1a152613f1c9b3bff272bfa88b986f63186e0426
680
py
Python
backend/src/restaurants/api/urls.py
devmaturi/restaurant_finder
31b737e705806080375d8ae7746ee294ecf7da26
[ "MIT" ]
null
null
null
backend/src/restaurants/api/urls.py
devmaturi/restaurant_finder
31b737e705806080375d8ae7746ee294ecf7da26
[ "MIT" ]
null
null
null
backend/src/restaurants/api/urls.py
devmaturi/restaurant_finder
31b737e705806080375d8ae7746ee294ecf7da26
[ "MIT" ]
null
null
null
from restaurants.api.views import RestaurantViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', RestaurantViewSet, basename='restaurants') urlpatterns = router.urls # from django.urls import path # from .views import ( RestaurantListView, RestaurantDetailView, # RestaurantCreateView, RestaurantUpdateView, RestaurantDeleteView ) # urlpatterns = [ # path('', RestaurantListView.as_view()), # path('create/', RestaurantCreateView.as_view()), # path('<pk>', RestaurantDetailView.as_view()), # path('<pk>/update/', RestaurantUpdateView.as_view()), # path('<pk>/delete/', RestaurantDeleteView.as_view()), # ]
35.789474
68
0.744118
from restaurants.api.views import RestaurantViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', RestaurantViewSet, basename='restaurants') urlpatterns = router.urls # from django.urls import path # from .views import ( RestaurantListView, RestaurantDetailView, # RestaurantCreateView, RestaurantUpdateView, RestaurantDeleteView ) # urlpatterns = [ # path('', RestaurantListView.as_view()), # path('create/', RestaurantCreateView.as_view()), # path('<pk>', RestaurantDetailView.as_view()), # path('<pk>/update/', RestaurantUpdateView.as_view()), # path('<pk>/delete/', RestaurantDeleteView.as_view()), # ]
0
0
0
d871051ace426998e7242e30f556f967efa26c23
1,090
py
Python
Sockets/SocketServ/SocketServ.py
evoicefire/playground
86d8fad5917757c356b8f54e57cdb315c5a1036d
[ "MIT" ]
null
null
null
Sockets/SocketServ/SocketServ.py
evoicefire/playground
86d8fad5917757c356b8f54e57cdb315c5a1036d
[ "MIT" ]
null
null
null
Sockets/SocketServ/SocketServ.py
evoicefire/playground
86d8fad5917757c356b8f54e57cdb315c5a1036d
[ "MIT" ]
null
null
null
import socket import sys __author__ = 'Gus' HOST = '' PORT = 8889 p = 0 e = 0 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('--Socket created--') try: s.bind((HOST, PORT)) except socket.error as msg: print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) sys.exit() print('Bound') s.listen(10) print('Listening') conn, addr = s.accept() print('Connection get {}'.format(addr)) while 1: if p > 0: conn, addr = s.accept() if e == 0: print('Connection get {}'.format(addr)) try: string = conn.recv(1024).decode("UTF-8") e += 1 print(string) except: try: try: while 1: string = conn.recv(4096).decode() print(string) except: print('And unknown error occurred, lost client?') pass except ConnectionResetError: print('Connection Reset') e = 0 p = 0 string = '' pass conn.close() p += 1
20.961538
76
0.501835
import socket import sys __author__ = 'Gus' HOST = '' PORT = 8889 p = 0 e = 0 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('--Socket created--') try: s.bind((HOST, PORT)) except socket.error as msg: print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) sys.exit() print('Bound') s.listen(10) print('Listening') conn, addr = s.accept() print('Connection get {}'.format(addr)) while 1: if p > 0: conn, addr = s.accept() if e == 0: print('Connection get {}'.format(addr)) try: string = conn.recv(1024).decode("UTF-8") e += 1 print(string) except: try: try: while 1: string = conn.recv(4096).decode() print(string) except: print('And unknown error occurred, lost client?') pass except ConnectionResetError: print('Connection Reset') e = 0 p = 0 string = '' pass conn.close() p += 1
0
0
0
86e7fa8f0d86380c6acc4c845c674a920302a313
5,417
py
Python
kashgari/processors/base_processor.py
SunYanCN/Kashgari
f0892db08b2144fe93bb4de3914cd771e9a98d8e
[ "Apache-2.0" ]
1
2020-04-15T11:41:29.000Z
2020-04-15T11:41:29.000Z
kashgari/processors/base_processor.py
Amaz0ser/Kashgari
9d72b7bc180336d3cfba94068e22af3dd56b8264
[ "Apache-2.0" ]
null
null
null
kashgari/processors/base_processor.py
Amaz0ser/Kashgari
9d72b7bc180336d3cfba94068e22af3dd56b8264
[ "Apache-2.0" ]
null
null
null
# encoding: utf-8 # author: BrikerMan # contact: eliyar917@gmail.com # blog: https://eliyar.biz # file: base_processor.py # time: 2019-05-21 11:27 import collections import logging import operator from typing import List, Optional, Union, Dict, Any import numpy as np from tensorflow.python.keras.preprocessing.sequence import pad_sequences from kashgari import utils class BaseProcessor(object): """ Corpus Pre Processor class """ def _build_token_dict(self, corpus: List[List[str]], min_count: int = 3): """ Build token index dictionary using corpus Args: corpus: List of tokenized sentences, like ``[['I', 'love', 'tf'], ...]`` min_count: """ token2idx = { self.token_pad: 0, self.token_unk: 1, self.token_bos: 2, self.token_eos: 3 } token2count = {} for sentence in corpus: for token in sentence: count = token2count.get(token, 0) token2count[token] = count + 1 self.token2count = token2count # 按照词频降序排序 sorted_token2count = sorted(token2count.items(), key=operator.itemgetter(1), reverse=True) token2count = collections.OrderedDict(sorted_token2count) for token, token_count in token2count.items(): if token not in token2idx and token_count >= min_count: token2idx[token] = len(token2idx) self.token2idx = token2idx self.idx2token = dict([(value, key) for key, value in self.token2idx.items()]) logging.debug(f"build token2idx dict finished, contains {len(self.token2idx)} tokens.") self.dataset_info['token_count'] = len(self.token2idx) if __name__ == "__main__": print("Hello world")
34.28481
95
0.572642
# encoding: utf-8 # author: BrikerMan # contact: eliyar917@gmail.com # blog: https://eliyar.biz # file: base_processor.py # time: 2019-05-21 11:27 import collections import logging import operator from typing import List, Optional, Union, Dict, Any import numpy as np from tensorflow.python.keras.preprocessing.sequence import pad_sequences from kashgari import utils class BaseProcessor(object): """ Corpus Pre Processor class """ def __init__(self, **kwargs): self.token2idx: Dict[str, int] = kwargs.get('token2idx', {}) self.idx2token: Dict[int, str] = dict([(v, k) for (k, v) in self.token2idx.items()]) self.token2count: Dict = {} self.label2idx: Dict[str, int] = kwargs.get('label2idx', {}) self.idx2label: Dict[int, str] = dict([(v, k) for (k, v) in self.label2idx.items()]) self.token_pad: str = kwargs.get('token_pad', '<PAD>') self.token_unk: str = kwargs.get('token_unk', '<UNK>') self.token_bos: str = kwargs.get('token_bos', '<BOS>') self.token_eos: str = kwargs.get('token_eos', '<EOS>') self.dataset_info: Dict[str, Any] = kwargs.get('dataset_info', {}) self.add_bos_eos: bool = kwargs.get('add_bos_eos', False) self.sequence_length = kwargs.get('sequence_length', None) self.min_count = kwargs.get('min_count', 3) def info(self): return { 'class_name': self.__class__.__name__, 'config': { 'label2idx': self.label2idx, 'token2idx': self.token2idx, 'token_pad': self.token_pad, 'token_unk': self.token_unk, 'token_bos': self.token_bos, 'token_eos': self.token_eos, 'dataset_info': self.dataset_info, 'add_bos_eos': self.add_bos_eos, 'sequence_length': self.sequence_length }, 'module': self.__class__.__module__, } def analyze_corpus(self, corpus: Union[List[List[str]]], labels: Union[List[List[str]], List[str]], force: bool = False): rec_len = sorted([len(seq) for seq in corpus])[int(0.95 * len(corpus))] self.dataset_info['RECOMMEND_LEN'] = rec_len if len(self.token2idx) == 0 or force: self._build_token_dict(corpus, self.min_count) if len(self.label2idx) == 0 or force: self._build_label_dict(labels) def _build_token_dict(self, corpus: List[List[str]], min_count: int = 3): """ Build token index dictionary using corpus Args: corpus: List of tokenized sentences, like ``[['I', 'love', 'tf'], ...]`` min_count: """ token2idx = { self.token_pad: 0, self.token_unk: 1, self.token_bos: 2, self.token_eos: 3 } token2count = {} for sentence in corpus: for token in sentence: count = token2count.get(token, 0) token2count[token] = count + 1 self.token2count = token2count # 按照词频降序排序 sorted_token2count = sorted(token2count.items(), key=operator.itemgetter(1), reverse=True) token2count = collections.OrderedDict(sorted_token2count) for token, token_count in token2count.items(): if token not in token2idx and token_count >= min_count: token2idx[token] = len(token2idx) self.token2idx = token2idx self.idx2token = dict([(value, key) for key, value in self.token2idx.items()]) logging.debug(f"build token2idx dict finished, contains {len(self.token2idx)} tokens.") self.dataset_info['token_count'] = len(self.token2idx) def _build_label_dict(self, corpus: Union[List[List[str]], List[str]]): raise NotImplementedError def process_x_dataset(self, data: List[List[str]], max_len: Optional[int] = None, subset: Optional[List[int]] = None) -> np.ndarray: if max_len is None: max_len = self.sequence_length if subset is not None: target = utils.get_list_subset(data, subset) else: target = data numerized_samples = self.numerize_token_sequences(target) return pad_sequences(numerized_samples, max_len, padding='post', truncating='post') def process_y_dataset(self, data: Union[List[List[str]], List[str]], max_len: Optional[int], subset: Optional[List[int]] = None) -> np.ndarray: raise NotImplementedError def numerize_token_sequences(self, sequences: List[List[str]]): raise NotImplementedError def numerize_label_sequences(self, sequences: List[List[str]]) -> List[List[int]]: raise NotImplementedError def reverse_numerize_label_sequences(self, sequence, **kwargs): raise NotImplementedError def __repr__(self): return f"<{self.__class__}>" def __str__(self): return self.__repr__() if __name__ == "__main__": print("Hello world")
3,211
0
297