hexsha
stringlengths
40
40
size
int64
5
2.06M
ext
stringclasses
11 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
251
max_stars_repo_name
stringlengths
4
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
251
max_issues_repo_name
stringlengths
4
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
251
max_forks_repo_name
stringlengths
4
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.05M
avg_line_length
float64
1
1.02M
max_line_length
int64
3
1.04M
alphanum_fraction
float64
0
1
fc12305fff510e126657094db88dd638e8718e01
1,042
py
Python
part01_basic/for_while_loop.py
ApprenticeOne/python_learn
2433726b3f164526e8a8fa18739854e052d76a2e
[ "MIT" ]
null
null
null
part01_basic/for_while_loop.py
ApprenticeOne/python_learn
2433726b3f164526e8a8fa18739854e052d76a2e
[ "MIT" ]
null
null
null
part01_basic/for_while_loop.py
ApprenticeOne/python_learn
2433726b3f164526e8a8fa18739854e052d76a2e
[ "MIT" ]
null
null
null
import random from math import sqrt sum = 0 for x in range(101): sum += x print(sum) ''' range(101) 0-100 101 range(1,101) 1-100 range(1,101,2) 1-100 2 range(100,0,-2) 100-0 -2 ''' sum = 0 for x in range(100, 0, -2): sum += x print(sum) # while # 0-100 answer = random.randint(0, 100) count = 0 while True: count += 1 number = int(input("Please enter the number: ")) if number < answer: print("more larger") elif number > answer: print("more smaller") else: print("right") print('you got d% times to get right answer' % count) for i in range(1, 10): for j in range(1, i + 1): print('%d*%d=%d' % (i, j, i * j), end='\t') print() # num = int(input(': ')) end = int(sqrt(num)) is_prime = True # end sqrt # sqrt for x in range(2, end + 1): if num % x == 0: is_prime = False break if is_prime and num != 1: print('%d' % num) else: print('%d' % num)
17.366667
53
0.589251
fc140cda2ae3ddb2fa94e33b0e36406cb6293308
12,340
py
Python
src/toil/batchSystems/htcondor.py
ElementGenomicsInc/toil
e29a07db194469afba3edf90ffeee8f981f7344b
[ "Apache-2.0" ]
2
2019-01-16T03:55:57.000Z
2019-01-16T04:04:38.000Z
src/toil/batchSystems/htcondor.py
ElementGenomicsInc/toil
e29a07db194469afba3edf90ffeee8f981f7344b
[ "Apache-2.0" ]
4
2018-10-02T00:39:18.000Z
2018-10-02T00:52:31.000Z
src/toil/batchSystems/htcondor.py
ElementGenomicsInc/toil
e29a07db194469afba3edf90ffeee8f981f7344b
[ "Apache-2.0" ]
2
2018-10-09T06:31:52.000Z
2018-11-16T00:49:40.000Z
# Copyright (C) 2018, HTCondor Team, Computer Sciences Department, # University of Wisconsin-Madison, WI. # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. You may # obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from builtins import str import sys import os import logging import time import math from toil.batchSystems.abstractGridEngineBatchSystem import AbstractGridEngineBatchSystem import htcondor import classad logger = logging.getLogger(__name__)
40.19544
121
0.569044
fc15adfda30a5ded3481fe570a59a41b60da2bcc
26,347
py
Python
paddlespeech/t2s/modules/tacotron2/decoder.py
alanlv/PaddleSpeech
7413c9e48ac77fdece45e0b4ffe41f7746ef0583
[ "Apache-2.0" ]
null
null
null
paddlespeech/t2s/modules/tacotron2/decoder.py
alanlv/PaddleSpeech
7413c9e48ac77fdece45e0b4ffe41f7746ef0583
[ "Apache-2.0" ]
null
null
null
paddlespeech/t2s/modules/tacotron2/decoder.py
alanlv/PaddleSpeech
7413c9e48ac77fdece45e0b4ffe41f7746ef0583
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Modified from espnet(https://github.com/espnet/espnet) """Tacotron2 decoder related modules.""" import paddle import paddle.nn.functional as F import six from paddle import nn from paddlespeech.t2s.modules.tacotron2.attentions import AttForwardTA
36.290634
87
0.537405
fc165549752f98bd300323b664ce1555196f65d8
661
py
Python
pyblazing/__init__.py
Mattlk13/pyBlazing
5c3042c510ab17e9f9d1647e1873d3d04313d900
[ "Apache-2.0" ]
null
null
null
pyblazing/__init__.py
Mattlk13/pyBlazing
5c3042c510ab17e9f9d1647e1873d3d04313d900
[ "Apache-2.0" ]
null
null
null
pyblazing/__init__.py
Mattlk13/pyBlazing
5c3042c510ab17e9f9d1647e1873d3d04313d900
[ "Apache-2.0" ]
null
null
null
from .api import run_query_get_token from .api import convert_to_dask from .api import run_query_get_results from .api import run_query_get_concat_results from .api import register_file_system from .api import deregister_file_system from .api import FileSystemType, DriverType, EncryptionType from .api import SchemaFrom from .api import create_table from .api import ResultSetHandle from .api import _get_client from .api import gdf_dtype from .api import get_dtype_values from .api import get_np_dtype_to_gdf_dtype from .api import SetupOrchestratorConnection from .apiv2.context import make_default_orc_arg from .apiv2.context import make_default_csv_arg
33.05
60
0.857791
fc180c50e2be52fc8b9a19b64b0af4e3927de263
12,367
py
Python
dataset/scan2cad/s2c_collect_pgroup.py
jeonghyunkeem/PointGroup
fa90830259aeb37d2e0f203471552d2f43cbc60b
[ "Apache-2.0" ]
null
null
null
dataset/scan2cad/s2c_collect_pgroup.py
jeonghyunkeem/PointGroup
fa90830259aeb37d2e0f203471552d2f43cbc60b
[ "Apache-2.0" ]
null
null
null
dataset/scan2cad/s2c_collect_pgroup.py
jeonghyunkeem/PointGroup
fa90830259aeb37d2e0f203471552d2f43cbc60b
[ "Apache-2.0" ]
null
null
null
# Jeonghyun Kim, UVR KAIST @jeonghyunct.kaist.ac.kr import os, sys import json import h5py import numpy as np import quaternion import torch from torch.utils.data import Dataset BASE_DIR_1 = os.path.dirname(os.path.abspath(__file__)) # scan2cad BASE_DIR = os.path.dirname(BASE_DIR_1) # dataset ROOT_DIR = os.path.dirname(BASE_DIR) # PointGroup DATA_DIR = os.path.dirname(ROOT_DIR) # /root/ DATA_DIR = os.path.join(DATA_DIR, 'Dataset') # /root/Dataset DUMP_DIR = os.path.join(ROOT_DIR, 'data') sys.path.append(BASE_DIR) sys.path.append(ROOT_DIR) from s2c_map import CLASS_MAPPING, ID2NAME, CARED_CLASS_MASK from s2c_config import Scan2CADDatasetConfig import s2c_utils sys.path.append(os.path.join(ROOT_DIR, 'models/retrieval/')) DC = Scan2CADDatasetConfig() MAX_NUM_POINT = 50000 MAX_NUM_OBJ = 64 INS_NUM_POINT = 2048 FEATURE_DIMENSION = 512 MAX_DATA_SIZE = 15000 CHUNK_SIZE = 1000 INF = 9999 NOT_CARED_ID = np.array([INF]) # wall, floor # Thresholds PADDING = 0.05 SCALE_THRASHOLD = 0.05 SEG_THRESHOLD = 1 REMAPPER = np.ones(35, dtype=np.int64) * (-1) for i, x in enumerate(CARED_CLASS_MASK): REMAPPER[x] = i print(f'REMAPPER[{x:2d}] => {i:2d}') SYM2CLASS = {"__SYM_NONE": 0, "__SYM_ROTATE_UP_2": 1, "__SYM_ROTATE_UP_4": 2, "__SYM_ROTATE_UP_INF": 3} # functions ============================================================================================== # ======================================================================================================== LOG_N = 100 if __name__ == "__main__": Dataset = Scan2CADCollect(split_set='all', distr_check=True) N = len(Dataset) Dataset.collect(N, dump=False)
38.052308
147
0.537479
fc18327783ac4d0615c52f0106bc59f803cb607d
3,590
py
Python
nappy/msd2diff.py
ryokbys/nap
ddd0b5a5a956f7c335a22adb4f8e00f1d38a7804
[ "MIT" ]
27
2015-10-05T06:21:28.000Z
2021-10-04T17:08:23.000Z
nappy/msd2diff.py
ryokbys/nap
ddd0b5a5a956f7c335a22adb4f8e00f1d38a7804
[ "MIT" ]
4
2020-11-08T12:39:38.000Z
2021-01-10T22:31:36.000Z
nappy/msd2diff.py
ryokbys/nap
ddd0b5a5a956f7c335a22adb4f8e00f1d38a7804
[ "MIT" ]
4
2015-01-29T23:10:34.000Z
2022-01-08T05:20:13.000Z
#!/usr/bin/env python """ Compute diffusion coefficient from MSD data. Time interval, DT, is obtained from in.pmd in the same directory. Usage: msd2diff.py [options] MSD_FILE Options: -h, --help Show this message and exit. -o, --offset OFFSET Offset of given data. [default: 0] --plot Plot a fitted graph. [default: False] """ from __future__ import print_function import os,sys from docopt import docopt import numpy as np __author__ = "RYO KOBAYASHI" __version__ = "191212" def msd2D(ts,msds,fac,dim=3): """ Compute diffusion coefficient from time [fs] vs MSD [Ang^2] data by solving least square problem using numpy. Return diffusion coefficient multiplied by FAC. """ A= np.array([ts, np.ones(len(ts))]) A = A.T xvar = np.var(A[:,0]) p,res,_,_ = np.linalg.lstsq(A,msds,rcond=None) a = p[0] b = p[1] # fac = 1.0e-16 /1.e-15 a = a *fac /(2.0*dim) b = b *fac # print(res[0],xvar,np.mean(A[:,0]),len(ts)) std = np.sqrt(res[0]/len(ts)/xvar) *fac /(2.0*dim) return a,b,std if __name__ == "__main__": args = docopt(__doc__) fname = args['MSD_FILE'] offset = int(args['--offset']) plot = args['--plot'] ts,msds = read_out_msd(fname,offset) #...Assuming input MSD unit in A^2/fs and output in cm^2/s fac = 1.0e-16 /1.0e-15 #...Least square a,b,std = msd2D(ts,msds,fac) print(' Diffusion coefficient = {0:12.4e}'.format(a)+ ' +/- {0:12.4e} [cm^2/s]'.format(std)) if plot: import matplotlib.pyplot as plt import seaborn as sns sns.set(context='talk',style='ticks') #...Original time unit == fs unit = 'fs' tfac = 1.0 if ts[-1] > 1.0e+5: #...if max t > 100ps, time unit in ps unit = 'ps' tfac = 1.0e-3 plt.xlabel('Time ({0:s})'.format(unit)) plt.ylabel('MSD (A^2/{0:s})'.format(unit)) fvals = np.array([ (t*a+b)/fac for t in ts ]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted curve') plt.savefig("graph_msd2D.png", format='png', dpi=300, bbox_inches='tight') print(' Wrote graph_msd2D.png')
29.186992
69
0.567688
fc186568dd52a9df9e70c87a7b31fe1c1c3e1f4d
1,172
py
Python
5/part2.py
jcsesznegi/advent-of-code-2017
9710e184e092b82aa798076b9ce3915c6e42758d
[ "MIT" ]
1
2020-04-12T17:54:52.000Z
2020-04-12T17:54:52.000Z
5/part2.py
jcsesznegi/advent-of-code-2017
9710e184e092b82aa798076b9ce3915c6e42758d
[ "MIT" ]
null
null
null
5/part2.py
jcsesznegi/advent-of-code-2017
9710e184e092b82aa798076b9ce3915c6e42758d
[ "MIT" ]
null
null
null
import os f = open(os.path.join(os.path.dirname(__file__), '../input/5/part2.txt'), 'r') if __name__ == '__main__': main()
23.44
78
0.619454
fc188927db9f5bd43bd5abe64681e14292f26e08
269
py
Python
features/steps/basic_account_add_bdd.py
MhmdRyhn/behavior_test
868252e0b31596e0bff4a969745cf3b633c13695
[ "MIT" ]
null
null
null
features/steps/basic_account_add_bdd.py
MhmdRyhn/behavior_test
868252e0b31596e0bff4a969745cf3b633c13695
[ "MIT" ]
null
null
null
features/steps/basic_account_add_bdd.py
MhmdRyhn/behavior_test
868252e0b31596e0bff4a969745cf3b633c13695
[ "MIT" ]
null
null
null
import behave
22.416667
47
0.762082
fc18a51ed3a62618a4f8d1b8d53f53c96ae69319
11,944
py
Python
tests/test_sync_module.py
naveengh6/blinkpy
e821687f2b7590b13532ac596c31e8eaa6c7b69a
[ "MIT" ]
272
2017-01-29T18:43:25.000Z
2022-03-27T20:43:50.000Z
tests/test_sync_module.py
naveengh6/blinkpy
e821687f2b7590b13532ac596c31e8eaa6c7b69a
[ "MIT" ]
434
2017-01-23T20:22:51.000Z
2022-03-31T18:10:36.000Z
tests/test_sync_module.py
naveengh6/blinkpy
e821687f2b7590b13532ac596c31e8eaa6c7b69a
[ "MIT" ]
77
2017-04-15T17:04:04.000Z
2022-03-04T10:03:39.000Z
"""Tests camera and system functions.""" import unittest from unittest import mock from blinkpy.blinkpy import Blink from blinkpy.helpers.util import BlinkURLHandler from blinkpy.sync_module import BlinkSyncModule, BlinkOwl from blinkpy.camera import BlinkCamera, BlinkCameraMini
40.488136
83
0.592264
fc1a91eb27f4ff382a15602726e82a1122f6307d
2,807
py
Python
dymos/examples/min_time_climb/aero/aero.py
naylor-b/dymos
56ee72041056ae20c3332d060e291c4da93844b1
[ "Apache-2.0" ]
null
null
null
dymos/examples/min_time_climb/aero/aero.py
naylor-b/dymos
56ee72041056ae20c3332d060e291c4da93844b1
[ "Apache-2.0" ]
null
null
null
dymos/examples/min_time_climb/aero/aero.py
naylor-b/dymos
56ee72041056ae20c3332d060e291c4da93844b1
[ "Apache-2.0" ]
null
null
null
from __future__ import absolute_import import numpy as np from openmdao.api import Group from .dynamic_pressure_comp import DynamicPressureComp from .lift_drag_force_comp import LiftDragForceComp from .cd0_comp import CD0Comp from .kappa_comp import KappaComp from .cla_comp import CLaComp from .cl_comp import CLComp from .cd_comp import CDComp from .mach_comp import MachComp
34.231707
79
0.530816
fc1b9449290073ccef5e51dfe2bdedbc18900050
7,035
py
Python
stats.py
jakeb1996/SBS
3bcc0017d22674d4290be1b272aeac4836f0d5ec
[ "MIT" ]
null
null
null
stats.py
jakeb1996/SBS
3bcc0017d22674d4290be1b272aeac4836f0d5ec
[ "MIT" ]
null
null
null
stats.py
jakeb1996/SBS
3bcc0017d22674d4290be1b272aeac4836f0d5ec
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt import argparse, csv, numpy, time, os, re if __name__ == "__main__": parser = argparse.ArgumentParser(description = 'Plotter for the Software Benchmarking Script') parser.add_argument('-f', help='Results file as input (in csv format)') parser.add_argument('-t', help='Name of tool', default=None) parser.add_argument('--wincntxmnu', help='Indicates SBS stats was launched from the Windows context menu. See README for help.', action='store_true') args = parser.parse_args() # Not used #if args.wincntxmnu: # args.t = raw_input('Enter the plot prefix: ') main(args.f, args.t)
33.341232
338
0.519119
fc1d23d6b61a9e5c408d579ed37655541819b9f0
23,402
py
Python
callback_handlers.py
andrey18106/vocabulary_bot
68a5835fb69e255df1766c2ed5c5228daaa4f06f
[ "MIT" ]
null
null
null
callback_handlers.py
andrey18106/vocabulary_bot
68a5835fb69e255df1766c2ed5c5228daaa4f06f
[ "MIT" ]
null
null
null
callback_handlers.py
andrey18106/vocabulary_bot
68a5835fb69e255df1766c2ed5c5228daaa4f06f
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # ===== Default imports ===== import asyncio import logging # ===== External libs imports ===== from aiogram import Bot, Dispatcher, types from aiogram.dispatcher import FSMContext # ===== Local imports ===== from analytics import BotAnalytics from db_manager import DbManager from lang_manager import LangManager from markups_manager import MarkupManager from states.Dictionary import DictionaryQuizState, DictionaryState, DictionaryEditWordState, DictionarySearchWordState from states.Mailing import AdminMailingState import pagination
61.746702
119
0.563499
fc1d28c4600f03845019e2280e8c9b05ec587f01
930
py
Python
1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/06_Nested-Loops/02.Exercise-06-Special-Numbers.py
karolinanikolova/SoftUni-Software-Engineering
7891924956598b11a1e30e2c220457c85c40f064
[ "MIT" ]
null
null
null
1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/06_Nested-Loops/02.Exercise-06-Special-Numbers.py
karolinanikolova/SoftUni-Software-Engineering
7891924956598b11a1e30e2c220457c85c40f064
[ "MIT" ]
null
null
null
1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/06_Nested-Loops/02.Exercise-06-Special-Numbers.py
karolinanikolova/SoftUni-Software-Engineering
7891924956598b11a1e30e2c220457c85c40f064
[ "MIT" ]
null
null
null
# 6. # , N, , "" # 1111 9999. , : # N . # : N = 16, 2418 : # 16 / 2 = 8 # 16 / 4 = 4 # 16 / 1 = 16 # 16 / 8 = 2 N = int(input()) for number in range(1111, 9999 + 1): is_number_special = True number_as_string = str(number) # Could also write for index, digit in enumerate(number_as_string): but since we don't need the index we don't need enumerate. for digit in number_as_string: if int(digit) == 0 or N % int(digit) != 0: is_number_special = False break if is_number_special: print(f'{number_as_string}', end = ' ')
35.769231
130
0.665591
fc1d95b3a3f568e9cf0561a8f283914e5b1db140
1,815
py
Python
skopt/tests/test_transformers.py
sqbl/scikit-optimize
c1866d5a9ad67efe93ac99736bfc2dc659b561d4
[ "BSD-3-Clause" ]
null
null
null
skopt/tests/test_transformers.py
sqbl/scikit-optimize
c1866d5a9ad67efe93ac99736bfc2dc659b561d4
[ "BSD-3-Clause" ]
null
null
null
skopt/tests/test_transformers.py
sqbl/scikit-optimize
c1866d5a9ad67efe93ac99736bfc2dc659b561d4
[ "BSD-3-Clause" ]
null
null
null
import pytest import numbers import numpy as np from numpy.testing import assert_raises from numpy.testing import assert_array_equal from numpy.testing import assert_equal from numpy.testing import assert_raises_regex from skopt.space import LogN, Normalize
34.245283
72
0.738292
fc1f1d11a9a9d323ee25ccd432c9e05f59ae89c2
29,526
py
Python
tokenization_numerical.py
dspoka/mnm
f212e8d5697a4556c6469d469a2930b203667828
[ "MIT" ]
1
2021-07-08T04:18:30.000Z
2021-07-08T04:18:30.000Z
tokenization_numerical.py
dspoka/mnm
f212e8d5697a4556c6469d469a2930b203667828
[ "MIT" ]
1
2021-08-24T03:36:53.000Z
2021-08-24T03:36:53.000Z
tokenization_numerical.py
dspoka/mnm
f212e8d5697a4556c6469d469a2930b203667828
[ "MIT" ]
1
2021-07-08T04:18:32.000Z
2021-07-08T04:18:32.000Z
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # 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. """Tokenization classes.""" from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging import os import sys import unicodedata from io import open from transformers import PreTrainedTokenizer logger = logging.getLogger(__name__) VOCAB_FILES_NAMES = {'vocab_file': 'vocab.txt'} PRETRAINED_VOCAB_FILES_MAP = { 'vocab_file': { 'bert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt", 'bert-large-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt", 'bert-base-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt", 'bert-large-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt", 'bert-base-multilingual-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt", 'bert-base-multilingual-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt", 'bert-base-chinese': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt", 'bert-base-german-cased': "https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt", 'bert-large-uncased-whole-word-masking': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt", 'bert-large-cased-whole-word-masking': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt", 'bert-large-uncased-whole-word-masking-finetuned-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt", 'bert-large-cased-whole-word-masking-finetuned-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt", 'bert-base-cased-finetuned-mrpc': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt", } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { 'bert-base-uncased': 512, 'bert-large-uncased': 512, 'bert-base-cased': 512, 'bert-large-cased': 512, 'bert-base-multilingual-uncased': 512, 'bert-base-multilingual-cased': 512, 'bert-base-chinese': 512, 'bert-base-german-cased': 512, 'bert-large-uncased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-base-cased-finetuned-mrpc': 512, } def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() with open(vocab_file, "r", encoding="utf-8") as reader: tokens = reader.readlines() for index, token in enumerate(tokens): token = token.rstrip('\n') vocab[token] = index return vocab def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens # _numbers = '[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?' # fraction_pattern = re.compile(_fraction) # number_pattern = re.compile(_numbers) def _is_whitespace(char): """Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat = unicodedata.category(char) if cat == "Zs": return True return False def _is_control(char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): return True return False def _is_punctuation(char): """Checks whether `chars` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for # consistency. if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)): return True cat = unicodedata.category(char) # if cat.startswith("P") and cp != 46: if cat.startswith("P"): return True return False ################ # Small = { 'zero': 0.0, 'one': 1.0, 'two': 2.0, 'three': 3.0, 'four': 4.0, 'five': 5.0, 'six': 6.0, 'seven': 7.0, 'eight': 8.0, 'nine': 9.0, 'ten': 10.0, 'eleven': 11.0, 'twelve': 12.0, 'thirteen': 13.0, 'fourteen': 14.0, 'fifteen': 15.0, 'sixteen': 16.0, 'seventeen': 17.0, 'eighteen': 18.0, 'nineteen': 19.0, 'twenty': 20.0, 'thirty': 30.0, 'forty': 40.0, 'fifty': 50.0, 'sixty': 60.0, 'seventy': 70.0, 'eighty': 80.0, 'ninety': 90.0 } Magnitude = { 'thousand': 1000.0, 'million': 1000000.0, 'billion': 1000000000.0, 'trillion': 1000000000000.0, 'quadrillion': 1000000000000000.0, 'quintillion': 1000000000000000000.0, 'sextillion': 1000000000000000000000.0, 'septillion': 1000000000000000000000000.0, 'octillion': 1000000000000000000000000000.0, 'nonillion': 1000000000000000000000000000000.0, } def preprocess(sent, remove_pos=False, never_split=None): """ Preprocess the sentence by: . remove commas from numbers (2,000 -> 2000) . remove endings from ordinal numbers (2nd -> 2) . convert "a {hundred,thousand...}" to "one {hundred,thousand,...}" so it can be handled by text2num function . convert "digit digitword" (24 hundred) -> 2400 and return the sentence's preprocessed list of words that should be passed into text2num. """ if remove_pos: words = [word[:word.rfind('_')] for word in sent.strip().split()] else: words = [word for word in sent.strip().split()] tokenizer = BasicTokenizer(do_lower_case=True, never_split=never_split) words = tokenizer.tokenize(sent) # sent = ' '.join(tokens) words_lower = [word.lower() for word in words] # remove commas from numbers "2,000" -> 2000 and remove endings from ordinal numbers for i in range(len(words)): new_word = words_lower[i].replace(',', '') if new_word.endswith(('th', 'rd', 'st', 'nd')): new_word = new_word[:-2] try: if new_word not in ['infinity', 'inf', 'nan']: int_word = float(new_word) # words[i] = str(int_word) words[i] = new_word except ValueError: pass # only modify this word if it's an int after preprocessing Magnitude_with_hundred = Magnitude.copy() Magnitude_with_hundred['hundred'] = 100 # convert "a {hundred,thousand,million,...}" to "one {hundred,thousand,million,...}" for i in range(len(words)-1): if words_lower[i] == 'a' and words_lower[i+1] in Magnitude_with_hundred: words[i] = 'one' # convert "24 {Magnitude}" -> 24000000000000 (mix of digits and words) new_words = [] sigs = [] i = 0 while i < len(words)-1: if check_int(words_lower[i]) and words_lower[i+1] in Magnitude_with_hundred: new_words.append(str(float(words_lower[i]) * Magnitude_with_hundred[words_lower[i+1]])) sigs.append(f'{words_lower[i]} {words_lower[i+1]}') i += 1 else: new_words.append(words[i]) sigs.append('') if i == len(words) - 2: new_words.append(words[i+1]) sigs.append('') i += 1 return new_words, sigs # # def normalize_numbers_in_sent(sent, remove_pos=False, never_split=None): """ Given a sentence, perform preprocessing and normalize number words to digits. :param sent: sentence (str) :return: a list of normalized words from the sentence """ out_words = [] words, sigfigs = preprocess(sent, remove_pos, never_split) out_sigfigs = [] i = 0 while i < len(words): for j in range(len(words), i, -1): try: number = str(text2num(words[i:j])) if sigfigs[i] == '': out_sigfigs.append(' '.join(words[i:j])) else: out_sigfigs.append(sigfigs[i]) out_words.append(number) i = j-1 # skip this sequence since we replaced it with a number break except NumberException: if j == i+1: out_sigfigs.append('-1') out_words.append(words[i]) i += 1 assert len(out_sigfigs) == len(out_words) return out_words, out_sigfigs
39.953992
183
0.601605
fc1f29f43c293c82628f38a87129e37c79fd02ea
6,694
py
Python
dipole/splitting_dipole.py
wheelerMT/spin-1_BEC
e8ea34699b4001847c6b4c7451c11be241ce598f
[ "MIT" ]
null
null
null
dipole/splitting_dipole.py
wheelerMT/spin-1_BEC
e8ea34699b4001847c6b4c7451c11be241ce598f
[ "MIT" ]
null
null
null
dipole/splitting_dipole.py
wheelerMT/spin-1_BEC
e8ea34699b4001847c6b4c7451c11be241ce598f
[ "MIT" ]
null
null
null
import numpy as np import multiprocessing as mp import pyfftw from numpy import pi, exp, sqrt, sin, cos, conj, arctan, tanh, tan from numpy import heaviside as heav from include import helper import h5py # ---------Spatial and potential parameters-------------- Mx = My = 64 Nx = Ny = 128 # Number of grid pts dx = dy = 1 / 2 # Grid spacing dkx = pi / (Mx * dx) dky = pi / (My * dy) # K-space spacing len_x = Nx * dx # Box length len_y = Ny * dy x = np.arange(-Mx, Mx) * dx y = np.arange(-My, My) * dy X, Y = np.meshgrid(x, y) # Spatial meshgrid data = h5py.File('../data/splitting_dipole_data.hdf5', 'a') data.create_dataset('grid/x', x.shape, data=x) data.create_dataset('grid/y', y.shape, data=y) kx = np.fft.fftshift(np.arange(-Mx, Mx) * dkx) ky = np.fft.fftshift(np.arange(-My, My) * dky) Kx, Ky = np.meshgrid(kx, ky) # K-space meshgrid # Initialising FFTs cpu_count = mp.cpu_count() wfn_data = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') fft_forward = pyfftw.FFTW(wfn_data, wfn_data, axes=(0, 1), threads=cpu_count) fft_backward = pyfftw.FFTW(wfn_data, wfn_data, direction='FFTW_BACKWARD', axes=(0, 1), threads=cpu_count) # Framework for wavefunction data psi_plus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_0_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') psi_minus_k = pyfftw.empty_aligned((Nx, Ny), dtype='complex128') # Controlled variables V = 0. # Doubly periodic box p = q = 0. c0 = 2 c1 = 0.5 # Effective 3-component BEC k = 0 # Array index # ------------------------------ Generating SQV's ------------------------- # Euler angles alpha = 0. beta = pi / 4 gamma = 0. N_vort = 2 # Number of vortices pos = [-10, 0, 10, 0] theta_k = np.empty((N_vort, Nx, Ny)) theta_tot = np.empty((Nx, Ny)) for k in range(N_vort // 2): # Scaling positional arguments Y_minus = 2 * pi * (Y - pos[k]) / len_y X_minus = 2 * pi * (X - pos[N_vort // 2 + k]) / len_x Y_plus = 2 * pi * (Y - pos[N_vort + k]) / len_y X_plus = 2 * pi * (X - pos[3 * N_vort // 2 + k]) / len_x x_plus = 2 * pi * pos[3 * N_vort // 2 + k] / len_x x_minus = 2 * pi * pos[N_vort // 2 + k] / len_x for nn in np.arange(-5, 5): theta_k[k, :, :] += arctan( tanh((Y_minus + 2 * pi * nn) / 2) * tan((X_minus - pi) / 2)) \ - arctan(tanh((Y_plus + 2 * pi * nn) / 2) * tan((X_plus - pi) / 2)) \ + pi * (heav(X_plus, 1.) - heav(X_minus, 1.)) theta_k[k, :, :] -= (2 * pi * Y / len_y) * (x_plus - x_minus) / (2 * pi) theta_tot += theta_k[k, :, :] # Initial wavefunction Psi = np.empty((3, Nx, Ny), dtype='complex128') Psi[0, :, :] = np.zeros((Nx, Ny)) + 0j Psi[1, :, :] = np.ones((Nx, Ny), dtype='complex128') * exp(1j * theta_tot) Psi[2, :, :] = np.zeros((Nx, Ny)) + 0j psi_plus, psi_0, psi_minus = helper.rotation(Psi, Nx, Ny, alpha, beta, gamma) # Performs rotation to wavefunction # Aligning wavefunction to potentially speed up FFTs pyfftw.byte_align(psi_plus) pyfftw.byte_align(psi_0) pyfftw.byte_align(psi_minus) # ------------------------------------------------------------------------ # Normalisation constants N_plus = dx * dy * np.linalg.norm(psi_plus) ** 2 N_0 = dx * dy * np.linalg.norm(psi_0) ** 2 N_minus = dx * dy * np.linalg.norm(psi_minus) ** 2 # Time steps, number and wavefunction save variables Nt = 80000 Nframe = 200 dt = 5e-3 t = 0. # Saving time variables: data.create_dataset('time/Nt', data=Nt) data.create_dataset('time/dt', data=dt) data.create_dataset('time/Nframe', data=Nframe) # Setting up variables to be sequentially saved: psi_plus_save = data.create_dataset('wavefunction/psi_plus', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_0_save = data.create_dataset('wavefunction/psi_0', (Nx, Ny, Nt/Nframe), dtype='complex128') psi_minus_save = data.create_dataset('wavefunction/psi_minus', (Nx, Ny, Nt/Nframe), dtype='complex128') for i in range(Nt): # Spin vector terms: F_perp = sqrt(2.) * (conj(psi_plus) * psi_0 + conj(psi_0) * psi_minus) Fz = abs(psi_plus) ** 2 - abs(psi_minus) ** 2 F = sqrt(abs(Fz) ** 2 + abs(F_perp) ** 2) # Magnitude of spin vector # Total density n = abs(psi_minus) ** 2 + abs(psi_0) ** 2 + abs(psi_plus) ** 2 # Sin and cosine terms for solution C = cos(c1 * F * (-1j * dt)) if F.min() == 0: S = np.zeros((Nx, Ny), dtype='complex128') # Ensures no division by zero else: S = 1j * sin(c1 * F * (-1j * dt)) / F # Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus, psi_minus_k) # Computing kinetic energy + quadratic Zeeman psi_plus_k *= exp(-0.25 * dt * (Kx ** 2 + Ky ** 2 + 2 * q)) / (Nx * Ny) psi_0_k *= exp(-0.25 * dt * (Kx ** 2 + Ky ** 2)) / (Nx * Ny) psi_minus_k *= exp(-0.25 * dt * (Kx ** 2 + Ky ** 2 + 2 * q)) / (Nx * Ny) # Inverse FFTs fft_backward(psi_plus_k, psi_plus) fft_backward(psi_0_k, psi_0) fft_backward(psi_minus_k, psi_minus) # Rescaling psi_plus *= (Nx * Ny) psi_0 *= (Nx * Ny) psi_minus *= (Nx * Ny) # Trap, linear Zeeman & interaction flow psi_plus = ((C - S * Fz) * psi_plus - 1. / sqrt(2.) * S * conj(F_perp) * psi_0) * exp(-dt * (V - p + c0 * n)) psi_0 = (-1. / sqrt(2.) * S * F_perp * psi_plus + C * psi_0 - 1. / sqrt(2.) * S * conj(F_perp) * psi_minus) \ * exp(-dt * (V + c0 * n)) psi_minus = (-1. / sqrt(2.) * S * F_perp * psi_0 + (C + S * Fz) * psi_minus) * exp(-dt * (V + p + c0 * n)) # Forward FFTs fft_forward(psi_plus, psi_plus_k) fft_forward(psi_0, psi_0_k) fft_forward(psi_minus, psi_minus_k) # Computing kinetic energy + quadratic Zeeman psi_plus_k *= exp(-0.25 * dt * (Kx ** 2 + Ky ** 2 + 2 * q)) / (Nx * Ny) psi_0_k *= exp(-0.25 * dt * (Kx ** 2 + Ky ** 2)) / (Nx * Ny) psi_minus_k *= exp(-0.25 * dt * (Kx ** 2 + Ky ** 2 + 2 * q)) / (Nx * Ny) # Inverse FFTs fft_backward(psi_plus_k, psi_plus) fft_backward(psi_0_k, psi_0) fft_backward(psi_minus_k, psi_minus) # Rescaling psi_plus *= (Nx * Ny) psi_0 *= (Nx * Ny) psi_minus *= (Nx * Ny) # Renormalizing wavefunction psi_plus *= sqrt(N_plus) / sqrt(dx * dy * np.linalg.norm(psi_plus) ** 2) psi_0 *= sqrt(N_0) / sqrt(dx * dy * np.linalg.norm(psi_0) ** 2) psi_minus *= sqrt(N_minus) / sqrt(dx * dy * np.linalg.norm(psi_minus) ** 2) # Prints current time and saves data to an array if np.mod(i, Nframe) == 0: print('it = %1.4f' % t) psi_plus_save[:, :, k] = psi_plus[:, :] psi_0_save[:, :, k] = psi_0[:, :] psi_minus_save[:, :, k] = psi_minus[:, :] k += 1 t += dt data.close()
34.864583
114
0.586047
fc1fa639ebbd112d3143f8455e253cf35ff2e2c9
1,033
py
Python
src/main/resources/scripts/crumbDiag.py
cam-laf/vectorcast-execution-plugin
fd54e8580886084d040d21fa809be8a609d44d8e
[ "MIT" ]
4
2019-06-28T22:46:06.000Z
2020-05-28T08:53:37.000Z
src/main/resources/scripts/crumbDiag.py
cam-laf/vectorcast-execution-plugin
fd54e8580886084d040d21fa809be8a609d44d8e
[ "MIT" ]
18
2018-09-26T15:32:11.000Z
2021-10-01T21:57:14.000Z
src/main/resources/scripts/crumbDiag.py
cam-laf/vectorcast-execution-plugin
fd54e8580886084d040d21fa809be8a609d44d8e
[ "MIT" ]
11
2017-03-19T18:37:16.000Z
2020-04-06T19:46:09.000Z
from __future__ import print_function import requests import sys import os verbose=True try: username=os.environ['USERNAME'] password=os.environ['PASSWORD'] except: print("Crumb Diaganostic requires USERNAME/PASSWORD to be set as environment variables") sys.exit(-1) jenkins_url=os.environ['JENKINS_URL'] url = jenkins_url + 'crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)' print(url) if username: crumb = requests.get(url, auth=(username, password)) if crumb.status_code == 200: crumb_headers = dict() crumb_headers[crumb.text.split(":")[0]] = crumb.text.split(":")[1] if verbose: print("Got crumb: %s" % crumb.text) else: print("Failed to get crumb") print("\nYou may need to enable \"Prevent Cross Site Request Forgery exploits\" from:") print("Manage Jenkins > Configure Global Security > CSRF Protection and select the appropriate Crumb Algorithm") print(jenkins_url + "/configureSecurity") sys.exit(-1)
35.62069
120
0.683446
fc20aff0ea13fa9ee03eb24e8c0870f91ab872ab
219
py
Python
URI/1-Beginner/1099.py
vicenteneto/online-judge-solutions
4176e2387658f083b980d7b49bc98300a4c28411
[ "MIT" ]
null
null
null
URI/1-Beginner/1099.py
vicenteneto/online-judge-solutions
4176e2387658f083b980d7b49bc98300a4c28411
[ "MIT" ]
null
null
null
URI/1-Beginner/1099.py
vicenteneto/online-judge-solutions
4176e2387658f083b980d7b49bc98300a4c28411
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- for i in range(int(raw_input())): x, y = [int(x) for x in raw_input().split()] if x > y: x, y = y, x x += 1 if x % 2 == 0 else 2 print sum([j for j in range(x, y, 2)])
19.909091
48
0.465753
fc2274d5bd59faf9232572f6514dafd536557966
625
py
Python
mock_file.py
MahirGulzar/fpointnet-tiny
e79406f648573d50fa3988ca987db652ab1286b8
[ "MIT" ]
null
null
null
mock_file.py
MahirGulzar/fpointnet-tiny
e79406f648573d50fa3988ca987db652ab1286b8
[ "MIT" ]
null
null
null
mock_file.py
MahirGulzar/fpointnet-tiny
e79406f648573d50fa3988ca987db652ab1286b8
[ "MIT" ]
null
null
null
import tensorflow as tf FLIPPING_TENSOR = tf.constant([1.0, -1.0, 1.0]) mock_data = tf.constant([ [1., 2., 3.], [4., 5., 6.], [7., 8., 9.] ]) mock_labels = tf.constant([ [1.], [0.], [1.] ]) sampling_lambda = lambda x, y: sample_data(x, y, 512) train_data = tf.data.Dataset.from_tensors((mock_data, mock_labels)) \ .map(sampling_lambda) \ .unbatch() \ .batch(1) \ .repeat(5) for x, y in train_data: print(x)
19.53125
69
0.6048
fc23560a0050cb2a7fdf80d872323f5e40124603
118
py
Python
myapp.py
dataholiks/flask_heroku_scheduler
d2b4c2c8fdee066aea729c1566bfbaf52c068557
[ "MIT" ]
7
2019-03-20T01:48:42.000Z
2021-07-02T15:51:36.000Z
myapp.py
dataholiks/flask_heroku_scheduler
d2b4c2c8fdee066aea729c1566bfbaf52c068557
[ "MIT" ]
null
null
null
myapp.py
dataholiks/flask_heroku_scheduler
d2b4c2c8fdee066aea729c1566bfbaf52c068557
[ "MIT" ]
1
2020-09-17T06:36:24.000Z
2020-09-17T06:36:24.000Z
from flask import Flask app = Flask(__name__)
14.75
40
0.669492
fc241e5e9d6a198e302aa50f27135ed63d4ecd94
629
py
Python
day_ok/schedule/migrations/0027_auto_20210216_1337.py
bostud/day_ok
2bcee68252b698f5818808d1766fb3ec3f07fce8
[ "MIT" ]
null
null
null
day_ok/schedule/migrations/0027_auto_20210216_1337.py
bostud/day_ok
2bcee68252b698f5818808d1766fb3ec3f07fce8
[ "MIT" ]
16
2021-02-27T08:36:19.000Z
2021-04-07T11:43:31.000Z
day_ok/schedule/migrations/0027_auto_20210216_1337.py
bostud/day_ok
2bcee68252b698f5818808d1766fb3ec3f07fce8
[ "MIT" ]
null
null
null
# Generated by Django 3.1.6 on 2021-02-16 11:37 from django.db import migrations, models
26.208333
101
0.599364
fc24427e78d6696d2cac568f07f35aa2881831bf
10,683
py
Python
Blog.py
OliverChao/PyWhoAmI
8742e0a44c4e673d038779b01b14b0cfb7d5395f
[ "MIT" ]
null
null
null
Blog.py
OliverChao/PyWhoAmI
8742e0a44c4e673d038779b01b14b0cfb7d5395f
[ "MIT" ]
null
null
null
Blog.py
OliverChao/PyWhoAmI
8742e0a44c4e673d038779b01b14b0cfb7d5395f
[ "MIT" ]
null
null
null
import aiohttp import asyncio import time import time import argparse import glob import os import shutil import random import re import requests import sys from concurrent import futures import pdfkit import time from retrying import retry from pygments import highlight from pygments.lexers import guess_lexer, get_lexer_by_name from pygments.lexers import CppLexer from pygments.formatters.terminal import TerminalFormatter from pygments.util import ClassNotFound from pyquery import PyQuery as pq from requests.exceptions import ConnectionError from requests.exceptions import SSLError import numbers if sys.version < '3': import codecs from urllib import quote as url_quote from urllib import getproxies # Handling Unicode: http://stackoverflow.com/a/6633040/305414 else: from urllib.request import getproxies from urllib.parse import quote as url_quote scripFilePath = os.path.split(os.path.realpath(__file__))[0] PDF_DIR = os.path.join(scripFilePath,'whoamiPDFdir') CPP_DIR = os.path.join(scripFilePath,'whoamiCPPdir')
33.914286
114
0.529346
fc24c739bd5d57047e0ff4c5f882289fbb007117
722
py
Python
corehq/apps/app_manager/tests/test_xml_parsing.py
dslowikowski/commcare-hq
ad8885cf8dab69dc85cb64f37aeaf06106124797
[ "BSD-3-Clause" ]
1
2015-02-10T23:26:39.000Z
2015-02-10T23:26:39.000Z
corehq/apps/app_manager/tests/test_xml_parsing.py
SEL-Columbia/commcare-hq
992ee34a679c37f063f86200e6df5a197d5e3ff6
[ "BSD-3-Clause" ]
null
null
null
corehq/apps/app_manager/tests/test_xml_parsing.py
SEL-Columbia/commcare-hq
992ee34a679c37f063f86200e6df5a197d5e3ff6
[ "BSD-3-Clause" ]
null
null
null
from django.test import SimpleTestCase as TestCase from corehq.apps.app_manager.models import _parse_xml import os
36.1
95
0.634349
fc26055543d8ffb1b618b1328cc4ad7000d27faf
25,605
py
Python
S4/S4 Library/generated/protocolbuffers/Localization_pb2.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
1
2021-05-20T19:33:37.000Z
2021-05-20T19:33:37.000Z
S4/S4 Library/generated/protocolbuffers/Localization_pb2.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
null
null
null
S4/S4 Library/generated/protocolbuffers/Localization_pb2.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
null
null
null
import protocolbuffers.Consts_pb2 as Consts_pb2 from google.protobuf import descriptor, message, reflection DESCRIPTOR = descriptor.FileDescriptor(name = 'Localization.proto', package = 'EA.Sims4.Network', serialized_pb = '\n\x12Localization.proto\x12\x10EA.Sims4.Network\x1a\x0cConsts.proto"\x85\n\n\x14LocalizedStringToken\x12G\n\x04type\x18\x01 \x02(\x0e20.EA.Sims4.Network.LocalizedStringToken.TokenType:\x07INVALID\x126\n\x08rdl_type\x18\x02 \x01(\x0e2$.EA.Sims4.Network.SocialRichDataType\x12\x12\n\nfirst_name\x18\x03 \x01(\t\x12\x11\n\tlast_name\x18\x04 \x01(\t\x12\x15\n\rfull_name_key\x18\x05 \x01(\r\x12\x11\n\tis_female\x18\x06 \x01(\x08\x12\x0e\n\x06sim_id\x18\x07 \x01(\x04\x126\n\x0btext_string\x18\x08 \x01(\x0b2!.EA.Sims4.Network.LocalizedString\x12\x0e\n\x06number\x18\t \x01(\x02\x12\x12\n\npersona_id\x18\n \x01(\x04\x12\x12\n\naccount_id\x18\x0b \x01(\x04\x12\x16\n\x0epersona_string\x18\x0c \x01(\t\x12\x0f\n\x07zone_id\x18\r \x01(\x04\x12\x10\n\x08world_id\x18\x0e \x01(\r\x12\x11\n\tzone_name\x18\x0f \x01(\t\x12\x10\n\x08event_id\x18\x10 \x01(\x04\x12\x17\n\x0fevent_type_hash\x18\x11 \x01(\r\x12\x17\n\x0fskill_name_hash\x18\x12 \x01(\r\x12\x13\n\x0bskill_level\x18\x13 \x01(\r\x12\x12\n\nskill_guid\x18\x14 \x01(\x04\x12\x17\n\x0ftrait_name_hash\x18\x15 \x01(\r\x12\x12\n\ntrait_guid\x18\x16 \x01(\x04\x12\x15\n\rbit_name_hash\x18\x17 \x01(\r\x12\x10\n\x08bit_guid\x18\x18 \x01(\x04\x12\x18\n\x10catalog_name_key\x18\x19 \x01(\r\x12\x1f\n\x17catalog_description_key\x18\x1a \x01(\r\x12\x13\n\x0bcustom_name\x18\x1b \x01(\t\x12\x1a\n\x12custom_description\x18\x1c \x01(\t\x12\x12\n\ncareer_uid\x18\x1d \x01(\x04\x12\x11\n\tmemory_id\x18\x1e \x01(\x04\x12\x1a\n\x12memory_string_hash\x18\x1f \x01(\r\x12\x10\n\x08raw_text\x18 \x01(\t\x12A\n\rdate_and_time\x18! \x01(\x0b2*.EA.Sims4.Network.LocalizedDateAndTimeData\x12E\n\x08sim_list\x18" \x03(\x0b23.EA.Sims4.Network.LocalizedStringToken.SubTokenData\x1a\x01\n\x0cSubTokenData\x12G\n\x04type\x18\x01 \x02(\x0e20.EA.Sims4.Network.LocalizedStringToken.TokenType:\x07INVALID\x12\x12\n\nfirst_name\x18\x02 \x01(\t\x12\x11\n\tlast_name\x18\x03 \x01(\t\x12\x15\n\rfull_name_key\x18\x04 \x01(\r\x12\x11\n\tis_female\x18\x05 \x01(\x08"\x93\x01\n\tTokenType\x12\x0b\n\x07INVALID\x10\x00\x12\x07\n\x03SIM\x10\x01\x12\n\n\x06STRING\x10\x02\x12\x0c\n\x08RAW_TEXT\x10\x03\x12\n\n\x06NUMBER\x10\x04\x12\n\n\x06OBJECT\x10\x05\x12\x11\n\rDATE_AND_TIME\x10\x06\x12\x0c\n\x08RICHDATA\x10\x07\x12\x0f\n\x0bSTRING_LIST\x10\x08\x12\x0c\n\x08SIM_LIST\x10\t"\x9e\x01\n\x18LocalizedDateAndTimeData\x12\x0f\n\x07seconds\x18\x01 \x01(\r\x12\x0f\n\x07minutes\x18\x02 \x01(\r\x12\r\n\x05hours\x18\x03 \x01(\r\x12\x0c\n\x04date\x18\x04 \x01(\r\x12\r\n\x05month\x18\x05 \x01(\r\x12\x11\n\tfull_year\x18\x06 \x01(\r\x12!\n\x19date_and_time_format_hash\x18\x07 \x01(\r"W\n\x0fLocalizedString\x12\x0c\n\x04hash\x18\x01 \x02(\r\x126\n\x06tokens\x18\x02 \x03(\x0b2&.EA.Sims4.Network.LocalizedStringToken"W\n\x17LocalizedStringValidate\x12<\n\x11localized_strings\x18\x01 \x03(\x0b2!.EA.Sims4.Network.LocalizedString') _LOCALIZEDSTRINGTOKEN_TOKENTYPE = descriptor.EnumDescriptor(name = 'TokenType', full_name = 'EA.Sims4.Network.LocalizedStringToken.TokenType', filename = None, file = DESCRIPTOR, values = [ descriptor.EnumValueDescriptor(name = 'INVALID', index = 0, number = 0, options = None, type = None), descriptor.EnumValueDescriptor(name = 'SIM', index = 1, number = 1, options = None, type = None), descriptor.EnumValueDescriptor(name = 'STRING', index = 2, number = 2, options = None, type = None), descriptor.EnumValueDescriptor(name = 'RAW_TEXT', index = 3, number = 3, options = None, type = None), descriptor.EnumValueDescriptor(name = 'NUMBER', index = 4, number = 4, options = None, type = None), descriptor.EnumValueDescriptor(name = 'OBJECT', index = 5, number = 5, options = None, type = None), descriptor.EnumValueDescriptor(name = 'DATE_AND_TIME', index = 6, number = 6, options = None, type = None), descriptor.EnumValueDescriptor(name = 'RICHDATA', index = 7, number = 7, options = None, type = None), descriptor.EnumValueDescriptor(name = 'STRING_LIST', index = 8, number = 8, options = None, type = None), descriptor.EnumValueDescriptor(name = 'SIM_LIST', index = 9, number = 9, options = None, type = None)], containing_type = None, options = None, serialized_start = 1193, serialized_end = 1340) _LOCALIZEDSTRINGTOKEN_SUBTOKENDATA = descriptor.Descriptor(name = 'SubTokenData', full_name = 'EA.Sims4.Network.LocalizedStringToken.SubTokenData', filename = None, file = DESCRIPTOR, containing_type = None, fields = [ descriptor.FieldDescriptor(name = 'type', full_name = 'EA.Sims4.Network.LocalizedStringToken.SubTokenData.type', index = 0, number = 1, type = 14, cpp_type = 8, label = 2, has_default_value = True, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'first_name', full_name = 'EA.Sims4.Network.LocalizedStringToken.SubTokenData.first_name', index = 1, number = 2, type = 9, cpp_type = 9, label = 1, has_default_value = False, default_value = b''.decode('utf-8'), message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'last_name', full_name = 'EA.Sims4.Network.LocalizedStringToken.SubTokenData.last_name', index = 2, number = 3, type = 9, cpp_type = 9, label = 1, has_default_value = False, default_value = b''.decode('utf-8'), message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'full_name_key', full_name = 'EA.Sims4.Network.LocalizedStringToken.SubTokenData.full_name_key', index = 3, number = 4, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'is_female', full_name = 'EA.Sims4.Network.LocalizedStringToken.SubTokenData.is_female', index = 4, number = 5, type = 8, cpp_type = 7, label = 1, has_default_value = False, default_value = False, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None)], extensions = [], nested_types = [], enum_types = [], options = None, is_extendable = False, extension_ranges = [], serialized_start = 1022, serialized_end = 1190) _LOCALIZEDSTRINGTOKEN = descriptor.Descriptor( name = 'LocalizedStringToken', full_name = 'EA.Sims4.Network.LocalizedStringToken', filename = None, file = DESCRIPTOR, containing_type = None, fields = [ descriptor.FieldDescriptor(name = 'type', full_name = 'EA.Sims4.Network.LocalizedStringToken.type', index = 0, number = 1, type = 14, cpp_type = 8, label = 2, has_default_value = True, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'rdl_type', full_name = 'EA.Sims4.Network.LocalizedStringToken.rdl_type', index = 1, number = 2, type = 14, cpp_type = 8, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'first_name', full_name = 'EA.Sims4.Network.LocalizedStringToken.first_name', index = 2, number = 3, type = 9, cpp_type = 9, label = 1, has_default_value = False, default_value = b''.decode('utf-8'), message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'last_name', full_name = 'EA.Sims4.Network.LocalizedStringToken.last_name', index = 3, number = 4, type = 9, cpp_type = 9, label = 1, has_default_value = False, default_value = b''.decode('utf-8'), message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'full_name_key', full_name = 'EA.Sims4.Network.LocalizedStringToken.full_name_key', index = 4, number = 5, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'is_female', full_name = 'EA.Sims4.Network.LocalizedStringToken.is_female', index = 5, number = 6, type = 8, cpp_type = 7, label = 1, has_default_value = False, default_value = False, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'sim_id', full_name = 'EA.Sims4.Network.LocalizedStringToken.sim_id', index = 6, number = 7, type = 4, cpp_type = 4, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'text_string', full_name = 'EA.Sims4.Network.LocalizedStringToken.text_string', index = 7, number = 8, type = 11, cpp_type = 10, label = 1, has_default_value = False, default_value = None, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'number', full_name = 'EA.Sims4.Network.LocalizedStringToken.number', index = 8, number = 9, type = 2, cpp_type = 6, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'persona_id', full_name = 'EA.Sims4.Network.LocalizedStringToken.persona_id', index = 9, number = 10, type = 4, cpp_type = 4, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'account_id', full_name = 'EA.Sims4.Network.LocalizedStringToken.account_id', index = 10, number = 11, type = 4, cpp_type = 4, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'persona_string', full_name = 'EA.Sims4.Network.LocalizedStringToken.persona_string', index = 11, number = 12, type = 9, cpp_type = 9, label = 1, has_default_value = False, default_value = b''.decode('utf-8'), message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'zone_id', full_name = 'EA.Sims4.Network.LocalizedStringToken.zone_id', index = 12, number = 13, type = 4, cpp_type = 4, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'world_id', full_name = 'EA.Sims4.Network.LocalizedStringToken.world_id', index = 13, number = 14, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'zone_name', full_name = 'EA.Sims4.Network.LocalizedStringToken.zone_name', index = 14, number = 15, type = 9, cpp_type = 9, label = 1, has_default_value = False, default_value = b''.decode('utf-8'), message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'event_id', full_name = 'EA.Sims4.Network.LocalizedStringToken.event_id', index = 15, number = 16, type = 4, cpp_type = 4, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'event_type_hash', full_name = 'EA.Sims4.Network.LocalizedStringToken.event_type_hash', index = 16, number = 17, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'skill_name_hash', full_name = 'EA.Sims4.Network.LocalizedStringToken.skill_name_hash', index = 17, number = 18, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'skill_level', full_name = 'EA.Sims4.Network.LocalizedStringToken.skill_level', index = 18, number = 19, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'skill_guid', full_name = 'EA.Sims4.Network.LocalizedStringToken.skill_guid', index = 19, number = 20, type = 4, cpp_type = 4, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'trait_name_hash', full_name = 'EA.Sims4.Network.LocalizedStringToken.trait_name_hash', index = 20, number = 21, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'trait_guid', full_name = 'EA.Sims4.Network.LocalizedStringToken.trait_guid', index = 21, number = 22, type = 4, cpp_type = 4, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'bit_name_hash', full_name = 'EA.Sims4.Network.LocalizedStringToken.bit_name_hash', index = 22, number = 23, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'bit_guid', full_name = 'EA.Sims4.Network.LocalizedStringToken.bit_guid', index = 23, number = 24, type = 4, cpp_type = 4, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'catalog_name_key', full_name = 'EA.Sims4.Network.LocalizedStringToken.catalog_name_key', index = 24, number = 25, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'catalog_description_key', full_name = 'EA.Sims4.Network.LocalizedStringToken.catalog_description_key', index = 25, number = 26, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'custom_name', full_name = 'EA.Sims4.Network.LocalizedStringToken.custom_name', index = 26, number = 27, type = 9, cpp_type = 9, label = 1, has_default_value = False, default_value = b''.decode('utf-8'), message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'custom_description', full_name = 'EA.Sims4.Network.LocalizedStringToken.custom_description', index = 27, number = 28, type = 9, cpp_type = 9, label = 1, has_default_value = False, default_value = b''.decode('utf-8'), message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'career_uid', full_name = 'EA.Sims4.Network.LocalizedStringToken.career_uid', index = 28, number = 29, type = 4, cpp_type = 4, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'memory_id', full_name = 'EA.Sims4.Network.LocalizedStringToken.memory_id', index = 29, number = 30, type = 4, cpp_type = 4, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'memory_string_hash', full_name = 'EA.Sims4.Network.LocalizedStringToken.memory_string_hash', index = 30, number = 31, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'raw_text', full_name = 'EA.Sims4.Network.LocalizedStringToken.raw_text', index = 31, number = 32, type = 9, cpp_type = 9, label = 1, has_default_value = False, default_value = b''.decode('utf-8'), message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'date_and_time', full_name = 'EA.Sims4.Network.LocalizedStringToken.date_and_time', index = 32, number = 33, type = 11, cpp_type = 10, label = 1, has_default_value = False, default_value = None, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'sim_list', full_name = 'EA.Sims4.Network.LocalizedStringToken.sim_list', index = 33, number = 34, type = 11, cpp_type = 10, label = 3, has_default_value = False, default_value = [], message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None)], extensions = [], nested_types = [_LOCALIZEDSTRINGTOKEN_SUBTOKENDATA], enum_types = [_LOCALIZEDSTRINGTOKEN_TOKENTYPE], options = None, is_extendable = False, extension_ranges = [], serialized_start = 55, serialized_end = 1340 ) _LOCALIZEDDATEANDTIMEDATA = descriptor.Descriptor(name = 'LocalizedDateAndTimeData', full_name = 'EA.Sims4.Network.LocalizedDateAndTimeData', filename = None, file = DESCRIPTOR, containing_type = None, fields = [ descriptor.FieldDescriptor(name = 'seconds', full_name = 'EA.Sims4.Network.LocalizedDateAndTimeData.seconds', index = 0, number = 1, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'minutes', full_name = 'EA.Sims4.Network.LocalizedDateAndTimeData.minutes', index = 1, number = 2, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'hours', full_name = 'EA.Sims4.Network.LocalizedDateAndTimeData.hours', index = 2, number = 3, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'date', full_name = 'EA.Sims4.Network.LocalizedDateAndTimeData.date', index = 3, number = 4, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'month', full_name = 'EA.Sims4.Network.LocalizedDateAndTimeData.month', index = 4, number = 5, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'full_year', full_name = 'EA.Sims4.Network.LocalizedDateAndTimeData.full_year', index = 5, number = 6, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'date_and_time_format_hash', full_name = 'EA.Sims4.Network.LocalizedDateAndTimeData.date_and_time_format_hash', index = 6, number = 7, type = 13, cpp_type = 3, label = 1, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None)], extensions = [], nested_types = [], enum_types = [], options = None, is_extendable = False, extension_ranges = [], serialized_start = 1343, serialized_end = 1501) _LOCALIZEDSTRING = descriptor.Descriptor(name = 'LocalizedString', full_name = 'EA.Sims4.Network.LocalizedString', filename = None, file = DESCRIPTOR, containing_type = None, fields = [ descriptor.FieldDescriptor(name = 'hash', full_name = 'EA.Sims4.Network.LocalizedString.hash', index = 0, number = 1, type = 13, cpp_type = 3, label = 2, has_default_value = False, default_value = 0, message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None), descriptor.FieldDescriptor(name = 'tokens', full_name = 'EA.Sims4.Network.LocalizedString.tokens', index = 1, number = 2, type = 11, cpp_type = 10, label = 3, has_default_value = False, default_value = [], message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None)], extensions = [], nested_types = [], enum_types = [], options = None, is_extendable = False, extension_ranges = [], serialized_start = 1503, serialized_end = 1590) _LOCALIZEDSTRINGVALIDATE = descriptor.Descriptor(name = 'LocalizedStringValidate', full_name = 'EA.Sims4.Network.LocalizedStringValidate', filename = None, file = DESCRIPTOR, containing_type = None, fields = [descriptor.FieldDescriptor(name = 'localized_strings', full_name = 'EA.Sims4.Network.LocalizedStringValidate.localized_strings', index = 0, number = 1, type = 11, cpp_type = 10, label = 3, has_default_value = False, default_value = [], message_type = None, enum_type = None, containing_type = None, is_extension = False, extension_scope = None, options = None)], extensions = [], nested_types = [], enum_types = [], options = None, is_extendable = False, extension_ranges = [], serialized_start = 1592, serialized_end = 1679) _LOCALIZEDSTRINGTOKEN_SUBTOKENDATA.fields_by_name['type'].enum_type = _LOCALIZEDSTRINGTOKEN_TOKENTYPE _LOCALIZEDSTRINGTOKEN_SUBTOKENDATA.containing_type = _LOCALIZEDSTRINGTOKEN _LOCALIZEDSTRINGTOKEN.fields_by_name['type'].enum_type = _LOCALIZEDSTRINGTOKEN_TOKENTYPE _LOCALIZEDSTRINGTOKEN.fields_by_name['rdl_type'].enum_type = Consts_pb2._SOCIALRICHDATATYPE _LOCALIZEDSTRINGTOKEN.fields_by_name['text_string'].message_type = _LOCALIZEDSTRING _LOCALIZEDSTRINGTOKEN.fields_by_name['date_and_time'].message_type = _LOCALIZEDDATEANDTIMEDATA _LOCALIZEDSTRINGTOKEN.fields_by_name['sim_list'].message_type = _LOCALIZEDSTRINGTOKEN_SUBTOKENDATA _LOCALIZEDSTRINGTOKEN_TOKENTYPE.containing_type = _LOCALIZEDSTRINGTOKEN _LOCALIZEDSTRING.fields_by_name['tokens'].message_type = _LOCALIZEDSTRINGTOKEN _LOCALIZEDSTRINGVALIDATE.fields_by_name['localized_strings'].message_type = _LOCALIZEDSTRING DESCRIPTOR.message_types_by_name['LocalizedStringToken'] = _LOCALIZEDSTRINGTOKEN DESCRIPTOR.message_types_by_name['LocalizedDateAndTimeData'] = _LOCALIZEDDATEANDTIMEDATA DESCRIPTOR.message_types_by_name['LocalizedString'] = _LOCALIZEDSTRING DESCRIPTOR.message_types_by_name['LocalizedStringValidate'] = _LOCALIZEDSTRINGVALIDATE
218.846154
2,866
0.754189
fc2653dfaa764320b8eb71e09ae9ebdeb59fea8c
287
py
Python
dynamic_programming/01/01-06.py
fumiyanll23/algo-method
d86ea1d399cbc5a1db0ae49d0c82e41042f661ab
[ "MIT" ]
null
null
null
dynamic_programming/01/01-06.py
fumiyanll23/algo-method
d86ea1d399cbc5a1db0ae49d0c82e41042f661ab
[ "MIT" ]
null
null
null
dynamic_programming/01/01-06.py
fumiyanll23/algo-method
d86ea1d399cbc5a1db0ae49d0c82e41042f661ab
[ "MIT" ]
null
null
null
# input N, M = map(int, input().split()) Ds = [*map(int, input().split())] # compute dp = [False] * (N+1) for ni in range(N+1): if ni == 0: dp[ni] = True for D in Ds: if ni >= D: dp[ni] = dp[ni] or dp[ni-D] # output print("Yes" if dp[-1] else "No")
17.9375
39
0.477352
fc26599fa48fc7ee6289bde05e441a088fd069d9
447
py
Python
swapsort.py
ArshSood/sorting
97e1188ad626420e8ffeab992f7e98a2a91ae4b1
[ "Apache-2.0" ]
null
null
null
swapsort.py
ArshSood/sorting
97e1188ad626420e8ffeab992f7e98a2a91ae4b1
[ "Apache-2.0" ]
null
null
null
swapsort.py
ArshSood/sorting
97e1188ad626420e8ffeab992f7e98a2a91ae4b1
[ "Apache-2.0" ]
null
null
null
# sorting n=int(input()) array=list(map(int,input().split())) i=0 count=[] counter=0 while i<len(array): min=i start=i+1 while(start<len(array)): if array[start]<array[min]: min=start start+=1 if i!=min: array[i],array[min]=array[min],array[i] count.append(i) count.append(min) counter+=1 i+=1 print(counter) for i in range(0,len(count)): print(count[i],end=" ")
19.434783
47
0.557047
fc267d60ba151acc5fd2bfd47790174a62234e97
1,043
py
Python
tests/news_test.py
mucciz/News
2484d91edaef181d9a6d4b86d6bee822781f931d
[ "MIT" ]
null
null
null
tests/news_test.py
mucciz/News
2484d91edaef181d9a6d4b86d6bee822781f931d
[ "MIT" ]
null
null
null
tests/news_test.py
mucciz/News
2484d91edaef181d9a6d4b86d6bee822781f931d
[ "MIT" ]
1
2019-07-29T12:45:00.000Z
2019-07-29T12:45:00.000Z
import unittest from app.models import News # News = news.News # if __name__ == '__main__': # unittest.main()
35.965517
207
0.67977
fc2698b4b0dd35425a260f9ab84e959ae7a54a73
365
py
Python
test/get-gh-comment-info.py
MQasimSarfraz/cilium
89b622cf4e0a960e27e5b1bf9f139abee25dfea0
[ "Apache-2.0" ]
1
2020-06-12T19:43:52.000Z
2020-06-12T19:43:52.000Z
test/get-gh-comment-info.py
MQasimSarfraz/cilium
89b622cf4e0a960e27e5b1bf9f139abee25dfea0
[ "Apache-2.0" ]
null
null
null
test/get-gh-comment-info.py
MQasimSarfraz/cilium
89b622cf4e0a960e27e5b1bf9f139abee25dfea0
[ "Apache-2.0" ]
1
2020-06-17T07:06:27.000Z
2020-06-17T07:06:27.000Z
import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default="") parser.add_argument('--version', type=str, default="") parser.add_argument('--retrieve', type=str, default="focus") args = parser.parse_args() print args.__dict__[args.retrieve]
30.416667
79
0.750685
fc26c7b5181466b2721115acd12b6c40ca2fe4ae
7,699
py
Python
preprocessing/booking.py
madcat1991/clustered_cars
a79b83d9d14360c6c51d4bf462217ef690e62c74
[ "Apache-2.0" ]
null
null
null
preprocessing/booking.py
madcat1991/clustered_cars
a79b83d9d14360c6c51d4bf462217ef690e62c74
[ "Apache-2.0" ]
null
null
null
preprocessing/booking.py
madcat1991/clustered_cars
a79b83d9d14360c6c51d4bf462217ef690e62c74
[ "Apache-2.0" ]
null
null
null
""" This script cleans and prepares the data set of bookings for the future usage """ import argparse import logging import sys import pandas as pd from preprocessing.common import canonize_datetime, raw_data_to_df, check_processed_columns, check_data OLD_BREAKPOINT_MATCHER = { 2001: [ (1, 1, "New Year"), (1, 6, "Winter"), (2, 17, "Half Terms"), (2, 24, "Spring and Autumn"), (4, 7, "Easter"), (4, 21, "Spring and Autumn"), (5, 26, "SBH"), (6, 2, "Early Summer"), (7, 21, "Summer holidays"), (9, 1, "Early Autumn"), (9, 15, "Spring and Autumn"), (10, 27, "Half Terms"), (11, 3, "Winter"), (12, 22, "Christmas"), (12, 29, "New Year"), ], 2002: [ (1, 1, "New Year"), (1, 5, "Winter"), (2, 16, "Half Terms"), (2, 23, "Spring and Autumn"), (4, 6, "Easter"), (4, 20, "Spring and Autumn"), (5, 25, "SBH"), (6, 1, "Early Summer"), (7, 20, "Summer holidays"), (8, 31, "Early Autumn"), (9, 14, "Spring and Autumn"), (10, 26, "Half Terms"), (11, 2, "Winter"), (12, 21, "Christmas"), (12, 28, "New Year"), ], 2003: [ (1, 1, "New Year"), (1, 4, "Winter"), (2, 15, "Half Terms"), (2, 22, "Spring and Autumn"), (4, 5, "Easter"), (4, 19, "Spring and Autumn"), (5, 24, "SBH"), (5, 31, "Early Summer"), (7, 19, "Summer holidays"), (8, 30, "Early Autumn"), (9, 13, "Spring and Autumn"), (10, 25, "Half Terms"), (11, 1, "Winter"), (12, 20, "Christmas"), (12, 27, "New Year"), ], 2004: [ (1, 1, "New Year"), (1, 3, "Winter"), (2, 14, "Half Terms"), (2, 21, "Spring and Autumn"), (4, 3, "Easter"), (4, 17, "Spring and Autumn"), (5, 22, "SBH"), (5, 29, "Early Summer"), (7, 17, "Summer holidays"), (8, 28, "Early Autumn"), (9, 11, "Spring and Autumn"), (10, 23, "Half Terms"), (10, 30, "Winter"), (12, 18, "Christmas"), ], 2005: [ (1, 1, "Winter"), (2, 12, "Half Terms"), (2, 19, "Spring and Autumn"), (4, 2, "Easter"), (4, 16, "Spring and Autumn"), (5, 21, "SBH"), (5, 28, "Early Summer"), (7, 16, "Summer holidays"), (8, 27, "Early Autumn"), (9, 10, "Spring and Autumn"), (10, 22, "Half Terms"), (10, 29, "Winter"), (12, 17, "Christmas"), (12, 31, "New Year"), ], 2006: [ (1, 1, "New Year"), (1, 7, "Winter"), (2, 18, "Half Terms"), (2, 25, "Spring and Autumn"), (4, 8, "Easter"), (4, 22, "Spring and Autumn"), (5, 27, "SBH"), (6, 3, "Early Summer"), (7, 22, "Summer holidays"), (9, 2, "Early Autumn"), (9, 16, "Spring and Autumn"), (10, 28, "Half Terms"), (11, 4, "Winter"), (12, 23, "Christmas"), (12, 30, "New Year"), ], 2007: [ (1, 1, "New Year"), (1, 6, "Winter"), (2, 17, "Half Terms"), (2, 24, "Spring and Autumn"), (4, 7, "Easter"), (4, 21, "Spring and Autumn"), (5, 26, "SBH"), (6, 2, "Early Summer"), (7, 21, "Summer holidays"), (9, 1, "Early Autumn"), (9, 15, "Spring and Autumn"), (10, 27, "Half Terms"), (11, 3, "Winter"), (12, 22, "Christmas"), (12, 29, "New Year"), ], 2008: [ (1, 1, "New Year"), (1, 5, "Winter"), (2, 16, "Half Terms"), (2, 23, "Spring and Autumn"), (3, 22, "Easter"), (4, 19, "Spring and Autumn"), (5, 24, "SBH"), (5, 31, "Early Summer"), (7, 19, "Summer holidays"), (8, 30, "Early Autumn"), (9, 13, "Spring and Autumn"), (10, 25, "Half Terms"), (11, 1, "Winter"), (12, 20, "Christmas"), ], } COLS_TO_DROP = [ 'pname', 'region', 'sleeps', 'stars', 'proppostcode', # can be taken from property 'bookdate_scoreboard', 'book_year', 'hh_gross', 'hh_net', 'ho', # HH specific 'holidayprice', # correlates with avg_spend_per_head 'bighouse', 'burghisland', 'boveycastle', # no need 'sourcecostid', # is a pair of u'sourcedesc', u'category' 'drivedistance', # correlates with drivetime ] NOT_NA_COLS = [u'bookcode', u'code', u'propcode', u'year', u'breakpoint', u'avg_spend_per_head'] DATE_COLS = [u'bookdate', u'sdate', u"fdate"] FLOAT_COLS = [u'avg_spend_per_head', u'drivetime'] INT_COLS = [u'adults', u'babies', u'children', u'pets'] CATEGORICAL_COLS = [u'sourcedesc', u'category'] if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', required=True, dest="input_csv", help=u'Path to a csv file with bookings') parser.add_argument('--id', default=";", dest="input_csv_delimiter", help=u"The input file's delimiter. Default: ';'") parser.add_argument('-o', default="bookings.csv", dest="output_csv", help=u'Path to an output file. Default: booking.csv') parser.add_argument("--log-level", default='INFO', dest="log_level", choices=['DEBUG', 'INFO', 'WARNINGS', 'ERROR'], help=u"Logging level") args = parser.parse_args() logging.basicConfig( format='%(asctime)s %(levelname)s:%(message)s', stream=sys.stdout, level=getattr(logging, args.log_level) ) main()
36.661905
113
0.56267
fc272e521d0e985bdda9352e00baa8b30c9ad89c
1,309
py
Python
src/api/wish.py
PKU-GeekGame/gs-backend
d13219609d4e52810540bda6a3bddac1bf5406ce
[ "MIT" ]
7
2022-02-06T09:49:27.000Z
2022-03-03T14:23:32.000Z
src/api/wish.py
PKU-GeekGame/gs-backend
d13219609d4e52810540bda6a3bddac1bf5406ce
[ "MIT" ]
null
null
null
src/api/wish.py
PKU-GeekGame/gs-backend
d13219609d4e52810540bda6a3bddac1bf5406ce
[ "MIT" ]
null
null
null
from sanic import Blueprint, Request, HTTPResponse, response from sanic.models.handler_types import RouteHandler from functools import wraps from inspect import isawaitable from typing import Callable, Dict, Any, Union, Awaitable, List, Optional ACCEPTED_WISH_VERS = ['wish.alpha.v1'] WishHandler = Callable[..., Union[Dict[str, Any], Awaitable[Dict[str, Any]]]]
37.4
124
0.612681
fc27b29cfbfd1ea2e06f38bfeb18691ed058b5af
5,579
py
Python
scripts/venv/lib/python2.7/site-packages/cogent/maths/function_optimisation.py
sauloal/cnidaria
fe6f8c8dfed86d39c80f2804a753c05bb2e485b4
[ "MIT" ]
3
2015-11-20T08:44:42.000Z
2016-12-14T01:40:03.000Z
scripts/venv/lib/python2.7/site-packages/cogent/maths/function_optimisation.py
sauloal/cnidaria
fe6f8c8dfed86d39c80f2804a753c05bb2e485b4
[ "MIT" ]
1
2017-09-04T14:04:32.000Z
2020-05-26T19:04:00.000Z
scripts/venv/lib/python2.7/site-packages/cogent/maths/function_optimisation.py
sauloal/cnidaria
fe6f8c8dfed86d39c80f2804a753c05bb2e485b4
[ "MIT" ]
null
null
null
#!/usr/bin/env python """Algorthims for function optimisation great_deluge() is a hillclimbing algorithm based on: Gunter Dueck: New Optimization Heuristics, The Great Deluge Algorithm and the Record-to-Record Travel. Journal of Computational Physics, Vol. 104, 1993, pp. 86 - 92 ga_evolve() is a basic genetic algorithm in which all internal functions can be overridden NOTE: both optimisation functions are generators. """ from numpy.random import normal __author__ = "Daniel McDonald and Rob Knight" __copyright__ = "Copyright 2007-2012, The Cogent Project" __credits__ = ["Daniel McDonald", "Rob Knight"] __license__ = "GPL" __version__ = "1.5.3" __maintainer__ = "Daniel McDonald" __email__ = "[email protected]" __status__ = "Production" def _simple_breed(best, num, mutation_rate, random_f): """Returns num copies of parent with mutation_rate changes""" result = [] score, parent = best for child_number in range(num): if random_f() <= mutation_rate: child = parent.mutate() result.append(child) else: result.append(parent) return result def _simple_score(child, target): """Returns the childs score as defined by the childs scoring function""" return child.score(target) def _simple_init(parent, num): """Creates a list parent copies""" return [parent.copy() for i in range(num)] def _simple_select(population, scores): """Returns a tuple: (best_score, best_child)""" scored = zip(scores, population) scored.sort() return scored[0]
42.915385
80
0.661767
fc2801c140aa271fa4c9a495e831e1f55bb54ab3
6,871
py
Python
collect_policies.py
jonathanbglass/parallel_prowler
453774a69f078c7fce11c9bb72b6deab6fc04217
[ "MIT" ]
3
2021-04-09T12:37:13.000Z
2021-10-18T19:41:39.000Z
collect_policies.py
jonathanbglass/parallel_prowler
453774a69f078c7fce11c9bb72b6deab6fc04217
[ "MIT" ]
5
2019-04-30T13:08:43.000Z
2019-04-30T13:21:25.000Z
collect_policies.py
jonathanbglass/parallel_prowler
453774a69f078c7fce11c9bb72b6deab6fc04217
[ "MIT" ]
null
null
null
import argparse import boto3 import json import logging import os from progressbar import ProgressBar import sys """ Collects IAM Policies Evaluates policies looking for badness (*.*, Effect:Allow + NotAction) Need to add more tests/use cases """ if __name__ == "__main__": # execute only if run as a script main()
33.193237
79
0.536603
fc2ae536bffe1db19ce9b95cd5dd88a0d55394cd
3,556
py
Python
test/molecule-role/molecule/integrations/tests/test_nagios.py
StackVista/stackstate-agent
843f66189fae107646c57f71fed962bdaab3b3be
[ "Apache-2.0" ]
2
2018-11-12T22:00:56.000Z
2019-11-07T22:14:23.000Z
test/molecule-role/molecule/integrations/tests/test_nagios.py
StackVista/stackstate-agent
843f66189fae107646c57f71fed962bdaab3b3be
[ "Apache-2.0" ]
49
2018-10-02T18:14:58.000Z
2022-01-20T21:06:31.000Z
test/molecule-role/molecule/integrations/tests/test_nagios.py
StackVista/stackstate-agent
843f66189fae107646c57f71fed962bdaab3b3be
[ "Apache-2.0" ]
3
2019-05-10T13:06:59.000Z
2020-05-21T17:29:33.000Z
import json import os import re from testinfra.utils.ansible_runner import AnsibleRunner import util testinfra_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations')
39.955056
119
0.604331
fc2b9cb9eed0c84da94b5402d4ee3d9ce1910b43
589
py
Python
erudition/util.py
papsebestyen/erudition
35aa502a96189131baff714a6212eb56de2b1272
[ "MIT" ]
null
null
null
erudition/util.py
papsebestyen/erudition
35aa502a96189131baff714a6212eb56de2b1272
[ "MIT" ]
null
null
null
erudition/util.py
papsebestyen/erudition
35aa502a96189131baff714a6212eb56de2b1272
[ "MIT" ]
1
2022-02-21T21:17:17.000Z
2022-02-21T21:17:17.000Z
import os import sys from contextlib import contextmanager from invoke import UnexpectedExit
22.653846
58
0.634975
fc2d6707aecf302c38a120bd486580b956d4c75c
1,263
py
Python
python3/distortion_correct_aksk_demo.py
MeekoI/ais-sdk
76240abc49795e914988f3cafb6d08f60dbdcb4c
[ "Apache-2.0" ]
null
null
null
python3/distortion_correct_aksk_demo.py
MeekoI/ais-sdk
76240abc49795e914988f3cafb6d08f60dbdcb4c
[ "Apache-2.0" ]
null
null
null
python3/distortion_correct_aksk_demo.py
MeekoI/ais-sdk
76240abc49795e914988f3cafb6d08f60dbdcb4c
[ "Apache-2.0" ]
null
null
null
# -*- coding:utf-8 -*- from ais_sdk.utils import encode_to_base64 from ais_sdk.utils import decode_to_wave_file from ais_sdk.distortion_correct import distortion_correct_aksk from ais_sdk.utils import init_global_env import json if __name__ == '__main__': # # access moderation distortion correct.post data by ak,sk # app_key = '*************' app_secret = '************' init_global_env(region='cn-north-1') demo_data_url = 'https://ais-sample-data.obs.cn-north-1.myhuaweicloud.com/vat-invoice.jpg' #call interface use the url correction is true means do not correction result = distortion_correct_aksk(app_key, app_secret, "", demo_data_url, True) result_obj = json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-1.png') else: print(result) # call interface use the file result = distortion_correct_aksk(app_key, app_secret, encode_to_base64('data/moderation-distortion.jpg'), '', True) result_obj = json.loads(result) if result_obj['result']['data'] != '': decode_to_wave_file(result_obj['result']['data'], 'data/moderation-distortion-aksk-2.png') else: print(result)
39.46875
119
0.695962
fc2e07191680875cf76ef21ec4089df4cb779bed
527
py
Python
exercise/migrations/0016_auto_20191025_1624.py
Arpit8081/Phishtray_Edited_Version
9f3342e6fd2620b7f01ad91ce5b36fa8ea111bc8
[ "MIT" ]
2
2020-03-31T12:38:10.000Z
2022-01-21T22:21:06.000Z
exercise/migrations/0016_auto_20191025_1624.py
Arpit8081/Phishtray_Edited_Version
9f3342e6fd2620b7f01ad91ce5b36fa8ea111bc8
[ "MIT" ]
252
2018-05-24T14:55:24.000Z
2022-02-26T13:02:10.000Z
exercise/migrations/0016_auto_20191025_1624.py
Arpit8081/Phishtray_Edited_Version
9f3342e6fd2620b7f01ad91ce5b36fa8ea111bc8
[ "MIT" ]
11
2018-06-23T14:54:42.000Z
2021-02-19T11:33:44.000Z
# Generated by Django 2.2.6 on 2019-10-25 16:24 from django.db import migrations, models import django.db.models.deletion
26.35
131
0.666034
fc2e4f714b9faba2c5ecf66e26fac9c7e7da6366
1,527
py
Python
rainbow/datasources/cfn_datasource.py
omribahumi/rainbow
17aad61231b1f1b9d0dca43979e2fa4c8a1603f3
[ "BSD-2-Clause-FreeBSD" ]
35
2015-01-04T15:23:49.000Z
2020-11-24T16:10:33.000Z
rainbow/datasources/cfn_datasource.py
omribahumi/rainbow
17aad61231b1f1b9d0dca43979e2fa4c8a1603f3
[ "BSD-2-Clause-FreeBSD" ]
10
2015-01-20T07:45:41.000Z
2015-06-23T15:03:42.000Z
rainbow/datasources/cfn_datasource.py
omribahumi/rainbow
17aad61231b1f1b9d0dca43979e2fa4c8a1603f3
[ "BSD-2-Clause-FreeBSD" ]
17
2015-01-04T14:20:31.000Z
2020-11-24T16:10:36.000Z
from rainbow.cloudformation import Cloudformation from base import DataSourceBase __all__ = ['CfnOutputsDataSource', 'CfnResourcesDataSource', 'CfnParametersDataSource']
30.54
108
0.717092
fc2e789c677ad0b86e4fb3d988a64d970401e0fa
401
py
Python
epio_commands/management/commands/epio_flush_redis.py
idan/pypostbin
61dd1c0960e8fb6e4460a5623971cbbc78a55ee7
[ "BSD-3-Clause" ]
2
2015-11-05T08:51:42.000Z
2016-03-01T22:13:25.000Z
epio_commands/management/commands/epio_flush_redis.py
idan/pypostbin
61dd1c0960e8fb6e4460a5623971cbbc78a55ee7
[ "BSD-3-Clause" ]
null
null
null
epio_commands/management/commands/epio_flush_redis.py
idan/pypostbin
61dd1c0960e8fb6e4460a5623971cbbc78a55ee7
[ "BSD-3-Clause" ]
null
null
null
import redis from bundle_config import config from django.core.management.base import NoArgsCommand
30.846154
126
0.688279
fc2e92525a1caaa4ddf0a3ef664b415296525d97
2,338
py
Python
python/flexflow_cffi_build.py
zmxdream/FlexFlow
7ea50d71a02e853af7ae573d88c911511b3e82e0
[ "Apache-2.0" ]
455
2018-12-09T01:57:46.000Z
2022-03-22T01:56:47.000Z
python/flexflow_cffi_build.py
zmxdream/FlexFlow
7ea50d71a02e853af7ae573d88c911511b3e82e0
[ "Apache-2.0" ]
136
2019-04-19T08:24:27.000Z
2022-03-28T01:39:19.000Z
python/flexflow_cffi_build.py
zmxdream/FlexFlow
7ea50d71a02e853af7ae573d88c911511b3e82e0
[ "Apache-2.0" ]
102
2018-12-22T07:38:05.000Z
2022-03-30T06:04:39.000Z
#!/usr/bin/env python # Copyright 2020 Stanford University, Los Alamos National Laboratory # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import absolute_import, division, print_function, unicode_literals import argparse import os import subprocess if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--ffhome-dir', required=True) parser.add_argument('--libname', required=True) parser.add_argument('--output-dir', required=False) args = parser.parse_args() build(args.output_dir, args.libname, args.ffhome_dir)
38.327869
116
0.727545
fc2eebcbe5bb3cf4ff6427b453a41d0127cdd332
1,414
py
Python
gaphor/plugins/xmiexport/__init__.py
tuxcell/gaphor
22eb13479f589a0105ad25a11aed968e9ad932dc
[ "Apache-2.0" ]
null
null
null
gaphor/plugins/xmiexport/__init__.py
tuxcell/gaphor
22eb13479f589a0105ad25a11aed968e9ad932dc
[ "Apache-2.0" ]
null
null
null
gaphor/plugins/xmiexport/__init__.py
tuxcell/gaphor
22eb13479f589a0105ad25a11aed968e9ad932dc
[ "Apache-2.0" ]
null
null
null
"""This plugin extends Gaphor with XMI export functionality.""" import logging from gaphor.abc import ActionProvider, Service from gaphor.core import action, gettext from gaphor.plugins.xmiexport import exportmodel from gaphor.ui.filedialog import FileDialog logger = logging.getLogger(__name__)
32.883721
83
0.666195
fc2f49e15f4138f716bca2a01da611b02c245377
2,278
py
Python
tests/utils.py
btk15049/online-judge-tools
22505e98359c50df06e7cc1d53a7d253cb096b14
[ "MIT" ]
null
null
null
tests/utils.py
btk15049/online-judge-tools
22505e98359c50df06e7cc1d53a7d253cb096b14
[ "MIT" ]
null
null
null
tests/utils.py
btk15049/online-judge-tools
22505e98359c50df06e7cc1d53a7d253cb096b14
[ "MIT" ]
null
null
null
import contextlib import os import pathlib import subprocess import sys import tempfile
24.76087
108
0.618086
fc2f8d6fdf5321bc7fa432fe83690f0311e43ce9
303
py
Python
git_operation.py
zerzerzerz/Computer-Virus
4a3125b45e0e4210fb1b8c970a0d6c6bde77f2e8
[ "MIT" ]
null
null
null
git_operation.py
zerzerzerz/Computer-Virus
4a3125b45e0e4210fb1b8c970a0d6c6bde77f2e8
[ "MIT" ]
null
null
null
git_operation.py
zerzerzerz/Computer-Virus
4a3125b45e0e4210fb1b8c970a0d6c6bde77f2e8
[ "MIT" ]
null
null
null
import os commit_string = "data" not_add = ['results', 'data', 'weights'] for item in os.listdir(): if item in not_add: # print(item) continue else: os.system(f"git add {item}") os.system(f'git commit -m "{commit_string}"') os.system("git push origin main")
25.25
45
0.636964
fc3035214a995b5b1335519d9f36c232352adce4
6,523
py
Python
src/cool_grammar.py
peanut-butter-jellyyy/cool-compiler-2021
63a668d435ed22cfb8dbb096bc3c82a34f09517b
[ "MIT" ]
null
null
null
src/cool_grammar.py
peanut-butter-jellyyy/cool-compiler-2021
63a668d435ed22cfb8dbb096bc3c82a34f09517b
[ "MIT" ]
null
null
null
src/cool_grammar.py
peanut-butter-jellyyy/cool-compiler-2021
63a668d435ed22cfb8dbb096bc3c82a34f09517b
[ "MIT" ]
null
null
null
from src.cmp.pycompiler import Grammar from src.ast_nodes import ( ProgramNode, ClassDeclarationNode, FuncDeclarationNode, AttrDeclarationNode, IfNode, WhileNode, LetNode, CaseNode, IsvoidNode, AssignNode, VarDeclarationNode, CaseItemNode, NotNode, LessNode, LessEqualNode, EqualNode, PlusNode, MinusNode, StarNode, DivNode, NegNode, InstantiateNode, BlockNode, CallNode, ConstantNumNode, VariableNode, BooleanNode, StringNode, )
36.038674
87
0.559099
fc30849700e1ea4826d82e5040dc0a3f7cab1d33
1,599
py
Python
userbot/plugins/selfdestruct.py
Aliensuniquebot/CatUserbot
93561a620fc1198c6fe6c259412088f4bc81d97b
[ "MIT" ]
1
2020-07-18T07:42:58.000Z
2020-07-18T07:42:58.000Z
userbot/plugins/selfdestruct.py
praveen368/CatUserbot
4b0cd970551ffaf86b9fdd5da584c1b3882821ff
[ "MIT" ]
null
null
null
userbot/plugins/selfdestruct.py
praveen368/CatUserbot
4b0cd970551ffaf86b9fdd5da584c1b3882821ff
[ "MIT" ]
2
2020-06-25T11:14:50.000Z
2021-04-04T13:49:13.000Z
# For @UniBorg # courtesy Yasir siddiqui """Self Destruct Plugin .sd <time in seconds> <text> """ import time from userbot import CMD_HELP from telethon.errors import rpcbaseerrors from userbot.utils import admin_cmd import importlib.util CMD_HELP.update({ "selfdestruct": ".sdm number | [text]\ \nUsage: self destruct this message in number seconds \ \n\n.self number | [text]\ \nUsage:self destruct this message in number seconds with showing that it will destruct. \ " })
28.052632
90
0.602251
fc311bab55ecedbbd72f07232e73e6cac438a6b2
1,101
py
Python
snippets/basic_render_template_class.py
OSAMAMOHAMED1234/python_projects
fb4bc7356847c3f46df690a9386cf970377a6f7c
[ "MIT" ]
null
null
null
snippets/basic_render_template_class.py
OSAMAMOHAMED1234/python_projects
fb4bc7356847c3f46df690a9386cf970377a6f7c
[ "MIT" ]
null
null
null
snippets/basic_render_template_class.py
OSAMAMOHAMED1234/python_projects
fb4bc7356847c3f46df690a9386cf970377a6f7c
[ "MIT" ]
null
null
null
import os obj = Template(template_name='test.html', context={'name': 'OSAMA'}) print(obj.render()) obj.context= None print(obj.render(context={'name': 'os'})) obj2 = Template(template_name='test.html') print(obj2.render(context={'name': 'os'}))
30.583333
123
0.693006
fc3188873ff10721356aeaf7e965132781c78f98
793
py
Python
level_one/strings.py
jameskzhao/python36
855e8a6e164065702efa7773da1f089454fdcbcc
[ "Apache-2.0" ]
null
null
null
level_one/strings.py
jameskzhao/python36
855e8a6e164065702efa7773da1f089454fdcbcc
[ "Apache-2.0" ]
null
null
null
level_one/strings.py
jameskzhao/python36
855e8a6e164065702efa7773da1f089454fdcbcc
[ "Apache-2.0" ]
null
null
null
#Basics a = "hello" a += " I'm a dog" print(a) print(len(a)) print(a[1:]) #Output: ello I'm a dog print(a[:5]) #Output: hello(index 5 is not included) print(a[2:5])#Output: llo(index 2 is included) print(a[::2])#Step size #string is immutable so you can't assign a[1]= b x = a.upper() print(x) x = a.capitalize() print(x) x = a.split('e') print(x) x = a.split() #splits the string by space print(x) x = a.strip() #removes any whitespace from beginning or the end print(x) x = a.replace('l','xxx') print(x) x = "Insert another string here: {}".format('insert me!') x = "Item One: {} Item Two: {}".format('dog', 'cat') print(x) x = "Item One: {m} Item Two: {m}".format(m='dog', n='cat') print(x) #command-line string input print("Enter your name:") x = input() print("Hello: {}".format(x))
22.027778
63
0.631778
fc321e4d24702ee71bce5b7e534a97061ead9698
2,950
py
Python
tests/test_01_accept_time_get_headers.py
glushkovvv/test_2gis
2affff49411a3c7ff77e9d399ec86eb314aa3757
[ "MIT" ]
null
null
null
tests/test_01_accept_time_get_headers.py
glushkovvv/test_2gis
2affff49411a3c7ff77e9d399ec86eb314aa3757
[ "MIT" ]
1
2020-08-05T06:27:23.000Z
2020-08-05T06:27:42.000Z
tests/test_01_accept_time_get_headers.py
glushkovvv/test_2gis
2affff49411a3c7ff77e9d399ec86eb314aa3757
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ test_01_accept_time_get_headers ~~~~~~~~~~~~~~ The 2GIS API Test Check time get headers :author: Vadim Glushkov :copyright: Copyright 2019, The2GIS API Test" :license: MIT :version: 1.0.0 :maintainer: Vadim Glushkov :email: [email protected] :status: Development """ import pytest import allure from tools.api_responses import get_response
38.815789
116
0.649831
fc3233cb1459781c899740baf647a5f25ec92581
541
py
Python
transformers/string/strlen_transformer.py
ucds-sg/h2oai
7042860767dc25d1a7d7122103bbd5016d02df53
[ "Apache-2.0" ]
null
null
null
transformers/string/strlen_transformer.py
ucds-sg/h2oai
7042860767dc25d1a7d7122103bbd5016d02df53
[ "Apache-2.0" ]
null
null
null
transformers/string/strlen_transformer.py
ucds-sg/h2oai
7042860767dc25d1a7d7122103bbd5016d02df53
[ "Apache-2.0" ]
null
null
null
"""Returns the string length of categorical values""" from h2oaicore.transformer_utils import CustomTransformer import datatable as dt import numpy as np
31.823529
82
0.724584
fc34bcbcfb8ac1f6bc09817c52d24607717e7ad1
235
py
Python
geometry/eolearn/geometry/__init__.py
eerzin/eo-learn
53c5cc229de13b98b5778aeb1d45950c25bf2f95
[ "MIT" ]
1
2019-04-12T09:03:52.000Z
2019-04-12T09:03:52.000Z
geometry/eolearn/geometry/__init__.py
eerzin/eo-learn
53c5cc229de13b98b5778aeb1d45950c25bf2f95
[ "MIT" ]
null
null
null
geometry/eolearn/geometry/__init__.py
eerzin/eo-learn
53c5cc229de13b98b5778aeb1d45950c25bf2f95
[ "MIT" ]
3
2019-05-03T09:43:57.000Z
2019-09-10T17:29:39.000Z
""" Subpackage containing EOTasks for geometrical transformations """ from .utilities import ErosionTask, VectorToRaster, RasterToVector from .sampling import PointSamplingTask, PointSampler, PointRasterSampler __version__ = '0.4.2'
26.111111
73
0.821277
fc35043bdda56bc264f387918b5687e34dea2849
1,152
py
Python
api/models/users.py
felipebarraza6/startup_comedy
42b4a4547bffc0d7cf34ace520355d80053bbd9e
[ "MIT" ]
null
null
null
api/models/users.py
felipebarraza6/startup_comedy
42b4a4547bffc0d7cf34ace520355d80053bbd9e
[ "MIT" ]
null
null
null
api/models/users.py
felipebarraza6/startup_comedy
42b4a4547bffc0d7cf34ace520355d80053bbd9e
[ "MIT" ]
null
null
null
"""User Model.""" # Django from django.db import models from django.contrib.auth.models import AbstractUser # Utilities from .utils import ApiModel
24
71
0.667535
fc3539d71d659a16209a54fcd5f9758f5e36c76b
3,993
py
Python
tests/test_server.py
m-bo-one/ethereumd-proxy
1d1eb3905dac4b28a8e23c283214859a13f6e020
[ "MIT" ]
21
2017-07-24T15:45:03.000Z
2019-09-21T16:18:48.000Z
tests/test_server.py
m-bo-one/ethereumd-proxy
1d1eb3905dac4b28a8e23c283214859a13f6e020
[ "MIT" ]
11
2017-07-24T20:14:16.000Z
2019-02-10T22:52:32.000Z
tests/test_server.py
DeV1doR/ethereumd-proxy
1d1eb3905dac4b28a8e23c283214859a13f6e020
[ "MIT" ]
8
2018-02-17T13:33:15.000Z
2020-08-16T05:21:34.000Z
from collections import namedtuple import json from asynctest.mock import patch import pytest from ethereumd.server import RPCServer from ethereumd.proxy import EthereumProxy from aioethereum.errors import BadResponseError from .base import BaseTestRunner Request = namedtuple('Request', ['json'])
33.554622
76
0.596043
fc371494e70184822be6d1e222d5e8799a784228
973
py
Python
neorl/rl/baselines/readme.py
evdcush/neorl
a1af069072e752ab79e7279a88ad95d195a81821
[ "MIT" ]
20
2021-04-20T19:15:33.000Z
2022-03-19T17:00:12.000Z
neorl/rl/baselines/readme.py
evdcush/neorl
a1af069072e752ab79e7279a88ad95d195a81821
[ "MIT" ]
17
2021-04-07T21:52:41.000Z
2022-03-06T16:05:31.000Z
neorl/rl/baselines/readme.py
evdcush/neorl
a1af069072e752ab79e7279a88ad95d195a81821
[ "MIT" ]
8
2021-05-07T03:36:30.000Z
2021-12-15T03:41:41.000Z
# This file is part of NEORL. # Copyright (c) 2021 Exelon Corporation and MIT Nuclear Science and Engineering # NEORL is free software: you can redistribute it and/or modify # it under the terms of the MIT LICENSE # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #NEORL team thanks stable-baselines as we have used their own implementation of different RL #algorathims to establish NEORL optimizers. We have used the files in this open-source repo: #https://github.com/hill-a/stable-baselines
54.055556
94
0.74409
fc3a04cfd338f72934bd5d86f8126f4adfa55c05
1,330
py
Python
Compare.py
sushantPatrikar/WaveCompartor
112395287b41c1b5533924ebe293c5641647a5e3
[ "MIT" ]
3
2019-10-27T03:45:18.000Z
2022-02-21T18:50:58.000Z
Compare.py
sushantPatrikar/WaveComparator
112395287b41c1b5533924ebe293c5641647a5e3
[ "MIT" ]
null
null
null
Compare.py
sushantPatrikar/WaveComparator
112395287b41c1b5533924ebe293c5641647a5e3
[ "MIT" ]
1
2021-04-20T07:39:37.000Z
2021-04-20T07:39:37.000Z
from scipy.io import wavfile import numpy as np import pingouin as pg import pandas as pd _,data = wavfile.read('wav//ed//mp3baked.wav') _,data1 = wavfile.read('wav//ing//ingeating.wav') i= data.shape[0]-1 j = data1.shape[0]-1 index_1 = -1 index_2 = -1 try: data.shape[1] except IndexError: data = data.reshape(data.shape[0],1) try: data1.shape[1] except IndexError: data1 = data1.reshape(data1.shape[0],1) while True: if data[i,0] !=0 and index_1==-1: index_1 = i pass if data1[j,0] !=0 and index_2==-1: index_2 = j pass if index_1!=-1 and index_2!=-1: break i-=1 j-=1 data = data[-index_1:,:] data1 = data1[-index_2:,:] data = data[-2000:,:] data1= data1[-2000:,:] x =pg.corr(x=data[:,0],y=data1[:,0]) print(x) # print(data.tostring()) # print(data1.tostring()) # data = data[:,:] # data1 = data1[:,:] # data = data.reshape(data.shape[0],1) # data1 = data1.reshape(data1.shape[0],1) # data = data[-10000:,:] # data1 = data1[-10000:,:] # print(data1.shape[1]) # df = pd.DataFrame(data,data1) # print(df.head()) # print(data1.shape) # data = data[-5000:,:] # data1 = data1[-5000:,:] # # # x =pg.corr(x=data[:,0],y=data1[:,0]) # print(x)
15.647059
50
0.552632
fc3abec567aafacd5d2829eabdf814ac53962d6d
495
py
Python
tests/comments/test_only_block_comment.py
sco1/pylox
b4820828306c20cee3f8533c2547fafb92c6c1bd
[ "MIT" ]
2
2021-12-18T01:52:50.000Z
2022-01-17T19:41:52.000Z
tests/comments/test_only_block_comment.py
sco1/pylox
b4820828306c20cee3f8533c2547fafb92c6c1bd
[ "MIT" ]
18
2021-11-30T04:05:53.000Z
2022-02-01T03:30:04.000Z
tests/comments/test_only_block_comment.py
sco1/pylox
b4820828306c20cee3f8533c2547fafb92c6c1bd
[ "MIT" ]
null
null
null
from textwrap import dedent import pytest from pylox.lox import Lox TEST_SRC = dedent( """\ /* This is a multiline block comment */ """ ) EXPECTED_STDOUTS: list[str] = []
18.333333
69
0.70101
fc3c853df2b1d6ee609b09518a9278f9e15018c1
114
py
Python
mlbase/lazy.py
n-kats/mlbase
7d69f259dcaf9608a921523083458fa6d0d6914b
[ "MIT" ]
null
null
null
mlbase/lazy.py
n-kats/mlbase
7d69f259dcaf9608a921523083458fa6d0d6914b
[ "MIT" ]
2
2018-09-23T18:39:01.000Z
2018-09-24T18:02:21.000Z
mlbase/lazy.py
n-kats/mlbase
7d69f259dcaf9608a921523083458fa6d0d6914b
[ "MIT" ]
null
null
null
from mlbase.utils.misc import lazy tensorflow = lazy("tensorflow") numpy = lazy("numpy") gensim = lazy("gensim")
19
34
0.72807
fc3d1481782a2c4ff97885d3937f7846223c55ab
1,082
py
Python
setup.py
sturmianseq/observed
d99fb99ff2a470a86efb2763685e8e2c021e799f
[ "MIT" ]
33
2015-04-29T08:11:42.000Z
2022-02-01T16:50:25.000Z
setup.py
sturmianseq/observed
d99fb99ff2a470a86efb2763685e8e2c021e799f
[ "MIT" ]
15
2015-02-04T15:11:17.000Z
2022-01-26T19:58:29.000Z
setup.py
sturmianseq/observed
d99fb99ff2a470a86efb2763685e8e2c021e799f
[ "MIT" ]
6
2017-06-11T19:40:31.000Z
2021-08-05T07:57:28.000Z
import re import setuptools README_FILENAME = "README.md" VERSION_FILENAME = "observed.py" VERSION_RE = r"^__version__ = ['\"]([^'\"]*)['\"]" # Get version information with open(VERSION_FILENAME, "r") as version_file: mo = re.search(VERSION_RE, version_file.read(), re.M) if mo: version = mo.group(1) else: msg = "Unable to find version string in %s." % (version_file,) raise RuntimeError(msg) # Get description information with open(README_FILENAME, "r") as description_file: long_description = description_file.read() setuptools.setup( name="observed", version=version, author="Daniel Sank", author_email="[email protected]", description="Observer pattern for functions and bound methods", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/DanielSank/observed", py_modules=["observed"], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
27.05
67
0.685767
fc3d20f3595ad33d1e9d9bf80ce974904075e7ce
3,536
py
Python
src/coco.py
catalyst-team/detector
383c17ba7701d960ca92be0aafbff05207f2de3a
[ "Apache-2.0" ]
15
2019-05-15T13:42:51.000Z
2020-11-09T23:13:06.000Z
src/coco.py
catalyst-team/detector
383c17ba7701d960ca92be0aafbff05207f2de3a
[ "Apache-2.0" ]
1
2020-01-09T08:53:49.000Z
2020-01-16T19:41:16.000Z
src/coco.py
catalyst-team/detection
383c17ba7701d960ca92be0aafbff05207f2de3a
[ "Apache-2.0" ]
null
null
null
import os import json import numpy as np import pickle from typing import Any from pycocotools.coco import COCO from torch.utils.data import Dataset
32.440367
97
0.588235
fc3d3b9be540fd17668cfe15a94b53ed79b67b0a
328
py
Python
UVa 10105 polynomial coefficients/sample/main.py
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 10105 polynomial coefficients/sample/main.py
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 10105 polynomial coefficients/sample/main.py
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
import sys import operator sys.stdin = open('input.txt') fact = [1, 1] for i in range(2, 15): fact.append(fact[-1] * i) while True: try: n, k = map(int, raw_input().split()) coef = map(int, raw_input().split()) except: break print fact[n] / reduce(operator.mul, [fact[c] for c in coef])
21.866667
65
0.579268
fc3d8c49e88cab357d3bb76422dab0b50f4b1b22
702
py
Python
pynotes/note/models.py
wallaceleonel/Flash-Cards
fd563455d437f77e42ddf96133214cf752b62bb6
[ "MIT" ]
2
2020-08-06T15:03:31.000Z
2020-10-18T14:40:19.000Z
pynotes/note/models.py
wallaceleonel/Flash-Cards
fd563455d437f77e42ddf96133214cf752b62bb6
[ "MIT" ]
1
2020-08-06T16:15:12.000Z
2020-08-06T16:15:12.000Z
pynotes/note/models.py
wallaceleonel/Flash-Cards
fd563455d437f77e42ddf96133214cf752b62bb6
[ "MIT" ]
null
null
null
from django.contrib.auth.models import User from django.db import models from django.urls import reverse # Create your models here.
27
65
0.710826
fc3e56f1b6dc2446fe20c8456364bfd95e849dd0
7,538
py
Python
infrastructure-provisioning/src/general/scripts/azure/common_notebook_configure_dataengine.py
DmytroLiaskovskyi/incubator-dlab
af995e98b3b3cf526fb9741a3e5117dd1e04f3aa
[ "Apache-2.0" ]
null
null
null
infrastructure-provisioning/src/general/scripts/azure/common_notebook_configure_dataengine.py
DmytroLiaskovskyi/incubator-dlab
af995e98b3b3cf526fb9741a3e5117dd1e04f3aa
[ "Apache-2.0" ]
null
null
null
infrastructure-provisioning/src/general/scripts/azure/common_notebook_configure_dataengine.py
DmytroLiaskovskyi/incubator-dlab
af995e98b3b3cf526fb9741a3e5117dd1e04f3aa
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # ***************************************************************************** # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 logging import json import sys from dlab.fab import * from dlab.meta_lib import * from dlab.actions_lib import * import os import uuid if __name__ == "__main__": local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) local_log_filepath = "/logs/" + os.environ['conf_resource'] + "/" + local_log_filename logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=local_log_filepath) try: # generating variables dictionary print('Generating infrastructure names and tags') notebook_config = dict() try: notebook_config['exploratory_name'] = os.environ['exploratory_name'].replace('_', '-') except: notebook_config['exploratory_name'] = '' try: notebook_config['computational_name'] = os.environ['computational_name'].replace('_', '-') except: notebook_config['computational_name'] = '' notebook_config['service_base_name'] = os.environ['conf_service_base_name'] notebook_config['resource_group_name'] = os.environ['azure_resource_group_name'] notebook_config['region'] = os.environ['azure_region'] notebook_config['user_name'] = os.environ['edge_user_name'].replace('_', '-') notebook_config['project_name'] = os.environ['project_name'].replace('_', '-') notebook_config['project_tag'] = os.environ['project_name'].replace('_', '-') notebook_config['endpoint_tag'] = os.environ['endpoint_name'].replace('_', '-') notebook_config['cluster_name'] = notebook_config['service_base_name'] + '-' + notebook_config['project_name'] + \ '-de-' + notebook_config['exploratory_name'] + '-' + \ notebook_config['computational_name'] notebook_config['master_node_name'] = notebook_config['cluster_name'] + '-m' notebook_config['slave_node_name'] = notebook_config['cluster_name'] + '-s' notebook_config['notebook_name'] = os.environ['notebook_instance_name'] notebook_config['key_path'] = os.environ['conf_key_dir'] + '/' + os.environ['conf_key_name'] + '.pem' notebook_config['dlab_ssh_user'] = os.environ['conf_os_user'] notebook_config['instance_count'] = int(os.environ['dataengine_instance_count']) try: notebook_config['spark_master_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['master_node_name']) notebook_config['notebook_ip'] = AzureMeta().get_private_ip_address( notebook_config['resource_group_name'], notebook_config['notebook_name']) except Exception as err: print('Error: {0}'.format(err)) sys.exit(1) notebook_config['spark_master_url'] = 'spark://{}:7077'.format(notebook_config['spark_master_ip']) except Exception as err: for i in range(notebook_config['instance_count'] - 1): slave_name = notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result("Failed to generate infrastructure names", str(err)) sys.exit(1) try: logging.info('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') print('[INSTALLING KERNELS INTO SPECIFIED NOTEBOOK]') params = "--cluster_name {0} --spark_version {1} --hadoop_version {2} --os_user {3} --spark_master {4}" \ " --keyfile {5} --notebook_ip {6} --datalake_enabled {7} --spark_master_ip {8}".\ format(notebook_config['cluster_name'], os.environ['notebook_spark_version'], os.environ['notebook_hadoop_version'], notebook_config['dlab_ssh_user'], notebook_config['spark_master_url'], notebook_config['key_path'], notebook_config['notebook_ip'], os.environ['azure_datalake_enable'], notebook_config['spark_master_ip']) try: local("~/scripts/{}_{}.py {}".format(os.environ['application'], 'install_dataengine_kernels', params)) except: traceback.print_exc() raise Exception except Exception as err: print('Error: {0}'.format(err)) for i in range(notebook_config['instance_count'] - 1): slave_name = notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result("Failed installing Dataengine kernels.", str(err)) sys.exit(1) try: logging.info('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]') print('[UPDATING SPARK CONFIGURATION FILES ON NOTEBOOK]') params = "--hostname {0} " \ "--keyfile {1} " \ "--os_user {2} " \ "--cluster_name {3} " \ .format(notebook_config['notebook_ip'], notebook_config['key_path'], notebook_config['dlab_ssh_user'], notebook_config['cluster_name']) try: local("~/scripts/{0}.py {1}".format('common_configure_spark', params)) except: traceback.print_exc() raise Exception except Exception as err: print('Error: {0}'.format(err)) for i in range(notebook_config['instance_count'] - 1): slave_name = notebook_config['slave_node_name'] + '{}'.format(i+1) AzureActions().remove_instance(notebook_config['resource_group_name'], slave_name) AzureActions().remove_instance(notebook_config['resource_group_name'], notebook_config['master_node_name']) append_result("Failed to configure Spark.", str(err)) sys.exit(1) try: with open("/root/result.json", 'w') as result: res = {"notebook_name": notebook_config['notebook_name'], "Action": "Configure notebook server"} print(json.dumps(res)) result.write(json.dumps(res)) except: print("Failed writing results.") sys.exit(0)
51.986207
122
0.628549
fc403c27d1d4da0e66a446351a2e2650278bc62d
1,527
py
Python
pyACA/ToolFreq2Bark.py
ruohoruotsi/pyACA
339e9395b65a217aa5965638af941b32d5c95454
[ "MIT" ]
81
2019-07-08T15:48:03.000Z
2022-03-21T22:52:25.000Z
pyACA/ToolFreq2Bark.py
ruohoruotsi/pyACA
339e9395b65a217aa5965638af941b32d5c95454
[ "MIT" ]
24
2019-10-03T19:20:18.000Z
2022-02-28T17:20:40.000Z
pyACA/ToolFreq2Bark.py
ruohoruotsi/pyACA
339e9395b65a217aa5965638af941b32d5c95454
[ "MIT" ]
26
2019-07-18T23:50:52.000Z
2022-03-10T14:59:35.000Z
# -*- coding: utf-8 -*- """ helper function: convert Hz to Bark scale Args: fInHz: The frequency to be converted, can be scalar or vector cModel: The name of the model ('Schroeder' [default], 'Terhardt', 'Zwicker', 'Traunmuller') Returns: Bark values of the input dimension """ import numpy as np import math
28.811321
95
0.591356
fc40aa5a0884df8e751f2fa5cfb93216f3c13768
16,560
py
Python
magenta/models/sketch_rnn/rnn.py
laurens-in/magenta
be6ed8d5b1eb2986ca277aa9c574a7912dd5ed0f
[ "Apache-2.0" ]
1
2021-12-27T10:43:39.000Z
2021-12-27T10:43:39.000Z
magenta/models/sketch_rnn/rnn.py
kyungyunlee/magenta
cf80d19fc0c2e935821f284ebb64a8885f793717
[ "Apache-2.0" ]
null
null
null
magenta/models/sketch_rnn/rnn.py
kyungyunlee/magenta
cf80d19fc0c2e935821f284ebb64a8885f793717
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 The Magenta Authors. # # 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. """SketchRNN RNN definition.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf from tensorflow.contrib import rnn as contrib_rnn def orthogonal(shape): """Orthogonal initilaizer.""" flat_shape = (shape[0], np.prod(shape[1:])) a = np.random.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) q = u if u.shape == flat_shape else v return q.reshape(shape) def orthogonal_initializer(scale=1.0): """Orthogonal initializer.""" return _initializer def lstm_ortho_initializer(scale=1.0): """LSTM orthogonal initializer.""" return _initializer def layer_norm_all(h, batch_size, base, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): """Layer Norm (faster version, but not using defun).""" # Performs layer norm on multiple base at once (ie, i, g, j, o for lstm) # Reshapes h in to perform layer norm in parallel h_reshape = tf.reshape(h, [batch_size, base, num_units]) mean = tf.reduce_mean(h_reshape, [2], keep_dims=True) var = tf.reduce_mean(tf.square(h_reshape - mean), [2], keep_dims=True) epsilon = tf.constant(epsilon) rstd = tf.rsqrt(var + epsilon) h_reshape = (h_reshape - mean) * rstd # reshape back to original h = tf.reshape(h_reshape, [batch_size, base * num_units]) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [4 * num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable( 'ln_beta', [4 * num_units], initializer=tf.constant_initializer(0.0)) if use_bias: return gamma * h + beta return gamma * h def layer_norm(x, num_units, scope='layer_norm', reuse=False, gamma_start=1.0, epsilon=1e-3, use_bias=True): """Calculate layer norm.""" axes = [1] mean = tf.reduce_mean(x, axes, keep_dims=True) x_shifted = x - mean var = tf.reduce_mean(tf.square(x_shifted), axes, keep_dims=True) inv_std = tf.rsqrt(var + epsilon) with tf.variable_scope(scope): if reuse: tf.get_variable_scope().reuse_variables() gamma = tf.get_variable( 'ln_gamma', [num_units], initializer=tf.constant_initializer(gamma_start)) if use_bias: beta = tf.get_variable( 'ln_beta', [num_units], initializer=tf.constant_initializer(0.0)) output = gamma * (x_shifted) * inv_std if use_bias: output += beta return output def raw_layer_norm(x, epsilon=1e-3): axes = [1] mean = tf.reduce_mean(x, axes, keep_dims=True) std = tf.sqrt( tf.reduce_mean(tf.square(x - mean), axes, keep_dims=True) + epsilon) output = (x - mean) / (std) return output def super_linear(x, output_size, scope=None, reuse=False, init_w='ortho', weight_start=0.0, use_bias=True, bias_start=0.0, input_size=None): """Performs linear operation. Uses ortho init defined earlier.""" shape = x.get_shape().as_list() with tf.variable_scope(scope or 'linear'): if reuse: tf.get_variable_scope().reuse_variables() w_init = None # uniform if input_size is None: x_size = shape[1] else: x_size = input_size if init_w == 'zeros': w_init = tf.constant_initializer(0.0) elif init_w == 'constant': w_init = tf.constant_initializer(weight_start) elif init_w == 'gaussian': w_init = tf.random_normal_initializer(stddev=weight_start) elif init_w == 'ortho': w_init = lstm_ortho_initializer(1.0) w = tf.get_variable( 'super_linear_w', [x_size, output_size], tf.float32, initializer=w_init) if use_bias: b = tf.get_variable( 'super_linear_b', [output_size], tf.float32, initializer=tf.constant_initializer(bias_start)) return tf.matmul(x, w) + b return tf.matmul(x, w) class LayerNormLSTMCell(contrib_rnn.RNNCell): """Layer-Norm, with Ortho Init. and Recurrent Dropout without Memory Loss. https://arxiv.org/abs/1607.06450 - Layer Norm https://arxiv.org/abs/1603.05118 - Recurrent Dropout without Memory Loss """ def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90): """Initialize the Layer Norm LSTM cell. Args: num_units: int, The number of units in the LSTM cell. forget_bias: float, The bias added to forget gates (default 1.0). use_recurrent_dropout: Whether to use Recurrent Dropout (default False) dropout_keep_prob: float, dropout keep probability (default 0.90) """ self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob def get_output(self, state): h, unused_c = tf.split(state, 2, 1) return h def __call__(self, x, state, timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__): h, c = tf.split(state, 2, 1) h_size = self.num_units x_size = x.get_shape().as_list()[1] batch_size = x.get_shape().as_list()[0] w_init = None # uniform h_init = lstm_ortho_initializer(1.0) w_xh = tf.get_variable( 'W_xh', [x_size, 4 * self.num_units], initializer=w_init) w_hh = tf.get_variable( 'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init) concat = tf.concat([x, h], 1) # concat for speed. w_full = tf.concat([w_xh, w_hh], 0) concat = tf.matmul(concat, w_full) #+ bias # live life without garbage. # i = input_gate, j = new_input, f = forget_gate, o = output_gate concat = layer_norm_all(concat, batch_size, 4, h_size, 'ln_all') i, j, f, o = tf.split(concat, 4, 1) if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else: g = tf.tanh(j) new_c = c * tf.sigmoid(f + self.forget_bias) + tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c, h_size, 'ln_c')) * tf.sigmoid(o) return new_h, tf.concat([new_h, new_c], 1) class HyperLSTMCell(contrib_rnn.RNNCell): """HyperLSTM with Ortho Init, Layer Norm, Recurrent Dropout, no Memory Loss. https://arxiv.org/abs/1609.09106 http://blog.otoro.net/2016/09/28/hyper-networks/ """ def __init__(self, num_units, forget_bias=1.0, use_recurrent_dropout=False, dropout_keep_prob=0.90, use_layer_norm=True, hyper_num_units=256, hyper_embedding_size=32, hyper_use_recurrent_dropout=False): """Initialize the Layer Norm HyperLSTM cell. Args: num_units: int, The number of units in the LSTM cell. forget_bias: float, The bias added to forget gates (default 1.0). use_recurrent_dropout: Whether to use Recurrent Dropout (default False) dropout_keep_prob: float, dropout keep probability (default 0.90) use_layer_norm: boolean. (default True) Controls whether we use LayerNorm layers in main LSTM & HyperLSTM cell. hyper_num_units: int, number of units in HyperLSTM cell. (default is 128, recommend experimenting with 256 for larger tasks) hyper_embedding_size: int, size of signals emitted from HyperLSTM cell. (default is 16, recommend trying larger values for large datasets) hyper_use_recurrent_dropout: boolean. (default False) Controls whether HyperLSTM cell also uses recurrent dropout. Recommend turning this on only if hyper_num_units becomes large (>= 512) """ self.num_units = num_units self.forget_bias = forget_bias self.use_recurrent_dropout = use_recurrent_dropout self.dropout_keep_prob = dropout_keep_prob self.use_layer_norm = use_layer_norm self.hyper_num_units = hyper_num_units self.hyper_embedding_size = hyper_embedding_size self.hyper_use_recurrent_dropout = hyper_use_recurrent_dropout self.total_num_units = self.num_units + self.hyper_num_units if self.use_layer_norm: cell_fn = LayerNormLSTMCell else: cell_fn = LSTMCell self.hyper_cell = cell_fn( hyper_num_units, use_recurrent_dropout=hyper_use_recurrent_dropout, dropout_keep_prob=dropout_keep_prob) def get_output(self, state): total_h, unused_total_c = tf.split(state, 2, 1) h = total_h[:, 0:self.num_units] return h def hyper_norm(self, layer, scope='hyper', use_bias=True): num_units = self.num_units embedding_size = self.hyper_embedding_size # recurrent batch norm init trick (https://arxiv.org/abs/1603.09025). init_gamma = 0.10 # cooijmans' da man. with tf.variable_scope(scope): zw = super_linear( self.hyper_output, embedding_size, init_w='constant', weight_start=0.00, use_bias=True, bias_start=1.0, scope='zw') alpha = super_linear( zw, num_units, init_w='constant', weight_start=init_gamma / embedding_size, use_bias=False, scope='alpha') result = tf.multiply(alpha, layer) if use_bias: zb = super_linear( self.hyper_output, embedding_size, init_w='gaussian', weight_start=0.01, use_bias=False, bias_start=0.0, scope='zb') beta = super_linear( zb, num_units, init_w='constant', weight_start=0.00, use_bias=False, scope='beta') result += beta return result def __call__(self, x, state, timestep=0, scope=None): with tf.variable_scope(scope or type(self).__name__): total_h, total_c = tf.split(state, 2, 1) h = total_h[:, 0:self.num_units] c = total_c[:, 0:self.num_units] self.hyper_state = tf.concat( [total_h[:, self.num_units:], total_c[:, self.num_units:]], 1) batch_size = x.get_shape().as_list()[0] x_size = x.get_shape().as_list()[1] self._input_size = x_size w_init = None # uniform h_init = lstm_ortho_initializer(1.0) w_xh = tf.get_variable( 'W_xh', [x_size, 4 * self.num_units], initializer=w_init) w_hh = tf.get_variable( 'W_hh', [self.num_units, 4 * self.num_units], initializer=h_init) bias = tf.get_variable( 'bias', [4 * self.num_units], initializer=tf.constant_initializer(0.0)) # concatenate the input and hidden states for hyperlstm input hyper_input = tf.concat([x, h], 1) hyper_output, hyper_new_state = self.hyper_cell(hyper_input, self.hyper_state) self.hyper_output = hyper_output self.hyper_state = hyper_new_state xh = tf.matmul(x, w_xh) hh = tf.matmul(h, w_hh) # split Wxh contributions ix, jx, fx, ox = tf.split(xh, 4, 1) ix = self.hyper_norm(ix, 'hyper_ix', use_bias=False) jx = self.hyper_norm(jx, 'hyper_jx', use_bias=False) fx = self.hyper_norm(fx, 'hyper_fx', use_bias=False) ox = self.hyper_norm(ox, 'hyper_ox', use_bias=False) # split Whh contributions ih, jh, fh, oh = tf.split(hh, 4, 1) ih = self.hyper_norm(ih, 'hyper_ih', use_bias=True) jh = self.hyper_norm(jh, 'hyper_jh', use_bias=True) fh = self.hyper_norm(fh, 'hyper_fh', use_bias=True) oh = self.hyper_norm(oh, 'hyper_oh', use_bias=True) # split bias ib, jb, fb, ob = tf.split(bias, 4, 0) # bias is to be broadcasted. # i = input_gate, j = new_input, f = forget_gate, o = output_gate i = ix + ih + ib j = jx + jh + jb f = fx + fh + fb o = ox + oh + ob if self.use_layer_norm: concat = tf.concat([i, j, f, o], 1) concat = layer_norm_all(concat, batch_size, 4, self.num_units, 'ln_all') i, j, f, o = tf.split(concat, 4, 1) if self.use_recurrent_dropout: g = tf.nn.dropout(tf.tanh(j), self.dropout_keep_prob) else: g = tf.tanh(j) new_c = c * tf.sigmoid(f + self.forget_bias) + tf.sigmoid(i) * g new_h = tf.tanh(layer_norm(new_c, self.num_units, 'ln_c')) * tf.sigmoid(o) hyper_h, hyper_c = tf.split(hyper_new_state, 2, 1) new_total_h = tf.concat([new_h, hyper_h], 1) new_total_c = tf.concat([new_c, hyper_c], 1) new_total_state = tf.concat([new_total_h, new_total_c], 1) return new_h, new_total_state
33.186373
80
0.634964
fc412db90075a83ae4e5731ee32b0fb7611791ff
6,034
py
Python
src/cogent3/cluster/UPGMA.py
u6052029/cogent3
ca0efcb7f60b715bcbfbecd924cdb98a53cefe20
[ "BSD-3-Clause" ]
null
null
null
src/cogent3/cluster/UPGMA.py
u6052029/cogent3
ca0efcb7f60b715bcbfbecd924cdb98a53cefe20
[ "BSD-3-Clause" ]
null
null
null
src/cogent3/cluster/UPGMA.py
u6052029/cogent3
ca0efcb7f60b715bcbfbecd924cdb98a53cefe20
[ "BSD-3-Clause" ]
null
null
null
# usr/bin/env python """Functions to cluster using UPGMA upgma takes an dictionary of pair tuples mapped to distances as input. UPGMA_cluster takes an array and a list of PhyloNode objects corresponding to the array as input. Can also generate this type of input from a DictArray using inputs_from_dict_array function. Both return a PhyloNode object of the UPGMA cluster """ import numpy from numpy import argmin, array, average, diag, ma, ravel, sum, take from cogent3.core.tree import PhyloNode from cogent3.util.dict_array import DictArray __author__ = "Catherine Lozupone" __copyright__ = "Copyright 2007-2020, The Cogent Project" __credits__ = ["Catherine Lozuopone", "Rob Knight", "Peter Maxwell"] __license__ = "BSD-3" __version__ = "2020.7.2a" __maintainer__ = "Catherine Lozupone" __email__ = "[email protected]" __status__ = "Production" numerictypes = numpy.core.numerictypes.sctype2char Float = numerictypes(float) BIG_NUM = 1e305 def upgma(pairwise_distances): """Uses the UPGMA algorithm to cluster sequences pairwise_distances: a dictionary with pair tuples mapped to a distance returns a PhyloNode object of the UPGMA cluster """ darr = DictArray(pairwise_distances) matrix_a, node_order = inputs_from_dict_array(darr) tree = UPGMA_cluster(matrix_a, node_order, BIG_NUM) index = 0 for node in tree.traverse(): if not node.parent: node.name = "root" elif not node.name: node.name = "edge." + str(index) index += 1 return tree def find_smallest_index(matrix): """returns the index of the smallest element in a numpy array for UPGMA clustering elements on the diagonal should first be substituted with a very large number so that they are always larger than the rest if the values in the array.""" # get the shape of the array as a tuple (e.g. (3,3)) shape = matrix.shape # turn into a 1 by x array and get the index of the lowest number matrix1D = ravel(matrix) lowest_index = argmin(matrix1D) # convert the lowest_index derived from matrix1D to one for the original # square matrix and return row_len = shape[0] return divmod(lowest_index, row_len) def condense_matrix(matrix, smallest_index, large_value): """converges the rows and columns indicated by smallest_index Smallest index is returned from find_smallest_index. For both the rows and columns, the values for the two indices are averaged. The resulting vector replaces the first index in the array and the second index is replaced by an array with large numbers so that it is never chosen again with find_smallest_index. """ first_index, second_index = smallest_index # get the rows and make a new vector that has their average rows = take(matrix, smallest_index, 0) new_vector = average(rows, 0) # replace info in the row and column for first index with new_vector matrix[first_index] = new_vector matrix[:, first_index] = new_vector # replace the info in the row and column for the second index with # high numbers so that it is ignored matrix[second_index] = large_value matrix[:, second_index] = large_value return matrix def condense_node_order(matrix, smallest_index, node_order): """condenses two nodes in node_order based on smallest_index info This function is used to create a tree while condensing a matrix with the condense_matrix function. The smallest_index is retrieved with find_smallest_index. The first index is replaced with a node object that combines the two nodes corresponding to the indices in node order. The second index in smallest_index is replaced with None. Also sets the branch length of the nodes to 1/2 of the distance between the nodes in the matrix""" index1, index2 = smallest_index node1 = node_order[index1] node2 = node_order[index2] # get the distance between the nodes and assign 1/2 the distance to the # lengthproperty of each node distance = matrix[index1, index2] nodes = [node1, node2] d = distance / 2.0 for n in nodes: if n.children: n.length = d - n.children[0].TipLength else: n.length = d n.TipLength = d # combine the two nodes into a new PhyloNode object new_node = PhyloNode() new_node.children.append(node1) new_node.children.append(node2) node1.parent = new_node node2.parent = new_node # replace the object at index1 with the combined node node_order[index1] = new_node # replace the object at index2 with None node_order[index2] = None return node_order def UPGMA_cluster(matrix, node_order, large_number): """cluster with UPGMA matrix is a numpy array. node_order is a list of PhyloNode objects corresponding to the matrix. large_number will be assigned to the matrix during the process and should be much larger than any value already in the matrix. WARNING: Changes matrix in-place. WARNING: Expects matrix to already have diagonals assigned to large_number before this function is called. """ num_entries = len(node_order) tree = None for i in range(num_entries - 1): smallest_index = find_smallest_index(matrix) index1, index2 = smallest_index # if smallest_index is on the diagonal set the diagonal to large_number if index1 == index2: matrix[diag([True] * len(matrix))] = large_number smallest_index = find_smallest_index(matrix) row_order = condense_node_order(matrix, smallest_index, node_order) matrix = condense_matrix(matrix, smallest_index, large_number) tree = node_order[smallest_index[0]] return tree def inputs_from_dict_array(darr): """makes inputs for UPGMA_cluster from a DictArray object """ darr.array += numpy.eye(darr.shape[0]) * BIG_NUM nodes = list(map(PhyloNode, darr.keys())) return darr.array, nodes
36.569697
82
0.716937
fc416ffd2f7c1bbdb707cd0d27fb98dd3ff367ba
881
py
Python
src/python/make_store_entry.py
kf7lsu/RegfileCompiler-public
0845f1458137cef06d584047bb4287a72c6afbab
[ "Apache-2.0" ]
null
null
null
src/python/make_store_entry.py
kf7lsu/RegfileCompiler-public
0845f1458137cef06d584047bb4287a72c6afbab
[ "Apache-2.0" ]
null
null
null
src/python/make_store_entry.py
kf7lsu/RegfileCompiler-public
0845f1458137cef06d584047bb4287a72c6afbab
[ "Apache-2.0" ]
null
null
null
#this code will generate the structural verilog for a single entry in the register file #takes in the output file manager, the entry number, the number of bits, the number of reads, and the width of the #tristate buffers on the read outputs #expects the same things as make_store_cell, ensure code is valid there #Matthew Trahms #EE 526 #4/20/21 from make_store_cell import make_store_cell if __name__ == '__main__': f = open('store_entry_test.txt', 'w') rows = 4 cols = 2 reads = 2 for row in range(rows): make_store_entry(f, row, cols, reads, 1, 0) f.close()
31.464286
114
0.760499
fc417b4336f77e529dd64d425d37722b3edade09
1,007
py
Python
module1/api.py
oceandelee/tac
62ffbcb31b374a9fa83a1ee6010b2e00f2de8a7c
[ "MIT" ]
null
null
null
module1/api.py
oceandelee/tac
62ffbcb31b374a9fa83a1ee6010b2e00f2de8a7c
[ "MIT" ]
null
null
null
module1/api.py
oceandelee/tac
62ffbcb31b374a9fa83a1ee6010b2e00f2de8a7c
[ "MIT" ]
null
null
null
"""API for AVB""" import json import sys import requests #Example of use if __name__ == "__main__": resp = actualite_found() result = get_result(resp,2,"description") print(result) print(nb_result(resp))
19.365385
69
0.5571
fc422cd23ef7241b5d35bfeb10b87ff16ba77128
7,782
py
Python
improver/cli/nbhood.py
cpelley/improver
ebf77fe2adc85ed7aec74c26671872a2e4388ded
[ "BSD-3-Clause" ]
77
2017-04-26T07:47:40.000Z
2022-03-31T09:40:49.000Z
improver/cli/nbhood.py
cpelley/improver
ebf77fe2adc85ed7aec74c26671872a2e4388ded
[ "BSD-3-Clause" ]
1,440
2017-03-29T10:04:15.000Z
2022-03-28T10:11:29.000Z
improver/cli/nbhood.py
MoseleyS/improver
ca028e3a1c842e3ff00b188c8ea6eaedd0a07149
[ "BSD-3-Clause" ]
72
2017-03-17T16:53:45.000Z
2022-02-16T09:41:37.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2021 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Script to run neighbourhood processing.""" from improver import cli from improver.constants import DEFAULT_PERCENTILES
42.758242
88
0.681187
fc43b75bb4a6cda564bcd320da8b77c8174105e4
58,644
py
Python
bonsai/model.py
ipa-mirb/bonsai
cb73317cdf779566f7c496fc39546c9c689aa09c
[ "MIT" ]
null
null
null
bonsai/model.py
ipa-mirb/bonsai
cb73317cdf779566f7c496fc39546c9c689aa09c
[ "MIT" ]
null
null
null
bonsai/model.py
ipa-mirb/bonsai
cb73317cdf779566f7c496fc39546c9c689aa09c
[ "MIT" ]
null
null
null
#Copyright (c) 2017 Andre Santos # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE. ############################################################################### # Language Model ############################################################################### # ----- Common Entities ------------------------------------------------------- def _children(self): """Yield all direct children of this object.""" if isinstance(self.value, CodeEntity): yield self.value def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ return '{}{} {} = {}'.format(' ' * indent, self.result, self.name, pretty_str(self.value)) def __repr__(self): """Return a string representation of this object.""" return '[{}] {} = ({})'.format(self.result, self.name, self.value) class CodeFunction(CodeEntity, CodeStatementGroup): """This class represents a program function. A function typically has a name, a return type (`result`), a list of parameters and a body (a code block). It also has an unique `id` that identifies it in the program and a list of references to it. If a function is a method of some class, its `member_of` should be set to the corresponding class. """ def __init__(self, scope, parent, id, name, result, definition=True): """Constructor for functions. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. id: An unique identifier for this function. name (str): The name of the function in the program. result (str): The return type of the function in the program. """ CodeEntity.__init__(self, scope, parent) self.id = id self.name = name self.result = result self.parameters = [] self.body = CodeBlock(self, self, explicit=True) self.member_of = None self.references = [] self._definition = self if definition else None def _add(self, codeobj): """Add a child (statement) to this object.""" assert isinstance(codeobj, (CodeStatement, CodeExpression)) self.body._add(codeobj) def _afterpass(self): """Assign a function-local index to each child object and register write operations to variables. This should only be called after the object is fully built. """ if hasattr(self, '_fi'): return fi = 0 for codeobj in self.walk_preorder(): codeobj._fi = fi fi += 1 if isinstance(codeobj, CodeOperator) and codeobj.is_assignment: if codeobj.arguments and isinstance(codeobj.arguments[0], CodeReference): var = codeobj.arguments[0].reference if isinstance(var, CodeVariable): var.writes.append(codeobj) def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ spaces = ' ' * indent params = ', '.join(map(lambda p: p.result + ' ' + p.name, self.parameters)) if self.is_constructor: pretty = '{}{}({}):\n'.format(spaces, self.name, params) else: pretty = '{}{} {}({}):\n'.format(spaces, self.result, self.name, params) if self._definition is not self: pretty += spaces + ' [declaration]' else: pretty += self.body.pretty_str(indent + 2) return pretty def __repr__(self): """Return a string representation of this object.""" params = ', '.join(map(str, self.parameters)) return '[{}] {}({})'.format(self.result, self.name, params) class CodeClass(CodeEntity): """This class represents a program class for object-oriented languages. A class typically has a name, an unique `id`, a list of members (variables, functions), a list of superclasses, and a list of references. If a class is defined within another class (inner class), it should have its `member_of` set to the corresponding class. """ def __init__(self, scope, parent, id_, name, definition=True): """Constructor for classes. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. id: An unique identifier for this class. name (str): The name of the class in the program. """ CodeEntity.__init__(self, scope, parent) self.id = id_ self.name = name self.members = [] self.superclasses = [] self.member_of = None self.references = [] self._definition = self if definition else None def _add(self, codeobj): """Add a child (function, variable, class) to this object.""" assert isinstance(codeobj, (CodeFunction, CodeVariable, CodeClass)) self.members.append(codeobj) codeobj.member_of = self def _afterpass(self): """Assign the `member_of` of child members and call their `_afterpass()`. This should only be called after the object is fully built. """ for codeobj in self.members: if not codeobj.is_definition: if not codeobj._definition is None: codeobj._definition.member_of = self codeobj._afterpass() def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ spaces = ' ' * indent pretty = spaces + 'class ' + self.name if self.superclasses: superclasses = ', '.join(self.superclasses) pretty += '(' + superclasses + ')' pretty += ':\n' if self.members: pretty += '\n\n'.join( c.pretty_str(indent + 2) for c in self.members ) else: pretty += spaces + ' [declaration]' return pretty def __repr__(self): """Return a string representation of this object.""" return '[class {}]'.format(self.name) class CodeNamespace(CodeEntity): """This class represents a program namespace. A namespace is a concept that is explicit in languages such as C++, but less explicit in many others. In Python, the closest thing should be a module. In Java, it may be the same as a class, or non-existent. A namespace typically has a name and a list of children objects (variables, functions or classes). """ def __init__(self, scope, parent, name): """Constructor for namespaces. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the namespace in the program. """ CodeEntity.__init__(self, scope, parent) self.name = name self.children = [] def _add(self, codeobj): """Add a child (namespace, function, variable, class) to this object.""" assert isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction, CodeVariable)) self.children.append(codeobj) def _afterpass(self): """Call the `_afterpass()` of child objects. This should only be called after the object is fully built. """ for codeobj in self.children: codeobj._afterpass() def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ spaces = ' ' * indent pretty = '{}namespace {}:\n'.format(spaces, self.name) pretty += '\n\n'.join(c.pretty_str(indent + 2) for c in self.children) return pretty def __repr__(self): """Return a string representation of this object.""" return '[namespace {}]'.format(self.name) class CodeGlobalScope(CodeEntity): """This class represents the global scope of a program. The global scope is the root object of a program. If there are no better candidates, it is the `scope` and `parent` of all other objects. It is also the only object that does not have a `scope` or `parent`. """ def __init__(self): """Constructor for global scope objects.""" CodeEntity.__init__(self, None, None) self.children = [] def _add(self, codeobj): """Add a child (namespace, function, variable, class) to this object.""" assert isinstance(codeobj, (CodeNamespace, CodeClass, CodeFunction, CodeVariable)) self.children.append(codeobj) def _afterpass(self): """Call the `_afterpass()` of child objects. This should only be called after the object is fully built. """ for codeobj in self.children: codeobj._afterpass() def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ return '\n\n'.join( codeobj.pretty_str(indent=indent) for codeobj in self.children ) # ----- Expression Entities --------------------------------------------------- def __repr__(self): """Return a string representation of this object.""" return '[{}] {}'.format(self.result, self.name) class SomeValue(CodeExpression): """This class represents an unknown value for diverse primitive types.""" def __init__(self, result): """Constructor for unknown values.""" CodeExpression.__init__(self, None, None, result, result) def _children(self): """Yield all the children of this object, that is no children.""" return iter(()) SomeValue.INTEGER = SomeValue("int") SomeValue.FLOATING = SomeValue("float") SomeValue.CHARACTER = SomeValue("char") SomeValue.STRING = SomeValue("string") SomeValue.BOOL = SomeValue("bool") CodeExpression.TYPES = (int, long, float, bool, basestring, SomeValue, CodeLiteral, CodeExpression) CodeExpression.LITERALS = (int, long, float, bool, basestring, CodeLiteral) def _children(self): """Yield all direct children of this object.""" for codeobj in self.arguments: if isinstance(codeobj, CodeExpression): yield codeobj def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ indent = ' ' * indent pretty = '{}({})' if self.parenthesis else '{}{}' if self.is_unary: operator = self.name + pretty_str(self.arguments[0]) else: operator = '{} {} {}'.format(pretty_str(self.arguments[0]), self.name, pretty_str(self.arguments[1])) return pretty.format(indent, operator) def __repr__(self): """Return a string representation of this object.""" if self.is_unary: return '[{}] {}({})'.format(self.result, self.name, self.arguments[0]) if self.is_binary: return '[{}] ({}){}({})'.format(self.result, self.arguments[0], self.name, self.arguments[1]) return '[{}] {}'.format(self.result, self.name) class CodeFunctionCall(CodeExpression): """This class represents a function call. A function call typically has a name (of the called function), a return type, a tuple of its arguments and a reference to the called function. If a call references a class method, its `method_of` should be set to the object on which a method is being called. """ def __init__(self, scope, parent, name, result, paren=False): """Constructor for function calls. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the function in the program. result (str): The return type of the expression in the program. Kwargs: paren (bool): Whether the expression is enclosed in parentheses. """ CodeExpression.__init__(self, scope, parent, name, result, paren) self.full_name = name self.arguments = () self.method_of = None self.reference = None def _add(self, codeobj): """Add a child (argument) to this object.""" assert isinstance(codeobj, CodeExpression.TYPES) self.arguments = self.arguments + (codeobj,) def _set_method(self, codeobj): """Set the object on which a method is called.""" assert isinstance(codeobj, CodeExpression) self.method_of = codeobj def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ indent = ' ' * indent pretty = '{}({})' if self.parenthesis else '{}{}' args = ', '.join(map(pretty_str, self.arguments)) if self.method_of: call = '{}.{}({})'.format(self.method_of.pretty_str(), self.name, args) elif self.is_constructor: call = 'new {}({})'.format(self.name, args) else: call = '{}({})'.format(self.name, args) return pretty.format(indent, call) def __repr__(self): """Return a string representation of this object.""" args = ', '.join(map(str, self.arguments)) if self.is_constructor: return '[{}] new {}({})'.format(self.result, self.name, args) if self.method_of: return '[{}] {}.{}({})'.format(self.result, self.method_of.name, self.name, args) return '[{}] {}({})'.format(self.result, self.name, args) class CodeDefaultArgument(CodeExpression): """This class represents a default argument. Some languages, such as C++, allow function parameters to have default values when not explicitly provided by the programmer. This class represents such omitted arguments. A default argument has only a return type. """ def __init__(self, scope, parent, result): """Constructor for default arguments. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. result (str): The return type of the argument in the program. """ CodeExpression.__init__(self, scope, parent, '(default)', result) # ----- Statement Entities ---------------------------------------------------- def statement_after(self, i): """Return the statement after the *i*-th one, or `None`.""" k = i + 1 o = len(self.body) n = o + len(self.else_body) if k > 0: if k < o: return self.body.statement(k) if k > o and k < n: return self.else_body.statement(k) if k < 0: if k < o - n and k > -n: return self.body.statement(k) if k > o - n: return self.else_body.statement(k) return None def get_branches(self): """Return a list with the conditional branch and the default branch.""" if self.else_branch: return [self.then_branch, self.else_branch] return [self.then_branch] def _add_default_branch(self, body): """Add a default body for this conditional (the `else` branch).""" assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.else_body = body else: self.else_body._add(body) def __len__(self): """Return the length of both branches combined.""" return len(self.body) + len(self.else_body) def _children(self): """Yield all direct children of this object.""" if isinstance(self.condition, CodeExpression): yield self.condition for codeobj in self.body._children(): yield codeobj for codeobj in self.else_body._children(): yield codeobj def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ spaces = ' ' * indent condition = pretty_str(self.condition) pretty = '{}if ({}):\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent + 2) if self.else_body: pretty += '\n{}else:\n'.format(spaces) pretty += self.else_body.pretty_str(indent=indent + 2) return pretty class CodeLoop(CodeControlFlow): """This class represents a loop (e.g. `while`, `for`). Some languages allow loops to define local declarations, as well as an increment statement. A loop has only a single branch, its condition plus the body that should be repeated while the condition holds. """ def __init__(self, scope, parent, name): """Constructor for loops. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. name (str): The name of the loop statement in the program. """ CodeControlFlow.__init__(self, scope, parent, name) self.declarations = None self.increment = None def _set_declarations(self, declarations): """Set declarations local to this loop (e.g. `for` variables).""" assert isinstance(declarations, CodeStatement) self.declarations = declarations declarations.scope = self.body def _set_increment(self, statement): """Set the increment statement for this loop (e.g. in a `for`).""" assert isinstance(statement, CodeStatement) self.increment = statement statement.scope = self.body def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ spaces = ' ' * indent condition = pretty_str(self.condition) v = self.declarations.pretty_str() if self.declarations else '' i = self.increment.pretty_str(indent=1) if self.increment else '' pretty = '{}for ({}; {}; {}):\n'.format(spaces, v, condition, i) pretty += self.body.pretty_str(indent=indent + 2) return pretty class CodeSwitch(CodeControlFlow): """This class represents a switch statement. A switch evaluates a value (its `condition`) and then declares at least one branch (*cases*) that execute when the evaluated value is equal to the branch value. It may also have a default branch. Switches are often one of the most complex constructs of programming languages, so this implementation might be lackluster. """ def __init__(self, scope, parent): """Constructor for switches. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. """ CodeControlFlow.__init__(self, scope, parent, "switch") self.cases = [] self.default_case = None def _add_branch(self, value, statement): """Add a branch/case (value and statement) to this switch.""" self.cases.append((value, statement)) def _add_default_branch(self, statement): """Add a default branch to this switch.""" self.default_case = statement def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ spaces = ' ' * indent condition = pretty_str(self.condition) pretty = '{}switch ({}):\n'.format(spaces, condition) pretty += self.body.pretty_str(indent=indent + 2) return pretty class CodeTryBlock(CodeStatement, CodeStatementGroup): """This class represents a try-catch block statement. `try` blocks have a main body of statements, just like regular blocks. Multiple `catch` blocks may be defined to handle specific types of exceptions. Some languages also allow a `finally` block that is executed after the other blocks (either the `try` block, or a `catch` block, when an exception is raised and handled). """ def __init__(self, scope, parent): """Constructor for try block structures. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. """ CodeStatement.__init__(self, scope, parent) self.body = CodeBlock(scope, self, explicit=True) self.catches = [] self.finally_body = CodeBlock(scope, self, explicit=True) def _set_body(self, body): """Set the main body for try block structure.""" assert isinstance(body, CodeBlock) self.body = body def _add_catch(self, catch_block): """Add a catch block (exception variable declaration and block) to this try block structure. """ assert isinstance(catch_block, self.CodeCatchBlock) self.catches.append(catch_block) def _set_finally_body(self, body): """Set the finally body for try block structure.""" assert isinstance(body, CodeBlock) self.finally_body = body def __len__(self): """Return the length of all blocks combined.""" n = len(self.body) + len(self.catches) + len(self.finally_body) n += sum(map(len, self.catches)) return n def __repr__(self): """Return a string representation of this object.""" return 'try {} {} {}'.format(self.body, self.catches, self.finally_body) def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ spaces = ' ' * indent pretty = spaces + 'try:\n' pretty += self.body.pretty_str(indent=indent + 2) for block in self.catches: pretty += '\n' + block.pretty_str(indent) if len(self.finally_body) > 0: pretty += '\n{}finally:\n'.format(spaces) pretty += self.finally_body.pretty_str(indent=indent + 2) return pretty ############################################################################### # Helpers ############################################################################### def pretty_str(something, indent=0): """Return a human-readable string representation of an object. Uses `pretty_str` if the given value is an instance of `CodeEntity` and `repr` otherwise. Args: something: Some value to convert. Kwargs: indent (int): The amount of spaces to use as indentation. """ if isinstance(something, CodeEntity): return something.pretty_str(indent=indent) else: return (' ' * indent) + repr(something)
35.889841
81
0.60325
fc44182959538bc560fdd3758022cac4683b26ba
737
py
Python
api/views/todo_views.py
felipe-menelau/todo-list-web
9b60a549dc6d5bdd88e1a584b8bb2c4f56131cb5
[ "MIT" ]
null
null
null
api/views/todo_views.py
felipe-menelau/todo-list-web
9b60a549dc6d5bdd88e1a584b8bb2c4f56131cb5
[ "MIT" ]
null
null
null
api/views/todo_views.py
felipe-menelau/todo-list-web
9b60a549dc6d5bdd88e1a584b8bb2c4f56131cb5
[ "MIT" ]
null
null
null
from django.contrib.auth.models import User from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, IsAdminUser from api.serializers import TODOListSerializer from api.models import TODOList
33.5
86
0.766621
fc4539e7bc135f9ebeba5ee7c487446b450f5f15
35
py
Python
Python/Tests/TestData/ProjectHomeProjects/Subfolder/ProgramB.py
techkey/PTVS
8355e67eedd8e915ca49bd38a2f36172696fd903
[ "Apache-2.0" ]
404
2019-05-07T02:21:57.000Z
2022-03-31T17:03:04.000Z
Python/Tests/TestData/ProjectHomeProjects/Subfolder/ProgramB.py
techkey/PTVS
8355e67eedd8e915ca49bd38a2f36172696fd903
[ "Apache-2.0" ]
1,672
2019-05-06T21:09:38.000Z
2022-03-31T23:16:04.000Z
Python/Tests/TestData/ProjectHomeProjects/Subfolder/ProgramB.py
techkey/PTVS
8355e67eedd8e915ca49bd38a2f36172696fd903
[ "Apache-2.0" ]
186
2019-05-13T03:17:37.000Z
2022-03-31T16:24:05.000Z
# ProgramB.py print('Hello World')
11.666667
20
0.714286
fc461d0fe4c1ef7384477f1e053ae3080c54c6a9
1,541
py
Python
donation/migrations/0043_auto_20180109_0012.py
effective-altruism-australia/donation-portal
45fe58edc44d0c4444b493e4ac025fc53897c799
[ "MIT" ]
1
2019-04-23T01:29:26.000Z
2019-04-23T01:29:26.000Z
donation/migrations/0043_auto_20180109_0012.py
effective-altruism-australia/donation-portal
45fe58edc44d0c4444b493e4ac025fc53897c799
[ "MIT" ]
68
2017-02-10T21:33:39.000Z
2019-06-22T13:40:02.000Z
donation/migrations/0043_auto_20180109_0012.py
effective-altruism-australia/donation-portal
45fe58edc44d0c4444b493e4ac025fc53897c799
[ "MIT" ]
5
2016-11-08T01:35:47.000Z
2020-12-08T07:32:34.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
35.022727
171
0.658663
fc4647689f1b8d8a1248e0d89dd5fa8d84dedfbf
350
py
Python
python/is_even.py
c1m50c/twitter-examples
c3ed7cf88dacbb761fed1b0b0dc593d7d3648378
[ "MIT" ]
null
null
null
python/is_even.py
c1m50c/twitter-examples
c3ed7cf88dacbb761fed1b0b0dc593d7d3648378
[ "MIT" ]
null
null
null
python/is_even.py
c1m50c/twitter-examples
c3ed7cf88dacbb761fed1b0b0dc593d7d3648378
[ "MIT" ]
null
null
null
# Never do that! Use one of these instead... is_even = lambda i : i % 2 == 0 is_even = lambda i : not i & 1 is_odd = lambda i : not is_even(i)
20.588235
44
0.511429
fc46a91fda80741480960994acf3dbc98c9e618b
8,886
py
Python
wordpress-brute.py
RandomRobbieBF/wordpress-bf
fe78d4367b7baaf18a4200c5c040595d37b4100f
[ "MIT" ]
1
2020-07-27T11:30:23.000Z
2020-07-27T11:30:23.000Z
wordpress-brute.py
RandomRobbieBF/wordpress-bf
fe78d4367b7baaf18a4200c5c040595d37b4100f
[ "MIT" ]
null
null
null
wordpress-brute.py
RandomRobbieBF/wordpress-bf
fe78d4367b7baaf18a4200c5c040595d37b4100f
[ "MIT" ]
1
2020-05-17T12:40:13.000Z
2020-05-17T12:40:13.000Z
#!/usr/bin/env python # # Wordpress Bruteforce Tool # # By @random_robbie # # import requests import json import sys import argparse import re import os.path from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) session = requests.Session() parser = argparse.ArgumentParser() parser.add_argument("-u", "--url", required=True, default="http://wordpress.lan", help="Wordpress URL") parser.add_argument("-f", "--file", required=True, default="pass.txt" ,help="Password File") args = parser.parse_args() url = args.url passfile = args.file http_proxy = "" proxyDict = { "http" : http_proxy, "https" : http_proxy, "ftp" : http_proxy } # Grab Wordpress Users via Wordpress JSON api # Grab Wordpress Users via Sitemap # Grab Wordpress Users via RSS Feed # Check we can get to wp-admin login. # Check URL is wordpress # Check if wordfence is installed as this limits the logins to 20 per ip # Test the logins # Dont no body like dupes. # Time For Some Machine Learning Quality IF statements. if basic_checks(url): print("[+] Confirmed Wordpress Website [+]") else: print ("[-] Sorry this is either not a wordpress website or there is a issue blocking wp-admin [-]") sys.exit(0) if os.path.isfile(passfile) and os.access(passfile, os.R_OK): print("[+] Password List Used: "+passfile+" [+]") else: print("[-] Either the file is missing or not readable [-]") sys.exit(0) # Method Value for which method to enumerate users from method = "None" attempts = "None" # Which method to use for enumeration if grab_users_api(url): print("[+] Users found via Rest API [-]") method = "restapi" if grab_users_rssfeed(url) and method == "None": print("[+] Users found via RSS Feed [+]") method = "rss" if grab_users_sitemap(url) and method == "None": print("[+] Users found via Authors Sitemap [-]") method = "sitemap" if method == "None": print ("[-] Oh Shit it seems I was unable to find a method to grab usernames from [-]") sys.exit(0) if check_wordfence(url): print ("[+] Wordfence is installed this will limit the testing to 20 attempts [+]") attempts = "20" # Kick off Parsing and attacking if method == "restapi": userdata = grab_users_api(url) attack_restapi(url,attempts,userdata,passfile) if method == "rss": userdata = grab_users_rssfeed(url) attack_rssfeed(url,attempts,userdata,passfile) if method == "sitemap": userdata = grab_users_sitemap(url) attack_sitemap(url,attempts,userdata,passfile)
31.399293
388
0.679721
fc48029eb6bc6d9c3b97d0e2970ae2bc11eb162e
5,626
py
Python
graph_search/week2/assignment_dijkstra_shortest_paths.py
liaoaoyuan97/standford_algorithms_specialization
2914fdd397ce895d986ac855e78afd7a51ceff68
[ "MIT" ]
null
null
null
graph_search/week2/assignment_dijkstra_shortest_paths.py
liaoaoyuan97/standford_algorithms_specialization
2914fdd397ce895d986ac855e78afd7a51ceff68
[ "MIT" ]
null
null
null
graph_search/week2/assignment_dijkstra_shortest_paths.py
liaoaoyuan97/standford_algorithms_specialization
2914fdd397ce895d986ac855e78afd7a51ceff68
[ "MIT" ]
1
2021-01-18T19:35:48.000Z
2021-01-18T19:35:48.000Z
import heapq import time from os import path from math import floor if __name__ == "__main__": # test case 1, output: {1: 0, 2: 1, 3: 2, 4: 2, 5: 3, 6: 4} # graph = { # 1: [(6, 7), (5, 3), (2, 1), (4, 2), (3, 3)], # 2: [(1, 1), (3, 1), (4, 1), (6, 6)], # 3: [(1, 3), (2, 1), (6, 2)], # 4: [(2, 1), (1, 2), (6, 5)], # 5: [(1, 3), (6, 3)], # 6: [(1, 7), (3, 2), (2, 6), (4, 5), (5, 3)] # } graph = read_graph("Dijkstra.txt") dedup_edges = set() for k, _ in graph.items(): for v in _: dedup_edges.add((k, v[0], v[1])) dedup_edges.add((v[0], k, v[1])) assert len(dedup_edges) == sum([len(e) for e in graph.values()]) # graph = {} # heap = Heap() # heap.insert((1,0)) # heap.insert((2,0)) # heap.pop() start_t = time.time() min_distances,X = get_shortest_paths_heapq(graph) print(time.time() - start_t) # print(min_distances) e = [7, 37, 59, 82, 99, 115, 133, 165, 188, 197] print(",".join([str(int(min_distances[i])) for i in e])) start_t = time.time() min_distances = get_shortest_paths_self_defined_heap(graph, X) print(time.time() - start_t) # print(min_distances) e = [7, 37, 59, 82, 99, 115, 133, 165, 188, 197] print(",".join([str(int(min_distances[i])) for i in e]))
27.714286
119
0.551369
fc480677b321e1843fe0812d2b7ce6bbeeb5090e
4,345
py
Python
ssod/utils/structure_utils.py
huimlight/SoftTeacher
97064fbcce1ab87b40977544ba7a9c488274d66f
[ "MIT" ]
604
2021-08-09T03:00:35.000Z
2022-03-31T13:43:14.000Z
ssod/utils/structure_utils.py
huimlight/SoftTeacher
97064fbcce1ab87b40977544ba7a9c488274d66f
[ "MIT" ]
158
2021-08-29T07:58:22.000Z
2022-03-31T15:23:27.000Z
ssod/utils/structure_utils.py
huimlight/SoftTeacher
97064fbcce1ab87b40977544ba7a9c488274d66f
[ "MIT" ]
92
2021-08-24T07:29:37.000Z
2022-03-29T03:01:34.000Z
import warnings from collections import Counter, Mapping, Sequence from numbers import Number from typing import Dict, List import numpy as np import torch from mmdet.core.mask.structures import BitmapMasks from torch.nn import functional as F _step_counter = Counter()
28.214286
88
0.607595
fc49b99b0326493e147f5f9c2af303341e2290ed
2,422
py
Python
tests/tabular_output/test_terminaltables_adapter.py
zzl0/cli_helpers
266645937423225bdb636ef6aa659f1a40ceec5f
[ "BSD-3-Clause" ]
null
null
null
tests/tabular_output/test_terminaltables_adapter.py
zzl0/cli_helpers
266645937423225bdb636ef6aa659f1a40ceec5f
[ "BSD-3-Clause" ]
null
null
null
tests/tabular_output/test_terminaltables_adapter.py
zzl0/cli_helpers
266645937423225bdb636ef6aa659f1a40ceec5f
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """Test the terminaltables output adapter.""" from __future__ import unicode_literals from textwrap import dedent import pytest from cli_helpers.compat import HAS_PYGMENTS from cli_helpers.tabular_output import terminaltables_adapter if HAS_PYGMENTS: from pygments.style import Style from pygments.token import Token def test_terminal_tables_adapter(): """Test the terminaltables output adapter.""" data = [['abc', 1], ['d', 456]] headers = ['letters', 'number'] output = terminaltables_adapter.adapter( iter(data), headers, table_format='ascii') assert "\n".join(output) == dedent('''\ +---------+--------+ | letters | number | +---------+--------+ | abc | 1 | | d | 456 | +---------+--------+''')
34.6
86
0.547069
fc4a04571ae8ad033810ff66b391deb8c9d55bed
1,642
py
Python
dev/Tools/build/waf-1.7.13/waflib/extras/fc_xlf.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Tools/build/waf-1.7.13/waflib/extras/fc_xlf.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Tools/build/waf-1.7.13/waflib/extras/fc_xlf.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
#! /usr/bin/env python # encoding: utf-8 # harald at klimachs.de import re from waflib import Utils,Errors from waflib.Tools import fc,fc_config,fc_scan from waflib.Configure import conf from waflib.Tools.compiler_fc import fc_compiler fc_compiler['aix'].insert(0, 'fc_xlf') def configure(conf): conf.find_xlf() conf.find_ar() conf.fc_flags() conf.fc_add_flags() conf.xlf_flags() conf.xlf_modifier_platform()
25.261538
115
0.693057
fc4af8f087c68aec19d9b595aee4bd3178dfeac2
9,119
py
Python
tutorials/create_table/tests.py
MeGustas-5427/SQL_Tutorials
627372c2d5d8656d72645830c9a1fae1df278fc7
[ "Apache-2.0" ]
13
2020-11-05T04:22:51.000Z
2022-02-27T08:44:50.000Z
tutorials/create_table/tests.py
MeGustas-5427/SQL_Tutorials
627372c2d5d8656d72645830c9a1fae1df278fc7
[ "Apache-2.0" ]
null
null
null
tutorials/create_table/tests.py
MeGustas-5427/SQL_Tutorials
627372c2d5d8656d72645830c9a1fae1df278fc7
[ "Apache-2.0" ]
2
2020-11-10T10:01:20.000Z
2021-04-07T02:33:29.000Z
#!/usr/bin/python3 # -*- coding:utf-8 -*- # __author__ = '__MeGustas__' from django.test import TestCase from django.db import connection from tutorials.create_table.models import * # Create your tests here.
67.051471
154
0.665205
fc4b846e57d2910c0d4eb0a932e3548a8ac421c6
31,822
py
Python
hero/hero.py
tmfds/dfk
91b6f95a4630b57deecf87cf4850b6576646c7d1
[ "MIT" ]
null
null
null
hero/hero.py
tmfds/dfk
91b6f95a4630b57deecf87cf4850b6576646c7d1
[ "MIT" ]
null
null
null
hero/hero.py
tmfds/dfk
91b6f95a4630b57deecf87cf4850b6576646c7d1
[ "MIT" ]
null
null
null
import copy from web3 import Web3 from .utils import utils as hero_utils CONTRACT_ADDRESS = '0x5f753dcdf9b1ad9aabc1346614d1f4746fd6ce5c' ABI = """ [ {"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"}, {"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"}, {"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"heroId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"summonerId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"assistantId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"statGenes","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"visualGenes","type":"uint256"}],"name":"HeroSummoned","type":"event"}, {"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"}, {"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"}, {"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"}, {"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"}, {"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"}, {"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"}, {"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"}, {"inputs":[],"name":"HERO_MODERATOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"}, {"inputs":[],"name":"MINTER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"}, {"inputs":[],"name":"MODERATOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"}, {"inputs":[],"name":"PAUSER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"uint256","name":"_statGenes","type":"uint256"},{"internalType":"uint256","name":"_visualGenes","type":"uint256"}, {"internalType":"enum IHeroTypes.Rarity","name":"_rarity","type":"uint8"}, {"internalType":"bool","name":"_shiny","type":"bool"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"summonerId","type":"uint256"},{"internalType":"uint256","name":"assistantId","type":"uint256"},{"internalType":"uint16","name":"generation","type":"uint16"},{"internalType":"uint256","name":"createdBlock","type":"uint256"},{"internalType":"uint256","name":"heroId","type":"uint256"},{"internalType":"uint8","name":"summonerTears","type":"uint8"},{"internalType":"uint8","name":"assistantTears","type":"uint8"},{"internalType":"address","name":"bonusItem","type":"address"},{"internalType":"uint32","name":"maxSummons","type":"uint32"},{"internalType":"uint32","name":"firstName","type":"uint32"},{"internalType":"uint32","name":"lastName","type":"uint32"},{"internalType":"uint8","name":"shinyStyle","type":"uint8"}],"internalType":"struct ICrystalTypes.HeroCrystal","name":"_crystal","type":"tuple"}],"name":"createHero","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"uint256","name":"_id","type":"uint256"}],"name":"getHero","outputs":[{"components":[{"internalType":"uint256","name":"id","type":"uint256"},{"components":[{"internalType":"uint256","name":"summonedTime","type":"uint256"},{"internalType":"uint256","name":"nextSummonTime","type":"uint256"},{"internalType":"uint256","name":"summonerId","type":"uint256"},{"internalType":"uint256","name":"assistantId","type":"uint256"},{"internalType":"uint32","name":"summons","type":"uint32"},{"internalType":"uint32","name":"maxSummons","type":"uint32"}],"internalType":"struct IHeroTypes.SummoningInfo","name":"summoningInfo","type":"tuple"},{"components":[{"internalType":"uint256","name":"statGenes","type":"uint256"},{"internalType":"uint256","name":"visualGenes","type":"uint256"},{"internalType":"enum IHeroTypes.Rarity","name":"rarity","type":"uint8"},{"internalType":"bool","name":"shiny","type":"bool"},{"internalType":"uint16","name":"generation","type":"uint16"},{"internalType":"uint32","name":"firstName","type":"uint32"},{"internalType":"uint32","name":"lastName","type":"uint32"},{"internalType":"uint8","name":"shinyStyle","type":"uint8"},{"internalType":"uint8","name":"class","type":"uint8"},{"internalType":"uint8","name":"subClass","type":"uint8"}],"internalType":"struct IHeroTypes.HeroInfo","name":"info","type":"tuple"},{"components":[{"internalType":"uint256","name":"staminaFullAt","type":"uint256"},{"internalType":"uint256","name":"hpFullAt","type":"uint256"},{"internalType":"uint256","name":"mpFullAt","type":"uint256"},{"internalType":"uint16","name":"level","type":"uint16"},{"internalType":"uint64","name":"xp","type":"uint64"},{"internalType":"address","name":"currentQuest","type":"address"},{"internalType":"uint8","name":"sp","type":"uint8"},{"internalType":"enum IHeroTypes.HeroStatus","name":"status","type":"uint8"}],"internalType":"struct IHeroTypes.HeroState","name":"state","type":"tuple"},{"components":[{"internalType":"uint16","name":"strength","type":"uint16"},{"internalType":"uint16","name":"intelligence","type":"uint16"},{"internalType":"uint16","name":"wisdom","type":"uint16"},{"internalType":"uint16","name":"luck","type":"uint16"},{"internalType":"uint16","name":"agility","type":"uint16"},{"internalType":"uint16","name":"vitality","type":"uint16"},{"internalType":"uint16","name":"endurance","type":"uint16"},{"internalType":"uint16","name":"dexterity","type":"uint16"},{"internalType":"uint16","name":"hp","type":"uint16"},{"internalType":"uint16","name":"mp","type":"uint16"},{"internalType":"uint16","name":"stamina","type":"uint16"}],"internalType":"struct IHeroTypes.HeroStats","name":"stats","type":"tuple"},{"components":[{"internalType":"uint16","name":"strength","type":"uint16"},{"internalType":"uint16","name":"intelligence","type":"uint16"},{"internalType":"uint16","name":"wisdom","type":"uint16"},{"internalType":"uint16","name":"luck","type":"uint16"},{"internalType":"uint16","name":"agility","type":"uint16"},{"internalType":"uint16","name":"vitality","type":"uint16"},{"internalType":"uint16","name":"endurance","type":"uint16"},{"internalType":"uint16","name":"dexterity","type":"uint16"},{"internalType":"uint16","name":"hpSm","type":"uint16"},{"internalType":"uint16","name":"hpRg","type":"uint16"},{"internalType":"uint16","name":"hpLg","type":"uint16"},{"internalType":"uint16","name":"mpSm","type":"uint16"},{"internalType":"uint16","name":"mpRg","type":"uint16"},{"internalType":"uint16","name":"mpLg","type":"uint16"}],"internalType":"struct IHeroTypes.HeroStatGrowth","name":"primaryStatGrowth","type":"tuple"},{"components":[{"internalType":"uint16","name":"strength","type":"uint16"},{"internalType":"uint16","name":"intelligence","type":"uint16"},{"internalType":"uint16","name":"wisdom","type":"uint16"},{"internalType":"uint16","name":"luck","type":"uint16"},{"internalType":"uint16","name":"agility","type":"uint16"},{"internalType":"uint16","name":"vitality","type":"uint16"},{"internalType":"uint16","name":"endurance","type":"uint16"},{"internalType":"uint16","name":"dexterity","type":"uint16"},{"internalType":"uint16","name":"hpSm","type":"uint16"},{"internalType":"uint16","name":"hpRg","type":"uint16"},{"internalType":"uint16","name":"hpLg","type":"uint16"},{"internalType":"uint16","name":"mpSm","type":"uint16"},{"internalType":"uint16","name":"mpRg","type":"uint16"},{"internalType":"uint16","name":"mpLg","type":"uint16"}],"internalType":"struct IHeroTypes.HeroStatGrowth","name":"secondaryStatGrowth","type":"tuple"},{"components":[{"internalType":"uint16","name":"mining","type":"uint16"},{"internalType":"uint16","name":"gardening","type":"uint16"},{"internalType":"uint16","name":"foraging","type":"uint16"},{"internalType":"uint16","name":"fishing","type":"uint16"}],"internalType":"struct IHeroTypes.HeroProfessions","name":"professions","type":"tuple"}],"internalType":"struct IHeroTypes.Hero","name":"","type":"tuple"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"address","name":"_address","type":"address"}],"name":"getUserHeroes","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"string","name":"_url","type":"string"},{"internalType":"address","name":"_statScienceAddress","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"string","name":"baseTokenURI","type":"string"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}, {"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"address","name":"_statScienceAddress","type":"address"}],"name":"setStatScienceAddress","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}, {"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenOfOwnerByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}, {"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}, {"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"components":[{"internalType":"uint256","name":"id","type":"uint256"},{"components":[{"internalType":"uint256","name":"summonedTime","type":"uint256"},{"internalType":"uint256","name":"nextSummonTime","type":"uint256"},{"internalType":"uint256","name":"summonerId","type":"uint256"},{"internalType":"uint256","name":"assistantId","type":"uint256"},{"internalType":"uint32","name":"summons","type":"uint32"},{"internalType":"uint32","name":"maxSummons","type":"uint32"}],"internalType":"struct IHeroTypes.SummoningInfo","name":"summoningInfo","type":"tuple"},{"components":[{"internalType":"uint256","name":"statGenes","type":"uint256"},{"internalType":"uint256","name":"visualGenes","type":"uint256"},{"internalType":"enum IHeroTypes.Rarity","name":"rarity","type":"uint8"},{"internalType":"bool","name":"shiny","type":"bool"},{"internalType":"uint16","name":"generation","type":"uint16"},{"internalType":"uint32","name":"firstName","type":"uint32"},{"internalType":"uint32","name":"lastName","type":"uint32"},{"internalType":"uint8","name":"shinyStyle","type":"uint8"},{"internalType":"uint8","name":"class","type":"uint8"},{"internalType":"uint8","name":"subClass","type":"uint8"}],"internalType":"struct IHeroTypes.HeroInfo","name":"info","type":"tuple"},{"components":[{"internalType":"uint256","name":"staminaFullAt","type":"uint256"},{"internalType":"uint256","name":"hpFullAt","type":"uint256"},{"internalType":"uint256","name":"mpFullAt","type":"uint256"},{"internalType":"uint16","name":"level","type":"uint16"},{"internalType":"uint64","name":"xp","type":"uint64"},{"internalType":"address","name":"currentQuest","type":"address"},{"internalType":"uint8","name":"sp","type":"uint8"},{"internalType":"enum IHeroTypes.HeroStatus","name":"status","type":"uint8"}],"internalType":"struct IHeroTypes.HeroState","name":"state","type":"tuple"},{"components":[{"internalType":"uint16","name":"strength","type":"uint16"},{"internalType":"uint16","name":"intelligence","type":"uint16"},{"internalType":"uint16","name":"wisdom","type":"uint16"},{"internalType":"uint16","name":"luck","type":"uint16"},{"internalType":"uint16","name":"agility","type":"uint16"},{"internalType":"uint16","name":"vitality","type":"uint16"},{"internalType":"uint16","name":"endurance","type":"uint16"},{"internalType":"uint16","name":"dexterity","type":"uint16"},{"internalType":"uint16","name":"hp","type":"uint16"},{"internalType":"uint16","name":"mp","type":"uint16"},{"internalType":"uint16","name":"stamina","type":"uint16"}],"internalType":"struct IHeroTypes.HeroStats","name":"stats","type":"tuple"},{"components":[{"internalType":"uint16","name":"strength","type":"uint16"},{"internalType":"uint16","name":"intelligence","type":"uint16"},{"internalType":"uint16","name":"wisdom","type":"uint16"},{"internalType":"uint16","name":"luck","type":"uint16"},{"internalType":"uint16","name":"agility","type":"uint16"},{"internalType":"uint16","name":"vitality","type":"uint16"},{"internalType":"uint16","name":"endurance","type":"uint16"},{"internalType":"uint16","name":"dexterity","type":"uint16"},{"internalType":"uint16","name":"hpSm","type":"uint16"},{"internalType":"uint16","name":"hpRg","type":"uint16"},{"internalType":"uint16","name":"hpLg","type":"uint16"},{"internalType":"uint16","name":"mpSm","type":"uint16"},{"internalType":"uint16","name":"mpRg","type":"uint16"},{"internalType":"uint16","name":"mpLg","type":"uint16"}],"internalType":"struct IHeroTypes.HeroStatGrowth","name":"primaryStatGrowth","type":"tuple"},{"components":[{"internalType":"uint16","name":"strength","type":"uint16"},{"internalType":"uint16","name":"intelligence","type":"uint16"},{"internalType":"uint16","name":"wisdom","type":"uint16"},{"internalType":"uint16","name":"luck","type":"uint16"},{"internalType":"uint16","name":"agility","type":"uint16"},{"internalType":"uint16","name":"vitality","type":"uint16"},{"internalType":"uint16","name":"endurance","type":"uint16"},{"internalType":"uint16","name":"dexterity","type":"uint16"},{"internalType":"uint16","name":"hpSm","type":"uint16"},{"internalType":"uint16","name":"hpRg","type":"uint16"},{"internalType":"uint16","name":"hpLg","type":"uint16"},{"internalType":"uint16","name":"mpSm","type":"uint16"},{"internalType":"uint16","name":"mpRg","type":"uint16"},{"internalType":"uint16","name":"mpLg","type":"uint16"}],"internalType":"struct IHeroTypes.HeroStatGrowth","name":"secondaryStatGrowth","type":"tuple"},{"components":[{"internalType":"uint16","name":"mining","type":"uint16"},{"internalType":"uint16","name":"gardening","type":"uint16"},{"internalType":"uint16","name":"foraging","type":"uint16"},{"internalType":"uint16","name":"fishing","type":"uint16"}],"internalType":"struct IHeroTypes.HeroProfessions","name":"professions","type":"tuple"}],"internalType":"struct IHeroTypes.Hero","name":"_hero","type":"tuple"}],"name":"updateHero","outputs":[],"stateMutability":"nonpayable","type":"function"}, {"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"userHeroes","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"} ] """
117.859259
5,003
0.671139
fc4c938deecee815416606c1468c7d127f759b88
364
py
Python
tests/test_langs_fr.py
honzajavorek/tipi
cbe51192725608b6fba1244a48610ae231b13e08
[ "MIT" ]
3
2016-04-13T17:49:09.000Z
2017-11-10T22:26:17.000Z
tests/test_langs_fr.py
honzajavorek/tipi
cbe51192725608b6fba1244a48610ae231b13e08
[ "MIT" ]
null
null
null
tests/test_langs_fr.py
honzajavorek/tipi
cbe51192725608b6fba1244a48610ae231b13e08
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from tipi import tipi as _tipi tipi = lambda s: _tipi(s, lang='fr')
17.333333
46
0.56044
fc50f97ead454f81e6290dc083d27cd62ab11353
2,878
py
Python
vendor/models.py
brethauer/mirage
396f61206bf76f997c0535277af918058aa1b827
[ "CC0-1.0" ]
8
2015-03-07T02:56:32.000Z
2016-08-30T17:09:30.000Z
vendor/models.py
brethauer/mirage
396f61206bf76f997c0535277af918058aa1b827
[ "CC0-1.0" ]
16
2015-02-25T16:09:39.000Z
2016-12-09T22:58:04.000Z
vendor/models.py
brethauer/mirage
396f61206bf76f997c0535277af918058aa1b827
[ "CC0-1.0" ]
13
2015-03-09T00:20:49.000Z
2021-02-14T11:02:32.000Z
from django.db import models VEHICLE_CHOICES = ( ('OASISSB', 'OASIS Small Business'), ('OASIS', 'OASIS Unrestricted') ) STATUS_CHOICES = ( ('P', 'In Progress'), ('C', 'Completed'), ('F', 'Cancelled') )
33.858824
82
0.709173
fc515ce56fd34f4315010ae886d6091f5950eab2
610
py
Python
two_qubit_simulator/circuits.py
L-McCormack/two-qubit-simulator
d7115f0630c9931724aa660dba4b89a50db4e2e0
[ "MIT" ]
null
null
null
two_qubit_simulator/circuits.py
L-McCormack/two-qubit-simulator
d7115f0630c9931724aa660dba4b89a50db4e2e0
[ "MIT" ]
null
null
null
two_qubit_simulator/circuits.py
L-McCormack/two-qubit-simulator
d7115f0630c9931724aa660dba4b89a50db4e2e0
[ "MIT" ]
null
null
null
""" Contains the QuantumCircuit class boom. """
23.461538
74
0.598361
fc519cd073372b79ff5e315d6c117f1de77e8ef5
602
py
Python
examples/bathymetricGradient.py
usgs/water-datapreptools
49c852a0c189e142a351331ba6e0d1ef9e7a408b
[ "CC0-1.0" ]
2
2021-06-22T18:18:47.000Z
2021-09-25T18:16:26.000Z
examples/bathymetricGradient.py
usgs/water-datapreptools
49c852a0c189e142a351331ba6e0d1ef9e7a408b
[ "CC0-1.0" ]
null
null
null
examples/bathymetricGradient.py
usgs/water-datapreptools
49c852a0c189e142a351331ba6e0d1ef9e7a408b
[ "CC0-1.0" ]
null
null
null
import sys sys.path.append("..") # change environment to see tools from make_hydrodem import bathymetricGradient workspace = r"" # path to geodatabase to use as a workspace snapGrid = r"" # path to snapping grid hucPoly = r"" # path to local folder polygon hydrographyArea = r"" # path to NHD area feature class hydrographyFlowline = r"" # path to NHD flowline feature class hydrographyWaterbody = r"" # path to NHD water body feature class cellsize = '' # cell size bathymetricGradient(workspace, snapGrid, hucPoly, hydrographyArea, hydrographyFlowline, hydrographyWaterbody,cellsize)
43
67
0.757475
fc52596785d1ffc33b3982ed9e7fa9443b9fefb7
9,799
py
Python
out/flowContext.py
hxb1997/Menge
7a09a6236d8eef23e3d15d08873d5918d064761b
[ "Apache-2.0" ]
null
null
null
out/flowContext.py
hxb1997/Menge
7a09a6236d8eef23e3d15d08873d5918d064761b
[ "Apache-2.0" ]
null
null
null
out/flowContext.py
hxb1997/Menge
7a09a6236d8eef23e3d15d08873d5918d064761b
[ "Apache-2.0" ]
1
2021-07-01T09:40:01.000Z
2021-07-01T09:40:01.000Z
# This is the OpenGL context for drawing flow calculation lines from Context import * from primitives import Vector2, Segment from OpenGL.GL import * from copy import deepcopy
37.98062
89
0.525462
fc526e31f18c99d7210b6012a52b4a8ccf202ae9
35
py
Python
instascrape/collectors/__init__.py
Paola351/instascrape
b4a50c9140fa9054187738f6d1564cecc32cbaab
[ "MIT" ]
1
2021-03-10T03:36:43.000Z
2021-03-10T03:36:43.000Z
examples/collectors/__init__.py
fo0nikens/instascrape
699dd2169a96438d1d71bce5b1401fd5c5f0e531
[ "MIT" ]
null
null
null
examples/collectors/__init__.py
fo0nikens/instascrape
699dd2169a96438d1d71bce5b1401fd5c5f0e531
[ "MIT" ]
null
null
null
from .interval_collectors import *
17.5
34
0.828571
fc5346e19911a49d8686625f457f771311d07483
324
py
Python
Codes/gracekoo/test.py
ghoslation/algorithm
5708bf89e59a80cd0f50f2e6138f069b4f9bc96e
[ "Apache-2.0" ]
256
2017-10-25T13:02:15.000Z
2022-02-25T13:47:59.000Z
Codes/gracekoo/test.py
IYoreI/Algorithm
0addf0cda0ec9e3f46c480eeda3a8ecb64c94121
[ "Apache-2.0" ]
56
2017-10-27T01:34:20.000Z
2022-03-01T00:20:55.000Z
Codes/gracekoo/test.py
IYoreI/Algorithm
0addf0cda0ec9e3f46c480eeda3a8ecb64c94121
[ "Apache-2.0" ]
83
2017-10-25T12:51:53.000Z
2022-02-15T08:27:03.000Z
# -*- coding: utf-8 -*- # @Time: 2020/11/8 23:47 # @Author: GraceKoo # @File: test.py # @Desc: from threading import Thread import time if __name__ == "__main__": t1 = Thread(target=print_numbers) t1.setDaemon(True) t1.start() # print("")
16.2
37
0.623457
fc534b79cb83ef68a1a71a69fd50a17561f7b0a3
5,894
py
Python
src/_main_/settings.py
gregory-chekler/api
11ecbea945e7eb6fa677a0c0bb32bda51ba15f28
[ "MIT" ]
null
null
null
src/_main_/settings.py
gregory-chekler/api
11ecbea945e7eb6fa677a0c0bb32bda51ba15f28
[ "MIT" ]
null
null
null
src/_main_/settings.py
gregory-chekler/api
11ecbea945e7eb6fa677a0c0bb32bda51ba15f28
[ "MIT" ]
null
null
null
""" Django settings for massenergize_portal_backend project. Generated by 'django-admin startproject' using Django 2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os import firebase_admin from firebase_admin import credentials from .utils.utils import load_json # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ******** LOAD CONFIG DATA ***********# IS_PROD = False path_to_config = '/_main_/config/massenergizeProdConfig.json' if IS_PROD else '/_main_/config/massenergizeProjectConfig.json' CONFIG_DATA = load_json(BASE_DIR + path_to_config) os.environ.update(CONFIG_DATA) # ******** END LOAD CONFIG DATA ***********# SECRET_KEY = CONFIG_DATA["SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'api.massenergize.org', 'apis.massenergize.org', 'api.massenergize.com', 'apis.massenergize.com', 'api-prod.massenergize.org', 'api.prod.massenergize.org', 'api-dev.massenergize.org', 'api.dev.massenergize.org', 'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com' ] INSTALLED_APPS = [ 'authentication', 'carbon_calculator', 'database', 'api', 'website', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #custom middlewares 'authentication.middleware.MassenergizeJWTAuthMiddleware' ] #-------- FILE STORAGE CONFIGURATION ---------------------# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #-------- FILE STORAGE CONFIGURATION ---------------------# #-------- AWS CONFIGURATION ---------------------# AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_VERSION = os.environ.get('AWS_S3_SIGNATURE_VERSION') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL = None #--------END AWS CONFIGURATION ---------------------# CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440*3 ROOT_URLCONF = '_main_.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '_main_.wsgi.application' CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'remote-default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : os.environ.get('DATABASE_NAME'), 'USER' : os.environ.get('DATABASE_USER'), 'PASSWORD' : os.environ.get('DATABASE_PASSWORD'), 'HOST' : os.environ.get('DATABASE_HOST'), 'PORT' : os.environ.get('DATABASE_PORT') }, 'default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : 'gchekler21', 'USER' : '', 'PASSWORD' : '', 'HOST' : 'localhost', 'PORT' : '5555' }, } firebase_service_account_path = '/_main_/config/massenergizeProdFirebaseServiceAccount.json' if IS_PROD else '/_main_/config/massenergizeFirebaseServiceAccount.json' FIREBASE_CREDENTIALS = credentials.Certificate(BASE_DIR + firebase_service_account_path) firebase_admin.initialize_app(FIREBASE_CREDENTIALS) # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' # Simplified static file serving. STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media'
29.918782
165
0.69172
fc545ada34aef15e72804247df9cc885de6ee820
2,657
py
Python
aiorpcgrid/client.py
urands/aiorpcgrid
7bc9ee9a80fa843998b2604d7c0803b323628480
[ "Apache-2.0" ]
null
null
null
aiorpcgrid/client.py
urands/aiorpcgrid
7bc9ee9a80fa843998b2604d7c0803b323628480
[ "Apache-2.0" ]
null
null
null
aiorpcgrid/client.py
urands/aiorpcgrid
7bc9ee9a80fa843998b2604d7c0803b323628480
[ "Apache-2.0" ]
null
null
null
import asyncio # from aiorpcgrid.client import Client from aiorpcgrid.task import AsyncTask, State
34.960526
77
0.546481
fc557f84938097fbd8c0d95d4d05c57f1ad0bde0
4,093
py
Python
python/src/otel/otel_sdk/opentelemetry/instrumentation/aws_lambda/__init__.py
matt-tyler/opentelemetry-lambda
6b427d351fa721620fcd387e836e9f2f9f20cb60
[ "Apache-2.0" ]
null
null
null
python/src/otel/otel_sdk/opentelemetry/instrumentation/aws_lambda/__init__.py
matt-tyler/opentelemetry-lambda
6b427d351fa721620fcd387e836e9f2f9f20cb60
[ "Apache-2.0" ]
null
null
null
python/src/otel/otel_sdk/opentelemetry/instrumentation/aws_lambda/__init__.py
matt-tyler/opentelemetry-lambda
6b427d351fa721620fcd387e836e9f2f9f20cb60
[ "Apache-2.0" ]
1
2021-01-24T12:08:18.000Z
2021-01-24T12:08:18.000Z
# Copyright 2020, OpenTelemetry Authors # # 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. # TODO: usage """ The opentelemetry-instrumentation-aws-lambda package allows tracing AWS Lambda function. Usage ----- .. code:: python # Copy this snippet into AWS Lambda function # Ref Doc: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html import boto3 from opentelemetry.instrumentation.aws_lambda import ( AwsLambdaInstrumentor ) # Enable instrumentation AwsLambdaInstrumentor().instrument() # Lambda function def lambda_handler(event, context): s3 = boto3.resource('s3') for bucket in s3.buckets.all(): print(bucket.name) return "200 OK" API --- """ import logging import os from importlib import import_module from wrapt import wrap_function_wrapper # TODO: aws propagator from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import ( AwsXRayFormat, ) from opentelemetry.instrumentation.aws_lambda.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap from opentelemetry.trace import SpanKind, get_tracer, get_tracer_provider logger = logging.getLogger(__name__)
34.108333
151
0.716101
fc572a69e6a41f7d2d8f4eb6c221dcaa2427e9e3
471
py
Python
instructors/migrations/0021_alter_user_avatar_url.py
bastoune57/gokiting_back_end
f3edcbeede292713349b28f2390b5d57e1420f8e
[ "MIT" ]
null
null
null
instructors/migrations/0021_alter_user_avatar_url.py
bastoune57/gokiting_back_end
f3edcbeede292713349b28f2390b5d57e1420f8e
[ "MIT" ]
null
null
null
instructors/migrations/0021_alter_user_avatar_url.py
bastoune57/gokiting_back_end
f3edcbeede292713349b28f2390b5d57e1420f8e
[ "MIT" ]
null
null
null
# Generated by Django 4.0.2 on 2022-04-01 16:09 from django.db import migrations, models
24.789474
108
0.651805
fc58e1c32b322dbf5e028fbcbb5c81a4dc6ff07a
1,348
py
Python
sopa/src/models/utils.py
SamplingAndEnsemblingSolvers/SamplingAndEnsemblingSolvers
5ad3cae76c3cc9cec4d347807012e61121ea61b9
[ "MIT" ]
25
2021-03-16T13:40:45.000Z
2021-08-12T04:54:39.000Z
sopa/src/models/utils.py
MetaSolver/icml2021
619774abe4a834ae371434af8b23379e9524e7da
[ "BSD-3-Clause" ]
null
null
null
sopa/src/models/utils.py
MetaSolver/icml2021
619774abe4a834ae371434af8b23379e9524e7da
[ "BSD-3-Clause" ]
1
2021-03-31T02:58:03.000Z
2021-03-31T02:58:03.000Z
import numpy as np import torch import random from .odenet_mnist.layers import MetaNODE
27.510204
99
0.635015
fc5ae40661fc1b76d02d932d2ea414f59839b072
319
py
Python
packages/micropython-official/v1.10/esp32/stubs/ubinascii.py
TheVinhLuong102/micropy-stubs
55ff1773008f7c4dfc3d70a403986486226eb6b3
[ "MIT" ]
18
2019-07-11T13:31:09.000Z
2022-01-27T06:38:40.000Z
packages/micropython-official/v1.10/esp32/stubs/ubinascii.py
TheVinhLuong102/micropy-stubs
55ff1773008f7c4dfc3d70a403986486226eb6b3
[ "MIT" ]
9
2019-09-01T21:44:49.000Z
2022-02-04T20:55:08.000Z
packages/micropython-official/v1.10/esp32/stubs/ubinascii.py
TheVinhLuong102/micropy-stubs
55ff1773008f7c4dfc3d70a403986486226eb6b3
[ "MIT" ]
6
2019-10-08T05:31:21.000Z
2021-04-22T10:21:01.000Z
""" Module: 'ubinascii' on esp32 1.10.0 """ # MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32 module with ESP32') # Stubber: 1.2.0
15.190476
126
0.623824
fc5b4e12e35ec5a1123e4672989f9b50567b330a
3,141
py
Python
jv/test_jv.py
chenwang/QuantEcon.lectures.code
8832a74acd219a71cb0a99dc63c5e976598ac999
[ "BSD-3-Clause" ]
56
2017-05-09T10:45:23.000Z
2022-01-20T20:33:27.000Z
jv/test_jv.py
chenwang/QuantEcon.lectures.code
8832a74acd219a71cb0a99dc63c5e976598ac999
[ "BSD-3-Clause" ]
7
2017-06-30T01:52:46.000Z
2019-05-01T20:09:47.000Z
jv/test_jv.py
QuantEcon/QuantEcon.lectures.code
d61ac7bc54529dd5c77470c17539eb2418b047c9
[ "BSD-3-Clause" ]
117
2017-04-25T16:09:17.000Z
2022-03-23T02:30:29.000Z
""" @author : Spencer Lyon """ from __future__ import division import sys import unittest from nose.plugins.skip import SkipTest from jv import JvWorker from quantecon import compute_fixed_point from quantecon.tests import get_h5_data_file, write_array, max_abs_diff # specify params -- use defaults A = 1.4 alpha = 0.6 beta = 0.96 grid_size = 50 if sys.version_info[0] == 2: v_nm = "V" else: # python 3 raise SkipTest("Python 3 tests aren't ready.") v_nm = "V_py3" def _new_solution(jv, f, grp): "gets new solution and updates data file" V = _solve_via_vfi(jv) write_array(f, grp, V, v_nm) return V def _solve_via_vfi(jv): "compute policy rules via value function iteration" v_init = jv.x_grid * 0.6 V = compute_fixed_point(jv.bellman_operator, v_init, max_iter=3000, error_tol=1e-5) return V
28.044643
78
0.606176
fc5bfb461089e67c5b2c46ef4db3208ad1a8b352
9,820
py
Python
excentury/command/config.py
LaudateCorpus1/excentury
8d0f20bb3e543382170e042fac51a56377c4024b
[ "BSD-2-Clause" ]
null
null
null
excentury/command/config.py
LaudateCorpus1/excentury
8d0f20bb3e543382170e042fac51a56377c4024b
[ "BSD-2-Clause" ]
null
null
null
excentury/command/config.py
LaudateCorpus1/excentury
8d0f20bb3e543382170e042fac51a56377c4024b
[ "BSD-2-Clause" ]
1
2021-12-31T13:24:16.000Z
2021-12-31T13:24:16.000Z
"""Config This module is in charge of providing all the necessary settings to the rest of the modules in excentury. """ import os import re import sys import textwrap import argparse from collections import OrderedDict from excentury.command import error, trace, import_mod DESC = """Edit a configuration file for excentury. Some actions performed by excentury can be overwritten by using configuration files. To see the values that the configuration file can overwrite use the `defaults` command. This will print a list of the keys and values excentury uses for the given command. """ RE = re.compile(r'\${(?P<key>.*?)}') RE_IF = re.compile( r'(?P<iftrue>.*?) IF\[\[(?P<cond>.*?)\]\]' ) RE_IFELSE = re.compile( r'(?P<iftrue>.*?) IF\[\[(?P<cond>.*?)\]\]ELSE (?P<iffalse>.*)' ) def disp(msg): """Wrapper around sys.stdout.write which is meant to behave as the print function but it does not add the newline character. """ sys.stdout.write(msg) def _replacer(*key_val): """Helper function for replace. Source: <http://stackoverflow.com/a/15221068/788553> """ replace_dict = dict(key_val) replacement_function = lambda match: replace_dict[match.group(0)] pattern = re.compile("|".join([re.escape(k) for k, _ in key_val]), re.M) return lambda string: pattern.sub(replacement_function, string) def replace(string, *key_val): """Replacement of strings done in one pass. Example: >>> replace("a < b && b < c", ('<', '&lt;'), ('&', '&amp;')) 'a &lt; b &amp;&amp; b &lt; c' Source: <http://stackoverflow.com/a/15221068/788553> """ return _replacer(*key_val)(string) def add_parser(subp, raw): "Add a parser to the main subparser. " tmpp = subp.add_parser('config', help='configure excentury', formatter_class=raw, description=textwrap.dedent(DESC)) tmpp.add_argument('var', type=str, nargs='?', default=None, help='Must be in the form of sec.key') tmpp.add_argument('-v', action='store_true', help='print config file location') tmpp.add_argument('--print', action=ConfigDispAction, nargs=0, help='print config file and exit') def _get_replacements(tokens, data, sec): """Helper function for _read_config. """ replacements = list() for token in tokens: if ':' in token: tsec, tkey = token.split(':') tval = '' if tsec in data: if tkey in data[tsec]: tval = data[tsec][tkey] else: if token in data[sec]: tval = data[sec][token] else: tval = '' replacements.append( ('${%s}' % token, tval) ) return replacements # pylint: disable=invalid-name # ARG and CFG are names that may be used in the configuration file. # ARG gives us access to the command line arguments and CFG gives us # access to the current configuration. Note that using CFG[key][sec] # is equivalent to ${key:sec}. These names go against the convention # so that they may be easy to spot in a configuration file. def _eval_condition(cond, ARG, CFG, line_num, fname): """Evaluates a string using the eval function. It prints a warning if there are any errors. Returns the result of the evaluation and an error number: 0 if everything is fine, 1 if there was an error. """ ARG.FILEPATH = '%s/%s/%s' % (ARG.cfg, CFG['xcpp']['path'], ARG.inputfile) try: # pylint: disable=eval-used # To be able to evaluate a condition without creating a whole # new parser we can use the eval function. We could have use # a python file as a configuration but then there would be # no simple structure to the files. cond = eval(cond) enum = 0 # pylint: disable=broad-except # Anything can go wrong during the execution of the `eval` # function. For this reason we must try to catch anything that # may come our way so that we may give out a warning message # and ignore it. except Exception as exception: cond = None enum = 1 trace( 'WARNING: error in line %d of %r: %s\n' % ( line_num, fname, exception.message ) ) return cond, enum def _read_config(fname, arg): """Simple parser to read configuration files. """ data = OrderedDict() sec = None line_num = 0 with open(fname, 'r') as fhandle: for line in fhandle: line_num += 1 if line[0] == '[': sec = line[1:-2] data[sec] = OrderedDict() elif '=' in line: tmp = line.split('=', 1) key = tmp[0].strip() val = tmp[1].strip() val = os.path.expandvars(val) replacements = _get_replacements( RE.findall(val), data, sec ) # pylint: disable=star-args if replacements: val = replace(val, *replacements) match = RE_IFELSE.match(val) if match: cond, enum = _eval_condition( match.group('cond'), arg, data, line_num, fname ) if enum == 1: continue groups = match.groups() val = groups[0] if cond else groups[2] else: match = RE_IF.match(val) if match: cond, enum = _eval_condition( match.group('cond'), arg, data, line_num, fname ) if enum == 1: continue if cond: val = match.group('iftrue') else: continue data[sec][key] = val return data def read_config(arg): """Read the configuration file xcpp.config""" path = arg.cfg if path == '.' and not os.path.exists('xcpp.config'): if 'XCPP_CONFIG_PATH' in os.environ: tmp_path = os.environ['XCPP_CONFIG_PATH'] if os.path.exists('%s/xcpp.config' % tmp_path): trace("Configured with: '%s/xcpp.config'\n" % tmp_path) path = tmp_path elif not os.path.exists('%s/xcpp.config' % path): error("ERROR: %s/xcpp.config does not exist\n" % path) arg.cfg = path try: config = _read_config('%s/xcpp.config' % path, arg) except IOError: config = OrderedDict() return config def run(arg): """Run command. """ config = read_config(arg) if arg.v: disp('path to xcpp.config: "%s"\n' % arg.cfg) if arg.var is None: for sec in config: disp('[%s]\n' % sec) for key in config[sec]: disp(' %s = %s\n' % (key, config[sec][key])) disp('\n') return try: command, var = arg.var.split('.', 1) except ValueError: error("ERROR: '%s' is not of the form sec.key\n" % arg.var) try: disp(config[command][var]+'\n') except KeyError: pass return def _update_single(cfg, name, defaults=None): "Helper function for get_cfg." if defaults: for var, val in defaults.iteritems(): cfg[name][var] = os.path.expandvars(str(val)) else: mod = import_mod('excentury.command.%s' % name) if hasattr(mod, "DEFAULTS"): for var, val in mod.DEFAULTS.iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_file(cfg, name, cfg_file): "Helper function for get_cfg." if name in cfg_file: for var, val in cfg_file[name].iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_arg(cfg, argdict, key): "Helper function for get_cfg." for var in cfg[key]: if var in argdict and argdict[var] is not None: cfg[key][var] = argdict[var] def get_cfg(arg, names, defaults=None): """Obtain the settings for a command. """ cfg = { 'xcpp': { 'root': '.', 'path': '.' } } cfg_file = read_config(arg) if 'xcpp' in cfg_file: for var, val in cfg_file['xcpp'].iteritems(): cfg['xcpp'][var] = os.path.expandvars(val) cfg['xcpp']['root'] = arg.cfg if isinstance(names, list): for name in names: cfg[name] = dict() _update_single(cfg, name) _update_from_file(cfg, name, cfg_file) else: if names != 'xcpp': cfg[names] = dict() _update_single(cfg, names, defaults) _update_from_file(cfg, names, cfg_file) argdict = vars(arg) if arg.parser_name in cfg: _update_from_arg(cfg, argdict, arg.parser_name) elif arg.parser_name == 'to' and arg.lang in cfg: _update_from_arg(cfg, argdict, arg.lang) _update_from_arg(cfg, argdict, 'xcpp') return cfg
33.175676
77
0.559063
fc5d1f91e8b522de235f963587514841692890ab
4,696
py
Python
tests/test_urls.py
pkjmesra/nseta
28cd8cede465efe9f506a38c5933602c463e5185
[ "MIT" ]
8
2020-10-12T02:59:03.000Z
2022-03-20T15:06:50.000Z
tests/test_urls.py
pkjmesra/nseta
28cd8cede465efe9f506a38c5933602c463e5185
[ "MIT" ]
3
2020-10-13T16:30:09.000Z
2021-01-07T23:57:05.000Z
tests/test_urls.py
pkjmesra/nseta
28cd8cede465efe9f506a38c5933602c463e5185
[ "MIT" ]
5
2020-10-12T14:57:41.000Z
2021-12-30T11:52:34.000Z
# -*- coding: utf-8 -*- ''' Created on Thu Nov 19 20:52:33 2015 @author: SW274998 ''' from nseta.common.commons import * import datetime import unittest import time from bs4 import BeautifulSoup from tests import htmls import json import requests import six from nseta.common.urls import * import nseta.common.urls as urls from six.moves.urllib.parse import urlparse from baseUnitTest import baseUnitTest if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUrls) result = unittest.TextTestRunner(verbosity=2).run(suite) if six.PY2: if result.wasSuccessful(): print('tests OK') for (test, error) in result.errors: print('=========Error in: %s===========' % test) print(error) print('======================================') for (test, failures) in result.failures: print('=========Error in: %s===========' % test) print(failures) print('======================================')
34.277372
178
0.643526
fc5d4359e9534912a4f50ac4cf894cf8797005d0
3,207
py
Python
accounts/forms.py
cheradenine/Django-CRM
692572ced050d314c1f880af8b4000c97cbf7440
[ "MIT" ]
2
2019-08-30T14:42:45.000Z
2019-09-01T01:49:38.000Z
accounts/forms.py
cheradenine/Django-CRM
692572ced050d314c1f880af8b4000c97cbf7440
[ "MIT" ]
7
2021-03-31T20:01:14.000Z
2022-03-12T00:47:10.000Z
accounts/forms.py
gthreepwood/Django-CRM
12de7e6c622d9d7483c210212c8b7fe3dbde2739
[ "MIT" ]
1
2021-10-09T10:03:46.000Z
2021-10-09T10:03:46.000Z
from django import forms from .models import Account from common.models import Comment, Attachments from leads.models import Lead from contacts.models import Contact from django.db.models import Q
41.115385
104
0.617399
fc5dc71b519a1377907665d2b2ecee494faf08a3
2,408
py
Python
pywren/pywren_ibm_cloud/invokers.py
thetolga/pywren-ibm-cloud
ce48c158cf469b55100ab68a75d3dcd6ae9a3ffe
[ "Apache-2.0" ]
null
null
null
pywren/pywren_ibm_cloud/invokers.py
thetolga/pywren-ibm-cloud
ce48c158cf469b55100ab68a75d3dcd6ae9a3ffe
[ "Apache-2.0" ]
null
null
null
pywren/pywren_ibm_cloud/invokers.py
thetolga/pywren-ibm-cloud
ce48c158cf469b55100ab68a75d3dcd6ae9a3ffe
[ "Apache-2.0" ]
null
null
null
# # Copyright 2018 PyWren Team # # 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 time import logging import random from pywren_ibm_cloud.cf_connector import CloudFunctions logger = logging.getLogger(__name__)
34.898551
148
0.658638
fc5f5a1b908ccb47f94225746e71f15650a97363
4,160
py
Python
Projet1/Dataset/addlinkRealExample.py
Arugakente/DataScienceP1
94ca874ed8a76a89a3da9ecf2fe6e554700f0507
[ "MIT" ]
null
null
null
Projet1/Dataset/addlinkRealExample.py
Arugakente/DataScienceP1
94ca874ed8a76a89a3da9ecf2fe6e554700f0507
[ "MIT" ]
null
null
null
Projet1/Dataset/addlinkRealExample.py
Arugakente/DataScienceP1
94ca874ed8a76a89a3da9ecf2fe6e554700f0507
[ "MIT" ]
null
null
null
import os import random inputDirectory = "./original" outputDirectory = "./processed" #probability parameters TopLevel = 0.6 SecondLevel = 0.5 ThirdLevel = 0.4 FourAndAbove = 0.2 pickInside = 0.5 pickOutside = 0.25 topics = [] siteLevel = [] fileStructure = [] count = 0 topicIndex=0 for foldername in os.listdir(inputDirectory) : if(foldername[0] != "."): topics.append(foldername) siteLevel.append([]) fileStructure.append([]) levelIndex=0 for categoryName in os.listdir(inputDirectory+"/"+foldername): if(categoryName[0] != "."): siteLevel[topicIndex].append(categoryName) fileStructure[topicIndex].append([]) for filename in os.listdir(inputDirectory+"/"+foldername+"/"+categoryName): if(filename[0] != "."): fileStructure[topicIndex][levelIndex].append(filename) levelIndex += 1 topicIndex += 1 for i in range(0,len(topics)): for j in range(0,len(siteLevel[i])): for k in range(0,len(fileStructure[i][j])): count += manageFile(inputDirectory+"/"+topics[i]+"/"+siteLevel[i][j]+"/"+fileStructure[i][j][k],outputDirectory+"/"+fileStructure[i][j][k],i,j,fileStructure[i][j][k]) print(str(count)+" liens crs")
33.821138
178
0.571394
fc61f699dd50ec363bb2a766f77f3f5058fefd54
13,616
py
Python
kkcalc/kk.py
benajamin/kkcalc
fcabfba288442dd297e3bd9910062c5db2231a91
[ "Zlib" ]
null
null
null
kkcalc/kk.py
benajamin/kkcalc
fcabfba288442dd297e3bd9910062c5db2231a91
[ "Zlib" ]
1
2021-02-09T10:18:14.000Z
2021-02-17T08:28:58.000Z
kkcalc/kk.py
benajamin/kkcalc
fcabfba288442dd297e3bd9910062c5db2231a91
[ "Zlib" ]
3
2021-02-06T23:37:14.000Z
2022-01-19T15:26:26.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the Kramers-Kronig Calculator software package. # # Copyright (c) 2013 Benjamin Watts, Daniel J. Lauk # # The software is licensed under the terms of the zlib/libpng license. # For details see LICENSE.txt """This module implements the Kramers-Kronig transformation.""" import logging, sys logger = logging.getLogger(__name__) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) logging.StreamHandler(stream=sys.stdout) import math import numpy import os import data def calc_relativistic_correction(stoichiometry): """Calculate the relativistic correction to the Kramers-Kronig transform. Parameters: ----------- stoichiometry : array of integer/float pairs Each pair in the list consists of an atomic number and the relative proportion of that element. Returns ------- This function returns a ``float`` holding the relativistic corection to the Kramers-Kronig transform. """ correction = 0 for z, n in stoichiometry: correction += (z - (z/82.5)**2.37) * n return correction def KK_General_PP(Eval_Energy, Energy, imaginary_spectrum, orders, relativistic_correction): """Calculate Kramers-Kronig transform with "Piecewise Polynomial" algorithm plus the Biggs and Lighthill extended data. Parameters ---------- Eval_Energy : numpy vector of `float` Set of photon energies describing points at which to evaluate the real spectrum Energy : numpy vector of `float` Set of photon energies describing intervals for which each row of `imaginary_spectrum` is valid imaginary_spectrum : two-dimensional `numpy.array` of `float` The array consists of columns of polynomial coefficients belonging to the power terms indicated by 'order' orders : numpy vector of integers The vector represents the polynomial indices corresponding to the columns of imaginary_spectrum relativistic_correction : float The relativistic correction to the Kramers-Kronig transform. You can calculate the value using the `calc_relativistic_correction` function. Returns ------- This function returns the real part of the scattering factors evaluated at photon energies specified by Eval_Energy. """ logger = logging.getLogger(__name__) logger.info("Calculate Kramers-Kronig transform using general piecewise-polynomial algorithm") # Need to build x-E-n arrays X = numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders))) E = numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders))) C = numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1)) N = numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1)) poles = numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders)))) # all N, ln(x+E) and ln(x-E) terms and poles Integral = numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2)) if numpy.any(orders<=-2): # N<=-2, ln(x) terms i = [slice(None,None,None),slice(None,None,None),orders<=-2] Integral += numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2)) if numpy.any(orders>=0): # N>=0, x^k terms for ni in numpy.where(orders>=0)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k in range(n,0,-2): Integral += numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) if numpy.any(orders <=-3): # N<=-3, x^k terms for ni in numpy.where(orders<=-3)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k in range(n+2,0,2): Integral += numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) logger.debug("Done!") return Integral / math.pi + relativistic_correction def KK_PP(Eval_Energy, Energy, imaginary_spectrum, relativistic_correction): """Calculate Kramers-Kronig transform with "Piecewise Polynomial" algorithm plus the Biggs and Lighthill extended data. Parameters ---------- Eval_Energy : numpy vector of `float` Set of photon energies describing points at which to evaluate the real spectrum Energy : numpy vector of `float` Set of photon energies describing intervals for which each row of `imaginary_spectrum` is valid imaginary_spectrum : two-dimensional `numpy.array` of `float` The array consists of five columns of polynomial coefficients: A_1, A_0, A_-1, A_-2, A_-3 relativistic_correction : float The relativistic correction to the Kramers-Kronig transform. You can calculate the value using the `calc_relativistic_correction` function. Returns ------- This function returns the real part of the scattering factors evaluated at photon energies specified by Eval_Energy. """ logger = logging.getLogger(__name__) logger.info("Calculate Kramers-Kronig transform using (n from 1 to -3) piecewise-polynomial algorithm") X1 = Energy[0:-1] X2 = Energy[1:] E = numpy.tile(Eval_Energy, (len(Energy)-1, 1)).T Full_coeffs = imaginary_spectrum.T Symb_1 = (( Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)-(Full_coeffs[3, :]/E+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4, :]/E*(X2**-1-X1**-1)) Symb_2 = ((-Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)+(Full_coeffs[3, :]/E-Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4, :]/E*(X2**-1-X1**-1))+(Full_coeffs[0, :]*E**2-Full_coeffs[1, :]*E+Full_coeffs[2, :]-Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E))) Symb_3 = (1-1*((X2==E)|(X1==E)))*(Full_coeffs[0, :]*E**2+Full_coeffs[1, :]*E+Full_coeffs[2, :]+Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E)))) Symb_B = numpy.sum(Symb_2 - Symb_1 - Symb_3, axis=1) # Sum areas for approximate integral # Patch singularities hits = Energy[1:-1]==E[:,0:-1] E_hits = numpy.append(numpy.insert(numpy.any(hits, axis=0),[0,0],False),[False,False]) Eval_hits = numpy.any(hits, axis=1) X1 = Energy[E_hits[2:]] XE = Energy[E_hits[1:-1]] X2 = Energy[E_hits[:-2]] C1 = Full_coeffs[:, E_hits[2:-1]] C2 = Full_coeffs[:, E_hits[1:-2]] Symb_singularities = numpy.zeros(len(Eval_Energy)) Symb_singularities[Eval_hits] = (C2[0, :]*XE**2+C2[1, :]*XE+C2[2, :]+C2[3, :]*XE**-1+C2[4, :]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE))) # Finish things off KK_Re = (Symb_B-Symb_singularities) / (math.pi*Eval_Energy) + relativistic_correction logger.debug("Done!") return KK_Re def improve_accuracy(Full_E, Real_Spectrum, Imaginary_Spectrum, relativistic_correction, tolerance, recursion=50): """Calculate extra data points so that a linear interpolation is more accurate. Parameters ---------- Full_E : numpy vector of `float` Set of photon energies describing intervals for which each row of `imaginary_spectrum` is valid Real_Spectrum : numpy vector of `float` The real part of the spectrum corresponding to magnitudes at photon energies in Full_E Imaginary_Spectrum : two-dimensional `numpy.array` of `float` The array consists of five columns of polynomial coefficients: A_1, A_0, A_-1, A_-2, A_-3 relativistic_correction : float The relativistic correction to the Kramers-Kronig transform. (You can calculate the value using the `calc_relativistic_correction` function.) tolerance : float Level of error in linear extrapolation of data values to be allowed. recursion : integer Number of times an energy interval can be halved before giving up. Returns ------- This function returns a numpy array with three columns respectively representing photon energy, the real spectrum and the imaginary spectrum. """ logger.debug("Improve data accuracy") new_points = numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1 Im_values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) #plot_Im_values = Im_values Re_values = Real_Spectrum E_values = Full_E temp_Im_spectrum = Imaginary_Spectrum[1:] count = 0 improved = 1 total_improved_points = 0 while count<recursion and numpy.sum(improved)>0: #get E_midpoints midpoints = (E_values[new_points-1]+E_values[new_points])/2. #evaluate at new points Im_midpoints = data.coeffs_to_ASF(midpoints, temp_Im_spectrum) Re_midpoints = KK_PP(midpoints, Full_E, Imaginary_Spectrum, relativistic_correction) #evaluate error levels Im_error = abs((Im_values[new_points-1]+Im_values[new_points])/2. - Im_midpoints) Re_error = abs((Re_values[new_points-1]+Re_values[new_points])/2. - Re_midpoints) improved = (Im_error>tolerance) | (Re_error>tolerance) logger.debug(str(numpy.sum(improved))+" points (out of "+str(len(improved))+") can be improved in pass number "+str(count+1)+".") total_improved_points += numpy.sum(improved) #insert new points and values Im_values = numpy.insert(Im_values,new_points[improved],Im_midpoints[improved]) Re_values = numpy.insert(Re_values,new_points[improved],Re_midpoints[improved]) E_values = numpy.insert(E_values,new_points[improved],midpoints[improved]) #prepare for next loop temp_Im_spectrum =numpy.repeat(temp_Im_spectrum[improved],2,axis=0) new_points = numpy.where(numpy.insert(numpy.zeros(Im_values.shape, dtype=numpy.bool),new_points[improved],True))[0] new_points = numpy.vstack((new_points, new_points+1)).T.flatten() count += 1 #import matplotlib #matplotlib.use('WXAgg') #import pylab #pylab.figure() #pylab.plot(Full_E,plot_Im_values,'ok') #pylab.plot(Full_E,Real_Spectrum,'og') #pylab.plot(midpoints,Im_midpoints,'+b') #pylab.plot(midpoints,Re_midpoints,'+r') #pylab.plot(E_values,Im_values,'b-') #pylab.plot(E_values,Re_values,'r-') #pylab.plot(midpoints,Im_error,'b-') #pylab.plot(midpoints,Re_error,'r-') #pylab.xscale('log') #pylab.show() logger.info("Improved data accuracy by inserting "+str(total_improved_points)+" extra points.") return numpy.vstack((E_values,Re_values,Im_values)).T def kk_calculate_real(NearEdgeDataFile, ChemicalFormula, load_options=None, input_data_type=None, merge_points=None, add_background=False, fix_distortions=False, curve_tolerance=None, curve_recursion=50): """Do all data loading and processing and then calculate the kramers-Kronig transform. Parameters ---------- NearEdgeDataFile : string Path to file containg near-edge data ChemicalFormula : string A standard chemical formula string consisting of element symbols, numbers and parentheses. merge_points : list or tuple pair of `float` values, or None The photon energy values (low, high) at which the near-edge and scattering factor data values are set equal so as to ensure continuity of the merged data set. Returns ------- This function returns a numpy array with columns consisting of the photon energy, the real and the imaginary parts of the scattering factors. """ Stoichiometry = data.ParseChemicalFormula(ChemicalFormula) Relativistic_Correction = calc_relativistic_correction(Stoichiometry) Full_E, Imaginary_Spectrum = data.calculate_asf(Stoichiometry) if NearEdgeDataFile is not None: NearEdge_Data = data.convert_data(data.load_data(NearEdgeDataFile, load_options),FromType=input_data_type,ToType='asf') Full_E, Imaginary_Spectrum = data.merge_spectra(NearEdge_Data, Full_E, Imaginary_Spectrum, merge_points=merge_points, add_background=add_background, fix_distortions=fix_distortions) Real_Spectrum = KK_PP(Full_E, Full_E, Imaginary_Spectrum, Relativistic_Correction) if curve_tolerance is not None: output_data = improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum, Relativistic_Correction, curve_tolerance, curve_recursion) else: Imaginary_Spectrum_Values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) output_data = numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T return output_data if __name__ == '__main__': #use argparse here to get command line arguments #process arguments and pass to a pythonic function #I will abuse this section of code for initial testing #Output = kk_calculate_real('../../data/Xy_norm_bgsub.txt', 'C10SH14', input_data_type='NEXAFS') Output = kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv', 'LaAlO3', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) #Output = kk_calculate_real('../../data/GaAs/As.xmu.csv', 'GaAs', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) Stoichiometry = data.ParseChemicalFormula('LaAlO3') #Stoichiometry = data.ParseChemicalFormula('GaAs') Relativistic_Correction = calc_relativistic_correction(Stoichiometry) ASF_E, ASF_Data = data.calculate_asf(Stoichiometry) ASF_Data3 = data.coeffs_to_linear(ASF_E, ASF_Data, 0.1) ASF_Data2 = data.coeffs_to_ASF(ASF_E, numpy.vstack((ASF_Data,ASF_Data[-1]))) #Test_E = (Output[1:,0]+Output[0:-1,0])*0.5 #Test_E = numpy.linspace(41257.87,41259.87,num=21) #Real_Spectrum2 = KK_PP(Test_E, Output[:,0], Im, Relativistic_Correction) import matplotlib matplotlib.use('WXAgg') import pylab pylab.figure() pylab.plot(Output[:,0],Output[:,1],'xg-',Output[:,0],Output[:,2],'xb-') pylab.plot(ASF_E,ASF_Data2,'+r') #pylab.plot(ASF_E,ASF_Data22,'xr') pylab.plot(ASF_Data3[0],ASF_Data3[1],'r-') #pylab.plot(Test_E,Real_Spectrum2,'*y') pylab.xscale('log') pylab.show()
47.608392
363
0.735238
fc62c8d6aa28b5a801e73fa4abc1d1fe577304dd
1,884
py
Python
random-images/hexxy.py
dominicschaff/random
14a19b976a09c768ab8844b7cda237c17a92c9ae
[ "MIT" ]
null
null
null
random-images/hexxy.py
dominicschaff/random
14a19b976a09c768ab8844b7cda237c17a92c9ae
[ "MIT" ]
null
null
null
random-images/hexxy.py
dominicschaff/random
14a19b976a09c768ab8844b7cda237c17a92c9ae
[ "MIT" ]
null
null
null
from PIL import ImageDraw, Image from math import cos,sin,radians from random import randint import sys a = "a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\"K\\l|L/m M\nn\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w W x X y Y z Z" if len(a) > 128: print("TOO MANY CHARACTERS") sys.exit(1) # for i in a: # print("%s -> %d %d %d %d %d %d %d "%(i, # 1 if a.index(i) & 1 == 1 else 0, # 1 if a.index(i) & 2 == 2 else 0, # 1 if a.index(i) & 4 == 4 else 0, # 1 if a.index(i) & 8 == 8 else 0, # 1 if a.index(i) & 16 == 16 else 0, # 1 if a.index(i) & 32 == 32 else 0, # 1 if a.index(i) & 64 == 64 else 0, # )) # sys.exit(0) WHITE=(255,255,255) PINK=(217,154,197) BLUE=(103,170,249) BLACK=(0,0,0) img = Image.new('RGB', (2560,1600), BLACK) id = ImageDraw.Draw(img) q = """This is a test 0123456789%""" s = 10 cutOff = int(2560/(s*7)) print (cutOff) x,y = 0,0 for c in q: drawHex(id, s*2 + x*s*7, s*3 + y*s*7, s, a.index(c)) x+=1 if x >= cutOff or c == "\n": x,y = 0,y+1 img.show()
28.545455
113
0.537686
fc63326e97a96ff49b392fe1692ec3ec3a6b80ad
16,626
py
Python
src/plugins/maimaidx.py
LonelyFantasy/Chiyuki-Bot
16a91b96661825c2a367a12c30d6a28ad13b95a9
[ "MIT" ]
null
null
null
src/plugins/maimaidx.py
LonelyFantasy/Chiyuki-Bot
16a91b96661825c2a367a12c30d6a28ad13b95a9
[ "MIT" ]
null
null
null
src/plugins/maimaidx.py
LonelyFantasy/Chiyuki-Bot
16a91b96661825c2a367a12c30d6a28ad13b95a9
[ "MIT" ]
null
null
null
import math from collections import defaultdict from typing import List, Dict, Any from nonebot import on_command, on_message, on_notice, on_regex, get_driver from nonebot.log import logger from nonebot.permission import Permission from nonebot.typing import T_State from nonebot.adapters import Event, Bot from nonebot.adapters.cqhttp import Message, MessageSegment, GroupMessageEvent, PrivateMessageEvent from src.libraries.maimaidx_guess import GuessObject from src.libraries.tool import hash from src.libraries.maimaidx_music import * from src.libraries.image import * from src.libraries.maimai_best_40 import generate import requests import json import random import time import re from urllib import parse driver = get_driver() inner_level = on_command('inner_level ', aliases={' '}) spec_rand = on_regex(r"^(?:dx|sd|)?[]?[0-9]+\+?") mr = on_regex(r".*maimai.*") search_music = on_regex(r"^.+") query_chart = on_regex(r"^([]?)id([0-9]+)") wm_list = ['', '', '', '', '', '', '', '', '', '', ''] jrwm = on_command('', aliases={'mai'}) music_aliases = defaultdict(list) f = open('src/static/aliases.csv', 'r', encoding='utf-8') tmp = f.readlines() f.close() for t in tmp: arr = t.strip().split('\t') for i in range(len(arr)): if arr[i] != "": music_aliases[arr[i].lower()].append(arr[0]) find_song = on_regex(r".+") query_score = on_command('') query_score_text = ''' <+id> <> 337 100 TAP GREAT BREAK 50 TAP GREAT TAP GREAT GREAT/GOOD/MISS TAP 1/2.5/5 HOLD 2/5/10 SLIDE 3/7.5/15 TOUCH 1/2.5/5 BREAK 5/12.5/25(200)''' query_score_mes = Message([{ "type": "image", "data": { "file": f"base64://{str(image_to_base64(text_to_image(query_score_text)), encoding='utf-8')}" } }]) best_40_pic = on_command('b40') disable_guess_music = on_command('', priority=0) guess_dict: Dict[Tuple[str, str], GuessObject] = {} guess_cd_dict: Dict[Tuple[str, str], float] = {} guess_music = on_command('', priority=0) guess_music_solve = on_message(priority=20)
33.318637
216
0.566582