content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
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)
[ 11748, 4738, 198, 6738, 10688, 1330, 19862, 17034, 198, 198, 16345, 796, 657, 198, 1640, 2124, 287, 2837, 7, 8784, 2599, 198, 220, 220, 220, 2160, 15853, 2124, 198, 4798, 7, 16345, 8, 198, 7061, 6, 198, 9521, 7, 8784, 8, 220, 657, ...
2.158371
442
# 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__)
[ 2, 15069, 357, 34, 8, 2864, 11, 22063, 623, 273, 4816, 11, 13851, 13473, 2732, 11, 198, 2, 2059, 286, 9279, 12, 46845, 11, 29360, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, ...
3.741036
251
# 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
[ 2, 15069, 357, 66, 8, 33448, 350, 37382, 47, 37382, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845...
3.585062
241
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
[ 6738, 764, 15042, 1330, 1057, 62, 22766, 62, 1136, 62, 30001, 198, 6738, 764, 15042, 1330, 10385, 62, 1462, 62, 67, 2093, 198, 6738, 764, 15042, 1330, 1057, 62, 22766, 62, 1136, 62, 43420, 198, 6738, 764, 15042, 1330, 1057, 62, 22766,...
3.22439
205
# 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)
[ 2, 3852, 19757, 88, 403, 6502, 11, 471, 13024, 509, 32, 8808, 2488, 18015, 19757, 88, 16260, 13, 4914, 396, 13, 330, 13, 38584, 198, 198, 11748, 28686, 11, 25064, 198, 11748, 33918, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, ...
2.422741
686
#!/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')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 7293, 1133, 44258, 35381, 422, 6579, 35, 1366, 13, 198, 7575, 16654, 11, 24311, 11, 318, 6492, 422, 287, 13, 4426, 67, 287, 262, 976, 8619, 13, 198, 198, 28350, 25, 198, ...
2.047059
1,105
import os f = open(os.path.join(os.path.dirname(__file__), '../input/5/part2.txt'), 'r') if __name__ == '__main__': main()
[ 11748, 28686, 198, 198, 69, 796, 1280, 7, 418, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 828, 705, 40720, 15414, 14, 20, 14, 3911, 17, 13, 14116, 33809, 705, 81, 11537, 628, 628, 198, 361, 11593, ...
2.258621
58
import behave
[ 11748, 17438, 628, 198 ]
4
4
"""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
[ 37811, 51, 3558, 4676, 290, 1080, 5499, 526, 15931, 198, 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 1330, 15290, 198, 198, 6738, 21019, 9078, 13, 2436, 676, 9078, 1330, 41732, 198, 6738, 21019, 9078, 13, 16794, 364, 13, 22602, 13...
3.76
75
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
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 1280, 9132, 5488, 13, 15042, 1330, 4912, 198, 198, 6738, 764, 67, 28995, 62, 36151, 62, 5589, 1330, 26977, 13800, 495, 7293, 198, ...
3.237288
118
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)
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 1822, 29572, 11, 269, 21370, 11, 299, 32152, 11, 640, 11, 28686, 11, 302, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 30...
2.771186
236
# -*- 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
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 29335, 15161, 17944, 29335, 198, 198, 11748, 30351, 952, 198, 11748, 18931, 198, 198, 2, 29335, 34579, 9195, 82, 17944, 29335, 198, 198, 6738, 257, 72, 21857, 13...
3.89726
146
# 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 = ' ')
[ 2, 718, 13, 197, 220, 198, 2, 220, 220, 220, 837, 220, 220, 220, 220, 220, 399, 11, 220, 220, 837, 220, 220, 220, 220, 13538, 198, 2, 220, 220, 13374, 16, 220, 860, 17032, 13, 220, 220, 220, 220, 220, 837, 220, 220, 220, 220, ...
2.031847
314
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
[ 11748, 12972, 9288, 198, 11748, 3146, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 32152, 13, 33407, 1330, 6818, 62, 430, 2696, 198, 6738, 299, 32152, 13, 33407, 1330, 6818, 62, 18747, 62, 40496, 198, 6738, 299, 32152, 13, 33407,...
3.575342
73
# 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
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 2864, 383, 3012, 9552, 15417, 4816, 46665, 290, 383, 12905, 2667, 32388, 3457, 13, 1074, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, ...
2.324895
4,266
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()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 18540, 305, 919, 278, 355, 29034, 198, 11748, 12972, 487, 4246, 198, 6738, 299, 32152, 1330, 31028, 11, 1033, 11, 19862, 17034, 11, 7813, 11, 8615, 11, 11644, 11, 610, 310, 272, 11, 25706, 71...
2.133886
3,137
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)
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 7007, 198, 11748, 25064, 198, 11748, 28686, 198, 198, 19011, 577, 28, 17821, 198, 28311, 25, 198, 220, 220, 220, 20579, 28, 418, 13, 268, 2268, 17816, 29904, 20608, 20520, 198, ...
2.5825
400
# -*- 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)])
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 1640, 1312, 287, 2837, 7, 600, 7, 1831, 62, 15414, 28955, 2599, 198, 220, 220, 220, 2124, 11, 331, 796, 685, 600, 7, 87, 8, 329, 2124, 287, 8246, 62, 15414, 2...
1.990909
110
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)
[ 11748, 11192, 273, 11125, 355, 48700, 198, 198, 3697, 31444, 2751, 62, 51, 16938, 1581, 796, 48700, 13, 9979, 415, 26933, 16, 13, 15, 11, 532, 16, 13, 15, 11, 352, 13, 15, 12962, 628, 198, 76, 735, 62, 7890, 796, 48700, 13, 9979, ...
1.986726
226
from flask import Flask app = Flask(__name__)
[ 6738, 42903, 1330, 46947, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 628 ]
3.357143
14
# Generated by Django 3.1.6 on 2021-02-16 11:37 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 21, 319, 33448, 12, 2999, 12, 1433, 1367, 25, 2718, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
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')
[ 11748, 257, 952, 4023, 201, 198, 11748, 30351, 952, 201, 198, 11748, 640, 201, 198, 11748, 640, 201, 198, 201, 198, 11748, 1822, 29572, 201, 198, 11748, 15095, 201, 198, 11748, 28686, 201, 198, 11748, 4423, 346, 201, 198, 11748, 4738, ...
2.915119
377
from django.test import SimpleTestCase as TestCase from corehq.apps.app_manager.models import _parse_xml import os
[ 6738, 42625, 14208, 13, 9288, 1330, 17427, 14402, 20448, 355, 6208, 20448, 198, 6738, 4755, 71, 80, 13, 18211, 13, 1324, 62, 37153, 13, 27530, 1330, 4808, 29572, 62, 19875, 198, 11748, 28686, 198 ]
3.382353
34
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
[ 11748, 8435, 36873, 364, 13, 3103, 6448, 62, 40842, 17, 355, 4757, 82, 62, 40842, 17, 198, 6738, 23645, 13, 11235, 672, 3046, 1330, 43087, 11, 3275, 11, 14580, 198, 198, 30910, 36584, 32961, 796, 43087, 13, 8979, 24564, 1968, 273, 7, ...
2.705831
9,209
# 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")
[ 2, 5128, 198, 45, 11, 337, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 30832, 796, 30138, 8899, 7, 600, 11, 5128, 22446, 35312, 3419, 15437, 198, 198, 2, 24061, 198, 26059, 796, 685, 25101, 60, 1635, 357, 45, 10, 16, 8,...
1.875817
153
# 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=" ")
[ 2, 29407, 198, 77, 28, 600, 7, 15414, 28955, 198, 18747, 28, 4868, 7, 8899, 7, 600, 11, 15414, 22446, 35312, 3419, 4008, 198, 72, 28, 15, 198, 9127, 28, 21737, 198, 24588, 28, 15, 198, 4514, 1312, 27, 11925, 7, 18747, 2599, 198, ...
1.951965
229
import unittest from app.models import News # News = news.News # if __name__ == '__main__': # unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 598, 13, 27530, 1330, 3000, 198, 2, 3000, 796, 1705, 13, 9980, 628, 198, 2, 611, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 2, 220, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198...
2.636364
44
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]
[ 11748, 1822, 29572, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 3419, 198, 48610, 13, 2860, 62, 49140, 10786, 456, 23893, 3256, 2099, 28, 2536, 8, 1303, 428, 318, 329, 1332, 12, 1326, 12, 29688, 20144, 198, 48610, 13, 2...
3.146552
116
""" 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()
[ 37811, 198, 1212, 4226, 20658, 290, 25978, 262, 1366, 900, 286, 1492, 654, 329, 262, 2003, 8748, 198, 37811, 198, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 25064, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, ...
2.116576
2,582
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]]]]
[ 6738, 5336, 291, 1330, 39932, 11, 19390, 11, 7154, 51, 4805, 9774, 2591, 11, 2882, 198, 6738, 5336, 291, 13, 27530, 13, 30281, 62, 19199, 1330, 18956, 25060, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 6738, 10104, 1330, 318, 707, ...
3.137931
116
#!/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__ = "mcdonadt@colorado.edu" __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]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 2348, 70, 1506, 12078, 329, 2163, 6436, 5612, 628, 220, 220, 1049, 62, 12381, 2217, 3419, 318, 257, 12788, 565, 320, 4623, 11862, 1912, 319, 25, 220, 220, 220, 220, 198, 220, ...
2.863799
558
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()
[ 11748, 1822, 29572, 198, 11748, 275, 2069, 18, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, 6738, 4371, 5657, 1330, 18387, 10374, 198, 11748, 25064, 198, 198, 37811, 198, 31337, 82, 314, 2390, 42283, 198, 198, 36, 2100, ...
3.264706
102
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')
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 302, 198, 198, 6738, 1332, 10745, 430, 13, 26791, 13, 504, 856, 62, 16737, 1330, 28038, 856, 49493, 198, 198, 11748, 7736, 198, 198, 9288, 10745, 430, 62, 4774, 82, 796, 28038, 856, 49493, ...
2.890411
73
import os import sys from contextlib import contextmanager from invoke import UnexpectedExit
[ 11748, 28686, 198, 11748, 25064, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 198, 6738, 26342, 1330, 471, 42072, 30337, 628, 198 ]
4.363636
22
# -*- 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)
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 6738, 257, 271, 62, 21282, 74, 13, 26791, 1330, 37773, 62, 1462, 62, 8692, 2414, 198, 6738, 257, 271, 62, 21282, 74, 13, 26791, 1330, 36899, 62, 1462, 62, 19204, 62, 7753...
2.551515
495
# Generated by Django 2.2.6 on 2019-10-25 16:24 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 21, 319, 13130, 12, 940, 12, 1495, 1467, 25, 1731, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
from rainbow.cloudformation import Cloudformation from base import DataSourceBase __all__ = ['CfnOutputsDataSource', 'CfnResourcesDataSource', 'CfnParametersDataSource']
[ 6738, 27223, 13, 17721, 1161, 1330, 10130, 1161, 198, 6738, 2779, 1330, 6060, 7416, 14881, 198, 198, 834, 439, 834, 796, 37250, 34, 22184, 26410, 82, 6601, 7416, 3256, 705, 34, 22184, 33236, 6601, 7416, 3256, 705, 34, 22184, 48944, 6601...
3.345455
55
import redis from bundle_config import config from django.core.management.base import NoArgsCommand
[ 11748, 2266, 271, 198, 6738, 18537, 62, 11250, 1330, 4566, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 1400, 42035, 21575, 198 ]
3.884615
26
#!/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)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 15069, 12131, 13863, 2059, 11, 5401, 41514, 418, 2351, 18643, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345...
3.424528
318
"""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__)
[ 37811, 1212, 13877, 14582, 402, 6570, 273, 351, 1395, 8895, 10784, 11244, 526, 15931, 198, 198, 11748, 18931, 198, 198, 6738, 308, 6570, 273, 13, 39305, 1330, 7561, 29495, 11, 4809, 198, 6738, 308, 6570, 273, 13, 7295, 1330, 2223, 11, ...
3.370787
89
import contextlib import os import pathlib import subprocess import sys import tempfile
[ 11748, 4732, 8019, 198, 11748, 28686, 198, 11748, 3108, 8019, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 11748, 20218, 7753, 628, 628, 628, 628, 628, 628 ]
3.666667
27
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")
[ 11748, 28686, 198, 198, 41509, 62, 8841, 796, 366, 7890, 1, 198, 1662, 62, 2860, 796, 37250, 43420, 3256, 705, 7890, 3256, 705, 43775, 20520, 198, 1640, 2378, 287, 28686, 13, 4868, 15908, 33529, 198, 220, 220, 220, 611, 2378, 287, 407...
2.416667
120
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, )
[ 6738, 12351, 13, 48991, 13, 9078, 5589, 5329, 1330, 20159, 3876, 201, 198, 6738, 12351, 13, 459, 62, 77, 4147, 1330, 357, 201, 198, 220, 220, 220, 6118, 19667, 11, 201, 198, 220, 220, 220, 5016, 37835, 10186, 19667, 11, 201, 198, 22...
2.121771
271
# 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. \ " })
[ 2, 1114, 2488, 3118, 72, 33, 2398, 198, 2, 12537, 25957, 343, 264, 1638, 1557, 72, 198, 37811, 24704, 8145, 1356, 42636, 198, 13, 21282, 1279, 2435, 287, 4201, 29, 1279, 5239, 29, 198, 37811, 628, 198, 11748, 640, 198, 6738, 2836, 1...
2.816667
180
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'}))
[ 11748, 28686, 628, 198, 26801, 796, 37350, 7, 28243, 62, 3672, 11639, 9288, 13, 6494, 3256, 4732, 34758, 6, 3672, 10354, 705, 2640, 25087, 6, 30072, 198, 4798, 7, 26801, 13, 13287, 28955, 198, 26801, 13, 22866, 28, 6045, 198, 4798, 7,...
2.786517
89
#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))
[ 2, 15522, 873, 198, 198, 64, 796, 366, 31373, 1, 198, 64, 15853, 366, 314, 1101, 257, 3290, 1, 198, 4798, 7, 64, 8, 198, 4798, 7, 11925, 7, 64, 4008, 198, 4798, 7, 64, 58, 16, 25, 12962, 1303, 26410, 25, 304, 18798, 314, 1101,...
2.478125
320
# -*- 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: plussg@yandex.ru :status: Development """ import pytest import allure from tools.api_responses import get_response
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 9288, 62, 486, 62, 13635, 62, 2435, 62, 1136, 62, 50145, 198, 15116, 8728, 4907, 198, 198, 464, 362, 38, 1797, 7824, 6208, 198, 9787, 640, 651, 24697, 198,...
2.683453
139
"""Returns the string length of categorical values""" from h2oaicore.transformer_utils import CustomTransformer import datatable as dt import numpy as np
[ 37811, 35561, 262, 4731, 4129, 286, 4253, 12409, 3815, 37811, 198, 6738, 289, 17, 12162, 291, 382, 13, 7645, 16354, 62, 26791, 1330, 8562, 8291, 16354, 198, 11748, 4818, 21156, 355, 288, 83, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.875
40
""" Subpackage containing EOTasks for geometrical transformations """ from .utilities import ErosionTask, VectorToRaster, RasterToVector from .sampling import PointSamplingTask, PointSampler, PointRasterSampler __version__ = '0.4.2'
[ 37811, 198, 7004, 26495, 7268, 412, 2394, 6791, 329, 4903, 908, 8143, 38226, 198, 37811, 198, 198, 6738, 764, 315, 2410, 1330, 412, 4951, 295, 25714, 11, 20650, 2514, 49, 1603, 11, 371, 1603, 2514, 38469, 198, 6738, 764, 37687, 11347, ...
3.357143
70
"""User Model.""" # Django from django.db import models from django.contrib.auth.models import AbstractUser # Utilities from .utils import ApiModel
[ 37811, 12982, 9104, 526, 15931, 198, 198, 2, 37770, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 220, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 27741, 12982, 198, 198, 2, 41086, 198, 6738, 764, 26791, 1330, ...
3.347826
46
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'])
[ 6738, 17268, 1330, 3706, 83, 29291, 198, 11748, 33918, 198, 6738, 355, 2047, 310, 395, 13, 76, 735, 1330, 8529, 198, 11748, 12972, 9288, 198, 198, 6738, 304, 17733, 67, 13, 15388, 1330, 39400, 10697, 198, 6738, 304, 17733, 67, 13, 364...
3.662651
83
# 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
[ 2, 220, 220, 220, 770, 2393, 318, 636, 286, 10635, 1581, 43, 13, 201, 198, 201, 198, 2, 220, 220, 220, 15069, 357, 66, 8, 33448, 1475, 417, 261, 10501, 290, 17168, 19229, 5800, 290, 14044, 201, 198, 2, 220, 220, 220, 10635, 1581, ...
3.069401
317
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)
[ 6738, 629, 541, 88, 13, 952, 1330, 266, 615, 7753, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 29400, 280, 259, 220, 355, 23241, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 201, 198, 62, 11, 7890, 796, 266, ...
1.881188
707
from textwrap import dedent import pytest from pylox.lox import Lox TEST_SRC = dedent( """\ /* This is a multiline block comment */ """ ) EXPECTED_STDOUTS: list[str] = []
[ 6738, 2420, 37150, 1330, 4648, 298, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 279, 2645, 1140, 13, 75, 1140, 1330, 406, 1140, 198, 198, 51, 6465, 62, 50, 7397, 796, 4648, 298, 7, 198, 220, 220, 220, 37227, 59, 198, 220, 220, 2...
2.27907
86
from mlbase.utils.misc import lazy tensorflow = lazy("tensorflow") numpy = lazy("numpy") gensim = lazy("gensim")
[ 6738, 25962, 8692, 13, 26791, 13, 44374, 1330, 16931, 198, 198, 83, 22854, 11125, 796, 16931, 7203, 83, 22854, 11125, 4943, 198, 77, 32152, 796, 16931, 7203, 77, 32152, 4943, 198, 70, 641, 320, 796, 16931, 7203, 70, 641, 320, 4943, 19...
2.714286
42
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="sank.daniel@gmail.com", 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", ], )
[ 11748, 302, 198, 11748, 900, 37623, 10141, 628, 198, 15675, 11682, 62, 46700, 1677, 10067, 796, 366, 15675, 11682, 13, 9132, 1, 198, 43717, 62, 46700, 1677, 10067, 796, 366, 672, 45852, 13, 9078, 1, 198, 43717, 62, 2200, 796, 374, 1, ...
2.746193
394
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
[ 11748, 28686, 198, 11748, 33918, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2298, 293, 198, 6738, 19720, 1330, 4377, 198, 198, 6738, 12972, 66, 420, 313, 10141, 13, 66, 25634, 1330, 327, 4503, 46, 198, 6738, 28034, 13, 26791, 13, ...
3.212766
47
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])
[ 11748, 25064, 198, 11748, 10088, 198, 198, 17597, 13, 19282, 259, 796, 1280, 10786, 15414, 13, 14116, 11537, 198, 22584, 796, 685, 16, 11, 352, 60, 198, 1640, 1312, 287, 2837, 7, 17, 11, 1315, 2599, 198, 220, 220, 220, 1109, 13, 332...
2.201342
149
from django.contrib.auth.models import User from django.db import models from django.urls import reverse # Create your models here.
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 198, 2, 13610, 534, 4981, 994, 13, 628 ]
3.526316
38
#!/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)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 2, 41906, 17174, 4557, 35625, 198, 2, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, ...
2.406001
3,133
# -*- 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
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 2978, 525, 2163, 25, 10385, 26109, 284, 20511, 5046, 628, 220, 943, 14542, 25, 198, 220, 220, 220, 277, 818, 7399, 25, 383, 8373, 284, 307, 11513, 11, 460,...
2.894737
114
# 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
[ 2, 15069, 13130, 383, 2944, 29188, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, ...
2.139085
6,363
# 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__ = "lozupone@colorado.edu" __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
[ 2, 514, 81, 14, 8800, 14, 24330, 21015, 198, 37811, 24629, 2733, 284, 13946, 1262, 471, 6968, 5673, 198, 198, 929, 70, 2611, 2753, 281, 22155, 286, 5166, 12777, 2374, 27661, 284, 18868, 355, 5128, 13, 198, 198, 52, 6968, 5673, 62, 5...
2.866508
2,105
#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()
[ 2, 5661, 2438, 481, 7716, 262, 13204, 3326, 346, 519, 329, 257, 2060, 5726, 287, 262, 7881, 2393, 198, 2, 83, 1124, 287, 262, 5072, 2393, 4706, 11, 262, 5726, 1271, 11, 262, 1271, 286, 10340, 11, 262, 1271, 286, 9743, 11, 290, 262...
2.968912
193
"""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))
[ 37811, 17614, 329, 14661, 33, 37811, 198, 198, 11748, 33918, 198, 11748, 25064, 198, 198, 11748, 7007, 628, 628, 198, 198, 2, 16281, 286, 779, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1217, 796...
2.722892
83
#!/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
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 16529, 32501, 198, 2, 357, 34, 8, 3517, 12223, 15069, 2177, 12, 1238, 2481, 3395, 4452, 13, 198, 2, 1439, 2489, ...
3.697342
489
#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)
[ 198, 2, 15269, 357, 66, 8, 2177, 10948, 28458, 198, 2, 198, 2, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 1659, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 25423, 12340, ...
2.494655
10,290
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
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 1334, 62, 30604, 1330, 5009, 1039, 11, 3722, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 6738, 1334, 62, 30604, 13, 525, 8481, 1330, 1148, 4...
4.028571
70
# ProgramB.py print('Hello World')
[ 2, 6118, 33, 13, 9078, 198, 4798, 10786, 15496, 2159, 11537, 198 ]
2.916667
12
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 2...
2.82
50
# 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)
[ 198, 2, 7236, 466, 326, 0, 5765, 530, 286, 777, 2427, 986, 198, 198, 271, 62, 10197, 796, 37456, 1312, 1058, 1312, 4064, 362, 6624, 657, 198, 271, 62, 10197, 796, 37456, 1312, 1058, 407, 1312, 1222, 352, 198, 271, 62, 5088, 796, 3...
2.716981
53
#!/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)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 9678, 8439, 30291, 891, 8387, 16984, 198, 2, 198, 2, 2750, 2488, 25120, 62, 305, 11848, 494, 198, 2, 220, 198, 2, 198, 198, 11748, 7007, 198, 11748, 33918, 198, 11748, 2...
2.720287
976
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]))
[ 11748, 24575, 80, 198, 11748, 640, 198, 6738, 28686, 1330, 3108, 198, 6738, 10688, 1330, 4314, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1303, 1332, 1339, 352, 11, 5072, 25, 1391,...
1.942857
700
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()
[ 11748, 14601, 198, 6738, 17268, 1330, 15034, 11, 337, 5912, 11, 45835, 198, 6738, 3146, 1330, 7913, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 8085, 15255, 13, 7295...
3.714286
77
# -*- 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 | +---------+--------+''')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 14402, 262, 5651, 2501, 2977, 5072, 21302, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 6738, 2420, 37150, 1330, 4648, 298...
2.498498
333
#! /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()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 2, 3971, 1940, 379, 479, 2475, 620, 82, 13, 2934, 198, 198, 11748, 302, 198, 6738, 266, 1878, 8019, 1330, 7273, 4487, 11, 9139, 5965, 198, ...
2.408046
174
#!/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.
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 11593, 9800, 834, 796, 705, 834, 5308, 38, 436, 292, 834, 6, 198, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, ...
2.864865
74
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"} ] """
[ 11748, 4866, 198, 6738, 3992, 18, 1330, 5313, 18, 198, 6738, 764, 26791, 1330, 3384, 4487, 355, 4293, 62, 26791, 198, 198, 10943, 5446, 10659, 62, 2885, 7707, 7597, 796, 705, 15, 87, 20, 69, 44550, 17896, 7568, 24, 65, 16, 324, 24, ...
3.451826
6,518
# -*- coding: utf-8 -*- from __future__ import unicode_literals from tipi import tipi as _tipi tipi = lambda s: _tipi(s, lang='fr')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 628, 198, 6738, 8171, 72, 1330, 8171, 72, 355, 4808, 22504, 72, 628, 198, 22504, 72, 796, 37456, 264, 25, 4...
2.464286
56
from django.db import models VEHICLE_CHOICES = ( ('OASISSB', 'OASIS Small Business'), ('OASIS', 'OASIS Unrestricted') ) STATUS_CHOICES = ( ('P', 'In Progress'), ('C', 'Completed'), ('F', 'Cancelled') )
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 6089, 39, 31419, 62, 44899, 34444, 796, 357, 198, 220, 220, 220, 19203, 46, 1921, 16744, 33, 3256, 705, 46, 1921, 1797, 10452, 7320, 33809, 198, 220, 220, 220, 19203, 46, 1921, 1797,...
2.287129
101
""" Contains the QuantumCircuit class boom. """
[ 37811, 198, 4264, 1299, 262, 29082, 31560, 5013, 1398, 198, 2127, 296, 13, 198, 37811, 198 ]
3
16
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)
[ 11748, 25064, 201, 198, 17597, 13, 6978, 13, 33295, 7203, 492, 4943, 1303, 1487, 2858, 284, 766, 4899, 201, 198, 6738, 787, 62, 15511, 305, 9536, 1330, 7837, 88, 4164, 1173, 42731, 1153, 201, 198, 201, 198, 5225, 10223, 796, 374, 1593...
3.071429
196
# 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
[ 2, 770, 318, 262, 30672, 4732, 329, 8263, 5202, 17952, 3951, 198, 6738, 30532, 1330, 1635, 198, 6738, 2684, 20288, 1330, 20650, 17, 11, 1001, 5154, 198, 6738, 30672, 13, 8763, 1330, 1635, 198, 6738, 4866, 1330, 2769, 30073, 198 ]
4.4
40
from .interval_collectors import *
[ 6738, 764, 3849, 2100, 62, 33327, 669, 1330, 1635, 198 ]
3.5
10
# -*- 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("")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 25, 12131, 14, 1157, 14, 23, 2242, 25, 2857, 198, 2, 2488, 13838, 25, 16156, 42, 2238, 198, 2, 2488, 8979, 25, 1332, 13, 9078, 198, 2, 2488, 24564, ...
2.224138
116
""" 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'
[ 37811, 198, 35, 73, 14208, 6460, 329, 2347, 877, 70, 1096, 62, 634, 282, 62, 1891, 437, 1628, 13, 198, 198, 8645, 515, 416, 705, 28241, 14208, 12, 28482, 923, 16302, 6, 1262, 37770, 362, 13, 16, 13, 19, 13, 198, 198, 1890, 517, ...
2.308656
2,553
import asyncio # from aiorpcgrid.client import Client from aiorpcgrid.task import AsyncTask, State
[ 11748, 30351, 952, 198, 198, 2, 422, 257, 1504, 14751, 25928, 13, 16366, 1330, 20985, 198, 6738, 257, 1504, 14751, 25928, 13, 35943, 1330, 1081, 13361, 25714, 11, 1812, 628 ]
3.366667
30
# 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__)
[ 2, 15069, 12131, 11, 4946, 31709, 41935, 46665, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, ...
3.081174
579
# Generated by Django 4.0.2 on 2022-04-01 16:09 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 13, 17, 319, 33160, 12, 3023, 12, 486, 1467, 25, 2931, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import numpy as np import torch import random from .odenet_mnist.layers import MetaNODE
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 4738, 198, 198, 6738, 764, 375, 268, 316, 62, 10295, 396, 13, 75, 6962, 1330, 30277, 45, 16820, 198, 220, 220, 220, 220, 220, 220, 220, 220 ]
2.621622
37
""" 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
[ 37811, 198, 26796, 25, 705, 549, 24252, 979, 72, 6, 319, 15024, 2624, 352, 13, 940, 13, 15, 198, 37811, 198, 2, 13122, 52, 25, 357, 17597, 3672, 11639, 9774, 2624, 3256, 18666, 12453, 11639, 9774, 2624, 3256, 2650, 11639, 16, 13, 94...
2.3625
80
""" @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
[ 37811, 198, 198, 31, 9800, 1058, 15971, 35193, 198, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 11748, 25064, 198, 11748, 555, 715, 395, 198, 6738, 9686, 13, 37390, 13, 48267, 1330, 32214, 14402, 198, 6738, 474, 85, 1330,...
2.270677
399
"""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
[ 37811, 16934, 198, 198, 1212, 8265, 318, 287, 3877, 286, 4955, 477, 262, 3306, 6460, 284, 198, 1169, 1334, 286, 262, 13103, 287, 409, 14792, 13, 198, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 11748, ...
2.094246
4,414
# -*- 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('======================================')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 41972, 319, 26223, 5267, 678, 1160, 25, 4309, 25, 2091, 1853, 198, 198, 31, 9800, 25, 12672, 1983, 28324, 23, 198, 7061, 6, 198, 6738, 299, 2617, 64, 1...
2.845029
342
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
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 764, 27530, 1330, 10781, 198, 6738, 2219, 13, 27530, 1330, 18957, 11, 3460, 620, 902, 198, 6738, 5983, 13, 27530, 1330, 20116, 198, 6738, 13961, 13, 27530, 1330, 14039, 198, 6738, 42625, 14208, ...
4.166667
48
# # 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__)
[ 2, 198, 2, 15069, 2864, 9485, 54, 918, 4816, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, ...
3.621212
198
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")
[ 11748, 28686, 198, 11748, 4738, 198, 198, 15414, 43055, 796, 366, 19571, 14986, 1, 198, 22915, 43055, 796, 366, 19571, 14681, 276, 1, 198, 198, 2, 1676, 65, 1799, 10007, 198, 9126, 4971, 796, 657, 13, 21, 198, 12211, 4971, 796, 657, ...
2.265411
584
#!/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()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 770, 2393, 318, 636, 286, 262, 509, 859, 364, 12, 42, 1313, 328, 43597, 3788, 5301, 13, 198, 2, 198, 2, 1...
2.527566
5,387
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()
[ 6738, 350, 4146, 1330, 7412, 25302, 11, 7412, 198, 6738, 10688, 1330, 8615, 11, 31369, 11, 6335, 1547, 198, 6738, 4738, 1330, 43720, 600, 198, 11748, 25064, 198, 198, 64, 796, 366, 64, 15, 32, 16, 65, 17, 33, 18, 66, 19, 34, 20, ...
1.770903
598
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)
[ 11748, 10688, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 19720, 1330, 7343, 11, 360, 713, 11, 4377, 198, 198, 6738, 4844, 13645, 1330, 319, 62, 21812, 11, 319, 62, 20500, 11, 319, 62, 42138, 11, 319, 62, 260, 25636, 11, 651, 62...
2.471154
832