content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
# Criar um dicionário com todos os mapeamentos conexoes = {} conexoes ["Casa"] = ["Amador Bueno"] conexoes ["Amador Bueno"] = ["Osasco"] conexoes ["Osasco"] = ["Júlio Prestes", "Pinheiros", "Amador Bueno"] conexoes ["Júlio Prestes"] = ["Barra Funda"] conexoes ["Barra Funda"] = ["Faculdade Impacta"] conexoes ["Pinheiros"] = ["Morumbi", "Consolação", "Santo Amaro"] conexoes ["Santo Amaro"] = [ "Santa Cruz"] conexoes ["Consolação"] = ["Anhangabaú"] conexoes ["Anhangabaú"] = ["Barra Funda"] conexoes ["Morumbi"] = ["Santo Amaro"] conexoes ["Sé"] = ["Barra Funda"] conexoes ["Faculdade Impacta"] = ["Barra Funda"] conexoes ["Santa Cruz"] = ["Sé"] # localização de todos os lugares localizacao = {} localizacao ["Casa"] = [3,8] localizacao ["Amador Bueno"] = [3,7] localizacao ["Osasco"] = [3,6] localizacao ["Pinheiros"]= [3,5] localizacao ["Morumbi"] = [2,4] localizacao ["Santo Amaro"] = [3,4] localizacao ["Consolação"] = [4,4] localizacao ["Santa Cruz"] = [3,3] localizacao ["Sé"] = [2,3] localizacao ["Anhangabaú"] = [4,3] localizacao ["Júlio Prestes"] = [4,2] localizacao ["Barra Funda"] = [1,7] localizacao ["Faculdade Impacta"] = [8,0]
[ 2, 327, 380, 283, 23781, 288, 47430, 6557, 27250, 401, 284, 37427, 28686, 285, 1758, 3263, 418, 198, 49180, 87, 3028, 796, 23884, 198, 49180, 87, 3028, 14631, 34, 15462, 8973, 796, 14631, 5840, 7079, 9842, 23397, 8973, 198, 49180, 87, ...
2.331976
491
from typing import Any, Dict from lithopscloud.modules.gen2.profile import ProfileConfig
[ 6738, 19720, 1330, 4377, 11, 360, 713, 198, 198, 6738, 24491, 2840, 17721, 13, 18170, 13, 5235, 17, 13, 13317, 1330, 13118, 16934, 628 ]
3.791667
24
import numpy as np import pandas as pd from pandas.core.frame import DataFrame from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation as LDA import pickle import spacy from spacy.tokens import Token import nltk from nltk.corpus import wordnet as wn def load_training_data(direc: str = '/data/nyt-articles-2020.csv', size: int = 50) -> DataFrame: """ opens csv file to train with, retrieve from: https://www.kaggle.com/benjaminawd/new-york-times-articles-comments-2020?select=nyt-articles-2020.csv takes size articles """ data = pd.read_csv(direc).head(size) data.dropna() print(data.head()) return data def tokenize(text: str) -> list[Token]: """ tokenizes the text to be easily vectorized/lemma/stopped/stemmed later """ tokenizer = spacy.lang.en.English() res = [] for token in tokenizer(text): if token.orth_.isspace(): continue elif token.like_url: res.append('URL') elif token.orth_.startswith('@'): res.append('SCREEN_NAME') else: res.append(token.lower_) return res def get_lemma(word: str) -> str: """ returns the lemma of a word (simplifies word as possible)""" lemma = wn.morphy(word) def train_LDA_model(data: DataFrame, direc: str) -> None: """ Use data from model training, save model to direc remove stop words, max_df set to exclude words that appear in 80% of articles. May have to change this as COVID may appear in >80% of articles. Should be safe to increase to 90%. min_df can be increased to exclude unneaded topics """ vect_to_word = CountVectorizer(max_df=.8, min_df=2, stop_words='english') vectorized_data = vect_to_word.fit_transform(data['Text'].values.astype('U')) lda = LDA(n_components=5) lda.fit(vectorized_data) for i in range(10): cur_topic = lda.components_[i] top_words = list(map(vect_to_word.get_feature_names().get,cur_topic.argsort()[-10:])) print(f'Topic #{i+1} words: {top_words}, Size={len(cur_topic)}') with open(direc, 'wb') as f: pickle.dump([lda, vectorized_data, vect_to_word])
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 19798, 292, 13, 7295, 13, 14535, 1330, 6060, 19778, 198, 6738, 1341, 35720, 13, 30053, 62, 2302, 7861, 13, 5239, 1330, 2764, 38469, 7509, 198, 6738, 1341, ...
2.446855
922
from . import pipeline from . import config
[ 6738, 764, 1330, 11523, 198, 6738, 764, 1330, 4566 ]
4.777778
9
# inspired by https://github.com/sandy1709/catuserbot/blob/master/userbot/plugins/__init__.py import os import re import time import math import heroku3 import requests from heroku_config import Var from userbot import telever from userbot.uniborgConfig import Config from telethon import events from datetime import datetime Heroku = heroku3.from_key(Var.HEROKU_API_KEY) heroku_api = "https://api.heroku.com" HEROKU_APP_NAME = Var.HEROKU_APP_NAME HEROKU_API_KEY = Var.HEROKU_API_KEY # inspired by https://github.com/sandy1709/catuserbot/blob/master/userbot/plugins/__init__.py # @sn12384
[ 2, 7867, 416, 3740, 1378, 12567, 13, 785, 14, 82, 10757, 1558, 2931, 14, 9246, 7220, 13645, 14, 2436, 672, 14, 9866, 14, 7220, 13645, 14, 37390, 14, 834, 15003, 834, 13, 9078, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 640...
2.805687
211
############################################################################## # Institute for the Design of Advanced Energy Systems Process Systems # Engineering Framework (IDAES PSE Framework) Copyright (c) 2018-2020, by the # software owners: The Regents of the University of California, through # Lawrence Berkeley National Laboratory, National Technology & Engineering # Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia # University Research Corporation, et al. All rights reserved. # # Please see the files COPYRIGHT.txt and LICENSE.txt for full copyright and # license information, respectively. Both files are also available online # at the URL "https://github.com/IDAES/idaes-pse". ############################################################################## """Get info about the environment IDAES is running in and the IDAES version """ __author__ = "John Eslick" import click from idaes.commands import cb @cb.command( name="environment-info", help="Print information about idaes, OS, dependencies...") @click.option( "--solver", multiple=True, help="Add solvers to list of solvers to check" ) @click.option( "--json", default=None, help="Write output ot a file" )
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 5136, 329, 262, 8495, 286, 13435, 6682, 11998, 10854, 11998, 198, 2, 14044, 25161, 357, 41957, 1546, 350, 5188, 25161, 8, 15069, 357, 66, 8, 2864, 12, 42334, 11, 416, 262, 198, 2, 3788, 4393, ...
3.908228
316
import os import argparse import json import glob import sys import shutil from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument( "-t", "--target-folder", required=True, help="Where to save the folder structure." ) parser.add_argument("-i", "--input", required=True, help="Input json structure.") parser.add_argument( "-nr", "--n-reference-images", required=True, help="Number of reference images to show.", ) args = parser.parse_args() if ( os.path.exists(args.target_folder) and len(list(glob.glob(os.path.join(args.target_folder, "*")))) > 0 ): print("Error: Target folder exists and is not empty.") sys.exit(-1) with open(args.input, "r") as f: data = json.load(f) experiment_name = os.path.basename(args.target_folder) tasks = data["tasks"] for task in tqdm(tasks, position=0): task_folder = os.path.join(args.target_folder, f"task_{task['index']}") os.makedirs(task_folder, exist_ok=True) # copy stimuli trials_folder = os.path.join(task_folder, "trials") os.makedirs(trials_folder, exist_ok=True) for i, trial in enumerate(tqdm(task["trials"], position=1, leave=False)): source_references_path = trial["references"] source_queries_path = trial["queries"] # create folders trial_folder = os.path.join(trials_folder, f"trial_{i + 1}") target_references_path = os.path.join(trial_folder, "references") target_queries_path = os.path.join(trial_folder, "queries") os.makedirs(trial_folder, exist_ok=True) os.makedirs(target_references_path, exist_ok=True) os.makedirs(target_queries_path, exist_ok=True) if trial["mode"] == "catch_trial": # copy queries shutil.copy( os.path.join(source_queries_path, "min_1.png"), os.path.join(target_queries_path, "min.png"), ) shutil.copy( os.path.join(source_queries_path, "max_8.png"), os.path.join(target_queries_path, "max.png"), ) else: # copy queries shutil.copy( os.path.join(source_queries_path, "min_0.png"), os.path.join(target_queries_path, "min.png"), ) shutil.copy( os.path.join(source_queries_path, "max_9.png"), os.path.join(target_queries_path, "max.png"), ) # copy references for source_reference in glob.glob( os.path.join(source_references_path, "*.png") ): target_reference = os.path.join( target_references_path, os.path.basename(source_reference) ) shutil.copy(source_reference, target_reference) # create index index = dict( task_name=f"{experiment_name}/task_{task['index']}", n_reference_images=args.n_reference_images, n_trials=len(task["trials"]), catch_trial_idxs=[ idx + 1 for idx in range(len(task["trials"])) if task["trials"][idx]["mode"] == "catch_trial" ], ) with open(os.path.join(task_folder, "index.json"), "w") as f: json.dump(index, f)
[ 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 15095, 198, 11748, 25064, 198, 11748, 4423, 346, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 628, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 3419, 198, ...
2.137294
1,515
# -*- coding: utf-8 -*- import skimage.io as skio import skimage.util as sku from tqdm import tqdm from glob import glob import os import SimpleITK as sitk import numpy as np # %% Helper functions # %% # %% if __name__ == '__main__': make_RIRE_forFID()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 11748, 1341, 9060, 13, 952, 355, 1341, 952, 201, 198, 11748, 1341, 9060, 13, 22602, 355, 1341, 84, 201, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 201, 198,...
2.316667
120
# Licensed under a 3-clause BSD style license - see LICENSE.txt """ SPIRE-specific code for HiRes. Copyright (c) 2012-2013, California Institute of Technology Developer: David Shupe """ import hires as hires try: import astropy.io.fits as pyfits except ImportError: import pyfits import numpy import glob hires.set_FLUX_UNITS('Jy/beam') #==================================================================== # Override hires.read_all_IN_files method def read_all_Spire_files(): ''' Read all SPIRE level products from the input directory and return a list of Sample objects ''' file_list = sorted( glob.glob(hires.INFILE_PREFIX + '*.fits') ) if len(file_list)==0: hires.log(hires.LOG_fatal, 'No input files for: ' + \ hires.INFILE_PREFIX) # QUIT if (hires.DIAG_PRODUCT): diagHdu = pyfits.open(hires.DIAG_PRODUCT) diagTable = diagHdu[1] chanNames = diagTable.data.field('channelName') scanNumbers = diagTable.data.field('scanNumber') coffsets = diagTable.data.field('a0') samples = [] scan = 0 for file in file_list: hduList = pyfits.open(file) maskHdu = hduList['mask'] signalHdu = hduList['signal'] raHdu = hduList['ra'] decHdu = hduList['dec'] names = [] for det in raHdu.data.names: if (det[:3] == hires.BAND and det[3] != 'T' and det[3] != 'R' and det[4] != 'P'): names.append(det) names.sort() crval1 = hires.get_FITS_keyword('CRVAL1') crval2 = hires.get_FITS_keyword('CRVAL2') projection = hires.Gnomonic(crval1, crval2) for det in names: if (hires.DIAG_PRODUCT): inz = (chanNames == det) & (scanNumbers == scan) offsettmp = coffsets[inz] if (len(offsettmp) != 1): raise ValueError('Did not find exactly one offset for %s in scan %d'\ %(det,scan)) a0 = coffsets[inz][0] else: a0 = 0 ra = raHdu.data.field(det) dec = decHdu.data.field(det) sig = signalHdu.data.field(det) - a0 + hires.FLUX_OFFSET mask = maskHdu.data.field(det) inx = numpy.all([(mask & 64401) == 0],axis=0) #hires.log(3, 'Generating samples for detector %s',det) x, y = projection.np_lonlat2xy(ra[inx], dec[inx]) # negate x because CDELT1 is negative # angle = 0.0 to ignore it if (len(sig[inx]) > 0): ss = hires.SampleSet(-x, y, sig[inx], '1', 0.0) thismin = numpy.min(sig[inx],axis=-1) if thismin < hires.GLOBAL_MIN: hires.GLOBAL_MIN = thismin samples.append(ss) scan += 1 return samples def read_all_Spire_tables(): ''' Read SPIRE table products and return a list of Sample objects ''' raHduList = pyfits.open('IN/m33_raTable2.fits') raHdu = raHduList[1] names = [] for det in raHdu.data.names: if (det[:3] == 'PLW' and det[3] != 'T' and det[3] != 'R' and det[4] != 'P'): names.append(det) names.sort() decHduList = pyfits.open('IN/m33_decTable2.fits') signalHduList = pyfits.open('IN/m33_signalTable2.fits') maskHduList = pyfits.open('IN/m33_maskTable2.fits') samples = [] crval1 = hires.get_FITS_keyword('CRVAL1') crval2 = hires.get_FITS_keyword('CRVAL2') projection = hires.Gnomonic(crval1, crval2) for det in names: #ra = raHduList[1].data[det] ra = raHduList[1].data.field(det)[::1] dec = decHduList[1].data.field(det)[::1] sig = signalHduList[1].data.field(det)[::1] + offset mask = maskHduList[1].data.field(det)[::1] # ra = raHduList[1].data.field(det)[::17] # dec = decHduList[1].data.field(det)[::17] # sig = signalHduList[1].data.field(det)[::17] # mask = maskHduList[1].data.field(det)[::17] #inx = numpy.all([mask <= 1024,mask != 256],axis=0) inx = numpy.all([(mask & 64401) == 0]) hires.log(3, 'Generating samples for detector %s',det) x, y = projection.np_lonlat2xy(ra[inx], dec[inx]) # negate x because CDELT1 is negative # angle = 0.0 to ignore it ss = hires.SampleSet(-x, y, sig[inx], '1', 0.0) # ss = hires.SampleSet(-x, y, sig[inx], 1, 0.0) # if (i%3333 == 0): # hires.log(3, 'Created %dth sample for detector %s, x=%f, y=%f, ra=%f, dec=%f',\ # i,det,x[i], y[i], ra[inx][i],dec[inx][i]) samples.append(ss) return samples #==================================================================== # Override hires.read_all_DRF_files method def read_all_Spire_beams(): ''' Read SPIRE beams and return a dictionary of response functions ''' # note: DRF_SET_ID now set in plw.params # global DRF_SET_ID DRF_SET_ID = 'single' detHduList = pyfits.open(hires.DRF_PREFIX) extn = hires.DRF_EXTN drf_array = detHduList[extn].data naxis1 = detHduList[extn].header['NAXIS1'] naxis2 = detHduList[extn].header['NAXIS2'] #deg_per_pix = 1./3600. #deg_per_pix = 0.8/3600. deg_per_pix = abs(detHduList[extn].header['CDELT1']) radius_pix = naxis1 / 2 radius_degrees = radius_pix * deg_per_pix detectors = {} #print names # def xy2response_function(x, y): ''' interpolate in detector response array x, y in degrees (relative to DRF center) ''' iFloat = (x + radius_degrees) / deg_per_pix jFloat = (y + radius_degrees) / deg_per_pix # cheap "interpolation" -- just takes nearest one iInt = int(iFloat+0.5) jInt = int(jFloat+0.5) if iInt<0 or iInt>=naxis1 or jInt<0 or jInt>=naxis2 : response = 0.0 else: response = drf_array[iInt, jInt] return response # # for id in names: # detector = hires.Detector(id, radius_degrees, xy2response_function) # detectors[id] = detector detectors['1'] = hires.Detector(1, radius_degrees, xy2response_function) return detectors hires.read_all_IN_files = read_all_Spire_files hires.read_all_DRF_files = read_all_Spire_beams #==================================================================== # Call hires if __name__ == "__main__": hires.main()
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 14116, 198, 37811, 220, 198, 4303, 41736, 12, 11423, 2438, 329, 15902, 4965, 13, 198, 198, 15269, 357, 66, 8, 2321, 12, 6390, 11, 3442, 5136,...
2.082534
3,126
"""Unit tests for the Diff class. Copyright (c) 2020-2021 Network To Code, LLC <info@networktocode.com> 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 pytest from diffsync.diff import Diff, DiffElement from diffsync.exceptions import ObjectAlreadyExists def test_diff_empty(): """Test the basic functionality of the Diff class when initialized and empty.""" diff = Diff() assert not diff.children assert not list(diff.groups()) assert not diff.has_diffs() assert not list(diff.get_children()) def test_diff_children(): """Test the basic functionality of the Diff class when adding child elements.""" diff = Diff() device_element = DiffElement("device", "device1", {"name": "device1"}) intf_element = DiffElement("interface", "eth0", {"device_name": "device1", "name": "eth0"}) diff.add(device_element) assert "device" in diff.children assert diff.children["device"] == {"device1": device_element} assert list(diff.groups()) == ["device"] assert not diff.has_diffs() assert list(diff.get_children()) == [device_element] with pytest.raises(ObjectAlreadyExists): diff.add(device_element) diff.add(intf_element) assert "interface" in diff.children assert diff.children["interface"] == {"eth0": intf_element} assert list(diff.groups()) == ["device", "interface"] assert not diff.has_diffs() assert list(diff.get_children()) == [device_element, intf_element] with pytest.raises(ObjectAlreadyExists): diff.add(intf_element) source_attrs = {"interface_type": "ethernet", "description": "my interface"} dest_attrs = {"description": "your interface"} intf_element.add_attrs(source=source_attrs, dest=dest_attrs) assert diff.has_diffs() def test_order_children_default(backend_a, backend_b): """Test that order_children_default is properly called when calling get_children.""" class MyDiff(Diff): """custom diff class to test order_children_default.""" @classmethod def order_children_default(cls, children): """Return the children ordered in alphabetical order.""" keys = sorted(children.keys(), reverse=False) for key in keys: yield children[key] # Validating default order method diff_a_b = backend_a.diff_from(backend_b, diff_class=MyDiff) children = diff_a_b.get_children() children_names = [child.name for child in children] assert children_names == ["atl", "nyc", "rdu", "sfo"] def test_order_children_custom(backend_a, backend_b): """Test that a custom order_children method is properly called when calling get_children.""" class MyDiff(Diff): """custom diff class to test order_children_site.""" @classmethod def order_children_site(cls, children): """Return the site children ordered in reverse-alphabetical order.""" keys = sorted(children.keys(), reverse=True) for key in keys: yield children[key] diff_a_b = backend_a.diff_from(backend_b, diff_class=MyDiff) children = diff_a_b.get_children() children_names = [child.name for child in children] assert children_names == ["sfo", "rdu", "nyc", "atl"]
[ 37811, 26453, 5254, 329, 262, 10631, 1398, 13, 198, 198, 15269, 357, 66, 8, 12131, 12, 1238, 2481, 7311, 1675, 6127, 11, 11419, 1279, 10951, 31, 27349, 40301, 1098, 13, 785, 29, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 1062...
2.918288
1,285
from gpiozero import Button import socket from multiprocessing import Pipe from sys import byteorder from datetime import timedelta, datetime as dt
[ 6738, 27809, 952, 22570, 1330, 20969, 198, 11748, 17802, 198, 6738, 18540, 305, 919, 278, 1330, 36039, 198, 6738, 25064, 1330, 18022, 2875, 198, 6738, 4818, 8079, 1330, 28805, 12514, 11, 4818, 8079, 355, 288, 83, 198 ]
4
37
# -*- coding: utf-8 -*- # # furl - URL manipulation made simple. # # Ansgar Grunseid # grunseid.com # grunseid@gmail.com # # License: Build Amazing Things (Unlicense) # import sys if sys.version_info[0] == 2: string_types = basestring # noqa else: string_types = (str, bytes) if list(sys.version_info[:2]) >= [2, 7]: from collections import OrderedDict # noqa else: from ordereddict import OrderedDict # noqa class UnicodeMixin(object): """ Mixin that defines proper __str__/__unicode__ methods in Python 2 or 3. """ if sys.version_info[0] >= 3: # Python 3 else: # Python 2
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 198, 2, 277, 6371, 532, 10289, 17512, 925, 2829, 13, 198, 2, 198, 2, 28038, 4563, 1902, 403, 325, 312, 198, 2, 44397, 325, 312, 13, 785, 198, 2, 44397, 325...
2.553279
244
# -*- coding: utf-8 -*- """ Created on Mon Jan 15 18:03:22 2018 @author: James Wu """ import cv2 import numpy as np import serial face_cascade = cv2.CascadeClassifier('./data/haarcascade_frontalface_default.xml') #============================================================================== # 1.多人脸形心检测函数 # 输入:视频帧 # 输出:各人脸总形心坐标 #============================================================================== #============================================================================== # ****************************主函数入口*********************************** #============================================================================== # 设置串口参数 ser = serial.Serial() ser.baudrate = 115200 # 设置比特率为115200bps ser.port = 'COM3' # 单片机接在哪个串口,就写哪个串口。这里默认接在"COM3"端口 ser.open() # 打开串口 #先发送一个中心坐标使初始化时云台保持水平 data = '#'+str('320')+'$'+str('240')+'\r\n' ser.write(data.encode()) cap = cv2.VideoCapture(1) #打开摄像头 while(cap.isOpened()): _, frame = cap.read() X, Y = Detection(frame) #执行多人脸形心检测函数 if(X<10000): print('X = ') print(X) print('Y =') print(Y) #按照协议将形心坐标打包并发送至串口 data = '#'+str(X)+'$'+str(Y)+'\r\n' ser.write(data.encode()) k = cv2.waitKey(5) & 0xFF if k==27: #按“Esc”退出 break ser.close() # 关闭串口 cv2.destroyAllWindows() cap.release()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 2365, 1315, 1248, 25, 3070, 25, 1828, 2864, 198, 198, 31, 9800, 25, 3700, 18027, 198, 37811, 198, 198, 11748, 269, 85, 17, 198, 11748, 29...
1.709716
844
from src.articles.domain.entities import category, article, tag from src.articles.services import unit_of_work
[ 6738, 12351, 13, 26845, 13, 27830, 13, 298, 871, 1330, 6536, 11, 2708, 11, 7621, 198, 6738, 12351, 13, 26845, 13, 30416, 1330, 4326, 62, 1659, 62, 1818, 628 ]
3.862069
29
from .filter_declarations import * # NOQA
[ 6738, 764, 24455, 62, 32446, 24355, 1330, 1635, 220, 1303, 8005, 48, 32, 198 ]
3.071429
14
from pathlib import Path import mimetypes import functools @banner def list_images(path: Path) -> None: """ Lista las imágenes del directorio indicado. """ for file in path.iterdir(): mime = mimetypes.guess_type(file)[0] if file.is_file() and mime == "image/jpeg": print(file.name)
[ 6738, 3108, 8019, 1330, 10644, 198, 11748, 17007, 2963, 12272, 198, 11748, 1257, 310, 10141, 628, 198, 198, 31, 3820, 1008, 198, 4299, 1351, 62, 17566, 7, 6978, 25, 10644, 8, 4613, 6045, 25, 198, 220, 220, 220, 37227, 198, 220, 220, ...
2.333333
141
from anthill.common.model import Model from anthill.common.validate import validate from anthill.common.deployment import DeploymentError, DeploymentMethods from . settings import NoSuchSettingsError, SettingsError import os
[ 198, 6738, 26794, 359, 13, 11321, 13, 19849, 1330, 9104, 198, 6738, 26794, 359, 13, 11321, 13, 12102, 378, 1330, 26571, 198, 6738, 26794, 359, 13, 11321, 13, 2934, 1420, 434, 1330, 34706, 434, 12331, 11, 34706, 434, 46202, 198, 198, 6...
4.017544
57
""" .. module:: reaction_message :platform: Unix :synopsis: A module that describes what the reaction should be when receiving a specific message. .. Copyright 2022 EDF .. moduleauthor:: Oscar RODRIGUEZ INFANTE, Tony ZHOU, Trang PHAM, Efflam OLLIVIER .. License:: This source code is licensed under the MIT License. """ class ReactionToIncomingMessage: """This is a class that contains any useful information about an incoming message and the reaction to it. """ @property @message.setter @property @extra_data.setter @property @property @msg_type.setter class SendMessage(ReactionToIncomingMessage): """This is a reaction to a message that tells it to send it. Inherits from ReactionToIncomingMessage. """ class TerminateSession(ReactionToIncomingMessage): """This is a reaction to a message that tells it to end the session. Inherits from ReactionToIncomingMessage. """ pass class ChangeState(ReactionToIncomingMessage): """This is a reaction to a message that tells it to change the state. Inherits from ReactionToIncomingMessage. Not really used, so consider removing it. """ pass class PauseSession(ReactionToIncomingMessage): """This is a reaction to a message that tells it to pause the session. Inherits from ReactionToIncomingMessage. Not really used, to be implemented in later versions. """ pass
[ 37811, 198, 492, 8265, 3712, 6317, 62, 20500, 198, 220, 220, 1058, 24254, 25, 33501, 198, 220, 220, 1058, 28869, 24608, 25, 317, 8265, 326, 8477, 644, 262, 6317, 815, 307, 618, 6464, 257, 2176, 3275, 13, 198, 198, 492, 15069, 33160, ...
3.388626
422
from typing import List from pandas._typing import ( FilePathOrBuffer, Scalar, StorageOptions, ) from pandas.compat._optional import import_optional_dependency from pandas.io.excel._base import BaseExcelReader
[ 6738, 19720, 1330, 7343, 198, 198, 6738, 19798, 292, 13557, 774, 13886, 1330, 357, 198, 220, 220, 220, 9220, 15235, 5574, 28632, 11, 198, 220, 220, 220, 34529, 283, 11, 198, 220, 220, 220, 20514, 29046, 11, 198, 8, 198, 6738, 19798, ...
3.082192
73
import boto3 from flask import make_response # "WHERE'S MY GENE" PROTOTYPE CODE WMG_DATA_BUCKET = "wmg-prototype-data-dev-public" WMG_DATA_S3_OBJ_PREFIX = "lung-tissue-10x-human-20220112"
[ 11748, 275, 2069, 18, 198, 6738, 42903, 1330, 787, 62, 26209, 198, 198, 2, 366, 47357, 6, 50, 17615, 24700, 36, 1, 48006, 2394, 56, 11401, 42714, 198, 198, 54, 20474, 62, 26947, 62, 33, 16696, 2767, 796, 366, 86, 11296, 12, 38124, ...
2.282353
85
""" test.py Copyright 2015 Jeroen Arnoldus <jeroen@repleo.nl> THIS SOFTWARE IS SUPPLIED WITHOUT WARRANTY OF ANY KIND, AND MAY BE COPIED, MODIFIED OR DISTRIBUTED IN ANY WAY, AS LONG AS THIS NOTICE AND ACKNOWLEDGEMENT OF AUTHORSHIP REMAIN. """ from django.test import TestCase import mimetypes from randomcab.home.views import MailForm
[ 37811, 198, 220, 220, 220, 1332, 13, 9078, 198, 220, 220, 220, 15069, 1853, 449, 3529, 268, 21418, 385, 1279, 73, 3529, 268, 31, 260, 1154, 78, 13, 21283, 29, 198, 220, 220, 220, 220, 198, 43559, 47466, 3180, 19549, 49094, 42881, 34...
2.84127
126
# -*- coding: utf-8 -*- import codecs import os import pickle #import io #from PIL import Image import numpy as np
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 40481, 82, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 2, 11748, 33245, 198, 2, 6738, 350, 4146, 1330, 7412, 198, 11748, 299, 32152, 355, 45941, 628, 628, 628 ...
2.727273
44
## This repo will use python code in general
[ 2235, 770, 29924, 481, 779, 21015, 2438, 287, 2276, 198 ]
4.5
10
# Copyright 2016 Red Hat, Inc. # 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. import json import logging import os import re import shutil import six import tempfile import warnings import yaml import jinja2 from tripleo_workflows import constants warnings.filterwarnings('once')
[ 2, 15069, 1584, 2297, 10983, 11, 3457, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846...
3.753488
215
# -*- coding: utf-8 -*- """ dp for Tornado MVC Web Application Framework with Tornado http://github.com/why2pac/dp-tornado Copyright (c) 2015, why2pac <youngyongpark@gmail.com> """ import tornado.web import tornado.ioloop import tornado.httpserver import time import os import multiprocessing import importlib from dp_tornado.engine.engine import EngineSingleton as dpEngineSingleton from dp_tornado.engine.bootstrap import Bootstrap as EngineBootstrap from dp_tornado.engine.scheduler import Scheduler from dp_tornado.engine.testing import Testing from dp_tornado.engine.plugin.static import Compressor from dp_tornado.engine.plugin.static import StaticURL from dp_tornado.engine.plugin.pagination import Pagination from dp_tornado.engine.plugin import ui_methods from dp_tornado.version import __version_info__ engine = dpEngineSingleton()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 628, 220, 288, 79, 329, 48970, 628, 220, 337, 15922, 5313, 15678, 25161, 351, 48970, 198, 220, 2638, 1378, 12567, 13, 785, 14, 22850, 17, 33587, 14, 26059, ...
3.196296
270
# AC A,B,C = map(int, input().split()) if C == 0: if A > B: print("Takahashi") else: print("Aoki") if C == 1: if A < B: print("Aoki") else: print("Takahashi")
[ 2, 7125, 198, 32, 11, 33, 11, 34, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 198, 361, 327, 6624, 657, 25, 198, 220, 220, 220, 611, 317, 1875, 347, 25, 198, 220, 220, 220, 220, 220, 220, 220, 3601, 7203, 51, 461, 9...
1.777778
117
import argparse import logging from sys import exit from py3tftp import __version__ EPILOG = """ Released under the MIT license. Copyright 2016 Matt O. <matt@mattscodecave.com> """ logging_config = { 'format': '%(asctime)s [%(levelname)s] %(message)s', 'level': logging.INFO, 'filename': None }
[ 11748, 1822, 29572, 198, 11748, 18931, 198, 6738, 25064, 1330, 8420, 198, 198, 6738, 12972, 18, 83, 701, 79, 1330, 11593, 9641, 834, 198, 198, 8905, 4146, 7730, 796, 37227, 198, 45037, 739, 262, 17168, 5964, 13, 198, 15269, 1584, 4705, ...
2.666667
117
from raptiformica.distributed.exec import try_machine_command def try_issue_shutdown(host_and_port_pairs): """ Iterate over host and port pairs and try to issue a shutdown on all nodes until one returns a nonzero exit code. At that point return the standard out output. If we ran out of host and port pairs to try, log a warning and return None :param list[tuple, ..] host_and_port_pairs: A list of tuples containing host and ports of remote hosts :return str standard_out | None: 'consul exec' output or None """ issue_global_shutdown_command = ["consul", "exec", "'shutdown -h now'"] attempt_message = "Trying to issue a global shutdown on {}:{}" all_failed_message = "Failed to issue a global shutdown on any of the nodes." output, _, _ = try_machine_command( host_and_port_pairs, issue_global_shutdown_command, attempt_message=attempt_message, all_failed_message=all_failed_message ) return output
[ 6738, 38404, 6933, 3970, 13, 17080, 6169, 13, 18558, 1330, 1949, 62, 30243, 62, 21812, 628, 198, 4299, 1949, 62, 21949, 62, 49625, 2902, 7, 4774, 62, 392, 62, 634, 62, 79, 3468, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, ...
2.946588
337
from .fixtures import app_harness, socket_client_factory # noqa
[ 6738, 764, 69, 25506, 1330, 598, 62, 9869, 1108, 11, 17802, 62, 16366, 62, 69, 9548, 220, 1303, 645, 20402, 198 ]
3.095238
21
import asyncio from decimal import Decimal from typing import ( Any, Dict, Optional, ) from hummingbot.connector.exchange.k2.k2_utils import convert_from_exchange_trading_pair from hummingbot.connector.in_flight_order_base import InFlightOrderBase from hummingbot.core.event.events import ( OrderType, TradeType )
[ 11748, 30351, 952, 198, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 19720, 1330, 357, 198, 220, 220, 220, 4377, 11, 198, 220, 220, 220, 360, 713, 11, 198, 220, 220, 220, 32233, 11, 198, 8, 198, 198, 6738, 41465, 13645, 13, 8443, ...
2.930435
115
from __future__ import absolute_import from flytekit.common.types import primitives as _primitives, blobs as _blobs, schema as _schema, helpers as _helpers, \ proto as _proto, containers as _containers
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 6129, 660, 15813, 13, 11321, 13, 19199, 1330, 2684, 20288, 355, 4808, 19795, 20288, 11, 698, 8158, 355, 4808, 2436, 8158, 11, 32815, 355, 4808, 15952, 2611, 11, 49385, 355, 4808...
3.393443
61
import logging import urllib2 from navi.app import main import os from flask import Flask, render_template from flask import request _STOP = '/stop' logging.basicConfig() _pwd = os.path.abspath(__file__) for i in range(4): _pwd = os.path.dirname(_pwd) _pwd += '/web' _app_flask = Flask(__name__, template_folder=_pwd, static_folder=os.path.join(_pwd, 'static'), static_url_path='') _global = {} @_app_flask.errorhandler(404) @_app_flask.errorhandler(500) @_app_flask.route('/') @_app_flask.route('/dashboard') @_app_flask.route('/settings', methods=['GET', 'POST']) @_app_flask.route('/static/<path:path>') @_app_flask.route(_STOP, methods=['POST']) @_app_flask.route('/amber_connect', methods=['GET', 'POST']) @_app_flask.route('/amber_disconnect', methods=['GET', 'POST'])
[ 11748, 18931, 198, 11748, 2956, 297, 571, 17, 198, 198, 6738, 6812, 72, 13, 1324, 1330, 1388, 198, 11748, 28686, 198, 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 198, 6738, 42903, 1330, 2581, 628, 198, 62, 2257, 3185, 796, 31051, 1...
2.455927
329
import json import random
[ 11748, 33918, 198, 11748, 4738 ]
5
5
# Generated by Django 3.0.8 on 2020-11-26 11:27 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 23, 319, 12131, 12, 1157, 12, 2075, 1367, 25, 1983, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
from typing import List from models.chapter import Chapter from models.event import Event from models.intruction import Instruction
[ 6738, 19720, 1330, 7343, 198, 198, 6738, 4981, 13, 43582, 1330, 7006, 198, 6738, 4981, 13, 15596, 1330, 8558, 198, 6738, 4981, 13, 600, 2762, 1330, 46486, 628 ]
4.785714
28
from django.shortcuts import render,redirect from .email import send_welcome_email from django.contrib.auth.decorators import login_required from .forms import NewsLetterForm from .forms import NewProjectsForm from .models import Profile , Projects from rest_framework.response import Response from rest_framework.views import APIView from .serializer import ProfileSerializer, ProjectsSerializer from rest_framework import status # Create your views here. @login_required(login_url='/accounts/login') # def task(request): # task = Image.objects.all() # return render(request, 'all-task/index.html', {"task":task}) @login_required(login_url='/accounts/login/') @login_required(login_url='/accounts/login/')
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 445, 1060, 198, 6738, 764, 12888, 1330, 3758, 62, 86, 9571, 62, 12888, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 7...
3.428571
210
__version__ = '1.0.0' __author__ = 'upnt' __author_email__ = 'base.shun0329@gmail.com' __url__ = 'https://github.com/upnt/othello-python'
[ 834, 9641, 834, 220, 220, 220, 220, 220, 220, 220, 220, 796, 705, 16, 13, 15, 13, 15, 6, 198, 834, 9800, 834, 220, 220, 220, 220, 220, 220, 220, 220, 220, 796, 705, 929, 429, 6, 198, 834, 9800, 62, 12888, 834, 220, 220, 220, ...
1.847826
92
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as mtick from sweetviz.config import config from sweetviz import sv_html_formatters from sweetviz.sv_types import FeatureType, FeatureToProcess import sweetviz.graph
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 83, 15799, 355, 285, 42298, 198, 198, 6738, 6029, 85, 528, 13, 11250...
3.2875
80
from keras import layers from tensorflow_probability import distributions import tensorflow as tf
[ 6738, 41927, 292, 1330, 11685, 198, 6738, 11192, 273, 11125, 62, 1676, 65, 1799, 1330, 24570, 198, 11748, 11192, 273, 11125, 355, 48700, 628 ]
4.125
24
''' .. module:: entree.projects .. moduleauthor:: Julien Spronck .. created:: Feb 2018 Module for all projects ''' from entree.projects.base import ProjectBase from entree.projects.flask import Flask from entree.projects.flask_large import FlaskLarge from entree.projects.html5 import HTML5 from entree.projects.python import Python from entree.projects.sqlalchemy import SQLAlchemy CLASSES = ProjectBase.__subclasses__() CLASS_LONG_NAMES = sorted([pcls.project_long_name for pcls in CLASSES]) CLASSES = {pcls.__name__.lower(): pcls for pcls in CLASSES}
[ 7061, 6, 198, 492, 8265, 3712, 920, 631, 13, 42068, 198, 492, 8265, 9800, 3712, 5979, 2013, 5522, 261, 694, 198, 492, 2727, 3712, 3158, 2864, 198, 198, 26796, 329, 477, 4493, 198, 7061, 6, 198, 198, 6738, 920, 631, 13, 42068, 13, ...
3.164773
176
from typing import Optional, Dict from flask import json, request, current_app, g, abort import requests
[ 6738, 19720, 1330, 32233, 11, 360, 713, 201, 198, 6738, 42903, 1330, 33918, 11, 2581, 11, 1459, 62, 1324, 11, 308, 11, 15614, 201, 198, 11748, 7007, 201, 198, 201, 198 ]
3.548387
31
import logging import asyncio from gym.common.profiler.profiler import Profiler from gym.common.identity import Peers, Identity from gym.common.mailing import Mailing from gym.common.messages import Message, rpc_map, Hello, Info from gym.common.events import EventBase, EventGreetings, EventMsg logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 11748, 30351, 952, 198, 198, 6738, 11550, 13, 11321, 13, 5577, 5329, 13, 5577, 5329, 1330, 4415, 5329, 198, 6738, 11550, 13, 11321, 13, 738, 414, 1330, 2631, 364, 11, 27207, 198, 6738, 11550, 13, 11321, 13, 4529, 27...
3.438776
98
from heartandsole.core.activity import Activity import heartandsole.api from heartandsole.util import time_from_timestring, timestring_from_time __version__ = '0.0.23' # __all__ = [ # 'Activity', # ]
[ 6738, 2612, 392, 6753, 13, 7295, 13, 21797, 1330, 24641, 198, 198, 11748, 2612, 392, 6753, 13, 15042, 198, 6738, 2612, 392, 6753, 13, 22602, 1330, 640, 62, 6738, 62, 16514, 395, 1806, 11, 4628, 395, 1806, 62, 6738, 62, 2435, 198, 19...
2.833333
72
# TODO: add docstrings from chip8.presenter import Presenter presenter = Presenter() presenter.run()
[ 2, 16926, 46, 25, 751, 2205, 37336, 198, 198, 6738, 11594, 23, 13, 25579, 263, 1330, 1763, 9255, 198, 198, 25579, 263, 796, 1763, 9255, 3419, 198, 25579, 263, 13, 5143, 3419, 198 ]
3.121212
33
#!/usr/bin/env python import rospy if __name__ == "__main__": try: main() except Exception as exc: print("Exception occurred: ", exc)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 686, 2777, 88, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1949, 25, 198, 220, 220, 220, 220, 220, 220, 220, 1388, 3419, 198, 220, ...
2.373134
67
import json from google.cloud.logging_v2.handlers import CloudLoggingFilter, CloudLoggingHandler from google.cloud.logging_v2.handlers._helpers import _parse_xcloud_trace from google.cloud.logging_v2.handlers.handlers import DEFAULT_LOGGER_NAME from google.cloud.logging_v2.handlers.transports import BackgroundThreadTransport from .request_logging_middleware import _FASTAPI_REQUEST_CONTEXT from .utils import serialize_json class FastAPILoggingFilter(CloudLoggingFilter): """ This LoggingFilter is extended for logging a request on FastAPI. This data can be manually overwritten using the `extras` argument when writing logs. """ def filter(self, record): """ Add new Cloud Logging data to each LogRecord as it comes in """ # infer request data from context_vars ( http_request, trace, span_id, trace_sampled, ) = self.get_request_data() if trace is not None and self.project is not None: # add full path for detected trace trace = f"projects/{self.project}/traces/{trace}" setattr(record, "trace", trace) setattr(record, "span_id", span_id) setattr(record, "trace_sampled", trace_sampled) setattr(record, "http_request", http_request) if self.structured and isinstance(record.msg, str): record.msg = {"message": record.msg} # for loguru if hasattr(record, "extra"): extra = getattr(record, "extra", {}) record.json_fields = json.loads(json.dumps(extra, default=serialize_json)) return super().filter(record=record) class FastAPILoggingHandler(CloudLoggingHandler): """ This LoggingHandler is extended for logging a request on FastAPI. Usage of this LoggingHandler is the same as CloudLoggingHandler. """ def __init__( self, client, *, name=DEFAULT_LOGGER_NAME, transport=BackgroundThreadTransport, resource=None, labels=None, stream=None, structured: bool = False, ): """ Args: client (~logging_v2.client.Client): The authenticated Google Cloud Logging client for this handler to use. name (str): the name of the custom log in Cloud Logging. Defaults to 'python'. The name of the Python logger will be represented in the ``python_logger`` field. transport (~logging_v2.transports.Transport): Class for creating new transport objects. It should extend from the base :class:`.Transport` type and implement :meth`.Transport.send`. Defaults to :class:`.BackgroundThreadTransport`. The other option is :class:`.SyncTransport`. resource (~logging_v2.resource.Resource): Resource for this Handler. If not given, will be inferred from the environment. labels (Optional[dict]): Additional labels to attach to logs. stream (Optional[IO]): Stream to be used by the handler. structured (bool): Treat every message as structured message. """ super().__init__( client, name=name, transport=transport, resource=resource, labels=labels, stream=stream, ) # replace default cloud logging filter for default_filter in self.filters: if isinstance(default_filter, CloudLoggingFilter): self.removeFilter(default_filter) log_filter = FastAPILoggingFilter( project=self.project_id, default_labels=labels, structured=structured ) self.addFilter(log_filter)
[ 11748, 33918, 198, 198, 6738, 23645, 13, 17721, 13, 6404, 2667, 62, 85, 17, 13, 4993, 8116, 1330, 10130, 11187, 2667, 22417, 11, 10130, 11187, 2667, 25060, 198, 6738, 23645, 13, 17721, 13, 6404, 2667, 62, 85, 17, 13, 4993, 8116, 13557...
2.388646
1,603
from Bio.Align.Applications import MuscleCommandline from Bio import AlignIO import operator
[ 6738, 16024, 13, 2348, 570, 13, 41995, 1330, 43683, 21575, 1370, 198, 6738, 16024, 1330, 978, 570, 9399, 198, 11748, 10088, 198 ]
4.227273
22
# Generated by Django 1.11.16 on 2019-07-11 from django.db import migrations from corehq.sql_db.operations import RawSQLMigration migrator = RawSQLMigration(('custom', 'icds_reports', 'migrations', 'sql_templates', 'database_views'))
[ 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 1433, 319, 13130, 12, 2998, 12, 1157, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 198, 6738, 4755, 71, 80, 13, 25410, 62, 9945, 13, 3575, 602, 1330, 16089, 17861, 44, 4254, ...
2.925926
81
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members """ Buildbot plugin infrastructure """ from buildbot import statistics from buildbot.interfaces import IBuildStep from buildbot.interfaces import IChangeSource from buildbot.interfaces import IScheduler from buildbot.interfaces import IWorker from buildbot.plugins.db import get_plugins __all__ = [ 'changes', 'schedulers', 'steps', 'util', 'reporters', 'statistics', 'worker', 'buildslave', # deprecated, use 'worker' instead. ] # Names here match the names of the corresponding Buildbot module, hence # 'changes', 'schedulers', but 'buildslave' changes = get_plugins('changes', IChangeSource) schedulers = get_plugins('schedulers', IScheduler) steps = get_plugins('steps', IBuildStep) util = get_plugins('util', None) reporters = get_plugins('reporters', None) # For plugins that are not updated to the new worker names, plus fallback of # current Buildbot plugins for old configuration files. buildslave = get_plugins('buildslave', IWorker) # Worker entry point for new/updated plugins. worker = get_plugins('worker', IWorker)
[ 2, 770, 2393, 318, 636, 286, 10934, 13645, 13, 220, 10934, 13645, 318, 1479, 3788, 25, 345, 460, 198, 2, 17678, 4163, 340, 290, 14, 273, 13096, 340, 739, 262, 2846, 286, 262, 22961, 3611, 5094, 198, 2, 13789, 355, 3199, 416, 262, ...
3.623967
484
from __future__ import absolute_import import time import random import functools from huskar_sdk_v2.six import iteritems from huskar_sdk_v2.utils import ( combine, decode_key, encode_key, get_function_name) from huskar_sdk_v2.consts import CACHE_KEYS, SWITCH_SUBDOMAIN from . import SignalComponent, Watchable, require_connection class Switch(SignalComponent, Watchable): """A component of Huskar for switching. Switch is usually used to enable or disable the API, it also has the ability to limit the passing rate. """ SUBDOMAIN = SWITCH_SUBDOMAIN def set_default_rate(self, rate): """Set default state by percentage. :arg int rate: ``0-100(default)`` as percentage, e.g. ``30`` means the switch has 30% chance of being on. ``0`` for always off, ``100`` for always on, see :meth:`set_default_rate`""" if not isinstance(rate, int): raise TypeError("Default rate should be int, get: %s" % rate) self.default_rate = rate def set_default_state(self, state): """Set default state of switch. This is equivalent to ``self.set_default_rate(100 if state else 0)`` :arg state: ``True`` for **ON** (default) ``False`` for **OFF**. """ self.set_default_rate(100 if state else 0) # TODO: this method name is confusing, the default should be eliminated # otherwise the method name should change to verb @require_connection def is_switched_on(self, name, default=None): """Get the current state of switch by ``name``. The result of this method may be outdated if the ZooKeeper connection is lost. If this happened, a warning logging will be recorded. :param default: This will be returned if the switch is not found. :returns: ``True`` or ``False`` decided by the pass rate of switch. """ if (not self.client.local_mode and not self.ready.is_set() and self.started_timeout.is_set()): self.logger.warning( 'Switch %r may be outdated caused by lost connection', name) if name in self.switches: pass_percent = self.switches[name].get('value') elif name in self.overall_switches: pass_percent = self.overall_switches[name].get('value') elif default is not None: return default else: pass_percent = self.default_rate if pass_percent == 100: return True elif pass_percent == 0: return False else: # to support float pass_percent, e.g. 0.01 means 1/10000 return self.rand.randint(0, 10000) / 100.0 <= pass_percent @require_connection def bind(self, name=None, default=None): """Decorator for binding switch. .. code:: python @bind(default='default') def api(): return 'value' :arg str name: indicates the name of switch, the name of function is used if not provided. :arg default: will be returned if switch is **OFF** return ``None`` if not provided. """ return wrapper
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 640, 198, 11748, 4738, 198, 11748, 1257, 310, 10141, 198, 198, 6738, 4791, 21070, 62, 21282, 74, 62, 85, 17, 13, 19412, 1330, 11629, 23814, 198, 6738, 4791, 21070, 62, 2...
2.457986
1,321
import asyncio import unittest from decimal import Decimal from unittest.mock import patch from hummingbot.connector.exchange.probit.probit_constants import \ MAX_ORDER_ID_LEN from hummingbot.connector.exchange.probit.probit_exchange import ProbitExchange from hummingbot.connector.utils import get_new_client_order_id from hummingbot.core.event.events import OrderType
[ 11748, 30351, 952, 198, 11748, 555, 715, 395, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 198, 6738, 41465, 13645, 13, 8443, 273, 13, 1069, 3803, 13, 1676, 2545, 13, 1676, 2545, 62, 99...
3.241379
116
import logging logger = logging.getLogger(__name__) import os from baseadmin.backend.interface import register_component from baseadmin.backend.socketio import command # add component UI register_component("SystemActions.js", os.path.dirname(__file__)) # respond to system actions @command("reboot") @command("shutdown") @command("update")
[ 11748, 18931, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198, 198, 11748, 28686, 198, 198, 6738, 2779, 28482, 13, 1891, 437, 13, 39994, 1330, 7881, 62, 42895, 198, 6738, 2779, 28482, 13, 1891, 437, 13, ...
3.261682
107
# This file is part of Pynguin. # # Pynguin is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pynguin is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Pynguin. If not, see <https://www.gnu.org/licenses/>. from unittest.mock import MagicMock import pynguin.testcase.statements.assignmentstatement as astmt import pynguin.testcase.variable.variablereferenceimpl as vri
[ 2, 770, 2393, 318, 636, 286, 9485, 782, 48441, 13, 198, 2, 198, 2, 9485, 782, 48441, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 290, 14, 273, 13096, 198, 2, 340, 739, 262, 2846, 286, 262, 22961, 12892, 263, 3611, 5094, 13789...
3.618026
233
from django.conf.urls import include, url, patterns from django.contrib import admin from contact_manager.views import IndexView,CreateEventView,EventProfileView,CreateContactView,ContactProfileView,ContactSearchView urlpatterns = patterns('', url(r'^$', IndexView.as_view(), name='index'), url(r'^new_event/$', CreateEventView.as_view(), name='create_event'), url(r'^(?P<nameyear>[a-z0-9-_]{1,200}[-]{1}[0-9]{4})/$', EventProfileView.as_view(), name='event_profile'), url(r'^(?P<nameyear>[a-z0-9-_]{1,200}[-]{1}[0-9]{4})/new_contact/$', CreateContactView.as_view(), name='create_contact'), url(r'^contact/(?P<endpoint>[a-z]{2,60}[0-9]{4})/$', ContactProfileView.as_view(), name='contact_profile'), url(r'^contact/search_results/$', ContactSearchView.as_view(), name='contact_search'), )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 2291, 11, 19016, 11, 7572, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 2800, 62, 37153, 13, 33571, 1330, 12901, 7680, 11, 16447, 9237, 7680, 11, 9237, 37046, 7680, ...
2.53271
321
"""Factory method for easily getting imdbs by name.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function __sets = {} from datasets.coco import coco from datasets.ade import ade from datasets.visual_genome import visual_genome import numpy as np # Set up coco_2014_<split> for year in ['2014']: for split in ['train', 'val', 'minival', 'valminusminival', 'trainval']: name = 'coco_{}_{}'.format(year, split) __sets[name] = (lambda split=split, year=year: coco(split, year)) # Set up coco_2015_<split> for year in ['2015']: for split in ['test', 'test-dev']: name = 'coco_{}_{}'.format(year, split) __sets[name] = (lambda split=split, year=year: coco(split, year)) # Set up ade_<split>_5 for split in ['train', 'val', 'mval', 'mtest']: name = 'ade_{}_5'.format(split) __sets[name] = (lambda split=split: ade(split)) # Set up vg_<split>_5,10 for split in ['train', 'val', 'test']: name = 'visual_genome_{}_5'.format(split) __sets[name] = (lambda split=split: visual_genome(split)) def get_imdb(name): """Get an imdb (image database) by name.""" if name not in __sets: raise KeyError('Unknown dataset: {}'.format(name)) return __sets[name]() def list_imdbs(): """List all registered imdbs.""" return list(__sets.keys())
[ 37811, 22810, 2446, 329, 3538, 1972, 545, 67, 1443, 416, 1438, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 834,...
2.740206
485
import numpy as np from sklearn.base import BaseEstimator, TransformerMixin
[ 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 8692, 1330, 7308, 22362, 320, 1352, 11, 3602, 16354, 35608, 259, 198 ]
3.454545
22
import unittest import falcon import falcon.testing import app.util.json as json from app import create_app
[ 11748, 555, 715, 395, 198, 198, 11748, 24215, 1102, 198, 11748, 24215, 1102, 13, 33407, 198, 198, 11748, 598, 13, 22602, 13, 17752, 355, 33918, 198, 6738, 598, 1330, 2251, 62, 1324, 628 ]
3.363636
33
from __future__ import print_function import uuid #========================================================================== # Example Server Code # NB: this is example code only. Does not cover # - authentication, # - security, # - timer events # - maintaining active connections (Player disconnects not monitored) # - assumes nobody is being dishonest ('spoofing' other players, etc) #========================================================================== #----------------------------------------------------------------- # Orchestrator class # Contains core logic for orchestrating (co-ordination) Threshold Signature #------------------------------------------------- #------------------------------------------------- # Register user with Orchestrator #------------------------------------------------- # m = recombination number of private key # n = total number in group # t = degree of polynomial (dervied from m-1 ) #------------------------------------------------- #------------------------------------------------- #------------------------------------------------- #------------------------------------------------- #------------------------------------------------- #------------------------------------------------- # Returns a list of users which is the participant List, # without the ordinal #------------------------------------------------- # get list of users ordinal : reference #------------------------------------------------- # collate data #------------------------------------------------- #------------------------------------------------- #------------------------------------------------- # collate V and W data #------------------------------------------------- # get collated V and W data #------------------------------------------------- # collate signature data #------------------------------------------------- # get collated signature data #------------------------------------------------- # This is here as a placeholder
[ 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 334, 27112, 628, 628, 198, 2, 23926, 2559, 855, 198, 2, 17934, 9652, 6127, 198, 2, 41354, 25, 428, 318, 1672, 2438, 691, 13, 220, 8314, 407, 3002, 220, 198, 2, 2...
4.507128
491
# Copyright 2015 Sindre Ilebekk Johansen and Andreas Sløgedal Løvland # 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 datetime import date from math import sqrt from pprint import pprint import pandas as pd import numpy as np import matplotlib matplotlib.use('PDF') import matplotlib.pyplot as plt SPINE_COLOR = 'gray' def latexify(fig_width=None, fig_height=None): """Set up matplotlib's RC params for LaTeX plotting. Call this before plotting a figure. Parameters ---------- fig_width : float, optional, inches fig_height : float, optional, inches """ # code adapted from http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples # Width and max height in inches for IEEE journals taken from # computer.org/cms/Computer.org/Journal%20templates/transactions_art_guide.pdf matplotlib.rcdefaults() if fig_width is None: fig_width = 6 if fig_height is None: golden_mean = (sqrt(5)-1.0)/2.0 # Aesthetic ratio fig_height = fig_width*golden_mean # height in inches MAX_HEIGHT_INCHES = 8.0 if fig_height > MAX_HEIGHT_INCHES: print("WARNING: fig_height too large:" + fig_height + "so will reduce to" + MAX_HEIGHT_INCHES + "inches.") fig_height = MAX_HEIGHT_INCHES params = {'backend': 'pdf', 'text.latex.preamble': ['\\usepackage{gensymb}'], 'axes.labelsize': 8, # fontsize for x and y labels (was 10) 'axes.titlesize': 8, 'text.fontsize': 8, # was 10 'legend.fontsize': 8, # was 10 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'text.usetex': True, 'figure.figsize': [fig_width,fig_height], 'font.family': 'serif', 'lines.linewidth': 0.3, 'patch.linewidth': 0.2, #'dpi': 300, } pprint(params) matplotlib.rcParams.update(params) colors = [ (31, 119, 180), (255, 127, 14) ] colors = [(r/255., g/255., b/255.) for r, g, b in colors] if __name__ == '__main__': print "Reading data..." data = read_data() print "Plotting data..." plot_speeds(data)
[ 2, 15069, 1853, 44830, 260, 314, 293, 47083, 74, 16053, 33807, 290, 33728, 3454, 24172, 2004, 282, 406, 24172, 85, 1044, 198, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, ...
2.451052
1,093
# -*- coding: utf-8 -*- # Implementation by Pedro Maat C. Massolino, # hereby denoted as "the implementer". # # To the extent possible under law, the implementer has waived all copyright # and related or neighboring rights to the source code in this file. # http://creativecommons.org/publicdomain/zero/1.0/ # sidh_constants = [ [ "p16", # prime constant f 1, # prime constant ea 2, # prime constant eb 3, # prime constant la 8, # prime constant lb 5, # coordinate x of point PA - Real 0x7F4, # coordinate x of point PA - Imaginary 0x1641, # coordinate x of point QA - Real 0xDCC, # coordinate x of point QA - Imaginary 0x6DF, # coordinate x of point RA - Real 0x2490, # coordinate x of point RA - Imaginary 0x3796, # coordinate x of point PB - Real 0x64B7, # coordinate x of point PB - Imaginary 0x0, # coordinate x of point QB - Real 0x80A2, # coordinate x of point QB - Imaginary 0x0, # coordinate x of point RB - Real 0x65DC, # coordinate x of point RB - Imaginary 0xC5E0, # splits Alice [2, 1, 1], # max Alice row 4, # max Alice points 2, # splits Bob [2, 1, 1, 1], # max Bob row 5, # max Bob points 3, # SIKE SK length, also known as message length 16, # SIKE shared secret length 16, ], [ "p434", # prime constant f 1, # prime constant ea 2, # prime constant eb 3, # prime constant la 216, # prime constant lb 137, # coordinate x of point PA - Real 0x3CCFC5E1F050030363E6920A0F7A4C6C71E63DE63A0E6475AF621995705F7C84500CB2BB61E950E19EAB8661D25C4A50ED279646CB48, # coordinate x of point PA - Imaginary 0x1AD1C1CAE7840EDDA6D8A924520F60E573D3B9DFAC6D189941CB22326D284A8816CC4249410FE80D68047D823C97D705246F869E3EA50, # coordinate x of point QA - Real 0xC7461738340EFCF09CE388F666EB38F7F3AFD42DC0B664D9F461F31AA2EDC6B4AB71BD42F4D7C058E13F64B237EF7DDD2ABC0DEB0C6C, # coordinate x of point QA - Imaginary 0x25DE37157F50D75D320DD0682AB4A67E471586FBC2D31AA32E6957FA2B2614C4CD40A1E27283EAAF4272AE517847197432E2D61C85F5, # coordinate x of point RA - Real 0xF37AB34BA0CEAD94F43CDC50DE06AD19C67CE4928346E829CB92580DA84D7C36506A2516696BBE3AEB523AD7172A6D239513C5FD2516, # coordinate x of point RA - Imaginary 0x196CA2ED06A657E90A73543F3902C208F410895B49CF84CD89BE9ED6E4EE7E8DF90B05F3FDB8BDFE489D1B3558E987013F9806036C5AC, # coordinate x of point PB - Real 0x8664865EA7D816F03B31E223C26D406A2C6CD0C3D667466056AAE85895EC37368BFC009DFAFCB3D97E639F65E9E45F46573B0637B7A9, # coordinate x of point PB - Imaginary 0x0, # coordinate x of point QB - Real 0x12E84D7652558E694BF84C1FBDAAF99B83B4266C32EC65B10457BCAF94C63EB063681E8B1E7398C0B241C19B9665FDB9E1406DA3D3846, # coordinate x of point QB - Imaginary 0x0, # coordinate x of point RB - Real 0x1CD28597256D4FFE7E002E87870752A8F8A64A1CC78B5A2122074783F51B4FDE90E89C48ED91A8F4A0CCBACBFA7F51A89CE518A52B76C, # coordinate x of point RB - Imaginary 0x147073290D78DD0CC8420B1188187D1A49DBFA24F26AAD46B2D9BB547DBB6F63A760ECB0C2B20BE52FB77BD2776C3D14BCBC404736AE4, # splits Alice [43, 28, 16, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 7, 4, 2, 1, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 12, 7, 4, 2, 1, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 16, 11, 7, 4, 2, 1, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 4, 3, 2, 1, 1, 1, 1, 2, 1, 1, 7, 4, 2, 1, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1], # max Alice row 108, # max Alice points 8, # splits Bob [49, 33, 21, 13, 8, 5, 3, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 5, 3, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 8, 5, 3, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 12, 8, 5, 3, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 16, 12, 8, 5, 3, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 5, 3, 3, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1], # max Bob row 137, # max Bob points 10, # SIKE SK length, also known as message length 16, # SIKE shared secret length 16, ], [ "p503", # prime constant f 1, # prime constant ea 2, # prime constant eb 3, # prime constant la 250, # prime constant lb 159, # coordinate x of point PA - Real 0x0002ED31A03825FA14BC1D92C503C061D843223E611A92D7C5FBEC0F2C915EE7EEE73374DF6A1161EA00CDCB786155E21FD38220C3772CE670BC68274B851678, # coordinate x of point PA - Imaginary 0x001EE4E4E9448FBBAB4B5BAEF280A99B7BF86A1CE05D55BD603C3BA9D7C08FD8DE7968B49A78851FFBC6D0A17CB2FA1B57F3BABEF87720DD9A489B5581F915D2, # coordinate x of point QA - Real 0x00325CF6A8E2C6183A8B9932198039A7F965BA8587B67925D08D809DBF9A69DE1B621F7F134FA2DAB82FF5A2615F92CC71419FFFAAF86A290D604AB167616461, # coordinate x of point QA - Imaginary 0x003E7B0494C8E60A8B72308AE09ED34845B34EA0911E356B77A11872CF7FEEFF745D98D0624097BC1AD7CD2ADF7FFC2C1AA5BA3C6684B964FA555A0715E57DB1, # coordinate x of point RA - Real 0x003D24CF1F347F1DA54C1696442E6AFC192CEE5E320905E0EAB3C9D3FB595CA26C154F39427A0416A9F36337354CF1E6E5AEDD73DF80C710026D49550AC8CE9F, # coordinate x of point RA - Imaginary 0x0006869EA28E4CEE05DCEE8B08ACD59775D03DAA0DC8B094C85156C212C23C72CB2AB2D2D90D46375AA6D66E58E44F8F219431D3006FDED7993F51649C029498, # coordinate x of point PB - Real 0x0032D03FD1E99ED0CB05C0707AF74617CBEA5AC6B75905B4B54B1B0C2D73697840155E7B1005EFB02B5D02797A8B66A5D258C76A3C9EF745CECE11E9A178BADF, # coordinate x of point PB - Imaginary 0x0, # coordinate x of point QB - Real 0x0039014A74763076675D24CF3FA28318DAC75BCB04E54ADDC6494693F72EBB7DA7DC6A3BBCD188DAD5BECE9D6BB4ABDD05DB38C5FBE52D985DCAF74422C24D53, # coordinate x of point QB - Imaginary 0x0, # coordinate x of point RB - Real 0x0000C1465FD048FFB8BF2158ED57F0CFFF0C4D5A4397C7542D722567700FDBB8B2825CAB4B725764F5F528294B7F95C17D560E25660AD3D07AB011D95B2CB522, # coordinate x of point RB - Imaginary 0x00288165466888BE1E78DB339034E2B8C7BDF0483BFA7AB943DFA05B2D1712317916690F5E713740E7C7D4838296E67357DC34E3460A95C330D5169721981758, # splits Alice [61, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 29, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 13, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 5, 4, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1], # max Alice row 125, # max Alice points 7, # splits Bob [71, 38, 21, 13, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 5, 4, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 17, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 33, 17, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1], # max Bob row 159, # max Bob points 8, # SIKE SK length, also known as message length 24, # SIKE shared secret length 24, ], [ "p610", # prime constant f 1, # prime constant ea 2, # prime constant eb 3, # prime constant la 305, # prime constant lb 192, # coordinate x of point PA - Real 0x00000001B368BC6019B46CD802129209B3E65B98BC64A92BC4DB2F9F3AC96B97A1B9C124DF549B528F18BEECB1666D27D47530435E84221272F3A97FB80527D8F8A359F8F1598D365744CA3070A5F26C, # coordinate x of point PA - Imaginary 0x00000001459685DCA7112D1F6030DBC98F2C9CBB41617B6AD913E6523416CCBD8ED9C7841D97DF83092B9B3F2AF00D62E08DAD8FA743CBCCCC1782BE0186A3432D3C97C37CA16873BEDE01F0637C1AA2, # coordinate x of point QA - Real 0x0000000025DA39EC90CDFB9BC0F772CDA52CB8B5A9F478D7AF8DBBA0AEB3E52432822DD88C38F4E3AEC0746E56149F1FE89707C77F8BA4134568629724F4A8E34B06BFE5C5E66E0867EC38B283798B8A, # coordinate x of point QA - Imaginary 0x00000002250E1959256AE502428338CB4715399551AEC78D8935B2DC73FCDCFBDB1A0118A2D3EF03489BA6F637B1C7FEE7E5F31340A1A537B76B5B736B4CDD284918918E8C986FC02741FB8C98F0A0ED, # coordinate x of point RA - Real 0x00000001B36A006D05F9E370D5078CCA54A16845B2BFF737C865368707C0DBBE9F5A62A9B9C79ADF11932A9FA4806210E25C92DB019CC146706DFBC7FA2638ECC4343C1E390426FAA7F2F07FDA163FB5, # coordinate x of point RA - Imaginary 0x0000000183C9ABF2297CA69699357F58FED92553436BBEBA2C3600D89522E7009D19EA5D6C18CFF993AA3AA33923ED93592B0637ED0B33ADF12388AE912BC4AE4749E2DF3C3292994DCF37747518A992, # coordinate x of point PB - Real 0x00000001587822E647707ED4313D3BE6A811A694FB201561111838A0816BFB5DEC625D23772DE48A26D78C04EEB26CA4A571C67CE4DC4C620282876B2F2FC2633CA548C3AB0C45CC991417A56F7FEFEB, # coordinate x of point PB - Imaginary 0x0, # coordinate x of point QB - Real 0x000000014E647CB19B7EAAAC640A9C26B9C26DB7DEDA8FC9399F4F8CE620D2B2200480F4338755AE16D0E090F15EA1882166836A478C6E161C938E4EB8C2DD779B45FFDD17DCDF158AF48DE126B3A047, # coordinate x of point QB - Imaginary 0x0, # coordinate x of point RB - Real 0x00000001DB73BC2DE666D24E59AF5E23B79251BA0D189629EF87E56C38778A448FACE312D08EDFB876C3FD45ECF3746D96E2CADBBA08B1A206C47DDD93137059E34C90E2E42E10F30F6E5F52DED74222, # coordinate x of point RB - Imaginary 0x00000001B2C30180DAF5D91871555CE8EFEC76A4D521F877B754311228C7180A3E2318B4E7A00341FF99F34E35BF7A1053CA76FD77C0AFAE38E2091862AB4F1DD4C8D9C83DE37ACBA6646EDB4C238B48, # splits Alice [67, 37, 21, 12, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 16, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 33, 16, 8, 5, 2, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1 ], # max Alice row 152, # max Alice points 8, # splits Bob [86, 48, 27, 15, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 12, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 21, 12, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 38, 21, 12, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 17, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1], # max Bob row 192, # max Bob points 10, # SIKE SK length, also known as message length 24, # SIKE shared secret length 24, ], [ "p751", # prime constant f 1, # prime constant ea 2, # prime constant eb 3, # prime constant la 372, # prime constant lb 239, # coordinate x of point PA - Real 0x00004514F8CC94B140F24874F8B87281FA6004CA5B3637C68AC0C0BDB29838051F385FBBCC300BBB24BFBBF6710D7DC8B29ACB81E429BD1BD5629AD0ECAD7C90622F6BB801D0337EE6BC78A7F12FDCB09DECFAE8BFD643C89C3BAC1D87F8B6FA, # coordinate x of point PA - Imaginary 0x0000158ABF500B5914B3A96CED5FDB37D6DD925F2D6E4F7FEA3CC16E1085754077737EA6F8CC74938D971DA289DCF2435BCAC1897D2627693F9BB167DC01BE34AC494C60B8A0F65A28D7A31EA0D54640653A8099CE5A84E4F0168D818AF02041, # coordinate x of point QA - Real 0x00001723D2BFA01A78BF4E39E3A333F8A7E0B415A17F208D3419E7591D59D8ABDB7EE6D2B2DFCB21AC29A40F837983C0F057FD041AD93237704F1597D87F074F682961A38B5489D1019924F8A0EF5E4F1B2E64A7BA536E219F5090F76276290E, # coordinate x of point QA - Imaginary 0x00002569D7EAFB6C60B244EF49E05B5E23F73C4F44169A7E02405E90CEB680CB0756054AC0E3DCE95E2950334262CC973235C2F87D89500BCD465B078BD0DEBDF322A2F86AEDFDCFEE65C09377EFBA0C5384DD837BEDB710209FBC8DDB8C35C7, # coordinate x of point RA - Real 0x00006066E07F3C0D964E8BC963519FAC8397DF477AEA9A067F3BE343BC53C883AF29CCF008E5A30719A29357A8C33EB3600CD078AF1C40ED5792763A4D213EBDE44CC623195C387E0201E7231C529A15AF5AB743EE9E7C9C37AF3051167525BB, # coordinate x of point RA - Imaginary 0x000050E30C2C06494249BC4A144EB5F31212BD05A2AF0CB3064C322FC3604FC5F5FE3A08FB3A02B05A48557E15C992254FFC8910B72B8E1328B4893CDCFBFC003878881CE390D909E39F83C5006E0AE979587775443483D13C65B107FADA5165, # coordinate x of point PB - Real 0x0000605D4697A245C394B98024A5554746DC12FF56D0C6F15D2F48123B6D9C498EEE98E8F7CD6E216E2F1FF7CE0C969CCA29CAA2FAA57174EF985AC0A504260018760E9FDF67467E20C13982FF5B49B8BEAB05F6023AF873F827400E453432FE, # coordinate x of point PB - Imaginary 0x0, # coordinate x of point QB - Real 0x00005BF9544781803CBD7E0EA8B96D934C5CBCA970F9CC327A0A7E4DAD931EC29BAA8A854B8A9FDE5409AF96C5426FA375D99C68E9AE714172D7F04502D45307FA4839F39A28338BBAFD54A461A535408367D5132E6AA0D3DA6973360F8CD0F1, # coordinate x of point QB - Imaginary 0x0, # coordinate x of point RB - Real 0x000055E5124A05D4809585F67FE9EA1F02A06CD411F38588BB631BF789C3F98D1C3325843BB53D9B011D8BD1F682C0E4D8A5E723364364E40DAD1B7A476716AC7D1BA705CCDD680BFD4FE4739CC21A9A59ED544B82566BF633E8950186A79FE3, # coordinate x of point RB - Imaginary 0x00005AC57EAFD6CC7569E8B53A148721953262C5B404C143380ADCC184B6C21F0CAFE095B7E9C79CA88791F9A72F1B2F3121829B2622515B694A16875ED637F421B539E66F2FEF1CE8DCEFC8AEA608055E9C44077266AB64611BF851BA06C821, # splits Alice [80, 48, 27, 15, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 12, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 21, 12, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 33, 20, 12, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 8, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1], # max Alice row 186, # max Alice points 8, # splits Bob [112, 63, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 31, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 15, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 49, 31, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 15, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 21, 12, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1], # max Bob row 239, # max Bob points 10, # SIKE SK length, also known as message length 32, # SIKE shared secret length 32, ], [ "p964", # prime constant f 1, # prime constant ea 2, # prime constant eb 3, # prime constant la 486, # prime constant lb 301, # coordinate x of point PA - Real 0x68bef5878630cacfeae7a298e819599beb99b10302b182af578b391e5cda524b118309bab2e1bf4309791cae8da4c5cde3b7b4250ed70142e9f7c0d1372827364cc48dd8f0259eaab40ed0ada021d7da417580420eb7549d557ee61efcc10f37ddc3966e713688864cc039407826bb88f8f8ac8fe05c4f3c7, # coordinate x of point PA - Imaginary 0x485fb8aafa5e3911e8a37afa878d64f50992e871f319896628fcb3ebbc1d26612865da8421149194fc71276b24a74e1b7d419fc69ed8af12265c453122cdb82383074531903d08df90cb2949c7628a2610415e72ed7655875ba6647601d0b2807eee627bb34810ec216f0219d926118d92f17e93ad6121c38, # coordinate x of point QA - Real 0x7e8b1ede7beae1754fb0a85628976a6f005ade35e5ff571708d24f64ffa84fbd401460b6c33ea875aca78db174f13e60d7ac89fc272dc0983a688df6efdb3868a8997dd8904604eaecc8e3d84ce3824d9068a5a724682b5e451d8f013b907da2f5bb525b14e9048e0852e5b698f8257495e41fb10e906c286, # coordinate x of point QA - Imaginary 0x642356fec8a2b492e288552e1fee2361bb693e6b06c913c409a25dace870e1744735c9adb5db19ad38a9acbe6cf7fe6b494624a0e7625961a4f429fe7ec299721edb10979aee619e4c053425958e411b7534ac07a116c47ad231121f467119058ab7e956a307895a2b69da9bc74957090bceaf5af890243bb, # coordinate x of point RA - Real 0x1608bb0c053e0ade53496ecab043f175afc0e3c220d6554bd76b6993ef0244eab975235d9acc5df2cd9884b79fba39459a3f1378d6f9e38bf41d9c5e9da7b36c80843f2041911185d4dfe6c354119449f9b2939ccfc9a1da114811151dfe8462621231241c6cae3af1963ec0d0106c81c03e4f84eb4f4744c, # coordinate x of point RA - Imaginary 0x124e20052856af1cf5b9e703d8adba71c1e16a347ef81e89cebed9193288397fa9eaa65988e7d9c8a0062c40dff84652672fee2da8ea7999da4d8027c230110e670b6500e77f922e580836561abce09267cd2570dc483728ae68987ee62d1e1fe3cc6201c41bdb3b0b4a8a250e3a58a4998b25551ae1bd6d4, # coordinate x of point PB - Real 0x1be3eb6a2ae87afe407b460477b8ba71bc5803c17192c1196b42bc25641d1fc7b1ab309c5f35bc6ffc640aaea99a9d483a4e518e3a3e9b5047aa234b999715fd3cfdc7bec233e0416ab93cc9d7a7a4e8cb0d6dd5f5f1941916bec1789c8971ce5ac427e0c1a58cf2977cbccd6ac35cefe18f0136d786b75a4, # coordinate x of point PB - Imaginary 0x0, # coordinate x of point QB - Real 0x804d52906d63c6a0e62f3cdecfc302e45eb77c0d5da00dd7f370b9985db1e305f05fd0936a020ca9c0451c959fb43668cfafb8bacf31b9aeec4196bfd04a390a725e30a3e5c69ea95f8bcf77bf2706186fec41aa60c24a143d40bebacdcb2e599e77e9b96311744ed07cbc9fa58466b66afdda9afcbf2339, # coordinate x of point QB - Imaginary 0x0, # coordinate x of point RB - Real 0x5870a37b0a265936d2c7888fc5f0a680662ad048ec48c97a1fc0a566bfc90fb2699a6f0129aa5990ef3ff37b16e6926249bcb9bfeac0573d5dd43e47fd1db4b39df9e6b85db757595a29319a74174db4abce551ddf3fdc0b3488f05f1b1d4c90c9de7c649a5703342b9bdddee9b7155e7bbdd25951910a370, # coordinate x of point RB - Imaginary 0x83294bd875073a5dc2373312e0bf8ece4130c32edc320bb53e4ebabac7e243fdc5a69d995f0ef01ea15f947b4f1dbe377e9d1c6ae1f9f539fdb78cd3be150d8eee2a89f43e06c51adf2c909c15a82c2c362bf94e4548e1df2f8e99a0cfc19f41285e91af33e850ce208b34141335f4a4758376baa7b659606, # splits Alice [116, 63, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 31, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 15, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 53, 31, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 15, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 22, 15, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 9, 5, 4, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1], # max Alice row 243, # max Alice points 10, # splits Bob [136, 71, 38, 25, 15, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 10, 7, 4, 2, 1, 1, 2, 1, 1, 3, 2, 1, 1, 1, 1, 4, 2, 2, 1, 1, 1, 2, 1, 1, 17, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 33, 17, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 65, 33, 17, 9, 5, 3, 2, 1, 1, 1, 1, 2, 1, 1, 1, 4, 2, 1, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 32, 16, 8, 4, 2, 1, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1], # max Bob row 301, # max Bob points 12, # SIKE SK length, also known as message length 32, # SIKE shared secret length 32, ] ]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 201, 198, 2, 46333, 416, 28855, 6669, 265, 327, 13, 5674, 349, 2879, 11, 201, 198, 2, 29376, 2853, 5191, 355, 366, 1169, 3494, 263, 1911, 201, 198, 2, 201, 198,...
1.808734
10,786
# Copyright 2019 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. """Tests for app specific trials and experiments.""" import json from pyfakefs import fake_filesystem_unittest from clusterfuzz._internal.bot.tasks import trials from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.system import environment from clusterfuzz._internal.tests.test_libs import helpers as test_helpers from clusterfuzz._internal.tests.test_libs import test_utils @test_utils.with_cloud_emulators('datastore') class TrialsTest(fake_filesystem_unittest.TestCase): """Tests for trials.""" def source_side_test(self, config_file_content, probability, app_name, app_args, trial_app_args): """Source side trials test template.""" self.fs.create_file('/src/clusterfuzz_trials_config.json') with open('/src/clusterfuzz_trials_config.json', 'w') as f: f.write(json.dumps(config_file_content)) self.mock.random.return_value = probability environment.set_value('APP_NAME', app_name) trial_selector = trials.Trials() trial_selector.setup_additional_args_for_app() self.assertEqual(environment.get_value('APP_ARGS'), app_args) self.assertEqual(environment.get_value('TRIAL_APP_ARGS'), trial_app_args) def test_no_effect_on_no_match(self): """Ensure that no additional flags are added if a binary has no trials.""" self.mock.random.return_value = 0.0 environment.set_value('APP_NAME', 'app_0') trial_selector = trials.Trials() trial_selector.setup_additional_args_for_app() self.assertEqual(environment.get_value('APP_ARGS'), '-x') self.assertIsNone(environment.get_value('TRIAL_APP_ARGS')) def test_trial_selected_one_option(self): """Ensure that the expected flags are added if a trial is selected.""" self.mock.random.return_value = 0.3 environment.set_value('APP_NAME', 'app_1') trial_selector = trials.Trials() trial_selector.setup_additional_args_for_app() self.assertEqual(environment.get_value('APP_ARGS'), '-x --a1') self.assertEqual(environment.get_value('TRIAL_APP_ARGS'), '--a1') def test_trial_not_selected(self): """Ensure no additional flags if a trial was not selected.""" self.mock.random.return_value = 0.5 environment.set_value('APP_NAME', 'app_2') trial_selector = trials.Trials() trial_selector.setup_additional_args_for_app() self.assertEqual(environment.get_value('APP_ARGS'), '-x') self.assertIsNone(environment.get_value('TRIAL_APP_ARGS')) def test_multiple_trial_selection(self): """Ensure that we can suggest the second trial in a batch of multiple.""" self.mock.random.return_value = 0.1 environment.set_value('APP_NAME', 'app_3') trial_selector = trials.Trials() trial_selector.setup_additional_args_for_app() self.assertEqual(environment.get_value('APP_ARGS'), '-x --c1 --c2 --c3') self.assertEqual(environment.get_value('TRIAL_APP_ARGS'), '--c1 --c2 --c3') def test_selection_for_windows_executable(self): """Ensure that flags are added when the app name ends in ".exe".""" self.mock.random.return_value = 0.3 environment.set_value('APP_NAME', 'app_1.exe') trial_selector = trials.Trials() trial_selector.setup_additional_args_for_app() self.assertEqual(environment.get_value('APP_ARGS'), '-x --a1') self.assertEqual(environment.get_value('TRIAL_APP_ARGS'), '--a1') def test_selection_for_android_apk(self): """Ensure that flags are added for the Android APK format.""" self.mock.random.return_value = 0.3 environment.set_value('APP_NAME', 'App_1.apk') trial_selector = trials.Trials() trial_selector.setup_additional_args_for_app() self.assertEqual(environment.get_value('APP_ARGS'), '-x --a1') self.assertEqual(environment.get_value('TRIAL_APP_ARGS'), '--a1') def test_no_effect_on_no_match_source_side(self): """Ensure that no additional flags are added if a binary has no trials on source side.""" config_file_content = [{ "app_args": "--c4", "app_name": "app_4", "probability": 0.2 }] self.source_side_test(config_file_content, 0.0, 'app_0', '-x', None) def test_trial_selected_one_option_source_side(self): """Ensure that the expected flags are added if a trial is selected on source side.""" config_file_content = [{ "app_args": "--c4", "app_name": "app_4", "probability": 0.5 }] self.source_side_test(config_file_content, 0.3, 'app_4', '-x --c4', '--c4') def test_trial_not_selected_source_side(self): """Ensure no additional flags if a trial was not selected on source side.""" config_file_content = [{ "app_args": "--c4", "app_name": "app_4", "probability": 0.4 }, { "app_args": "--c5", "app_name": "app_4", "probability": 0.2 }] self.source_side_test(config_file_content, 0.5, 'app_4', '-x', None) def test_multiple_trial_selection_source_side(self): """Ensure that we can suggest the second trial in a batch of multiple on source side.""" config_file_content = [{ "app_args": "--c4", "app_name": "app_4", "probability": 1.0 }, { "app_args": "--c5", "app_name": "app_4", "probability": 0.2 }, { "app_args": "--c6", "app_name": "app_4", "probability": 0.2 }] self.source_side_test(config_file_content, 0.1, 'app_4', '-x --c4 --c5 --c6', '--c4 --c5 --c6') def test_selection_for_windows_executable_source_side(self): """Ensure that flags are added when the app name ends in ".exe" on source side.""" config_file_content = [{ "app_args": "--c4", "app_name": "app_4", "probability": 1.0 }] self.source_side_test(config_file_content, 0.3, 'app_4.exe', '-x --c4', '--c4') def test_selection_for_android_apk_source_side(self): """Ensure that flags are added for the Android APK format on source side.""" config_file_content = [{ "app_args": "--c4", "app_name": "app_4", "probability": 1.0 }] self.source_side_test(config_file_content, 0.3, 'App_4.apk', '-x --c4', '--c4') def test_trial_args_adding_using_config_file(self): """Ensure that a trial can add args using the config file.""" config_file_content = [{ "app_args": "--c4", "app_name": "app_1", "probability": 0.5 }] self.source_side_test(config_file_content, 0.3, 'app_1', '-x --a1 --c4', '--a1 --c4') def test_trial_probability_override_using_config_file(self): """Ensure that a trial probability can be overriden using the config file.""" config_file_content = [{ "app_args": "--a1", "app_name": "app_1", "probability": 0.8 }] self.source_side_test(config_file_content, 0.7, 'app_1', '-x --a1', '--a1') def test_corrupted_config_file_is_ignored(self): """Ensure that a trial probability will not be overriden using a corrupted config file.""" config_file_content = '[{"app_args": "--a1", "app_name": "app_1", "probability": 0.8]' self.source_side_test(config_file_content, 0.7, 'app_1', '-x', None)
[ 2, 15069, 13130, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
2.466667
3,165
#open files for reading inFile = open("inFile.txt", "r") inFile2 = open("stolen.txt", "r") #initialize dictionary D = {} for line in inFile: #find lines with 7 characters for the license plates and store into dictionary #dictionary holds total percentage and total occurences if line[4] == '-': temp = line.split(" ") if len(temp[5]) == 8: #first instance of characters if D.get(temp[5]) == None: D[temp[5]] = [float(temp[7][:5]), 1] #every other instance found characters else: x = D[temp[5]] D[temp[5]][0] = x[0] + float(temp[7][:5]) D[temp[5]][1] = x[1] + 1 #calculate the average percentage of each finalList = [] for i in D.keys(): finalList.append( [i, D[i][0]/D[i][1]] ) highOcc = 0 highPlates = '0' highest = 0 j = 0 #find the highest occured plate for i in D.keys(): j = j+1 if highOcc < D[i][1]: highOcc = D[i][1] highPlates = i highest = finalList[j][1] #if highest occured is the same, choose the highest average percentage elif highOcc == D[i][1]: if(finalList[j][1] > highest): highOcc = D[i][1] highPlates = i highest = finalList[j][1] #look through the database and print if stolen plate is found done = 0 print highPlates print "Average Confidence: ", str(highest) print "Occured ", str(highOcc), " times" for line in inFile2: if line[:7] == highPlates[:7]: print "IS A STOLEN PLATE" done = 1 break if done == 0: print "NOT A STOLEN PLATE" inFile.close() inFile2.close()
[ 2, 9654, 3696, 329, 3555, 198, 259, 8979, 796, 1280, 7203, 259, 8979, 13, 14116, 1600, 366, 81, 4943, 198, 259, 8979, 17, 796, 1280, 7203, 301, 8622, 13, 14116, 1600, 366, 81, 4943, 198, 198, 2, 36733, 1096, 22155, 198, 35, 796, 2...
2.173177
768
import os import numpy as np import json from io import BytesIO import time import argparse import requests from cli import DefaultArgumentParser from client import Client from s3client import ObjectStorageClient from zounds.persistence import DimensionEncoder, DimensionDecoder import zounds from mp3encoder import encode_mp3 from http import client from pathlib import Path import soundfile
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 33918, 198, 6738, 33245, 1330, 2750, 4879, 9399, 198, 11748, 640, 198, 11748, 1822, 29572, 198, 198, 11748, 7007, 198, 6738, 537, 72, 1330, 15161, 28100, 1713, 46677, 198, 6738...
3.903846
104
#!/usr/bin/python ''' 1. blo m8 format output 2. query file length 3. allowed mismatch ''' from sys import argv from collections import defaultdict try: blom8f = open(argv[1]) lenf = open(argv[2]) allowedMM = int(argv[3]) except: exit(__doc__) lenD = defaultdict(int) for l in lenf: segs = l.rstrip().split('\t') seqName, seqLen = segs[:2] lenD[seqName] = int(seqLen) lenf.close() for l in blom8f: ''' segs[0] col_1 KRAS_p.G12A_c.35G>C_mut segs[1] col_2 NC_000020.11 segs[2] col_3 100.000 segs[3] col_4 14 segs[4] col_5 0 segs[5] col_6 0 segs[6] col_7 1 segs[7] col_8 14 segs[8] col_9 47942880 segs[9] col_10 47942867 segs[10] col_11 101 segs[11] col_12 26.5 ''' segs = l.rstrip().split('\t') q, h, perc, M, m, g, qs, qe, s, e, evalue, score = segs hitCoord = '|'.join([h, s, e]) qlen = lenD[q] match = int(M) - int(m) - int(g) mm = qlen - match if mm <= allowedMM: print l.rstrip() blom8f.close()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 7061, 6, 198, 16, 13, 24924, 285, 23, 5794, 5072, 220, 198, 17, 13, 12405, 2393, 4129, 198, 18, 13, 3142, 46318, 198, 7061, 6, 198, 6738, 25064, 1330, 1822, 85, 198, 6738, 17268, 133...
1.821366
571
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np import pickle from tqdm import tqdm import os import logging import torch from torch.utils.data import Dataset, DataLoader from utility.utils import MODEL_CLASSES
[ 2, 15069, 357, 66, 8, 5413, 10501, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2298, 293, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 11748, 28686, 198, 11748, 18931, ...
3.16092
87
from collections import OrderedDict from decimal import Decimal from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from django.db import transaction from django.utils import six from django.utils.module_loading import import_string from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import force_text from rest_framework import serializers, exceptions from rest_framework.utils import html from rest_framework.exceptions import ValidationError from oscar.core.loading import get_model, get_class from oscarapi.serializers.checkout import ( CheckoutSerializer as OscarCheckoutSerializer, OrderSerializer as OscarOrderSerializer, ) from oscarapi.basket.operations import get_basket from .signals import pre_calculate_total from .states import PENDING from . import utils, settings Basket = get_model('basket', 'Basket') Order = get_model('order', 'Order') BillingAddress = get_model('order', 'BillingAddress') ShippingAddress = get_model('order', 'ShippingAddress') OrderTotalCalculator = get_class('checkout.calculators', 'OrderTotalCalculator') class DiscriminatedUnionSerializer(serializers.Serializer): """ Serializer for building a discriminated-union of other serializers Usage: DiscriminatedUnionSerializer( # (string) Field name that will uniquely identify which serializer to use. discriminant_field_name="some_field_name", # (dict <string: serializer class>) Dictionary that indicates which # serializer class should be used, based on the value of ``discriminant_field_name``. types={ "some_choice_in_some_field_name": SomeSerializer(), ... } # Other serializers.Serializer arguments ) See this documentation for a good introduction to the concept of discriminated unions. - https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions - https://en.wikipedia.org/wiki/Tagged_union """ class PaymentMethodsSerializer(serializers.DictField): """ Dynamic serializer created based on the configured payment methods (settings.API_ENABLED_PAYMENT_METHODS) """ def to_internal_value(self, data): """Dicts of native values <- Dicts of primitive datatypes.""" if html.is_html_input(data): data = html.parse_html_dict(data) if not isinstance(data, dict): self.fail('not_a_dict', input_type=type(data).__name__) return self.run_child_validation(data)
[ 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 19200, ...
3.042503
847
from tooz import coordination coordinator = coordination.get_coordinator('zake://', b'host-1') coordinator.start() partitioner = coordinator.join_partitioned_group("group1") # Returns {'host-1'} member = partitioner.members_for_object(object()) coordinator.leave_partitioned_group(partitioner) coordinator.stop()
[ 6738, 1165, 89, 1330, 19877, 198, 198, 37652, 20900, 796, 19877, 13, 1136, 62, 37652, 20900, 10786, 89, 539, 1378, 3256, 275, 6, 4774, 12, 16, 11537, 198, 37652, 20900, 13, 9688, 3419, 198, 3911, 653, 263, 796, 16052, 13, 22179, 62, ...
3.16
100
''' Roll your dice ''' # to get help help(str.split) import random x= '' while x != 'xit': ''' randint - A random integer takes in range [start, end] including the end points. every time we execute randint it will give random values from 1 thru 6 including 1 and 6 ''' print(random.randint(1, 6)) x= input('Roll the dice again, xit to Exit')
[ 7061, 6, 198, 26869, 534, 17963, 198, 7061, 6, 198, 198, 2, 284, 651, 1037, 198, 16794, 7, 2536, 13, 35312, 8, 198, 198, 11748, 4738, 198, 198, 87, 28, 10148, 198, 4514, 2124, 14512, 705, 10198, 10354, 198, 220, 220, 220, 705, 706...
2.838462
130
"""test_train/conftest.py. Tests blocks and networks are differentiable and trainable """
[ 37811, 9288, 62, 27432, 14, 1102, 701, 395, 13, 9078, 13, 198, 198, 51, 3558, 7021, 290, 7686, 389, 1180, 3379, 290, 4512, 540, 198, 37811, 198 ]
3.37037
27
import torch from torch import nn from models.tabular.TabModelBase import TabModelBase class TabMLP(TabModelBase): """ Straightforward MLP model for tabular data, loosely based on github.com/fastai/fastai/blob/master/fastai/tabular layer_sizes can contain ints, indicating the # of hidden units, or floats, indicating multiples of init_feat_dim """ def forward(self, input): """ Returns logits for output classes """ # t = time.perf_counter() cat_feats, cont_feats = input cat_feats = [init(cat_feats[:, i]) for i, init in enumerate(self.cat_initializers.values())] if cat_feats != []: cat_feats = torch.cat(cat_feats, dim=1) # if self.training: # self.writer.add_scalar('CodeProfiling/Model/TabMLPInitCatFeatures', time.perf_counter() - t, # self.writer.batches_done) # t = time.perf_counter() if isinstance(cont_feats, torch.Tensor): cont_feats = self.cont_norm(cont_feats) if isinstance(cat_feats, torch.Tensor) and isinstance(cont_feats, torch.Tensor): feats = torch.cat((cat_feats, cont_feats), dim=1) elif isinstance(cat_feats, torch.Tensor): feats = cat_feats else: feats = cont_feats out = self.layers(feats) if self.act_on_output: out = self.get_act()(out) # if self.training: # self.writer.add_scalar('CodeProfiling/Model/TabMLPLayers', time.perf_counter() - t, # self.writer.batches_done) return out
[ 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 198, 6738, 4981, 13, 8658, 934, 13, 33349, 17633, 14881, 1330, 16904, 17633, 14881, 628, 198, 4871, 16904, 5805, 47, 7, 33349, 17633, 14881, 2599, 198, 220, 220, 220, 37227, 198, 220, ...
2.14941
763
# -*- coding: utf-8 -*- import logging import os import re import arrow import requests from bs4 import BeautifulSoup from nightwatch_imax.movie import is_imax_movie from nightwatch_imax.schedule import create_schedule_info, save_schedule_list logger = logging.getLogger() logger.setLevel(logging.INFO)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 302, 198, 198, 11748, 15452, 198, 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 198, 6738, 1755, 8340, 6...
2.961905
105
import PySimpleGUI as sg sg.theme('DarkBlue16') pw = "" b64Img = b'iVBORw0KGgoAAAANSUhEUgAAAC8AAAAtCAYAAAA+7zKnAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAACxMAAAsTAQCanBgAAANpSURBVGhDzZlbSBVBGMd3SzO60wUigoqoh4goiiCIkkKiIBCV5Gh0ewgCK3qLKILo8hZIV+glo7weRUqyMIp8K8wKioiEgiyoh8IyUbxsv29nk3M8xzyXmfH84M/MN0fc/8x+Mzs76zrjSFVNeAXFLfQ8Qu9DxUWDlGMy3uZXUbxW0TC/0As03CFvKKuzJJRPNRor5sPhRqd/cEBGeTOa4Tc6zmPUh0aaj8dXFHl32vr7erqMm2d0Z1HcQIVIzHYj4QpqQImYH8kQajNqHuOTKVrRHFSGWsjnAUqfUdImUX5OCCqmOIaWoVxMN0ca14Ex8w0NkhHOPlSB6c8S6CZp89zqbHQB3UZLguYY+vqHsiiWojd+gwFSGfn96DgqRS10YL40xuLJfJL/rzVVIknF/KKgFGRkm+nATBXaRUfOr0aNVbX+ymIVHeaFXMdz7lTXhCcGsRV0mRcKPMe5yh2wtuVwydd5lDIJp/otY7MFbVTVuJydNiXnVHdPLwPjviI+ylL5RP0UDddO6yEl5p9S2aRibRzG8OWgPirpmpe0WavqWinHWHFQN4aYN5Gj8n8r6ECeCs2gc8KOJAfV04F1KtSPSfPCdHSfDixXoV5MmxdkNXtIBxaoUB82zAuLUVN1dZ3W69kyL6zxXHdhUNeCTfPtqFNV9WDL/Ee0kweXvHtqw4b572gbxuUEQCumzf9GOzD+QYV6MWlejjkKMC4HSEYQ8+xktSO5vQfjj1RoBjHfpqpaOYLx2qBuDNkSz6XcixLdz29F/9tCn3G9gdOOm+16jneN+BIdeat+ioZrp7efDyoJwwXPUZxQUQzXGY9DoeJC/q4um7rk/QHM31Q/R5OueZ0Tth6ViXFb6DIvr3mljHBC5+q60GH+JcrHuKSIVVIx/ykohQ60HePyQcA6yZt3HZl855F8jsnD+DdpjoXFRh31TfJDA5g+n5eV5BkdPKhaosmk1SYeLJ3ObkyuVKFeTI+8HP/dRevRSXQPdSFJqV4kncrMkQ+WzgIk86McfUHyTeoPuohSRTr/0tq5IndhNsUG9O9roHzVky1JMiP/DlWJGJgOa+bjkeCElVfHGlRJkreHdhX5jUKmmv+BZLtRSX60lozy+phJ5ntQE6pED0iLMZ/Y421evorLxBXDjRhO4kntOH8BhCoR5A1uBiEAAAAASUVORK5CYII=' path =r"C:\\Users\\rober\\PycharmProjects\\Password-Generator\\lock.png" col = [[sg.Button("", image_data=b64Img, button_color=(sg.theme_background_color(), sg.theme_background_color()), border_width=0, key='exitgen', tooltip="Exits the password generator")]] generatorly = [[sg.Column(col, justification="right")], [sg.Text('Password Generator', pad=(0, 40), font="SegoeUI 35")], [sg.Text('Click on generate for a password!', font="SegoeUI 16")], [sg.Image(path), sg.InputText(justification="center", text_color="black", disabled=True, font="SegoeUI 16", size=(16, 10), key="generatedPW"), sg.Button("Copy", tooltip="Copies the password to clipboard", key="copy", border_width=0, font="SegoeUI 13")], [sg.Button('Generate', key="gen", border_width=0, font="SegoeUI 13")], [sg.Button("2", button_color=("#1c44ac", "#1c44ac"), border_width=0, key="btn2")]] # Create the Window genWindow = sg.Window('Password Generator', generatorly,size=(640, 480), element_justification="center", keep_on_top=True, no_titlebar=True, grab_anywhere=True, ttk_theme="DarkBlue16")
[ 11748, 9485, 26437, 40156, 355, 264, 70, 628, 198, 45213, 13, 43810, 10786, 17367, 14573, 1433, 11537, 220, 220, 198, 79, 86, 796, 13538, 198, 65, 2414, 3546, 70, 796, 275, 6, 72, 44526, 1581, 86, 15, 42, 38, 2188, 29697, 1565, 1256...
1.695985
1,569
from hitch import Hitch from hitch.macros import Macros from hitch import HitchUtils from os import getcwd from os.path import join as pjoin
[ 6738, 35996, 1330, 36456, 198, 6738, 35996, 13, 20285, 4951, 1330, 4100, 4951, 198, 6738, 35996, 1330, 36456, 18274, 4487, 198, 6738, 28686, 1330, 651, 66, 16993, 198, 6738, 28686, 13, 6978, 1330, 4654, 355, 279, 22179, 628, 198 ]
3.666667
39
import pigpio from read_encoder import decoder _pi = pigpio.pi() if not _pi.connected: raise IOError("Can't connect to pigpio") DECODER_LEFT_PINS = (20,21) DECODER_RIGHT_PINS = (19,16)
[ 11748, 12967, 79, 952, 198, 6738, 1100, 62, 12685, 12342, 1330, 875, 12342, 198, 198, 62, 14415, 796, 12967, 79, 952, 13, 14415, 3419, 198, 361, 407, 4808, 14415, 13, 15236, 25, 198, 220, 220, 220, 5298, 24418, 12331, 7203, 6090, 470,...
2.329268
82
from kivy.clock import Clock class Rotator(object): ''' A class that handles the rotation of widgets ''' def rotate_this(self, widget): ''' Starts rotating the given widget ''' self.widgets.append(widget) if len(self.widgets) == 1: Clock.schedule_interval(self.rotate, 0.05)
[ 6738, 479, 452, 88, 13, 15750, 1330, 21328, 628, 198, 4871, 18481, 1352, 7, 15252, 2599, 198, 220, 220, 220, 705, 7061, 317, 1398, 326, 17105, 262, 13179, 286, 40803, 705, 7061, 628, 220, 220, 220, 825, 23064, 62, 5661, 7, 944, 11, ...
2.515625
128
import pyaudio import scipy.io.wavfile as wavfile import matplotlib.pylab as plt import numpy as np import wave from scipy.fft import fft, fftfreq from playsound import playsound ## Reproducir audio playsound('/home/angie/Git/python_dsp/alejandro.wav') ## trear, extraer y gráficar los datos de audio fs, data = wavfile.read("alejandro.wav") plt.figure(1) plt.plot(data) plt.grid() ## aplicar transformada a la señalgir l = len(data) t = 1/fs x = np.linspace(0.0, l*t, l) yf = fft(data) xf = fftfreq(l, t)[:l//2] plt.figure(2) plt.plot(xf, 2.0/l * np.abs(yf[0:l//2])) plt.grid() plt.show()
[ 11748, 12972, 24051, 198, 11748, 629, 541, 88, 13, 952, 13, 45137, 7753, 355, 266, 615, 7753, 198, 11748, 2603, 29487, 8019, 13, 79, 2645, 397, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 6769, 198, 198, 6738, 629, ...
2.186813
273
import probRobScene from pyrep import PyRep from pyrep.objects import Camera import numpy as np import sys from probRobScene.wrappers.coppelia.prbCoppeliaWrapper import cop_from_prs if len(sys.argv) != 2: print("python3 coppeliaView.py <path-to-scenario-file>") sys.exit(0) scenario_file = sys.argv[1] scenario = probRobScene.scenario_from_file(scenario_file) pr = PyRep() pr.launch("scenes/emptyVortex.ttt", headless=False, responsive_ui=True) ex_world, used_its = scenario.generate() c_objs = cop_from_prs(pr, ex_world) pr.start() pr.step() pr.stop() input("Simulation Finished. To Quit, Press Enter") pr.shutdown()
[ 11748, 1861, 14350, 36542, 198, 6738, 12972, 7856, 1330, 9485, 6207, 198, 6738, 12972, 7856, 13, 48205, 1330, 20432, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 25064, 198, 6738, 1861, 14350, 36542, 13, 29988, 11799, 13, 1073, 381, 25...
2.644351
239
# coding: utf-8 # by Joao Bueno from random import randrange, choice import pygame FR = 30 SIZE = 640, 480 BGCOLOR = (255,255,255) NODECOLOR = (255,0,255) NODESIZE = 20,20 GRIDSPACING = 50 MAXTRIES = 1000 STARTINGNODES = 7 #need to eventually get to 20... # Pattern in Python to make the same module # be reusable as main program or importable module: # if the builtin "__name__" variable is set to "__main__" # this is the main module, and should perform some action # (otherwise it is set to the module name) if __name__ == "__main__": main()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 416, 5302, 5488, 9842, 23397, 198, 6738, 4738, 1330, 43720, 9521, 11, 3572, 198, 11748, 12972, 6057, 198, 198, 10913, 796, 1542, 198, 33489, 796, 33759, 11, 23487, 198, 33, 15916, 3535, 1581, ...
2.880208
192
@apply
[ 31, 39014, 198 ]
2.333333
3
# -*- coding: utf-8 -*- from collections import OrderedDict import numpy as np import math import h5py as h5 from ...autograd import Variable class Module(object): '''Base class for all neural network modules in qualia.\n Module can incoporate Modules, allowing to nest them in a tree structure. Examples:: >>> class DeepConvNet(Module): >>> def __init__(self): >>> super().__init__() >>> # (N,1,28,28) -> (N,16,28,28) >>> self.conv1 = Conv2d(1, 16, 5, padding=2) >>> # (N,16,28,28) -> (N,16,14,14) >>> self.pool1 = MaxPool2d((2,2)) >>> # (N,16,14,14) -> (N,16,14,14) >>> self.conv2 = Conv2d(16, 16, 5, padding=2) >>> # (N,16,14,14) -> (N,16,7,7) >>> self.pool2 = MaxPool2d((2,2)) >>> # Reshape >>> self.linear1 = Linear(16*7*7, 128) >>> self.linear2 = Linear(128, 10) >>> >>> def forward(self, x): >>> x = leakyrelu(self.conv1(x)) >>> x = self.pool1(x) >>> x = leakyrelu(self.conv2(x)) >>> x = self.pool2(x) >>> x = reshape(x, (-1, 16*7*7)) >>> x = leakyrelu(self.linear1(x)) >>> x = leakyrelu(self.linear2(x)) >>> return x ''' def save(self, filename): '''Saves internal parameters of the Module in HDF5 format.\n Args: filename (str): specify the filename as well as the saving path without the file extension. (ex) path/to/filename ''' with h5.File(filename + '.hdf5', 'w') as file: if not self._modules: for key, value in self._params.items(): file.create_dataset(str(key), dtype='f8', data=value.data) else: for name, module in self._modules.items(): grp = file.create_group(str(name)) for key, value in module._params.items(): grp.create_dataset(str(key), dtype='f8', data=value.data) def load(self, filename): '''Loads parameters saved in HDF5 format to the Module.\n Args: filename (str): specify the filename as well as the path to the file without the file extension. (ex) path/to/filename ''' with h5.File(filename + '.hdf5', 'r') as file: if not self._modules: for i in file: self._params[i].data = np.array(file[i]) else: for i in file: for j in file[i]: self._modules[i]._params[j].data = np.array(file[i][j]) class Sequential(Module): r'''A sequential container.\n Modules will be added to it in the order they are passed in the constructor. Examples:: >>> # model can be defiened by adding Modules >>> model = Sequential( >>> nn.Conv2d(1,20,5), >>> nn.ReLU(), >>> nn.Conv2d(20,64,5), >>> nn.ReLU() >>> ) >>> # name for each layers can also be specified >>> model = Sequential( >>> 'conv1' = nn.Conv2d(1,20,5), >>> 'relu1' = nn.ReLU(), >>> 'conv2' = nn.Conv2d(20,64,5), >>> 'relu2' = nn.ReLU() >>> ) '''
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 220, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 220, 198, 11748, 299, 32152, 355, 45941, 220, 198, 11748, 10688, 220, 198, 11748, 289, 20, 9078, 355, 289, 20, 220, 198, ...
1.854796
1,887
close_price = driver.find_element_by_xpath( "/html/body/div[2]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[2]/div[1]/div[2]/div/div[4]/div[2]" ).text open_price = driver.find_element_by_xpath( "/html/body/div[2]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[2]/div[1]/div[2]/div/div[1]/div[2]" ).text ema20 = driver.find_element_by_xpath( "/html/body/div[2]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[2]/div[2]/div[2]/div[2]/div[3]/div/div/div" ).text vol = driver.find_element_by_xpath( "/html/body/div[2]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[2]/div[2]/div[2]/div[3]/div[3]/div/div[1]/div" ).text vol_ema = driver.find_element_by_xpath( "/html/body/div[2]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[2]/div[2]/div[2]/div[3]/div[3]/div/div[2]/div" ).text if "K" in vol: vol = float(vol[:len(vol) - 1]) * 1000 if "K" in vol_ema: vol_ema = float(vol_ema[:len(vol_ema) - 1]) * 1000 sar = driver.find_element_by_xpath( "/html/body/div[2]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[2]/div[2]/div[2]/div[4]/div[3]/div/div/div" ).text dif_sar = float(close_price) - float(sar) dif_sar = round(dif_sar, 5) """klinger1 = driver.find_element_by_xpath( "/html/body/div[2]/div[1]/div[3]/div[1]/div/table/tr[3]/td[2]/div/div[2]/div/div[2]/div[2]/div[3]/div/div[1]/div" ).text klinger2 = driver.find_element_by_xpath( "/html/body/div[2]/div[1]/div[3]/div[1]/div/table/tr[3]/td[2]/div/div[2]/div/div[2]/div[2]/div[3]/div/div[2]/div" ).text klinger = float(klinger1) - float(klinger2)""" rsi = driver.find_element_by_xpath( "/html/body/div[2]/div[1]/div[3]/div[1]/div/table/tr[3]/td[2]/div/div[2]/div/div[2]/div[2]/div[3]/div/div/div" ).text
[ 19836, 62, 20888, 796, 4639, 13, 19796, 62, 30854, 62, 1525, 62, 87, 6978, 7, 198, 220, 220, 220, 220, 220, 220, 220, 12813, 6494, 14, 2618, 14, 7146, 58, 17, 60, 14, 7146, 58, 16, 60, 14, 7146, 58, 18, 60, 14, 7146, 58, 16, ...
1.738562
1,071
from setuptools import setup, find_packages import io version = '0.2.1' author = 'ZSAIm' author_email = 'zzsaim@163.com' with io.open('README.rst', 'r', encoding='utf-8') as freadme: long_description = freadme.read() setup( name='PyJSCaller', version=version, description='Run JavaScript code from Python', long_description=long_description, author=author, author_email=author_email, url='https://github.com/ZSAIm/PyJSCaller', license='Apache-2.0 License', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], packages=find_packages(), )
[ 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 11748, 33245, 198, 198, 9641, 796, 705, 15, 13, 17, 13, 16, 6, 198, 9800, 796, 705, 57, 4090, 3546, 6, 198, 9800, 62, 12888, 796, 705, 3019, 82, 1385, 31, ...
2.511429
350
import logging from .backends.email import DjangoEmailBackend from .models import Message, Messager from .templates import REGISTER_VERIFY_CODE from utils.data import guid logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 198, 6738, 764, 1891, 2412, 13, 12888, 1330, 37770, 15333, 7282, 437, 198, 6738, 764, 27530, 1330, 16000, 11, 10626, 3536, 198, 6738, 764, 11498, 17041, 1330, 23337, 41517, 62, 5959, 5064, 56, 62, 34, 16820, 198, 6738...
3.365079
63
#!/usr/bin/env python import argparse import build import fetcher import os import sys import threading import time import utils if __name__ == '__main__': parser = argparse.ArgumentParser(description='Blitz repos') parser.add_argument('config', type=argparse.FileType('r'), help='Config file as JSON') parser.add_argument('-f', '--folder', default='', help='Output folder') parser.add_argument('-i', '--init', action='store_true', help='Initialize only, download sources') parser.add_argument('-b', '--build', action='store_true', help='Build sources') parser.add_argument('-c', '--configure', action='store_true', help='Build sources') parser.add_argument('-t', '--test', action='store_true', help='Run tests') parser.add_argument('--interval', type=float, default=1.0, help='Interval in seconds between updates') parser.add_argument('-v', '--verbose', action='store_true', help='Verbose') parser.add_argument('-a', '--all', action='store_true', help='Perform all actions') basedir = os.path.dirname(os.path.realpath(__file__)) if os.path.isfile(basedir + '/python-sshserver/sshserver.py'): parser.add_argument('-s', '--serve', action='store_true', help='Serve over SSH') parser.add_argument('--serve-port', default=2242, help='SSH server port') parser.add_argument('--serve-auth', default='', help='SSH auth file') sys.path.append(basedir + '/python-sshserver') res = parser.parse_args() args = vars(res) config = utils.parse(args['config']) args['config'].close() utils.set_print_verb(args['verbose']) if not init(config, args): sys.exit(1) if 'serve' in args and args['serve']: import serve upd = threading.Thread(target=updater, args=(config, args)) upd.start() serve.serve(config, args)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 1822, 29572, 198, 11748, 1382, 198, 11748, 11351, 2044, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 4704, 278, 198, 11748, 640, 198, 11748, 3384, 4487, 628, 628, 198, 198, 3...
2.704082
686
from setuptools import setup import versioneer from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() requirements = [ # package requirements go here ] setup( name='eazyprofiler', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description="EazyProfiler is forked version of Lazyprofiler which is a simple utility to collect CPU, GPU, RAM and GPU Memorystats while the program is running.", long_description=long_description, long_description_content_type='text/markdown', license="MIT", author="Damianos Park", author_email='damianospark@gmail.com', url='https://github.com/damianospark/eazyprofiler', packages=['eazyprofiler'], entry_points={ 'console_scripts': [ 'eazyprofiler=eazyprofiler.cli:cli' ] }, install_requires=requirements, keywords='eazyprofiler', classifiers=[ 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ] )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 11748, 2196, 28153, 198, 6738, 28686, 1330, 3108, 198, 5661, 62, 34945, 796, 3108, 13, 397, 2777, 776, 7, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198, 4480, 1280, 7, 6978, 13, 22179, ...
2.711982
434
# Generated by Django 2.0.3 on 2018-09-30 09:48 from django.db import migrations, models import django.utils.timezone
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 18, 319, 2864, 12, 2931, 12, 1270, 7769, 25, 2780, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 26791, 13, 2435, 11340, 628 ]
2.926829
41
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 4 08:56:58 2021 @author: Thore """ import numpy as np from numpy.random import exponential from random import randint, uniform
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 2365, 220, 604, 8487, 25, 3980, 25, 3365, 33448, 198, 198, 31, 9800, 25, 536, 382, ...
2.842857
70
import os import tempfile import platform import pytest from grep import print_helper from tests.helper_for_tests import with_f_bwrite, hotfix_delete_temp_dir @print_helper.color_term_in_string # TODO do not call hotfix_delete_temp_dir manually
[ 11748, 28686, 198, 11748, 20218, 7753, 198, 11748, 3859, 198, 11748, 12972, 9288, 198, 198, 6738, 42717, 1330, 3601, 62, 2978, 525, 198, 6738, 5254, 13, 2978, 525, 62, 1640, 62, 41989, 1330, 351, 62, 69, 62, 65, 13564, 11, 3024, 13049...
3.023529
85
import ncadquery as cq # These can be modified rather than hardcoding values for each dimension. circle_radius = 3.0 # The outside radius of the plate thickness = 0.25 # The thickness of the plate # Make a plate with two cutouts in it by moving the workplane center point # 1. Establishes a workplane that an object can be built on. # 1a. Uses the named plane orientation "front" to define the workplane, meaning # that the positive Z direction is "up", and the negative Z direction # is "down". # 1b. The initial workplane center point is the center of the circle, at (0,0). # 2. A circle is created at the center of the workplane # 2a. Notice that circle() takes a radius and not a diameter result = cq.Workplane("front").circle(circle_radius) # 3. The work center is movide to (1.5, 0.0) by calling center(). # 3a. The new center is specified relative to the previous center,not # relative to global coordinates. # 4. A 0.5mm x 0.5mm 2D square is drawn inside the circle. # 4a. The plate has not been extruded yet, only 2D geometry is being created. result = result.center(1.5, 0.0).rect(0.5, 0.5) # 5. The work center is moved again, this time to (-1.5, 1.5). # 6. A 2D circle is created at that new center with a radius of 0.25mm. result = result.center(-1.5, 1.5).circle(0.25) # 7. All 2D geometry is extruded to the specified thickness of the plate. # 7a. The small circle and the square are enclosed in the outer circle of the # plate and so it is assumed that we want them to be cut out of the plate. # A separate cut operation is not needed. result = result.extrude(thickness) # Displays the result of this script show_object(result)
[ 11748, 299, 66, 324, 22766, 355, 269, 80, 198, 198, 2, 2312, 460, 307, 9518, 2138, 621, 1327, 66, 7656, 3815, 329, 1123, 15793, 13, 198, 45597, 62, 42172, 796, 513, 13, 15, 220, 1303, 383, 2354, 16874, 286, 262, 7480, 198, 400, 62...
3.214149
523
""" Module: Potential This module shall be used to implement subclasses of Potentials that formulate a potential as an Function with N-Dimensions. This module contains all available potentials. """ import numpy as np import sympy as sp from ensembler.util import ensemblerTypes as t from ensembler.util.ensemblerTypes import Number, Union, Iterable # Base Classes from ensembler.potentials._basicPotentials import _potentialNDCls class harmonicOscillatorPotential(_potentialNDCls): """ ND harmonic oscillator potential """ name: str = "harmonicOscilator" nDimensions: int = sp.symbols("nDimensions") position: sp.Matrix = sp.Matrix([sp.symbols("r")]) r_shift: sp.Matrix = sp.Matrix([sp.symbols("r_shift")]) Voff: sp.Matrix = sp.Matrix([sp.symbols("V_off")]) k: sp.Matrix = sp.Matrix([sp.symbols("k")]) V_dim = 0.5 * k * (position - r_shift) ** 2 + Voff i = sp.Symbol("i") V_functional = sp.Sum(V_dim[i, 0], (i, 0, nDimensions)) def __init__(self, k: np.array = np.array([1.0, 1.0, 1.0]), r_shift: np.array = np.array([0.0, 0.0, 0.0]), Voff: np.array = np.array([0.0, 0.0, 0.0]), nDimensions: int = 3): """ __init__ Constructs an harmonic Oscillator with an on runtime defined dimensionality. Parameters ---------- k: List[float], optional force constants, as many as nDim, defaults to [1.0, 1.0, 1.0] x_shift: List[float], optional shift of the minimum in the x Axis, as many as nDim, defaults to [0.0, 0.0, 0.0] y_shift: List[float], optional shift on the y Axis, as many as nDim, defaults to [0.0, 0.0, 0.0] nDim dimensionality of the harmoic oscillator object. default: 3 """ self.constants = {self.nDimensions:nDimensions} self.constants.update({"k_" + str(j): k[j] for j in range(self.constants[self.nDimensions])}) self.constants.update({"r_shift" + str(j): r_shift[j] for j in range(self.constants[self.nDimensions])}) self.constants.update({"V_off_" + str(j): Voff[j] for j in range(self.constants[self.nDimensions])}) super().__init__(nDimensions=nDimensions) def _initialize_functions(self): """ Build up the nDimensionssymbolic definitions """ # Parameters nDimensions= self.constants[self.nDimensions] self.position = sp.Matrix([sp.symbols("r_" + str(i)) for i in range(nDimensions)]) self.r_shift = sp.Matrix([sp.symbols("r_shift" + str(i)) for i in range(nDimensions)]) self.V_off = sp.Matrix([sp.symbols("V_off_" + str(i)) for i in range(nDimensions)]) self.k = sp.Matrix([sp.symbols("k_" + str(i)) for i in range(nDimensions)]) # Function self.V_dim = 0.5 * sp.matrix_multiply_elementwise(self.k, ( (self.position - self.r_shift).applyfunc(lambda x: x ** 2))) # +self.Voff self.V_functional = sp.Sum(self.V_dim[self.i, 0], (self.i, 0, self.nDimensions - 1)) class envelopedPotential(_potentialNDCls): """ This implementation of exponential Coupling for EDS is a more numeric robust and variable implementation, it allows N states. Therefore the computation of energies and the deviation is not symbolic. Here N-states are coupled by the log-sum-exp resulting in a new reference state $V_R$, $V_R = -1/{\beta} * \ln(\sum_i^Ne^(-\beta*s*(V_i-E^R_i)))$ This potential coupling is for example used in EDS. """ name = "Enveloping Potential" T, kb, position = sp.symbols("T kb r") beta = 1 / (kb * T) Vis = sp.Matrix(["V_i"]) Eoffis = sp.Matrix(["Eoff_i"]) sis = sp.Matrix(["s_i"]) i, nStates = sp.symbols("i N") V_functional = -1 / (beta * sis[0, 0]) * sp.log( sp.Sum(sp.exp(-beta * sis[i, 0] * (Vis[i, 0] - Eoffis[i, 0])), (i, 0, nStates))) def __init__(self, V_is: t.List[_potentialNDCls] = ( harmonicOscillatorPotential(nDimensions=2), harmonicOscillatorPotential(r_shift=[3,3], nDimensions=2)), s: float = 1.0, eoff: t.List[float] = None, T: float = 1, kb: float = 1): """ __init__ This function constructs a enveloped potential, enveloping all given states. Parameters ---------- V_is: List[_potential1DCls], optional The states(potential classes) to be enveloped (default: [harmonicOscillatorPotential(), harmonicOscillatorPotential(x_shift=3)]) s: float, optional the smoothing parameter, lowering the barriers between the states eoff: List[float], optional the energy offsets of the individual states in the reference potential. These can be used to allow a more uniform sampling. (default: seta ll to 0) T: float, optional the temperature of the reference state (default: 1 = T) kb: float, optional the boltzman constant (default: 1 = kb) """ self.constants = {self.T: T, self.kb: kb} nStates = len(V_is) self._Eoff_i = [0 for x in range(nStates)] self._s = [0 for x in range(nStates)] self._V_is = [0 for x in range(nStates)] # for calculate implementations self.V_is = V_is self.s_i = s self.Eoff_i = eoff super().__init__(nDimensions=V_is[0].constants[V_is[0].nDimensions], nStates=len(V_is)) def _initialize_functions(self): """ build the symbolic functionality. """ # for sympy Sympy Updates - Check!: self.statePotentials = {"state_" + str(j): self.V_is[j] for j in range(self.constants[self.nStates])} Eoffis = {"Eoff_" + str(i): self.Eoff_i[i] for i in range(self.constants[self.nStates])} sis = {"s_" + str(i): self.s_i[i] for i in range(self.constants[self.nStates])} keys = zip(sorted(self.statePotentials.keys()), sorted(Eoffis.keys()), sorted(sis.keys())) self.states = sp.Matrix([sp.symbols(l) * (sp.symbols(j) - sp.symbols(k)) for j, k, l in keys]) self.constants.update({**{state: value.V for state, value in self.statePotentials.items()}, **Eoffis, **sis}) self.V_functional = -1 / (self.beta * self.sis[0, 0]) * sp.log( sp.Sum(sp.exp(-self.beta * self.states[self.i, 0]), (self.i, 0, self.nStates - 1))) self._update_functions() # also make sure that states are up to work: [V._update_functions() for V in self.V_is] if (all([self.s_i[0] == s for s in self.s_i[1:]])): self.ene = self._calculate_energies_singlePos_overwrite_oneS else: self.ene = self._calculate_energies_singlePos_overwrite_multiS self.force = self._calculate_dvdpos_singlePos_overwrite @property def V_is(self) -> t.List[_potentialNDCls]: """ V_is are the state potential classes enveloped by the reference state. Returns ------- V_is: t.List[_potential1DCls] """ return self._V_is @V_is.setter def set_Eoff(self, Eoff: Union[Number, Iterable[Number]]): """ This function is setting the Energy offsets of the states enveloped by the reference state. Parameters ---------- Eoff: Union[Number, Iterable[Number]] """ self.Eoff_i = Eoff @property def Eoff(self) -> t.List[Number]: """ The Energy offsets are used to bias the single states in the reference potential by a constant offset. Therefore each state of the enveloping potential has its own energy offset. Returns ------- Eoff:t.List[Number] """ return self.Eoff_i @Eoff.setter @property def Eoff_i(self) -> t.List[Number]: """ The Energy offsets are used to bias the single states in the reference potential by a constant offset. Therefore each state of the enveloping potential has its own energy offset. Returns ------- Eoff:t.List[Number] """ return self._Eoff_i @Eoff_i.setter def set_s(self, s: Union[Number, Iterable[Number]]): """ set_s is a function used to set an smoothing parameter. Parameters ---------- s:Union[Number, Iterable[Number]] Returns ------- """ self.s_i = s @property @s.setter @property @s_i.setter def _calculate_dvdpos_singlePos_overwrite(self, positions: (t.Iterable[float])) -> np.array: """ Parameters ---------- positions Returns ------- """ positions = np.array(positions, ndmin=2) # print("Pos: ", position) V_R_part, V_Is_ene = self._logsumexp_calc_gromos(positions) V_R_part = np.array(V_R_part, ndmin=2).T # print("V_R_part: ", V_R_part.shape, V_R_part) # print("V_I_ene: ",V_Is_ene.shape, V_Is_ene) V_Is_dhdpos = np.array([-statePot.force(positions) for statePot in self.V_is], ndmin=1).T # print("V_I_force: ",V_Is_dhdpos.shape, V_Is_dhdpos) adapt = np.concatenate([V_R_part for s in range(self.constants[self.nStates])], axis=1) # print("ADAPT: ",adapt.shape, adapt) scaling = np.exp(V_Is_ene - adapt) # print("scaling: ", scaling.shape, scaling) dVdpos_state = np.multiply(scaling, V_Is_dhdpos) # np.array([(ene/V_R_part) * force for ene, force in zip(V_Is_ene, V_Is_dhdpos)]) # print("state_contributions: ",dVdpos_state.shape, dVdpos_state) dVdpos = np.sum(dVdpos_state, axis=1) # print("forces: ",dVdpos.shape, dVdpos) return np.squeeze(dVdpos) def _logsumexp_calc_gromos(self, position): """ code from gromos: Parameters ---------- position Returns ------- """ prefactors = [] beta = self.constants[self.T] * self.constants[self.kb] # kT - *self.constants[self.T] partA = np.array(-beta * self.s_i[0] * (self.V_is[0].ene(position) - self.Eoff_i[0]), ndmin=1) partB = np.array(-beta * self.s_i[1] * (self.V_is[1].ene(position) - self.Eoff_i[1]), ndmin=1) partAB = np.array([partA, partB]).T log_prefac = 1 + np.exp(np.min(partAB, axis=1) - np.max(partAB, axis=1)) sum_prefactors = np.max(partAB, axis=1) + np.log(log_prefac) prefactors.append(partA) prefactors.append(partB) # more than two states! for state in range(2, self.constants[self.nStates]): partN = np.array(-beta * self.s_i[state] * (self.V_is[state].ene(position) - self.Eoff_i[state]), ndmin=1) prefactors.append(partN) sum_prefactors = np.max([sum_prefactors, partN], axis=1) + np.log(1 + np.exp( np.min([sum_prefactors, partN], axis=1) - np.max([sum_prefactors, partN], axis=1))) # print("prefactors: ", sum_prefactors) return sum_prefactors, np.array(prefactors, ndmin=2).T class lambdaEDSPotential(envelopedPotential): """ This implementation of exponential Coupling combined with linear compling is called $\lambda$-EDS the implementation of function is more numerical robust to the hybrid coupling class. Here two-states are coupled by the log-sum-exp and weighted by lambda resulting in a new reference state $V_R$, $V_R = -\frac{1}{\beta*s} * \ln(\lambda * e^(-\beta*s*(V_A-E^R_A)) + (1-\lambda)*e^(-\beta*s*(V_B-E^R_B)))$ This potential coupling is for example used in $\lambda$-EDS. """ name: str = "lambda enveloped Potential" T, kb, position = sp.symbols("T kb r") beta = 1 / (kb * T) Vis = sp.Matrix(["V_i"]) Eoffis = sp.Matrix(["Eoff_i"]) sis = sp.Matrix(["s_i"]) lamis = sp.Matrix(["λ"]) i, nStates = sp.symbols("i N") V_functional = -1 / (beta * sis[0, 0]) * sp.log( sp.Sum(lamis[i, 0] * sp.exp(-beta * sis[i, 0] * (Vis[i, 0] - Eoffis[i, 0])), (i, 0, nStates))) @property @lam.setter @property @lam_i.setter class sumPotentials(_potentialNDCls): """ Adds n different potentials. For adding up wavepotentials, we recommend using the addedwavePotential class. """ name: str = "Summed Potential" position = sp.symbols("r") potentials: sp.Matrix = sp.Matrix([sp.symbols("V_x")]) nPotentials = sp.symbols("N") i = sp.symbols("i", cls=sp.Idx) V_functional = sp.Sum(potentials[i, 0], (i, 0, nPotentials)) def __init__(self, potentials: t.List[_potentialNDCls] = (harmonicOscillatorPotential(), harmonicOscillatorPotential(r_shift=[1,1,1], nDimensions=3))): """ __init__ This is the Constructor of an summed Potentials Parameters ---------- potentials: List[_potential2DCls], optional it uses the 2D potential class to generate its potential, default to (wavePotential(), wavePotential(multiplicity=[3, 3])) """ if(all([potentials[0].constants[V.nDimensions] == V.constants[V.nDimensions] for V in potentials])): nDim = potentials[0].constants[potentials[0].nDimensions] else: raise ValueError("The potentials don't share the same dimensionality!\n\t"+str([V.constants[V.nDimensions] for V in potentials])) self.constants = {self.nPotentials: len(potentials)} self.constants.update({"V_" + str(i): potentials[i].V for i in range(len(potentials))}) super().__init__(nDimensions=nDim) def _initialize_functions(self): """ _initialize_functions converts the symbolic mathematics of sympy to a matrix representation that is compatible with multi-dimentionality. """ self.position = sp.Matrix([sp.symbols("r_" + str(i)) for i in range(self.constants[self.nDimensions])]) self.potentials = sp.Matrix( [sp.symbols("V_" + str(i)) for i in range(self.constants[self.nPotentials])]) # Function self.V_functional = sp.Sum(self.potentials[self.i, 0], (self.i, 0, self.nPotentials - 1)) # OVERRIDE def _update_functions(self): """ _update_functions calculates the current energy and derivative of the energy """ super()._update_functions() self.tmp_Vfunc = self._calculate_energies self.tmp_dVdpfunc = self._calculate_dVdpos
[ 37811, 198, 26796, 25, 32480, 198, 220, 220, 220, 770, 8265, 2236, 307, 973, 284, 3494, 850, 37724, 286, 6902, 14817, 326, 46418, 257, 2785, 355, 281, 15553, 351, 399, 12, 29271, 5736, 13, 198, 220, 220, 220, 220, 770, 8265, 4909, 4...
2.246643
6,479
from CommonServerPython import * import os import demistomock as demisto RETURN_ERROR_TARGET = 'HTMLDocsAutomation.return_error' # md = '''Key | Value # - | - # city | Mountain View # country | US # hostname | dns.google # ip | 8.8.8.8 # loc | 37.3860,-122.0838 # org | AS15169 Google LLC # postal | 94035 # readme | https://ipinfo.io/missingauth # region | California # {"lat": 37.386, "lng": -122.0838}''' # # print(human_readable_example_to_html(md))
[ 6738, 8070, 10697, 37906, 1330, 1635, 198, 198, 11748, 28686, 198, 11748, 1357, 396, 296, 735, 355, 1357, 396, 78, 628, 198, 26087, 27064, 62, 24908, 62, 51, 46095, 796, 705, 28656, 23579, 82, 38062, 341, 13, 7783, 62, 18224, 6, 628, ...
2.545946
185
#!/usr/bin/env python # coding: utf-8 # # Example Seldon Core Deployments using Helm with Istio # # Prequisites # # * [Install istio](https://istio.io/latest/docs/setup/getting-started/#download) # ## Setup Cluster and Ingress # # Use the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Setup-Cluster) with [Istio Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Istio). Instructions [also online](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html). # In[1]: get_ipython().system('kubectl create namespace seldon') # In[2]: get_ipython().system('kubectl config set-context $(kubectl config current-context) --namespace=seldon') # ## Configure Istio # # For this example we will create the default istio gateway for seldon which needs to be called `seldon-gateway`. You can supply your own gateway by adding to your SeldonDeployments resources the annotation `seldon.io/istio-gateway` with values the name of your istio gateway. # Create a gateway for our istio-ingress # In[3]: get_ipython().run_cell_magic('writefile', 'resources/seldon-gateway.yaml', 'apiVersion: networking.istio.io/v1alpha3\nkind: Gateway\nmetadata:\n name: seldon-gateway\n namespace: istio-system\nspec:\n selector:\n istio: ingressgateway # use istio default controller\n servers:\n - port:\n number: 80\n name: http\n protocol: HTTP\n hosts:\n - "*"') # In[4]: get_ipython().system('kubectl create -f resources/seldon-gateway.yaml -n istio-system') # Ensure the istio ingress gatewaty is port-forwarded to localhost:8004 # # * Istio: `kubectl port-forward $(kubectl get pods -l istio=ingressgateway -n istio-system -o jsonpath='{.items[0].metadata.name}') -n istio-system 8004:8080` # In[1]: ISTIO_GATEWAY = "localhost:8004" VERSION = get_ipython().getoutput('cat ../version.txt') VERSION = VERSION[0] VERSION # In[2]: from IPython.core.magic import register_line_cell_magic @register_line_cell_magic # ## Start Seldon Core # # Use the setup notebook to [Install Seldon Core](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Install-Seldon-Core) with Istio Ingress. Instructions [also online](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html). # ## Serve Single Model # In[7]: get_ipython().system('helm install mymodel ../helm-charts/seldon-single-model --set model.image=seldonio/mock_classifier:$VERSION') # In[8]: get_ipython().system('helm template mymodel ../helm-charts/seldon-single-model --set model.image=seldonio/mock_classifier:$VERSION | pygmentize -l json') # In[9]: get_ipython().system('kubectl rollout status deploy/mymodel-default-0-model') # ### Get predictions # In[10]: from seldon_core.seldon_client import SeldonClient sc = SeldonClient( deployment_name="mymodel", namespace="seldon", gateway_endpoint=ISTIO_GATEWAY ) # #### REST Request # In[11]: r = sc.predict(gateway="istio", transport="rest") assert r.success == True print(r) # ## gRPC Request # In[12]: r = sc.predict(gateway="istio", transport="grpc") assert r.success == True print(r) # In[13]: get_ipython().system('helm delete mymodel') # ## Host Restriction # # In this example we will restriction request to those with the Host header "seldon.io" # In[3]: get_ipython().run_cell_magic('writetemplate', 'resources/model_seldon.yaml', 'apiVersion: machinelearning.seldon.io/v1\nkind: SeldonDeployment\nmetadata:\n name: example-seldon\n annotations:\n "seldon.io/istio-host": "seldon.io"\nspec:\n protocol: seldon\n predictors:\n - componentSpecs:\n - spec:\n containers:\n - image: seldonio/mock_classifier:{VERSION}\n name: classifier\n graph:\n name: classifier\n type: MODEL\n name: model\n replicas: 1') # In[4]: get_ipython().system('kubectl apply -f resources/model_seldon.yaml') # In[5]: get_ipython().system("kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=example-seldon -o jsonpath='{.items[0].metadata.name}')") # In[6]: for i in range(60): state = get_ipython().getoutput("kubectl get sdep example-seldon -o jsonpath='{.status.state}'") state = state[0] print(state) if state == "Available": break time.sleep(1) assert state == "Available" # In[15]: X = get_ipython().getoutput('curl -s -d \'{"data": {"ndarray":[[1.0, 2.0, 5.0]]}}\' -X POST http://localhost:8003/seldon/seldon/example-seldon/api/v1.0/predictions -H "Content-Type: application/json" assert X == []') # In[16]: import json X = get_ipython().getoutput('curl -s -d \'{"data": {"ndarray":[[1.0, 2.0, 5.0]]}}\' -X POST http://localhost:8003/seldon/seldon/example-seldon/api/v1.0/predictions -H "Content-Type: application/json" -H "Host: seldon.io"') d=json.loads(X[0]) print(d) assert(d["data"]["ndarray"][0][0] > 0.4) # In[17]: get_ipython().system('kubectl delete -f resources/model_seldon.yaml') # In[ ]:
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 1303, 17934, 1001, 25900, 7231, 34706, 902, 1262, 28351, 351, 314, 301, 952, 198, 2, 220, 198, 2, 3771, 421, 31327, 198, 2, 220, 198, ...
2.647757
1,939
def code(): """ Example G-code module, a square. Please simulate first, before milling. """ return """ G91 G0 X20 Y0 G0 X0 Y20 G0 X-20 Y0 G0 X0 Y-20 """
[ 4299, 2438, 33529, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 17934, 402, 12, 8189, 8265, 11, 257, 6616, 13, 628, 220, 220, 220, 4222, 29308, 717, 11, 878, 3939, 278, 13, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1441, 37...
1.847458
118
from consent import provider_reg from add_org import add_organization import psycopg2 import random, string name = { "title" : "Mr.", "firstName" : "Testing", "lastName" : "Testing" } csr = "-----BEGIN CERTIFICATE REQUEST-----\nMIICjDCCAXQCAQAwRzELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRQwEgYDVQQK\nDAtNeU9yZywgSW5jLjEVMBMGA1UEAwwMbXlkb21haW4uY29tMIIBIjANBgkqhkiG\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyhF2a5PeL72zGdL47/6zVQQQtZJcO01iVbjR\nSSyswUa2jcfYfoQEVKo1JAz25G3nYfSW1Te3OWjuihvPhZeatFSUwTxcZJFxzIWm\n4/gOQIhJKCA/Wry3liW2sjIGLuHxeH2BoQCIEZyYcqVpRWEJ9RusRFcwPgvROigh\nhMXhgE86uaIRs0yPqzhc7sl53T4qx6qvQJ6uTXBWBvUELgSSgeyaT0gwU1mGmPck\n7Svo6tsWfBFfgT5Ecbqsc2nqChAExgocp5tkPJYcy8FB/tU/FW0rFthqecSvMrpS\ncZW9+iyzseyPrcK9ka6XSlVu9EoX82RW7SRyRL2T5VN3JemXfQIDAQABoAAwDQYJ\nKoZIhvcNAQELBQADggEBAJRFEYn6dSzEYpgYLItUm7Sp3LzquJw7QfMyUvsy45rp\n0VTdQdYp/hVR2aCLiD33ht4FxlhbZm/8XcTuYolP6AbF6FldxWmmFFS9LRAj7nTV\ndU1pZftwFPp6JsKUCYHVsuxs7swliXbEcBVtD6QktzZNrRJmUKi38DAFcbFwgLaM\nG/iRIm4DDj2hmanKp+vUWjXfj13naa7bDtIlzW96y24jsu+naabg8MVShfGCStIv\nrX3T2JkkSjpTw7YzIpgI8/Zg9VR1l0udvfh9bn7mjmOYc3EYwJKvuJDn1TzVuIIi\n9NmVasTjhZJ0PyWithWuZplo/LXUwSoid8HVyqe5ZVI=\n-----END CERTIFICATE REQUEST-----\n" with open("../passwords/auth.db.password", "r") as f: pg_password = f.read().strip() conn_string = "host='localhost' dbname='postgres' user='auth' password='" + pg_password + "'" try: conn = psycopg2.connect(conn_string) except psycopg2.DatabaseError as error: quit() cursor = conn.cursor()
[ 6738, 8281, 1330, 10131, 62, 2301, 198, 6738, 751, 62, 2398, 1330, 751, 62, 9971, 1634, 198, 11748, 17331, 22163, 70, 17, 198, 11748, 4738, 11, 4731, 198, 198, 3672, 796, 1391, 366, 7839, 1, 220, 220, 220, 220, 220, 220, 220, 1058, ...
1.625663
943
from .BoundBox_class import BoundBox from .Point_class import Point from .Line_class import Line
[ 6738, 764, 49646, 14253, 62, 4871, 1330, 30149, 14253, 198, 6738, 764, 12727, 62, 4871, 1330, 6252, 198, 6738, 764, 13949, 62, 4871, 1330, 6910, 198 ]
3.730769
26
#!/usr/bin/env python3 # Purpose: Create a new EMR cluster and submits a variable # number of Steps defined in a separate JSON file # Author: Gary A. Stafford (November 2020) import argparse import json import logging import os import boto3 from botocore.exceptions import ClientError from scripts.parameters import parameters logging.basicConfig(format='[%(asctime)s] %(levelname)s - %(message)s', level=logging.INFO) emr_client = boto3.client('emr') def run_job_flow(params, steps): """Create EMR cluster, run Steps, and then terminate cluster""" try: response = emr_client.run_job_flow( Name='demo-cluster-run-job-flow', LogUri=f's3n://{params["logs_bucket"]}', ReleaseLabel='emr-6.2.0', Instances={ 'InstanceFleets': [ { 'Name': 'MASTER', 'InstanceFleetType': 'MASTER', 'TargetSpotCapacity': 1, 'InstanceTypeConfigs': [ { 'InstanceType': 'm5.xlarge', }, ] }, { 'Name': 'CORE', 'InstanceFleetType': 'CORE', 'TargetSpotCapacity': 2, 'InstanceTypeConfigs': [ { 'InstanceType': 'r5.2xlarge', }, ], }, ], 'Ec2KeyName': params['ec2_key_name'], 'KeepJobFlowAliveWhenNoSteps': False, 'TerminationProtected': False, 'Ec2SubnetId': params['ec2_subnet_id'], }, Steps=steps, BootstrapActions=[ { 'Name': 'string', 'ScriptBootstrapAction': { 'Path': f's3://{params["bootstrap_bucket"]}/bootstrap_actions.sh', } }, ], Applications=[ { 'Name': 'Spark' }, ], Configurations=[ { 'Classification': 'spark-hive-site', 'Properties': { 'hive.metastore.client.factory.class': 'com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory' } } ], VisibleToAllUsers=True, JobFlowRole=params['emr_ec2_role'], ServiceRole=params['emr_role'], Tags=[ { 'Key': 'Environment', 'Value': 'Development' }, { 'Key': 'Name', 'Value': 'EMR Demo Project Cluster' }, { 'Key': 'Owner', 'Value': 'Data Analytics' }, ], EbsRootVolumeSize=32, StepConcurrencyLevel=5, ) print(f'Response: {response}') except ClientError as e: logging.error(e) return False return True def get_steps(params, job_type): """ Load EMR Steps from a separate JSON-format file and substitutes tags for SSM parameter values """ dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) file = open(f'{dir_path}/job_flow_steps/job_flow_steps_{job_type}.json', 'r') steps = json.load(file) new_steps = [] for step in steps: step['HadoopJarStep']['Args'] = list( map(lambda st: str.replace(st, '{{ work_bucket }}', params['work_bucket']), step['HadoopJarStep']['Args'])) new_steps.append(step) return new_steps def parse_args(): """Parse argument values from command-line""" parser = argparse.ArgumentParser(description='Arguments required for script.') parser.add_argument('-t', '--job-type', required=True, choices=['process', 'analyze'], help='process or analysis') args = parser.parse_args() return args if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 32039, 25, 13610, 257, 649, 412, 13599, 13946, 290, 850, 24883, 257, 7885, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1271, 286, 32144, 5447, 287, 257, 4553, ...
1.789671
2,401
from neo4j import GraphDatabase port = 7688 data_uri = 'bolt://localhost:' + str(port) username = 'neo4j' password = 'abc123' # data_creds = (username, password) data_creds = None driver = GraphDatabase.driver(data_uri, auth=data_creds) """ @param pkg_data : Python dictionary of package data to be inserted """ if __name__ == '__main__': print("Running tests for neo-wrapper.") clear_db() pkg1 = { "name": "pack3", "main_name": "Josh", "main_email": "Josh@email.com", "auth_name": "Aadesh", "auth_email": "Aadesh@email.com", "downloads": 30, "license": "Apache v2.0", "dep_list": ["packone", "packtwo"] } push_pkg(pkg1) pkg2 = { "name": "testpack", "main_name": "Jane", "main_email": "Jane@email.com", "auth_name": "Aadesh", "auth_email": "Aadesh@email.com", "downloads": 20, "license": "Apache v2.0", "dep_list": ["pack3", "packtwo"] } push_pkg(pkg2) pkg3 = { "name": "packtwo", "main_name": "Mike", "main_email": "Jike@email.com", "auth_name": "Heather", "auth_email": "Heather@email.com", "downloads": 20, "license": "Apache v2.0", "dep_list": [] } push_pkg(pkg3) close_db() print("Done.")
[ 6738, 19102, 19, 73, 1330, 29681, 38105, 198, 198, 634, 796, 767, 34427, 198, 7890, 62, 9900, 796, 705, 25593, 1378, 36750, 32105, 1343, 965, 7, 634, 8, 198, 198, 29460, 796, 705, 710, 78, 19, 73, 6, 198, 28712, 796, 705, 39305, 1...
2.04812
665
from flask_login import UserMixin from config.flask_config import CRUD
[ 6738, 42903, 62, 38235, 1330, 11787, 35608, 259, 198, 6738, 4566, 13, 2704, 2093, 62, 11250, 1330, 8740, 8322 ]
3.684211
19
import pytest from graphene import ObjectType, Schema from graphene.test import Client from parler.utils.context import switch_language from django_ilmoitin.api.schema import Query from django_ilmoitin.dummy_context import COMMON_CONTEXT, DummyContext from django_ilmoitin.models import NotificationTemplate from django_ilmoitin.registry import notifications @pytest.fixture(autouse=True) @pytest.fixture(autouse=True) @pytest.fixture @pytest.fixture
[ 11748, 12972, 9288, 198, 6738, 42463, 1330, 9515, 6030, 11, 10011, 2611, 198, 6738, 42463, 13, 9288, 1330, 20985, 198, 6738, 1582, 1754, 13, 26791, 13, 22866, 1330, 5078, 62, 16129, 198, 198, 6738, 42625, 14208, 62, 346, 5908, 270, 259,...
3.172414
145
import requests # Vuln Base Info # Vender Fingerprint # Proof of Concept # Exploit, can be same with poc() # Utils
[ 11748, 7007, 628, 198, 2, 25442, 77, 7308, 14151, 628, 198, 2, 569, 2194, 39454, 4798, 198, 198, 2, 29999, 286, 26097, 628, 198, 2, 5905, 30711, 11, 460, 307, 976, 351, 279, 420, 3419, 628, 198, 2, 7273, 4487 ]
3.075
40