content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
""" you have a string "ddaaiillyypprrooggrraammeerr". We want to remove all the consecutive duplicates and put them in a separate string, which yields two separate instances of the string "dailyprogramer". use this list for testing: input: "balloons" expected output: "balons" "lo" input: "ddaaiillyypprrooggrraammeerr" expected output: "dailyprogramer" "dailyprogramer" input: "aabbccddeded" expected output: "abcdeded" "abcd" input: "flabby aapples" expected output: "flaby aples" "bap" """ inp = "ddaaiillyypprrooggrraammeerr" org = "" extra = "" hold = "" for a in range(len(inp)): if hold == inp[a]: extra += inp[a] else: org += inp[a] hold = inp[a] print("original:\t", inp) print("first:\t\t", org) print("repeats:\t", extra)
[ 37811, 198, 5832, 423, 257, 4731, 366, 1860, 64, 1872, 6548, 88, 381, 81, 305, 519, 2164, 430, 321, 1326, 8056, 1911, 775, 765, 284, 4781, 477, 262, 12785, 14184, 16856, 290, 1234, 606, 287, 257, 198, 25512, 378, 4731, 11, 543, 1929...
2.534653
303
#!/usr/bin/env python3 import typing import PIL.Image from enum import Enum import re import preppipe.commontypes from preppipe.vnmodel import * # we define an MIR infrastructure for backend... Engine Model (EM) # helper functions def _get_label_name(name : str, type_prefix : str, scope_prefix: str, name_dict : typing.Dict[str, typing.Any], prefix : str = "") -> str: # get the base name base_label = re.sub(r'[^a-zA-Z0-9_]', '', name.replace(" ", "_")) # ensure the name does not start with number or underscore, or is not empty if len(base_label) > 0: frontchar = base_label[0] if frontchar == '_' or frontchar.isnumeric(): base_label = type_prefix + "_" + base_label else: # we have no alphanumetic characters base_label = type_prefix + "_anon" # make sure it is unique # we may have duplicates # try to add scope prefix to resolve this if prefix + base_label in name_dict and len(scope_prefix) > 0: base_label = scope_prefix + "_" + base_label # now add the prefix; we no longer add prefix to base label if len(prefix) > 0: base_label = prefix + base_label # if not working, add a numeric suffix numeric_suffix = 0 result = base_label while result in name_dict: numeric_suffix += 1 result = base_label + '_' + str(numeric_suffix) # done return result def label_branch_targets(model : VNModel, reserved_set : typing.Set[str] = [], include_basicblock : bool = True) -> typing.Dict[VNValue, str]: """Assign all functions (and optionally basic blocks) with a label that is: 1. alphanumeric, non-empty 2. does not start with underscore '_' 3. unique across all functions and basic blocks We may need this labeling even when functions already has no duplicated label so avoid sanitization issue or reserved keywords """ name_dict = {} # label -> element (used internally) elem_dict = {} # element -> label (for returning) # add all reserved keywords to name_dict for reserved in reserved_set: assert isinstance(reserved, str) name_dict[reserved] = None # actual work for func in model.get_function_list(): func_label = _get_label_name(func.get_name(), "control_label", "", name_dict) name_dict[func_label] = func elem_dict[func] = func_label if include_basicblock: for bb in func.get_basicblock_list(): bbname = bb.get_name() if len(bbname) == 0 and bb is func.get_entry_block(): bbname = "entry" bb_label = _get_label_name(bbname, "control_label", func_label, name_dict) name_dict[bb_label] = bb elem_dict[bb] = bb_label return elem_dict def label_basicblocks(func : VNFunction, reserved_set : typing.Set[str] = []) -> typing.Dict[VNBasicBlock, str]: """Assign labels to basic blocks with the same criteria as label_branch_targets: 1. alphanumeric, non-empty 2. does not start with underscore '_' 3. unique """ name_dict = {} # label -> element (used internally) elem_dict = {} # element -> label (for returning) # add all reserved keywords to name_dict for reserved in reserved_set: assert isinstance(reserved, str) name_dict[reserved]= None for bb in func.get_basicblock_list(): bbname = bb.get_name() if len(bbname) == 0 and bb is func.get_entry_block(): bbname = "entry" bb_label = _get_label_name(bbname, "label", "", name_dict, ".") name_dict[bb_label] = bb elem_dict[bb] = bb_label return elem_dict def label_sayer_identity(model : VNModel, reserved_set : typing.Set[str] = []) -> typing.Dict[str, str]: """make sure all characters and sayers have (alphanumeric) labels""" name_dict = {} elem_dict = {} for reserved in reserved_set: assert isinstance(reserved, str) name_dict[reserved] = None for character in model.get_character_list(): name = _get_label_name(character.get_name(), "character", "", name_dict) name_dict[name] = character elem_dict[character] = name for sayer in model.get_sayer_list(): character = sayer.get_identity() character_label = elem_dict[character] name = _get_label_name(character_label + sayer.get_name(), "sayer", "", name_dict) name_dict[name] = sayer elem_dict[sayer] = name return elem_dict
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 201, 198, 201, 198, 11748, 19720, 201, 198, 11748, 350, 4146, 13, 5159, 201, 198, 6738, 33829, 1330, 2039, 388, 201, 198, 11748, 302, 201, 198, 201, 198, 11748, 662, 381, 3757, 13, 78...
2.603071
1,693
from openprocurement.tender.limited.models import Tender
[ 6738, 1280, 36942, 495, 434, 13, 83, 2194, 13, 10698, 13, 27530, 1330, 309, 2194, 628 ]
3.625
16
from pprint import pprint import requests import base64 import json import argparse import sys p = argparse.ArgumentParser(description="New") p.add_argument('-f','--folder-name', required=True, help='Folder name of the images/metadata files') p.add_argument('-s','--start', required=False, help='Start ID to upload') p.add_argument('-e','--end', required=False, help='End number for IDs to upload') p.add_argument('--ids', nargs="+", required=False, help='List of local IDs to upload') if len(sys.argv)==1: p.print_help(sys.stderr) sys.exit(1) args = p.parse_args() # Some variables you will need api_key = "api_key_from_nftmakerpro" nft_project_id = "12345" upload_url = f'https://api.nft-maker.io/UploadNft/{api_key}/{nft_project_id}' prefixName="WoodCastleProject" prefixDispalyName="Wood Castle: Wood Lords S1 " # Leave a space at the end as we will add the #number of token at the end. projectDescription="Wood Castle Studios Presents Woods Lords: Season One" # Lord details folder_name = args.folder_name ids_list = args.ids # See example Metadata file to use for adding metadata main()
[ 6738, 279, 4798, 1330, 279, 4798, 198, 11748, 7007, 198, 11748, 2779, 2414, 198, 11748, 33918, 198, 11748, 1822, 29572, 198, 11748, 25064, 628, 198, 79, 796, 1822, 29572, 13, 28100, 1713, 46677, 7, 11213, 2625, 3791, 4943, 198, 79, 13, ...
3.029891
368
import logging from queue import Queue from redis_queue.queue import RedisQueue from runner.base import BaseRunner logger = logging.getLogger(__name__) if __name__ == '__main__': # python -m event.runner from handler import * r = TestRedisRunner('test_runner', [], [], [HeartBeatHandler(), TimeFramePublisher(timezone=0)]) r.run()
[ 11748, 18931, 198, 6738, 16834, 1330, 4670, 518, 198, 198, 6738, 2266, 271, 62, 36560, 13, 36560, 1330, 2297, 271, 34991, 198, 6738, 17490, 13, 8692, 1330, 7308, 49493, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, ...
2.638889
144
# -*- coding: utf-8 -*- from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecuritySignValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityAverageValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityXAverageValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityMACDValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityExpValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityLogValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecuritySqrtValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityPowValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityAbsValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityAcosValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityAcoshValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityAsinValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityAsinhValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityNormInvValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityCeilValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityFloorValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityRoundValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityDiffValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityRoundValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecuritySigmoidValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityTanhValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecuritySimpleReturnValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityLogReturnValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityMaximumValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityMinimumValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingAverage from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingDecay from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingMax from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingArgMax from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingMin from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingArgMin from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingRank from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingQuantile from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingAllTrue from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingAnyTrue from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingSum from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingVariance from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingStandardDeviation from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingCountedPositive from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingPositiveAverage from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingCountedNegative from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingNegativeAverage from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingPositiveDifferenceAverage from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingNegativeDifferenceAverage from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingRSI from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingLogReturn from ultron.sentry.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingCorrelation __all__ = ['SecuritySignValueHolder', 'SecurityAverageValueHolder', 'SecurityXAverageValueHolder', 'SecurityMACDValueHolder', 'SecurityExpValueHolder', 'SecurityLogValueHolder', 'SecuritySqrtValueHolder', 'SecurityPowValueHolder', 'SecurityAbsValueHolder', 'SecurityAcosValueHolder', 'SecurityAcoshValueHolder', 'SecurityAsinValueHolder', 'SecurityAsinhValueHolder', 'SecurityNormInvValueHolder', 'SecurityCeilValueHolder', 'SecurityFloorValueHolder', 'SecurityRoundValueHolder', 'SecurityDiffValueHolder', 'SecurityTanhValueHolder', 'SecuritySigmoidValueHolder', 'SecuritySimpleReturnValueHolder', 'SecurityLogReturnValueHolder', 'SecurityMaximumValueHolder', 'SecurityMinimumValueHolder', 'SecurityMovingAverage', 'SecurityMovingDecay', 'SecurityMovingMax', 'SecurityMovingArgMax', 'SecurityMovingMin', 'SecurityMovingArgMin', 'SecurityMovingRank', 'SecurityMovingQuantile', 'SecurityMovingAllTrue', 'SecurityMovingAnyTrue', 'SecurityMovingSum', 'SecurityMovingVariance', 'SecurityMovingStandardDeviation', 'SecurityMovingCountedPositive', 'SecurityMovingPositiveAverage', 'SecurityMovingCountedNegative', 'SecurityMovingNegativeAverage', 'SecurityMovingPositiveDifferenceAverage', 'SecurityMovingNegativeDifferenceAverage', 'SecurityMovingRSI', 'SecurityMovingLogReturn', 'SecurityMovingCorrelation']
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 3789, 1313, 13, 82, 13000, 13, 32750, 13, 45638, 32750, 13, 9012, 1203, 45638, 2025, 26266, 364, 1330, 4765, 11712, 11395, 39, 19892, 198, 6738, 3789, 1313, 1...
3.356401
2,023
# from app.common.utils import * from sqlalchemy import desc from settings import Config from app.models import * from app.extensions import db from app.models.base import _BaseModel from app.common.message import DBError # # ------------------------------ # ------------------------------ # ------------------------------ from sqlalchemy.exc import IntegrityError
[ 2, 422, 598, 13, 11321, 13, 26791, 1330, 1635, 198, 6738, 44161, 282, 26599, 1330, 1715, 198, 6738, 6460, 1330, 17056, 198, 6738, 598, 13, 27530, 1330, 1635, 198, 6738, 598, 13, 2302, 5736, 1330, 20613, 198, 6738, 598, 13, 27530, 13, ...
4.010101
99
from unittest import TestCase import mock from cloudshell.cp.azure.domain.services.vm_credentials_service import VMCredentialsService from cloudshell.cp.azure.models.vm_credentials import VMCredentials def test_prepare_windows_credentials_without_user_and_password(self): """Check that method will return default username and generate password if credentials weren't provided""" generated_pass = mock.MagicMock() self.vm_credentials._generate_password = mock.MagicMock(return_value=generated_pass) username, password = self.vm_credentials._prepare_windows_credentials("", "") self.assertEqual(username, self.vm_credentials.DEFAULT_WINDOWS_USERNAME) self.assertEqual(password, generated_pass) def test_prepare_linux_credentials(self): """Check that method will return same credentials if username and password were provided""" username, password, ssh_key = self.vm_credentials._prepare_linux_credentials( username=self.test_username, password=self.test_password, storage_service=self.test_storage_service, key_pair_service=self.test_key_pair_service, storage_client=self.test_storage_client, group_name=self.test_group_name, storage_name=self.test_storage_name) self.assertEqual(username, self.test_username) self.assertEqual(password, self.test_password) self.assertIsNone(ssh_key) def test_prepare_linux_credentials_without_user_and_password(self): """Check that method will return default username and ssh_key if credentials weren't provided""" returned_ssh_key = mock.MagicMock() self.vm_credentials._get_ssh_key = mock.MagicMock(return_value=returned_ssh_key) username, password, ssh_key = self.vm_credentials._prepare_linux_credentials( username="", password="", storage_service=self.test_storage_service, key_pair_service=self.test_key_pair_service, storage_client=self.test_storage_client, group_name=self.test_group_name, storage_name=self.test_storage_name) self.assertEqual(username, self.vm_credentials.DEFAULT_LINUX_USERNAME) self.assertEqual(password, "") self.assertEqual(ssh_key, returned_ssh_key)
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 11748, 15290, 198, 198, 6738, 6279, 29149, 13, 13155, 13, 1031, 495, 13, 27830, 13, 30416, 13, 14761, 62, 66, 445, 14817, 62, 15271, 1330, 569, 9655, 445, 14817, 16177, 198, 6738, 6279...
2.453061
980
from sys import platform import pygame from handler.handler import Handler
[ 6738, 25064, 1330, 3859, 198, 198, 11748, 12972, 6057, 198, 198, 6738, 21360, 13, 30281, 1330, 32412, 628 ]
4.333333
18
import requests import requests.exceptions import datetime import ujson as json import logging
[ 11748, 7007, 198, 11748, 7007, 13, 1069, 11755, 198, 198, 11748, 4818, 8079, 198, 11748, 334, 17752, 355, 33918, 198, 198, 11748, 18931, 628 ]
4.083333
24
from flask import ( abort, current_app, flash, redirect, render_template, request, session, url_for, ) from flask_login import current_user, login_required from notifications_python_client.errors import HTTPError from notifications_utils.field import Field from notifications_utils.formatters import formatted_list from app import ( billing_api_client, current_service, email_branding_client, inbound_number_client, organisations_client, service_api_client, user_api_client, zendesk_client, ) from app.main import main from app.main.forms import ( BrandingOptionsEmail, ConfirmPasswordForm, FreeSMSAllowance, InternationalSMSForm, LetterBranding, LinkOrganisationsForm, OrganisationTypeForm, RenameServiceForm, RequestToGoLiveForm, ServiceBasicViewForm, ServiceContactLinkForm, ServiceEditInboundNumberForm, ServiceInboundNumberForm, ServiceLetterContactBlockForm, ServiceReplyToEmailForm, ServiceSetBranding, ServiceSmsSenderForm, ServiceSwitchLettersForm, SMSPrefixForm, branding_options_dict, ) from app.utils import ( AgreementInfo, email_safe, get_cdn_domain, user_has_permissions, user_is_platform_admin, ) def switch_service_permissions(service_id, permission, sms_sender=None): force_service_permission( service_id, permission, on=permission not in current_service['permissions'], sms_sender=sms_sender ) def force_service_permission(service_id, permission, on=False, sms_sender=None): permissions, permission = set(current_service['permissions']), {permission} update_service_permissions( service_id, permissions | permission if on else permissions - permission, sms_sender=sms_sender ) def update_service_permissions(service_id, permissions, sms_sender=None): current_service['permissions'] = list(permissions) data = {'permissions': current_service['permissions']} if sms_sender: data['sms_sender'] = sms_sender service_api_client.update_service_with_properties(service_id, data) def get_branding_as_value_and_label(email_branding): return [ (branding['id'], branding['name']) for branding in email_branding ]
[ 6738, 42903, 1330, 357, 198, 220, 220, 220, 15614, 11, 198, 220, 220, 220, 1459, 62, 1324, 11, 198, 220, 220, 220, 7644, 11, 198, 220, 220, 220, 18941, 11, 198, 220, 220, 220, 8543, 62, 28243, 11, 198, 220, 220, 220, 2581, 11, 1...
2.680226
885
#!/usr/bin/env python2 """ spelling.py Filter the output of 'lynx -dump' into a list of words to spell check. """ from __future__ import print_function from collections import Counter import optparse import re import sys def Options(): """Returns an option parser instance.""" p = optparse.OptionParser() p.add_option( '--known-words', dest='known_words', help='List of words like /usr/share/dict/words') p.add_option( '--more-than-bash', dest='more_than_bash', type=int, default=0, help='Expected number of cases where OSH starts more processes than bash') return p def main(argv): o = Options() opts, argv = o.parse_args(argv[1:]) action = argv[0] if action == 'word-split': contents = sys.stdin.read() for w in SplitWords(contents): print(w) elif action == 'check': word_files = argv[1:] d = Counter() for path in word_files: with open(path) as f: for word in WordList(f): d[word] += 1 print('') print('Most common words') print('') for word, count in d.most_common()[:20]: print('%10d %s' % (count, word)) print('') print('Least common words') print('') for word, count in d.most_common()[-20:]: print('%10d %s' % (count, word)) log('%d word files', len(word_files)) log('%d unique words', len(d)) known_words = {} with open(opts.known_words) as f: for w in WordList(f): known_words[w] = True print('') print('Potential Misspellings') print('') for path in word_files: print() print('\t%s' % path) print() with open(path) as f: unknown = {} for w in WordList(f): #if d.get(word) == 1: # print(word) if w not in known_words: unknown[w] = True if unknown: for u in sorted(unknown): # only occurs once if d.get(u) == 1: print(u) log('\t%d unknown words in %s', len(unknown), path) # Checking algorithms: # # - Does it appear in the dictionary? Problem: most computer terms # - Does it appear only once or twice in the whole corpus? # - Is the edit distance very close to a dictinoary word? # - e.g. subsitutions is a typo else: raise RuntimeError('Invalid action %r' % action) if __name__ == '__main__': try: main(sys.argv) except RuntimeError as e: print('FATAL: %s' % e, file=sys.stderr) sys.exit(1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 37811, 198, 4125, 2680, 13, 9078, 198, 198, 22417, 262, 5072, 286, 705, 6213, 87, 532, 39455, 6, 656, 257, 1351, 286, 2456, 284, 4822, 2198, 13, 198, 37811, 198, 6738, 11593, 374...
2.342032
1,073
#!/usr/bin/env python3 # Based on: https://github.com/facebookresearch/DeepSDF using MIT LICENSE (https://github.com/facebookresearch/DeepSDF/blob/master/LICENSE) # Copyright 2021-present Philipp Friedrich, Josef Kamysek. All Rights Reserved. import functools import json import logging import math import os import signal import sys import time import warnings import deep_ls import deep_ls.workspace as ws import torch import torch.multiprocessing as mp import torch.utils.data as data_utils from scipy.spatial import cKDTree import numpy as np if not sys.warnoptions: warnings.simplefilter("ignore") def get_learning_rate_schedules(specs): schedule_specs = specs["LearningRateSchedule"] schedules = [] for schedule_specs in schedule_specs: if schedule_specs["Type"] == "Step": schedules.append( StepLearningRateSchedule( schedule_specs["Initial"], schedule_specs["Interval"], schedule_specs["Factor"], ) ) elif schedule_specs["Type"] == "Warmup": schedules.append( WarmupLearningRateSchedule( schedule_specs["Initial"], schedule_specs["Final"], schedule_specs["Length"], ) ) elif schedule_specs["Type"] == "Constant": schedules.append(ConstantLearningRateSchedule(schedule_specs["Value"])) else: raise Exception( 'no known learning rate schedule of type "{}"'.format( schedule_specs["Type"] ) ) return schedules def save_model(experiment_directory, filename, decoder, epoch): model_params_dir = ws.get_model_params_dir(experiment_directory, True) torch.save( {"epoch": epoch, "model_state_dict": decoder.state_dict()}, os.path.join(model_params_dir, filename), ) def save_optimizer(experiment_directory, filename, optimizer, epoch): optimizer_params_dir = ws.get_optimizer_params_dir(experiment_directory, True) torch.save( {"epoch": epoch, "optimizer_state_dict": optimizer.state_dict()}, os.path.join(optimizer_params_dir, filename), ) def load_optimizer(experiment_directory, filename, optimizer): full_filename = os.path.join( ws.get_optimizer_params_dir(experiment_directory), filename ) if not os.path.isfile(full_filename): raise Exception( 'optimizer state dict "{}" does not exist'.format(full_filename) ) data = torch.load(full_filename) optimizer.load_state_dict(data["optimizer_state_dict"]) return data["epoch"] def save_latent_vectors(experiment_directory, filename, latent_vec, epoch): latent_codes_dir = ws.get_latent_codes_dir(experiment_directory, True) all_latents = latent_vec.state_dict() torch.save( {"epoch": epoch, "latent_codes": all_latents}, os.path.join(latent_codes_dir, filename), ) # TODO: duplicated in workspace if __name__ == "__main__": import argparse arg_parser = argparse.ArgumentParser(description="Train a DeepLS autodecoder") arg_parser.add_argument( "--experiment", "-e", dest="experiment_directory", required=True, help="The experiment directory. This directory should include " + "experiment specifications in 'specs.json', and logging will be " + "done in this directory as well.", ) arg_parser.add_argument( "--continue", "-c", dest="continue_from", help="A snapshot to continue from. This can be 'latest' to continue" + "from the latest running snapshot, or an integer corresponding to " + "an epochal snapshot.", ) arg_parser.add_argument( "--batch_split", dest="batch_split", default=1, help="This splits the batch into separate subbatches which are " + "processed separately, with gradients accumulated across all " + "subbatches. This allows for training with large effective batch " + "sizes in memory constrained environments.", ) deep_ls.add_common_args(arg_parser) args = arg_parser.parse_args() deep_ls.configure_logging(args) main_function(args.experiment_directory, args.continue_from, int(args.batch_split))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 13403, 319, 25, 3740, 1378, 12567, 13, 785, 14, 19024, 34033, 14, 29744, 50, 8068, 1262, 17168, 38559, 24290, 357, 5450, 1378, 12567, 13, 785, 14, 19024, 34033, 14, 29744, 50, ...
2.427874
1,844
from distutils.core import setup setup( name = 'python-ethereumrpc', packages = ['python-ethereumrpc'], version = '0.1', description = 'A python interface for ethereum JSON-RPC service.', author = 'Nicolas Sandller', author_email = 'nicosandller@gmail.com', url = 'https://github.com/nicosandller/python-ethereumrpc', download_url = 'https://github.com/nicosandller/python-ethereumrpc/tarball/0.1', keywords = ['ethereum', 'rpc', 'api', 'JSON', 'JSON-RPC'], classifiers = [], )
[ 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 40406, 7, 198, 220, 1438, 796, 705, 29412, 12, 316, 1456, 388, 81, 14751, 3256, 198, 220, 10392, 796, 37250, 29412, 12, 316, 1456, 388, 81, 14751, 6, 4357, 198, 220, 2196, 796, 705, 15, ...
2.721311
183
# /robotafm/motor/interface.py # Main web interface, contains basic # information display # imports: import xml.dom.minidom from flask import Flask, render_template # constants: LANG = "./lang/rus.xml" # XML: load text strings from language file dom = xml.dom.minidom.parse(LANG) main_title = dom.getElementsByTagName("main_title")[0].childNodes[0].nodeValue language = dom.getElementsByTagName("language")[0].childNodes[0].nodeValue greeting = dom.getElementsByTagName("greeting")[0].childNodes[0].nodeValue invitation = dom.getElementsByTagName("invitation")[0].childNodes[0].nodeValue main_page_text = dom.getElementsByTagName("main_page_text")[0].childNodes[0].nodeValue # Flask init: app = Flask(__name__) # Main site page:
[ 2, 1220, 305, 13645, 1878, 76, 14, 76, 20965, 14, 39994, 13, 9078, 201, 198, 2, 8774, 3992, 7071, 11, 4909, 4096, 201, 198, 2, 1321, 3359, 201, 198, 201, 198, 2, 17944, 25, 201, 198, 11748, 35555, 13, 3438, 13, 1084, 312, 296, 2...
2.681979
283
from eval_codalab_basic import eval_codalab_basic if __name__ == '__main__': # 1. run first round to prepare full memory eval_codalab_basic(output_suffix='online', skip_first_round_if_memory_is_ready=True) # 2. do offline evaluation when memory is ready eval_codalab_basic(output_suffix='offline')
[ 6738, 5418, 62, 19815, 282, 397, 62, 35487, 1330, 5418, 62, 19815, 282, 397, 62, 35487, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1303, 352, 13, 1057, 717, 2835, 284, 8335, 1336, 4088, 1...
2.80531
113
UP = "U" DOWN = "D" ALLOWED_PATH_I = [UP, DOWN] def update_high_for_step(high: int, step: str) -> int: """Update the current high given a step""" if step == UP: high += 1 elif step == DOWN: high -= 1 return high def count_valley(steps: int, path: str) -> int: """Function which returns the number of valley encountered in a given path""" if len(path) != steps: raise Exception("Steps should match length of path") valleys = 0 high = 0 previous_high = 0 for i in range(steps): previous_high = high high = update_high_for_step(high, path[i]) valleys = update_valley_count(valleys, high, previous_high) return valleys
[ 8577, 796, 366, 52, 1, 201, 198, 41925, 796, 366, 35, 1, 201, 198, 7036, 3913, 1961, 62, 34219, 62, 40, 796, 685, 8577, 11, 30320, 60, 201, 198, 201, 198, 201, 198, 4299, 4296, 62, 8929, 62, 1640, 62, 9662, 7, 8929, 25, 493, 1...
2.382637
311
from gpanel import * coordinates(-3, -3, 11, 11) line(0, 0, 8, 8) line(8, 0, 0, 8)
[ 6738, 308, 35330, 1330, 1635, 198, 198, 37652, 17540, 32590, 18, 11, 532, 18, 11, 1367, 11, 1367, 8, 198, 1370, 7, 15, 11, 657, 11, 807, 11, 807, 8, 198, 1370, 7, 23, 11, 657, 11, 657, 11, 807, 8, 198 ]
2
42
preo = float(input('Preo: ')) print('''Preencha a forma de pagamento com: 1 - p/ VISTA 2 - p/ CARTO 1x 3 - p/ CARTO 2x 4 - p/ CARTO 3x ou mais ''') pagto = str(input('Pagamento: ')).strip() if pagto == '1': preo = preo*0.9 elif pagto == '2': preo = preo*0.95 elif pagto == '4': preo = preo*1.2 print(preo)
[ 3866, 78, 796, 12178, 7, 15414, 10786, 6719, 78, 25, 705, 4008, 198, 4798, 7, 7061, 6, 47, 1361, 11693, 257, 1296, 64, 390, 42208, 3263, 78, 401, 25, 198, 16, 532, 279, 14, 220, 50035, 5603, 198, 17, 532, 279, 14, 327, 7227, 46,...
1.95122
164
import logging import sys from .application import Application from .document import Document, Track, Event if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) app = Application(sys.argv) if '--debug' in sys.argv: # # Load a document. # # We absolutely MUST have the document constructed fully BEFORE # # setting it here. There are side effects to setting it. # # HACK: This is just a hack for now. # # doc = Document() doc = Document('/Users/mikeboers/Desktop/example.MOV') # doc = Document('/Users/mikeboers/Desktop/C00000S00A20091231112932302.avi') doc.add_track(Track( name='A behaviour', key='q', group='top two', # events=[ # Event(10, 15), Event(50, 65), Event(500, 600) # ] )) doc.add_track(Track( name='Nothin here', key='w', group='top two', # events=[] )) doc.add_track(Track( name='Better one', key='e', # events=[ # Event(25, 26), Event(70, 71), Event(700, 701) # ] )) app.doc = doc app.run()
[ 198, 11748, 18931, 198, 11748, 25064, 198, 198, 6738, 764, 31438, 1330, 15678, 198, 6738, 764, 22897, 1330, 16854, 11, 17762, 11, 8558, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 18931, 13, ...
2
632
"""Module with core functionality for a single pipeline stage """ import pathlib import os import sys from textwrap import dedent import shutil import cProfile from abc import abstractmethod from . import errors from .monitor import MemoryMonitor from .config import StageConfig, cast_to_streamable SERIAL = "serial" MPI_PARALLEL = "mpi" DASK_PARALLEL = "dask" IN_PROGRESS_PREFIX = "inprogress_" ############################################# # Parallelism-related methods and properties. ############################################# def is_parallel(self): """ Returns True if the code is being run in parallel. Right now is_parallel() will return the same value as is_mpi(), but that may change in future if we implement other forms of parallelization. """ return self._parallel != SERIAL def is_mpi(self): """ Returns True if the stage is being run under MPI. """ return self._parallel == MPI_PARALLEL def is_dask(self): """ Returns True if the stage is being run in parallel with Dask. """ return self._parallel == DASK_PARALLEL def start_dask(self): """ Prepare dask to run under MPI. After calling this method only a single process, MPI rank 1 will continue to exeute code """ # using the programmatic dask configuration system # does not seem to work. Presumably the loggers have already # been created by the time we modify the config. Doing it with # env vars seems to work. If the user has already set this then # we use that value. Otherwise we only want error logs key = "DASK_LOGGING__DISTRIBUTED" os.environ[key] = os.environ.get(key, "error") try: import dask import dask_mpi import dask.distributed except ImportError: #pragma: no cover print( "ERROR: Using --mpi option on stages that use dask requires " "dask[distributed] and dask_mpi to be installed." ) raise if self.size < 3: #pragma: no cover raise ValueError( "Dask requires at least three processes. One becomes a scheduler " "process, one is a client that runs the code, and more are required " "as worker processes." ) # This requires my fork until/unless they merge the PR, to allow # us to pass in these two arguments. In vanilla dask-mpi sys.exit # is called at the end of the event loop without returning to us. # After this point only a single process, MPI rank 1, # should continue to exeute code. The others enter an event # loop and return with is_client=False, which we return here # to tell the caller that they should not run everything. is_client = dask_mpi.initialize(comm=self.comm, exit=False) if is_client: # Connect this local process to remote workers. self.dask_client = dask.distributed.Client() # I don't yet know how to see this dashboard link at nersc print(f"Started dask. Diagnostics at {self.dask_client.dashboard_link}") return is_client ################################################## # Input and output-related methods and properties. ################################################## def get_input(self, tag): """Return the path of an input file with the given tag""" return self._inputs[tag] def get_output(self, tag, final_name=False): """Return the path of an output file with the given tag If final_name is False then use a temporary name - file will be moved to its final name at the end """ path = self._outputs[tag] # If not the final version, add a tag at the start of the filename if not final_name: p = pathlib.Path(path) p = p.parent / (IN_PROGRESS_PREFIX + p.name) path = str(p) return path def open_input(self, tag, wrapper=False, **kwargs): """ Find and open an input file with the given tag, in read-only mode. For general files this will simply return a standard python file object. For specialized file types like FITS or HDF5 it will return a more specific object - see the types.py file for more info. """ path = self.get_input(tag) input_class = self.get_input_type(tag) obj = input_class(path, "r", **kwargs) if wrapper: #pragma: no cover return obj return obj.file def open_output(self, tag, wrapper=False, final_name=False, **kwargs): #pragma: no cover """ Find and open an output file with the given tag, in write mode. If final_name is True then they will be opened using their final target output name. Otherwise we will prepend "inprogress_" to their file name. This means we know that if the final file exists then it is completed. If wrapper is True this will return an instance of the class of the file as specified in the cls.outputs. Otherwise it will return an open file object (standard python one or something more specialized). Parameters ---------- tag: str Tag as listed in self.outputs wrapper: bool Default=False. Whether to return a wrapped file final_name: bool Default=False. Whether to save to **kwargs: Extra args are passed on to the file's class constructor. """ path = self.get_output(tag, final_name=final_name) output_class = self.get_output_type(tag) # HDF files can be opened for parallel writing # under MPI. This checks if: # - we have been told to open in parallel # - we are actually running under MPI # and adds the flags required if all these are true run_parallel = kwargs.pop("parallel", False) and self.is_mpi() if run_parallel: kwargs["driver"] = "mpio" kwargs["comm"] = self.comm # XXX: This is also not a dependency, but it should be. # Or even better would be to make it a dependency of descformats where it # is actually used. import h5py if not h5py.get_config().mpi: print( dedent( """\ Your h5py installation is not MPI-enabled. Options include: 1) Set nprocess to 1 for all stages 2) Upgrade h5py to use mpi. See instructions here: http://docs.h5py.org/en/latest/build.html#custom-installation Note: If using conda, the most straightforward way is to enable it is conda install -c spectraldns h5py-parallel """ ) ) raise RuntimeError("h5py module is not MPI-enabled.") # Return an opened object representing the file obj = output_class(path, "w", **kwargs) if wrapper: return obj return obj.file def get_input_type(self, tag): """Return the file type class of an input file with the given tag.""" for t, dt in self.inputs_(): if t == tag: return dt raise ValueError(f"Tag {tag} is not a known input") #pragma: no cover def get_output_type(self, tag): """Return the file type class of an output file with the given tag.""" for t, dt in self.outputs_(): if t == tag: return dt raise ValueError(f"Tag {tag} is not a known output") #pragma: no cover ################################################## # Configuration-related methods and properties. ################################################## def read_config(self, args): """ This function looks for the arguments of the pipeline stage using a combination of default values, command line options and separate configuration file. The order for resolving config options is first looking for a default value, then looking for a In case a mandatory argument (argument with no default) is missing, an exception is raised. Note that we recognize arguments with no default as the ones where self.config_options holds a type instead of a value. """ # Try to load configuration file if provided import yaml config_file = self.get_input("config") # This is all the config information in the file, including # things for other stages if config_file is not None: with open(config_file) as _config_file: overall_config = yaml.safe_load(_config_file) else: overall_config = {} # The user can define global options that are inherited by # all the other sections if not already specified there. input_config = overall_config.get("global", {}) # This is just the config info in the file for this stage. # It may be incomplete - there may be things specified on the # command line instead, or just using their default values stage_config = overall_config.get(self.instance_name, {}) input_config.update(stage_config) self._configs.set_config(input_config, args) def get_config_dict(self, ignore=None, reduce_config=False): """Write the current configuration to a dict Parameters ---------- ignore : dict or None Global parameters not to write reduce_config : bool If true, reduce the configuration by parsing out the inputs, outputs and global params Returns ------- out_dict : dict The configuration """ out_dict = {} if reduce_config: ignore_keys = self.input_tags() + self.output_tags() + ['config'] else: ignore_keys = [] ignore = ignore or {} for key, val in self.config.items(): if reduce_config: if key in ignore: if ignore[key] == val: continue if key in ignore_keys: continue out_dict[key] = cast_to_streamable(val) return out_dict def find_inputs(self, pipeline_files): """Find and retrun all the inputs associated to this stage in the FileManager These are returned as a dictionary of tag : path pairs """ ret_dict = {} for tag, _ in self.inputs_(): aliased_tag = self.get_aliased_tag(tag) ret_dict[aliased_tag] = pipeline_files[aliased_tag] return ret_dict def find_outputs(self, outdir): """Find and retrun all the outputs associated to this stage These are returned as a dictionary of tag : path pairs """ ret_dict = {} for tag, ftype in self.outputs_(): aliased_tag = self.get_aliased_tag(tag) ret_dict[aliased_tag] = f"{outdir}/{ftype.make_name(aliased_tag)}" return ret_dict def print_io(self, stream=sys.stdout): """Print out the tags, paths and types for all the inputs and outputs of this stage""" stream.write("Inputs--------\n") for tag, ftype in self.inputs_(): aliased_tag = self.get_aliased_tag(tag) stream.write(f"{tag:20} : {aliased_tag:20} :{str(ftype):20} : {self._inputs[tag]}\n") stream.write("Outputs--------\n") for tag, ftype in self.outputs_(): aliased_tag = self.get_aliased_tag(tag) stream.write(f"{tag:20} : {aliased_tag:20} :{str(ftype):20} : {self._outputs[aliased_tag]}\n") def should_skip(self, run_config): """Return true if we should skip a stage b/c it's outputs already exist and we are in resume mode""" outputs = self.find_outputs(run_config["output_dir"]).values() already_run_stage = all(os.path.exists(output) for output in outputs) return already_run_stage and run_config["resume"] def already_finished(self): """Print a warning that a stage is being skipped""" print(f"Skipping stage {self.instance_name} because its outputs exist already") ################################ # Pipeline-related methods ################################
[ 37811, 26796, 351, 4755, 11244, 329, 257, 2060, 11523, 3800, 37227, 198, 198, 11748, 3108, 8019, 198, 11748, 28686, 198, 11748, 25064, 198, 6738, 2420, 37150, 1330, 4648, 298, 198, 11748, 4423, 346, 198, 11748, 269, 37046, 198, 198, 6738,...
2.446322
5,207
#!/usr/bin/env python import rospy import numpy as np import math from geometry_msgs.msg import PoseStamped, Transform from TrinaPointAndClick.msg import Marker, MarkerArray if __name__ == '__main__': """ Initializes node and names it Parameters: None Returns: None """ print "Initializing Marker_Node..." rospy.init_node('Marker_Node') try: Marker_Node = Marker_Node() except rospy.ROSInterruptException: rospy.logerror("Failed to start server node.") pass
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 686, 2777, 88, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 6738, 22939, 62, 907, 14542, 13, 19662, 1330, 37557, 1273, 13322, 11, 26981, 198, 6738, 833, 1437, 12727...
2.269841
252
from mininet.topo import Topo from mininet.link import TCLink topos = { 'topology': ( lambda: Topology() ) }
[ 6738, 949, 42504, 13, 4852, 78, 1330, 5849, 78, 198, 6738, 949, 42504, 13, 8726, 1330, 309, 5097, 676, 198, 220, 198, 4852, 418, 796, 1391, 705, 4852, 1435, 10354, 357, 37456, 25, 5849, 1435, 3419, 1267, 1782, 198 ]
2.846154
39
# -*- coding: utf-8 -*- """ Created on Thu Apr 12 23:00:28 2018 @author: wangshuai """ import urllib import urllib.request as urllib2 import http.cookiejar as cookielib import io import re import gzip from selenium import webdriver import datetime if __name__ == '__main__': config = Config() ifile = open(config.get("outputPath")+"rough_info.txt","w",encoding='utf-8') getArticle = GetArticle(config, handler = ifile) getArticle.index_detail() ifile.close()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 2758, 1105, 2242, 25, 405, 25, 2078, 2864, 198, 31, 9800, 25, 266, 648, 1477, 84, 1872, 198, 37811, 198, 11748, 2956, 297, 571, 198, 117...
1.75495
404
import tensorflow as tf
[ 11748, 11192, 273, 11125, 355, 48700, 198 ]
3.428571
7
from os import path, listdir import ocgis from flyingpigeon import subset from flyingpigeon import utils from flyingpigeon.ocgis_module import call def get_prediction(gam_model, ncs_indices): # mask=None """ predict the probabillity based on the gam_model and the given climate index datasets :param gam_model: fitted gam (output from sdm.get_gam) :pram nsc_indices: list of netCDF files containing climate indices of one dataset :param mask: 2D array of True/False to exclude areas (e.g ocean) for prediction :return array: 3D array with prediction values """ from netCDF4 import Dataset from os.path import basename from numpy import squeeze, ravel, array, reshape # , zeros, broadcast_arrays, nan from flyingpigeon.utils import get_variable from rpy2.robjects.packages import importr import rpy2.robjects as ro import rpy2.robjects.numpy2ri rpy2.robjects.numpy2ri.activate() mgcv = importr("mgcv") stats = importr("stats") ncs_indices.sort() data = {} for i, nc in enumerate(ncs_indices): var = get_variable(nc) agg = basename(nc).split('_')[-2] ds = Dataset(nc) vals = squeeze(ds.variables[var]) if i == 0: dims = vals.shape # if mask != None: # mask = broadcast_arrays(vals, mask)[1] # vals[mask==False] = nan indice = '%s_%s' % (var, agg) data[str(indice)] = ro.FloatVector(ravel(vals)) dataf = ro.DataFrame(data) predict_gam = mgcv.predict_gam(gam_model, newdata=dataf, type="response", progress="text", newdata_guaranteed=True, na_action=stats.na_pass) prediction = array(predict_gam).reshape(dims) return prediction p = "/home/nils/data/AFR-44/tas/" ncs = [path.join(p, nc) for nc in listdir(p)] ncd = utils.sort_by_filename(ncs) geom = subset.get_geom('CMR') ugid = subset.get_ugid('CMR', geom=geom) # from ocgis import RequestDataset, OcgOperations keys = ncd.keys() print len(keys) ocgis.env.OVERWRITE = True dmap = ocgis.DimensionMap() dmap.set_variable('x', 'lon', dimension='rlon') dmap.set_variable('y', 'lat', dimension='rlat') dmap.set_variable('time', 'time', dimension='time') # # print dmap # rd = ocgis.RequestDataset(ncd[keys[0]][0], crs=ocgis.crs.Spherical(), ) # geos = ocgis.OcgOperations(rd, geom=geom, select_ugid=ugid, output_format='nc', prefix='one_file').execute() # geos for key in ncd.keys(): # rd = ocgis.RequestDataset(ncd[key], crs=ocgis.crs.Spherical(), dimension_map=dmap) # geos = ocgis.OcgOperations(rd, # geom=geom, select_ugid=ugid, # output_format='nc', # prefix=key, # add_auxiliary_files=False).execute() geos = call(ncd[key], geom=geom, select_ugid=ugid, output_format='nc', prefix=key, variable='tas', crs=ocgis.crs.Spherical(), dimension_map=dmap) print geos # # rd = RequestDataset(ncd[keys[0]][0]) # geos = OcgOperations(rd, geom=geom, select_ugid=ugid, output_format='nc').execute() # # ncd[keys[0]] # # rd = RequestDataset(ncd[keys[0]]) # # geos = OcgOperations(rd, geom=geom, select_ugid=ugid, output_format='nc').execute()
[ 6738, 28686, 1330, 3108, 11, 1351, 15908, 198, 11748, 267, 66, 70, 271, 198, 198, 6738, 7348, 79, 10045, 261, 1330, 24637, 198, 6738, 7348, 79, 10045, 261, 1330, 3384, 4487, 198, 6738, 7348, 79, 10045, 261, 13, 420, 70, 271, 62, 214...
2.187377
1,521
# Generated by Django 2.1.2 on 2018-10-18 15:36 from django.db import migrations, models from django.db.models import F
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 17, 319, 2864, 12, 940, 12, 1507, 1315, 25, 2623, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 376, 628, 198 ]
2.860465
43
import pytest
[ 11748, 12972, 9288, 628, 220, 220, 220, 220 ]
2.375
8
from splicemachine.mlflow_support import * from splicemachine.mlflow_support.mlflow_support import _GORILLA_SETTINGS import gorilla import mlflow.onnx gorilla.apply(gorilla.Patch(mlflow.onnx, _log_model.__name__.lstrip('_'), _log_model, settings=_GORILLA_SETTINGS))
[ 6738, 4328, 291, 368, 20480, 13, 76, 1652, 9319, 62, 11284, 1330, 1635, 198, 6738, 4328, 291, 368, 20480, 13, 76, 1652, 9319, 62, 11284, 13, 76, 1652, 9319, 62, 11284, 1330, 4808, 38, 1581, 8267, 32, 62, 28480, 51, 20754, 198, 11748...
2.542857
105
## Shorty ## Copyright 2009 Joshua Roesslein ## See LICENSE ## @url short.to
[ 2235, 10073, 88, 198, 2235, 15069, 3717, 20700, 5564, 408, 33663, 198, 2235, 4091, 38559, 24290, 198, 198, 2235, 2488, 6371, 1790, 13, 1462, 628 ]
3.16
25
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical import numpy as np import gym from gym.spaces import Discrete, Box if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--env_name', '--env', type=str, default='CartPole-v0') parser.add_argument('--render', action='store_true') parser.add_argument('--lr', type=float, default=1e-2) args = parser.parse_args() print('\nUsing simplest formulation of policy gradient.\n') train(env_name=args.env_name, render=args.render, lr=args.lr)
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 13, 17080, 2455, 507, 1330, 327, 2397, 12409, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11550, 198, 673...
2.861751
217
import asynmsg import struct import google.protobuf.message
[ 11748, 355, 2047, 19662, 198, 11748, 2878, 198, 11748, 23645, 13, 11235, 672, 3046, 13, 20500, 628, 628, 628 ]
3.421053
19
import collections from thegame.abilities import Ability Vector = collections.namedtuple('Vector', ('x', 'y')) Vector.__doc__ = ''' A 2D vector. Used to represent a point and velocity in thegame ''' HeroAbility = collections.namedtuple( 'HeroAbility', ['level', 'value'] ) HeroAbilityList = collections.namedtuple( 'HeroAbilityList', [ab.as_camel for ab in Ability] )
[ 11748, 17268, 198, 6738, 262, 6057, 13, 5738, 1330, 20737, 628, 198, 38469, 796, 17268, 13, 13190, 83, 29291, 10786, 38469, 3256, 19203, 87, 3256, 705, 88, 6, 4008, 198, 38469, 13, 834, 15390, 834, 796, 705, 7061, 198, 32, 362, 35, ...
2.962963
135
import os import json # import wget from flask import ( Flask, jsonify, send_from_directory, request, redirect, url_for ) from flask_sqlalchemy import SQLAlchemy import werkzeug werkzeug.cached_property = werkzeug.utils.cached_property from werkzeug.utils import secure_filename from werkzeug.middleware.proxy_fix import ProxyFix from flask_restx import Api, Resource, fields, abort, reqparse from celery import Celery import celery.states as states from . import api_functions from . import topic_model_classifier # global variables CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL') CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND') celery = Celery('tasks', broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND) app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) app.config.from_object("project.config.Config") db = SQLAlchemy(app) api = Api(app, version='1.0', title='UGC API services', description='REST APIs for processing user-generated content') ns = api.namespace('comments_api', description='REST services API for news comments') # input and output definitions topic_model_single_input = api.model('TopicModelSingleInput', { 'text': fields.String(required=True, description='input text for topic') }) topic_model_single_output = api.model('TopicModelSingleOutput', { 'suggested_label': fields.List(fields.String(), required=True, description='suggested label for topics'), 'description': fields.List(fields.String(), required=True, description='description of suggested label'), 'topic_words': fields.List(fields.String(), required=True, description='topic words') }) topic_model_list_input = api.model('TopicModelListInput', { 'texts': fields.List(fields.String, required=True, description='input list of texts for topic') }) topic_model_list_output = api.model('TopicModelListOutput', { 'suggested_label': fields.List(fields.String(), required=True, description='suggested label for topics'), 'description': fields.List(fields.String(), required=True, description='description of suggested label'), 'topic_words': fields.List(fields.String(), required=True, description='topic words') })
[ 11748, 28686, 198, 11748, 33918, 198, 2, 1330, 266, 1136, 198, 198, 6738, 42903, 1330, 357, 198, 220, 220, 220, 46947, 11, 198, 220, 220, 220, 33918, 1958, 11, 198, 220, 220, 220, 3758, 62, 6738, 62, 34945, 11, 198, 220, 220, 220, ...
3.119382
712
# Welcome to the wonderful world of police databases: MALE = "male" FEMALE = "female"
[ 2, 19134, 284, 262, 7932, 995, 286, 1644, 20083, 25, 198, 198, 44, 21358, 796, 366, 22606, 1, 198, 37, 3620, 21358, 796, 366, 24724, 1, 198 ]
3.222222
27
from django.shortcuts import render from django.http import HttpResponse from backups_operator.servers.models import Server # Create your views here.
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 198, 6738, 35872, 62, 46616, 13, 2655, 690, 13, 27530, 1330, 9652, 198, 2, 13610, 534, 5009, 994, 13 ]
3.947368
38
import argparse import sys import subprocess import psutil def insepect_process(pid): """Determine 1. is the process running in the container 2. if it's true, ourput the container id and the user :return: """ assert psutil.pid_exists(pid), "The process doesn't exist" try: result = subprocess.check_output(f'cat /proc/{pid}/cgroup', shell=True) # print(result) except subprocess.CalledProcessError as e: return_code = e.returncode print(f"Inspect Wrong Error Code{return_code}") sys.exit(1) line = result.decode('utf-8').split('\n')[0].strip() is_in_container = 'docker' in line container_id = '' user_name = '' if is_in_container: container_id = line.split('/')[-1][:12] #Only save first 12 char of container id container_info = subprocess.check_output(f'docker ps -a|grep {container_id}', shell=True).decode('utf-8') user_name = container_info.strip().split()[-1] return is_in_container, container_id, user_name if __name__ == '__main__': parser = argparse.ArgumentParser(description="Inspector for docker") parser.add_argument("-p", type=int, help="the pid") args = parser.parse_args() is_in_container, container_id, user_name = insepect_process(args.p) print(f"Is the process running in the container :{is_in_container}") print(f"The container id {container_id}") print(f"The user name {user_name}")
[ 11748, 1822, 29572, 198, 11748, 25064, 198, 11748, 850, 14681, 198, 11748, 26692, 22602, 198, 198, 4299, 287, 325, 806, 62, 14681, 7, 35317, 2599, 198, 220, 220, 220, 37227, 35, 2357, 3810, 198, 220, 220, 220, 352, 13, 318, 262, 1429,...
2.59325
563
ano = int(input('Digite o ano do seu carro: ')) idadecarro = 2022 - ano print('Carro novo' if idadecarro <=3 else 'Carro Velho')
[ 5733, 796, 493, 7, 15414, 10786, 19511, 578, 267, 281, 78, 466, 384, 84, 1097, 305, 25, 705, 4008, 198, 312, 671, 7718, 305, 796, 33160, 532, 281, 78, 198, 4798, 10786, 9914, 305, 645, 13038, 6, 611, 4686, 671, 7718, 305, 19841, 1...
2.509804
51
""" implements a wrapper for loading live data from the serial connection and passing it to plotting """ import serial import time import struct import plotly.express as px try: from . import log_parser except ImportError: import log_parser # TODO: clean up CLI code if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("input_file", nargs="?",default="/dev/ttyACM0") ns = parser.parse_args() for [type, *fields] in log_parser.parse_data(log_parser.parse_raw_entries(LiveLogFile(ns.input_file))): if type != 4: continue # ignore all but IMU data print(*map("{:>8}".format, fields), sep=",")
[ 37811, 198, 320, 1154, 902, 257, 29908, 329, 11046, 2107, 1366, 422, 262, 11389, 4637, 290, 6427, 340, 284, 29353, 198, 37811, 198, 11748, 11389, 198, 11748, 640, 198, 11748, 2878, 198, 11748, 7110, 306, 13, 42712, 355, 279, 87, 198, ...
2.80315
254
import sys import dbops from pathlib import Path if len(sys.argv) < 2: print("Bucephalus Remove File Script") print("Usage: " + sys.argv[0] + " <identifier>") sys.exit() sys.argv.pop(0) ident = sys.argv.pop(0) if dbops.remove_record_by_id(ident) == None: print("*** Error: failed to remove record.")
[ 11748, 25064, 198, 198, 11748, 20613, 2840, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 361, 18896, 7, 17597, 13, 853, 85, 8, 1279, 362, 25, 198, 220, 3601, 7203, 33, 7234, 27451, 385, 17220, 9220, 12327, 4943, 198, 220, 3601, 7203,...
2.586777
121
import os
[ 11748, 28686, 628 ]
3.666667
3
""" """ from PyQt5 import QtWidgets, QtCore from GUI.GUI_windows_source import TranslationLanguage from json import load, dump from functools import partial import copy from scripts.stylesheets import choosen_lang_style, not_chosen_lang_style
[ 37811, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 37811, 198, 198, 6738, 9485, 48, 83, 20, 1330, 33734, 54...
2.657143
105
"""Map widget for Dear PyGui""" __version__ = "0.0.1"
[ 37811, 13912, 26295, 329, 23420, 9485, 8205, 72, 37811, 198, 198, 834, 9641, 834, 796, 366, 15, 13, 15, 13, 16, 1, 198 ]
2.391304
23
from flask import ( Blueprint, request)#, flash, g, redirect, render_template, get_template_attribute, url_for, jsonify # ) # from werkzeug.exceptions import abort import requests # from demosaurus.db import get_db # import pandas as pd # from nltk.metrics import distance # import re # import numpy as np bp = Blueprint('subject_headings', __name__) annif_url = 'https://kbresearch.nl/annif/v1/'
[ 6738, 42903, 1330, 357, 198, 220, 220, 220, 220, 39932, 11, 2581, 8, 2, 11, 7644, 11, 308, 11, 18941, 11, 8543, 62, 28243, 11, 651, 62, 28243, 62, 42348, 11, 19016, 62, 1640, 11, 33918, 1958, 198, 2, 1267, 198, 2, 422, 266, 9587...
2.977941
136
from django.http import HttpResponse from django.http.response import JsonResponse from django.shortcuts import render from rest_framework.serializers import Serializer from admin import settings import requests from rest_framework import viewsets from time import gmtime, strftime from Kusa.models import SteamUser from django.views.decorators.csrf import csrf_exempt from bson import ObjectId import json from smtplib import SMTPException from django.http import BadHeaderError from django.http.response import JsonResponse from django.shortcuts import redirect from admin import settings from admin.settings import FRONTEND_URL from Kusa.authentication import get_token from Kusa.authentication import validate_token from collections import OrderedDict # keep this line for get_user_daily_hours from datetime import datetime from django.core.mail import send_mail from Kusa.data_collection import get_steam_user JWT_SECRET_KEY = settings.JWT_SECRET_KEY conf = settings.CONF def get_user_daily_hours(request): """ will return an array of the user's daily hours Parameters: request Returns: returns a list of json obj -> [{"date" : date1, "hours" : num_hours1},{"date" : date2, "hours" : num_hours2}] """ response = validate_token(request) if "steamid" in response: user = get_steam_user(response["steamid"]) daily_hours = user['daily_hours'] list_of_json = [dict(day) for day in eval(daily_hours)] return JsonResponse(list_of_json, safe=False) else: return response def get_user_achievements(request): """ Returns: returns a list of json obj -> [{id" : 1, "progress" : 0, "date_achieved" : "N/A"},...,{id" : 10, "progress" : 20, "date_achieved" : "03/10/2022"}] """ response = validate_token(request) if "steamid" in response: user = get_steam_user(response["steamid"]) achievements = user['achievements'] list_of_json = [dict(a) for a in eval(achievements)] return JsonResponse(list_of_json , safe=False) else: return response
[ 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 4023, 13, 26209, 1330, 449, 1559, 31077, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 1334, 62, 30604, 13, 46911, 11341, 1330, 23283,...
2.914685
715
import os from redis import StrictRedis
[ 11748, 28686, 201, 198, 6738, 2266, 271, 1330, 520, 2012, 7738, 271, 201, 198, 201, 198, 201, 198 ]
2.555556
18
""" Generative language models. Classes ------- SMILESEncoderDecoder A generative recurrent neural network to encode-decode SMILES strings. SMILESEncoderDecoderFineTuner The fine-tuner of SMILESEncoderDecoder model. """ __all__ = ( 'SMILESEncoderDecoder', 'SMILESEncoderDecoderFineTuner', ) import json import warnings from typing import Optional, Union import mxnet as mx from mxnet import gluon from . import _gluon_common from .base import SMILESEncoderDecoderABC from ..description.common import OneHotEncoder
[ 37811, 198, 8645, 876, 3303, 4981, 13, 198, 198, 9487, 274, 198, 26866, 198, 12310, 4146, 1546, 27195, 12342, 10707, 12342, 198, 220, 220, 220, 317, 1152, 876, 42465, 17019, 3127, 284, 37773, 12, 12501, 1098, 9447, 4146, 1546, 13042, 13...
2.983333
180
from grappa import GrappaExperiment, MPIRunGrappaExperiment tpch_bigdatann = MPIRunGrappaExperiment({ 'trial': range(1, 3 + 1), #'qn': [x for x in range(8, 20 + 1) if x!=7 and x!=9 and x!=8 and x!=10 and x!=11], # exclude 7 that runs forever #'qn': [x for x in range(1, 20 + 1) if x!=7 and x!=10 and x!=11 and x!=20], # exclude 7 that runs forever 'qn': [x for x in range(1, 20 + 1) if x!=7], # exclude 7 that runs forever 'exe': lambda qn: "grappa_tpc_q{0}_sym_gbp.exe".format(qn), 'sf': 10, 'ppn': 16, 'nnode': 16, 'np': lambda ppn, nnode: ppn*nnode, 'query': lambda qn: 'q{0}'.format(qn), 'vtag': 'v99-noalign', 'machine': 'bigdata', 'system': 'radish-sym-gbp-noalign' }, { 'shared_pool_memory_fraction': 0.5 }) tpch_sampa = GrappaExperiment({ 'trial': range(1, 3 + 1), #'qn': [x for x in range(8, 20 + 1) if x!=7 and x!=9 and x!=8 and x!=10 and x!=11], # exclude 7 that runs forever 'qn': [x for x in range(1, 20)], #if x!=7 and x!=10 and x!=11 and x!=20], # exclude 7 that runs forever 'exe': lambda qn: "grappa_tpc_q{0}_sym_gbp.exe".format(qn), 'sf': 10, 'ppn': 12, 'nnode': 16, 'np': lambda ppn, nnode: ppn*nnode, 'query': lambda qn: 'q{0}'.format(qn), 'vtag': 'align-fix', 'machine': 'sampa', 'system': 'radish-sym-gbp' }, { 'shared_pool_memory_fraction': 0.5 }) #tpch_bigdatann.run() tpch_sampa.run()
[ 6738, 21338, 64, 1330, 7037, 44989, 20468, 3681, 11, 4904, 4663, 403, 46971, 44989, 20468, 3681, 198, 198, 34788, 354, 62, 14261, 19608, 1236, 796, 4904, 4663, 403, 46971, 44989, 20468, 3681, 15090, 198, 220, 220, 220, 220, 220, 220, 22...
1.467541
1,602
import numpy as np from scipy.special import softmax np.set_printoptions(precision=6) if __name__ == "__main__": x = np.array([[1, 4.2, 0.6, 1.23, 4.3, 1.2, 2.5]]) print("Input Array: ", x) print("Softmax Array: ", k_softmax(x)) print("Softmax Array: ", softmax(x))
[ 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 20887, 1330, 2705, 9806, 198, 198, 37659, 13, 2617, 62, 4798, 25811, 7, 3866, 16005, 28, 21, 8, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198,...
2.251969
127
import tensorflow as tf from tensorflow.keras.layers import Conv2D, ReLU, SeparableConv2D, Input, SpatialDropout2D, MaxPool2D, Concatenate, Conv2DTranspose, BatchNormalization from tensorflow.keras.regularizers import l1, l2 from models.net import Net from layers.kerasGroupNorm import GroupNormalization
[ 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 75, 6962, 1330, 34872, 17, 35, 11, 797, 41596, 11, 8621, 283, 540, 3103, 85, 17, 35, 11, 23412, 11, 1338, 34961, 26932, 448, 17, 35, 11, 5436, ...
3.080808
99
"""PostDB class definition. PostDB encapsualte interactions (lookup, scan, insert) with the posts table. Typical usage example: from post import Post from post_db import PostDB post_db = PostDB(mode = "dev") post = Post( post_url = "https://www.example.com/", title = "Test", main_image_url = "https://www.example.com/foo.png", description = "Bar") post_db.insert(post) """ import logging import sqlalchemy from util.database import Database from util.post import Post # Max post index to return in scan(). MAX_POSTS_TO_START = 1000 logger = logging.getLogger()
[ 37811, 6307, 11012, 1398, 6770, 13, 628, 220, 2947, 11012, 32652, 723, 660, 12213, 357, 5460, 929, 11, 9367, 11, 7550, 8, 351, 262, 6851, 3084, 13, 628, 220, 48752, 8748, 1672, 25, 628, 220, 422, 1281, 1330, 2947, 198, 220, 422, 128...
2.951456
206
# coding: utf-8 from slackbot.bot import respond_to from slacker import Slacker import slackbot_settings # @respond_to("") # @respond_to("") # def cheer(message): # message.reply("") import MeCab import random import ChatBotScript import SentenceGenerator import datetime import webbrowser import time import sys try: import urllib.request as urllib2 except ImportError: import urllib2 import json import requests from requests.exceptions import Timeout import os # # # def greeting(): # todaydetail = datetime.datetime.today() # if 4 <= todaydetail.hour <= 10: # message.reply(ChatBotScript.greeting[0] + symbol[random.randrange(2)]) # elif 11 <= todaydetail.hour <= 17: # message.reply(ChatBotScript.greeting[1] + symbol[random.randrange(2)]) # else: # message.reply(ChatBotScript.greeting[2]) # #-------------- #---------- #-------------- t_count = 0 f_count = 0 count_talk = 0 # count() symbol = ["", "", ""] main_talk()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 30740, 13645, 13, 13645, 1330, 3031, 62, 1462, 198, 6738, 1017, 10735, 1330, 3454, 10735, 198, 11748, 30740, 13645, 62, 33692, 198, 198, 2, 2488, 5546, 62, 1462, 7203, 4943, 198, 2, 24...
2.691057
369
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # ----------------------------------------------------------------------------- # # P A G E B O T # # Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens # www.pagebot.io # Licensed under MIT conditions # # Supporting DrawBot, www.drawbot.com # Supporting Flat, xxyxyz.org/flat # ----------------------------------------------------------------------------- # # conditions.py # if __name__ == '__main__': import doctest import sys sys.exit(doctest.testmod()[0])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 2, 16529, 32501, 198, 2, 198, 2, 220, 220, 220, 220, 350, 317, 402, 412, 347, 440, 309, 198, 2, 198, 2, 220, 220...
3.038251
183
from PIL import Image import streamlit as st from streamlit_drawable_canvas import st_canvas from Streamlit_Pix2Pix_Generator import Generator import numpy as np import urllib.request from keras.preprocessing.image import load_img from keras.models import load_model import requests # Page intro st.title('Pix2Pix See Your Sketches Brought to Life!') st.text('') st.markdown('Sketch out an object using the canvas below, and let your computer do the rest of the heavy lifting.') st.text('') st.text('') # Links and FAQ section st.sidebar.markdown("### [SRGANs Web Page](https://share.streamlit.io/nb094/easy-gans/main/SRGAN/Streamlit_SRGAN_Main.py)") st.sidebar.markdown("### [NumGen Web Page](https://share.streamlit.io/nb094/easy-gans/main/NumGen/Streamlit_NumGen_Main.py)") st.sidebar.text('') expander = st.sidebar.expander("Pix2Pix Frequently-Asked Questions", expanded=True) expander.write("**What type of machine learning is being used?** \n\n \ The model's architecture is based on solving image-to-image translation with a Conditional Generative Adversarial Network, or cGAN. \n\n &nbsp \n\n \ **How do GANs work?** \n\n \ There are two main components to GAN models: a *discriminator* and a *generator*. \n\n \ The purpose of the discriminator is to classify images presented to it as real or fake. \ The purpose of the generator is to create plausible images to fool the discriminator. \n\n \ After many cycles of training, the skill of the generator improves enough to produce some impressive results! \n\n &nbsp \n\n \ **What is the difference between a GAN and a cGAN?** \n\n \ The basic idea behind cGANs is the same. The primary difference is way the model improves after each cycle, which is based on \ a *loss* calculation. For cGANs, this calculation optimizes the structure or joint configuration of the output. \n\n &nbsp \n\n \ **What are the possible applications of cGANs?** \n\n \ cGANs have been used in self-driving cars, creating maps from satellite images, colorizing black and white photos, and much more. \n\n &nbsp \n\n \ **Where can I read more about cGANs?** \n\n \ For more information on cGANs, check out [this paper.](https://arxiv.org/abs/1611.07004) \n\n &nbsp \n\n \ **Who developed this web page?** \n\n \ This web page and the underlying models were developed by Niklas Bergen with the help of some additional resources. \ Check out the [GitHub repo](https://github.com/NB094/Easy-GANs) for more information.") ##### CODE FOR Pix2Pix ##### # Define page layout left_column, right_column = st.columns([2,1]) # Create selection box and logic for various sketch subjects. subject_selection = left_column.selectbox(label = 'Select what you wish to draw...', options = ['Human', 'Shoe', 'Handbag'], index = 0) if subject_selection == 'Human': stroke_color = '#F44F36' background_color='#000000' else: stroke_color = '#F44F36' background_color='#FFFFFF' # Initialize a random number in the session state. Used to randomize examples shown. if 'random_num' not in st.session_state: st.session_state.random_num = 1 # Change the random example number whenever the radio buttons are changed. # Retrieve a randomly-selected example image urllib.request.urlretrieve(f'https://github.com/NB094/Easy-GANs/raw/main/Pix2Pix/example_images_streamlit/example_{str.lower(subject_selection)}{st.session_state.random_num}.jpg?raw=true', \ 'example_img.jpg') # Create more options menus canvas_mode = st.radio(label = 'Select canvas mode...', options = ('Draw on a blank canvas', 'View an example sketch', 'Try tracing an example sketch'), \ index = 1, help='Example sketches are chosen randomly out of 5 options.', on_change=random_num) drawing_mode = right_column.selectbox(label = "Drawing tool:", options = ("freedraw", "line", "rect", "circle", "polygon", "transform"), index = 0) # Create the drawing canvas if canvas_mode == 'View an example sketch': st.image('example_img.jpg') else: canvas_result = st_canvas( fill_color="rgba(255, 255, 255, 0.0)", # Fill colors from shape objects have full transparency stroke_width=1, stroke_color=stroke_color, background_color=background_color, background_image=Image.open('example_img.jpg') if canvas_mode == 'Try tracing an example sketch' else None, height=256, width=256, drawing_mode=drawing_mode, key="canvas") ##### SKETCH PROCESSING ##### if canvas_mode == 'View an example sketch': drawn_image = load_img('example_img.jpg') else: # Store canvas sketch data into a variable drawn_image = canvas_result.image_data # Insert try/except loop to prevent website from temporarily throwing error when unchecking the box. try: # Convert sketch data into parseable numpy array drawn_image = np.array(Image.fromarray((drawn_image * 255).astype(np.uint8)).resize((256, 256)).convert('RGB')) drawn_image = (drawn_image * 255).astype(np.uint8) # If needed, convert black background to white before passing image to generator. if subject_selection != 'Human': drawn_image[drawn_image == 0] = 255 except: pass # Download load model files. Cache due to large file sizes humans_model, shoes_model, handbags_model = cache_all_models() if subject_selection=='Human': model = humans_model elif subject_selection=='Shoe': model = shoes_model elif subject_selection=='Handbag': model = handbags_model # Insert try/except loop to prevent website from temporarily throwing error when unchecking the box. try: # Pass numpy array into generator, and predict gen = Generator(drawn_image, subject_selection) gen_image = gen.generate_image(model) # Display prediction st.image(gen_image) except: pass
[ 6738, 350, 4146, 1330, 7412, 198, 11748, 4269, 18250, 355, 336, 198, 6738, 4269, 18250, 62, 19334, 540, 62, 5171, 11017, 1330, 336, 62, 5171, 11017, 198, 6738, 13860, 18250, 62, 47, 844, 17, 47, 844, 62, 8645, 1352, 1330, 35986, 198, ...
2.95611
2,005
""" The MIT License (MIT) Copyright (c) 2017 SML 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. """ import os from __main__ import send_cmd_help from cogs.utils import checks from cogs.utils.dataIO import dataIO from discord.ext import commands import discord LOOP_INTERVAL = 60 SERVER_DEFAULTS = { 'autorole': { "role_name": "Guest", "role_id": None, "timer": 86400 } } PATH = os.path.join('data', 'rbs') JSON = os.path.join(PATH, 'settings.json') def check_folder(): """Check folder.""" if not os.path.exists(PATH): os.makedirs(PATH) def check_file(): """Check files.""" if not dataIO.is_valid_json(JSON): dataIO.save_json(JSON, SERVER_DEFAULTS) def setup(bot): """Setup bot.""" check_folder() check_file() n = RBS(bot) bot.add_cog(n)
[ 37811, 198, 464, 17168, 13789, 357, 36393, 8, 198, 198, 15269, 357, 66, 8, 2177, 311, 5805, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 198, 30073, 286, 428, 3788, 290, 3917, 10314, 3...
3.03172
599
""" .. module:: test_iterfunction :synopsis: Unit tests for iterfunction module """ import time import nutsflow.iterfunction as itf from six.moves import range
[ 37811, 198, 492, 8265, 3712, 1332, 62, 2676, 8818, 198, 220, 220, 1058, 28869, 24608, 25, 11801, 5254, 329, 11629, 8818, 8265, 198, 37811, 198, 198, 11748, 640, 198, 11748, 14380, 11125, 13, 2676, 8818, 355, 340, 69, 198, 198, 6738, 2...
3.254545
55
""" Alias convention tests. """ from io import BytesIO from json import loads from uuid import uuid4 from hamcrest import ( all_of, anything, assert_that, contains, equal_to, has_entries, has_entry, has_item, has_key, is_, is_not, ) from marshmallow import Schema, fields from microcosm.api import create_object_graph from microcosm_flask.conventions.base import EndpointDefinition from microcosm_flask.conventions.swagger import configure_swagger from microcosm_flask.conventions.upload import configure_upload from microcosm_flask.namespaces import Namespace from microcosm_flask.operations import Operation from microcosm_flask.swagger.definitions import build_path from microcosm_flask.tests.conventions.fixtures import Person
[ 37811, 198, 40489, 9831, 5254, 13, 198, 198, 37811, 198, 6738, 33245, 1330, 2750, 4879, 9399, 198, 6738, 33918, 1330, 15989, 198, 6738, 334, 27112, 1330, 334, 27112, 19, 198, 198, 6738, 8891, 66, 2118, 1330, 357, 198, 220, 220, 220, 4...
2.950943
265
''' molecool.io package configure access to subpackage functions ''' from .pdb import open_pdb from .xyz import open_xyz, write_xyz
[ 7061, 6, 198, 76, 2305, 24494, 13, 952, 5301, 198, 198, 11250, 495, 1895, 284, 850, 26495, 5499, 198, 7061, 6, 198, 198, 6738, 764, 79, 9945, 1330, 1280, 62, 79, 9945, 198, 6738, 764, 5431, 89, 1330, 1280, 62, 5431, 89, 11, 3551, ...
2.8125
48
#!/usr/bin/env python import sys import json from flatten_dict import flatten as _flatten try: data = json.load(sys.stdin)['object'] except Exception as ex: print("Missing or invalid test data:", ex) sys.exit(1) try: results = json.load(open(sys.argv[1], "r"))['results'] except Exception as ex: print("Missing or invalid test results:", ex) sys.exit(1) data = flatten(data) ok = True for r in [ flatten(i) for i in results ]: for k, v in r.items(): if k not in data: print(f'{k} not found in {data}') ok = False elif v != data[k]: print(f'{k}={data[k]} do not matches {k}={v}') ok = False else: print(f"Match: {r}") sys.exit(0 if ok else 1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 25064, 198, 11748, 33918, 198, 6738, 27172, 268, 62, 11600, 1330, 27172, 268, 355, 4808, 2704, 41769, 198, 198, 28311, 25, 198, 220, 220, 220, 1366, 796, 33918, 13, 2220, 7...
2.17765
349
__all__ = [ 'make_aio_client', 'make_sync_client', 'TAsyncHTTPXClient', 'THTTPXClient', ] from .aio import TAsyncHTTPXClient, make_client as make_aio_client from .sync import THTTPXClient, make_client as make_sync_client from ._version import get_versions __version__ = get_versions()['version'] del get_versions
[ 834, 439, 834, 796, 685, 198, 220, 220, 220, 705, 15883, 62, 64, 952, 62, 16366, 3256, 198, 220, 220, 220, 705, 15883, 62, 27261, 62, 16366, 3256, 198, 220, 220, 220, 705, 51, 42367, 40717, 55, 11792, 3256, 198, 220, 220, 220, 705...
2.713115
122
import sys import random from kalc.model.system.base import ModularKind from typing import Set from kalc.model.system.primitives import Label, StatusNode from kalc.model.system.base import HasLabel from kalc.misc.util import cpuConvertToAbstractProblem, memConvertToAbstractProblem from kalc.misc.const import STATUS_NODE from kalc.model.system.globals import GlobalVar # def __repr__(self): # return 'Nodename : ' + str(self._get_value()) Node.NODE_NULL = Node("NULL") Node.NODE_NULL.isNull = True Node.NODE_NULL.status = STATUS_NODE["Inactive"] Node.NODE_NULL.metadata_name = "Null-Node" Node.NODE_NULL.searchable = False
[ 11748, 25064, 198, 11748, 4738, 198, 6738, 479, 282, 66, 13, 19849, 13, 10057, 13, 8692, 1330, 3401, 934, 35854, 198, 6738, 19720, 1330, 5345, 198, 6738, 479, 282, 66, 13, 19849, 13, 10057, 13, 19795, 20288, 1330, 36052, 11, 12678, 19...
2.869955
223
from Module import AbstractModule def read_fastqc_results(fastqc_path): import os from genomicode import filelib summary_file = os.path.join(fastqc_path, "summary.txt") data_file = os.path.join(fastqc_path, "fastqc_data.txt") filelib.assert_exists_nz(summary_file) filelib.assert_exists_nz(data_file) summary = read_fastqc_summary(summary_file) data = read_fastqc_data(data_file) # Figure out the sample names from the filenames. samples = sorted([x[-1] for x in summary]) assert samples[0] == samples[-1], "%s %s" % (samples[0], samples[-1]) sample = samples[0] if sample.lower().endswith(".gz"): sample = sample[:-3] if sample.lower().endswith(".fq"): sample = sample[:-3] if sample.lower().endswith(".fastq"): sample = sample[:-6] # Make the statistics dictionary. statistics = {} statistics_order = [] for x in summary: status, statistic, x = x assert statistic not in statistics statistics[statistic] = status statistics_order.append(statistic) x = FastQCResults( sample, data["total_sequences"], data["filtered_sequences"], data["sequence_length"], data["percent_gc"], statistics, statistics_order) return x def read_fastqc_summary(filename): # Return list of (<status>, <statistic>, <filename>) import os from genomicode import filelib assert os.path.exists(filename) data = [] for x in filelib.read_cols(filename): assert len(x) == 3 status, statistic, filename = x data.append((status, statistic, filename)) return data def read_fastqc_data(filename): # Return a dictionary of: # total_sequences <int> # filtered_sequences <int> # sequence_length <str> "205", "15-205" # percent_gc <float> from genomicode import parselib data = {} for line in open(filename): # Line seems to end with: # 'Total Sequences\t1056547\t\n' # Not enough just to strip \r\n. #cols = line.rstrip("\r\n").split("\t") cols = line.rstrip().split("\t") if line.startswith("Total Sequences"): assert len(cols) == 2, repr(line) data["total_sequences"] = int(cols[1]) elif line.startswith("Filtered Sequences"): assert len(cols) == 2 data["filtered_sequences"] = int(cols[1]) elif line.startswith("Sequences flagged as poor quality"): # Seems to be alternative to "Filtered Sequences". assert len(cols) == 2 data["filtered_sequences"] = int(cols[1]) elif line.startswith("Sequence length"): assert len(cols) == 2 data["sequence_length"] = cols[1] elif line.startswith("%GC"): assert len(cols) == 2 data["percent_gc"] = float(cols[1])/100 expected = [ "total_sequences", "filtered_sequences", "sequence_length", "percent_gc"] x = [x for x in expected if x not in data] assert not x, "Missing (%s) from fastqc_data: %s" % ( parselib.pretty_list(x), filename) return data
[ 6738, 19937, 1330, 27741, 26796, 628, 198, 198, 4299, 1100, 62, 7217, 80, 66, 62, 43420, 7, 7217, 80, 66, 62, 6978, 2599, 198, 220, 220, 220, 1330, 28686, 198, 220, 220, 220, 422, 45752, 1098, 1330, 2393, 8019, 628, 220, 220, 220, ...
2.316401
1,378
# noinspection PyUnresolvedReferences import propnet.symbols from propnet.models import serialized, python, composite from propnet.core.registry import Registry # This is just to enable importing the model directly from this module for example code generation _update_globals()
[ 2, 645, 1040, 14978, 9485, 3118, 411, 5634, 19927, 198, 11748, 2632, 3262, 13, 1837, 2022, 10220, 198, 6738, 2632, 3262, 13, 27530, 1330, 11389, 1143, 11, 21015, 11, 24185, 198, 6738, 2632, 3262, 13, 7295, 13, 2301, 4592, 1330, 33432, ...
3.985915
71
import csv import re regex = re.compile('[^a-zA-Z]') if __name__ == '__main__': for user in ['katyperry', 'TheEllenShow', 'YouTube', 'realDonaldTrump', 'BillGates', 'nytimes', 'CNN', 'espn', 'NASA', 'aliciakeys']: clean_dataset(user)
[ 201, 198, 11748, 269, 21370, 201, 198, 11748, 302, 201, 198, 201, 198, 260, 25636, 796, 302, 13, 5589, 576, 10786, 58, 61, 64, 12, 89, 32, 12, 57, 60, 11537, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 7...
2.028986
138
#!/usr/bin/python import sys import os from nltk.tokenize import TreebankWordTokenizer as Tokenizer from nltk.tag.perceptron import PerceptronTagger import operator from itertools import chain import nltk from sklearn.metrics import classification_report, confusion_matrix from sklearn.preprocessing import LabelBinarizer import sklearn import pycrfsuite import re import kpcommon as kpc import mdb_common_lib as mdbcl if __name__ == "__main__": try: debug = True if sys.argv[-1] == "debug" else False debug_tests = 3 file_count = 0 dir_corpus = sys.argv[1] dir_output = sys.argv[2] try: training_crfsuite = sys.argv[3] except: training_crfsuite = 'keyphrase.crfsuite' tokenizer = Tokenizer() #pos tagger = PerceptronTagger() extra_features = True qr = mdbcl.QueryResources() crftagger = pycrfsuite.Tagger() crftagger.open(training_crfsuite) #test_sents = [] for (dirname, _, filenames) in os.walk(dir_corpus): for f in filenames: ext = f[-4:] if ext == '.ann': file_count += 1 if debug and file_count > debug_tests: break file_text = os.path.join(dirname, f[:-4] + ".txt") text_file = open(file_text, "r") file_kpe = os.path.join(dir_output, f[:-4] + ".ann") kpe_file = open(file_kpe, "w") raw_text = unicode(text_file.read(), encoding="utf-8") tokens = tokenizer.tokenize(raw_text) tagged_text = [t + ("None",) for t in tagger.tag(tokens)] text_file.close() #test_sents.append(tagged_text) if extra_features: X_test = kpc.sent2features_extra(tagged_text, qr) else: X_test = kpc.sent2features(tagged_text) is_not_kp = "None" tmp_label = is_not_kp new_kp = [] kp_list = [] for kp in zip(crftagger.tag(X_test), [tt[0] for tt in tagged_text]): if debug and False: print >> sys.stderr, " ---- ", kp if kp[0][0:2] == "B-": if new_kp and tmp_label != is_not_kp: kp_list.append((tmp_label, " ".join(new_kp))) tmp_label = kp[0][2:] new_kp = [] new_kp.append(kp[1]) if new_kp: kp_list.append((tmp_label, " ".join(new_kp))) if debug and False: print >> sys.stderr, raw_text kp_index = 0 for kp in kp_list: print kp kp_iter_counter = 0 for m in re.finditer("\W?(" + re.escape(kp[1]) + ")\W", raw_text): kp_iter_counter += 1 kp_index += 1 #print kp_iter_counter, m.groups() start = m.start(1) end = m.end(1) term_string = "T" + str(kp_index) + "\t" + kp[0] + " " + str(start) + " " + str(end) + "\t" + raw_text[start:end] term_string = term_string.encode("utf-8") print >> kpe_file, term_string #tmp_kps_candidates.append((start, end, m.span(1), kp, raw_text[start:end])) if debug and kp_iter_counter == 0: """ There is an error here and in the projections. The match is made by tokens. When some of semi-colon, comma or ( ) there is an extra espace. """ #print >> sys.stderr, raw_text print >> sys.stderr, kp_iter_counter, ": ", kp[1].encode("utf-8") kpe_file.close() except: print >> sys.stderr print >> sys.stderr, "usage: python", sys.argv[0], "<corpus_dir_path> <output_dir_path>" print >> sys.stderr, "example:" print >> sys.stderr, " python", sys.argv[0], "some/path/to/corpus/ some/path/to/output/" print >> sys.stderr, "Error: ", sys.exc_info()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 220, 198, 11748, 25064, 198, 11748, 28686, 198, 6738, 299, 2528, 74, 13, 30001, 1096, 1330, 12200, 17796, 26449, 30642, 7509, 355, 29130, 7509, 198, 6738, 299, 2528, 74, 13, 12985, 13, 525, 984, 1...
1.673804
2,802
#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 import math import torch.nn as nn import torch from .GDN import GDN from .attention import Attention # class Analysis_transform(nn.Module): # def __init__(self, num_filters=128): # super(Analysis_transform, self).__init__() # self.conv_shortcut0 = nn.Conv2d(3, num_filters, 1, stride=2, padding=0) # self.conv0 = nn.Conv2d(3, num_filters, 3, stride=2, padding=1) # self.conv1 = nn.Conv2d(num_filters, num_filters, 3, stride=1, padding=1) # self.leaky_relu1 = nn.LeakyReLU() # self.conv2 = nn.Conv2d(num_filters, num_filters, 3, stride=1, padding=1) # self.leaky_relu2 = nn.LeakyReLU() # self.conv_shortcut = nn.Conv2d(num_filters, num_filters, 1, stride=2, padding=0) # self.conv3 = nn.Conv2d(num_filters, num_filters, 3, stride=2, padding=1) # self.leaky_relu3 = nn.LeakyReLU() # self.conv4 = nn.Conv2d(num_filters, num_filters, 3, stride=1, padding=1) # self.gdn = GDN(num_filters) # # self.leaky_relu4 = nn.LeakyReLU() # self.conv5 = nn.Conv2d(num_filters, num_filters, 3, stride=2, padding=1, bias=False) # self.attention1 = Attention(num_filters) # self.attention2 = Attention(num_filters) # # # def forward(self, x): # for i in range(4): # if i > 0: # x2 = self.conv1(x) # x2 = self.leaky_relu1(x2) # # print("a 3x3 1") # # print("%d"%(i), x2.shape) # x2 = self.conv2(x2) # x2 = self.leaky_relu2(x2) # # print("b 3x3 1") # # print("%d"%(i), x2.shape) # x = x + x2 # # print("resblock result: ", x.shape) # # # if i == 0: # shortcut_tensor = self.conv_shortcut0(x) # x = self.conv0(x) # x = self.leaky_relu3(x) # # print("c 3x3 2") # # print("%d"%(i), x.shape) # x = self.conv4(x) # # x = self.leaky_relu4(x) # x = self.gdn(x) # # print("d 3x3 1") # # print("%d"%(i), x.shape) # x = x + shortcut_tensor # # print("resblock result: ", x.shape) # elif i < 3: # shortcut_tensor = self.conv_shortcut(x) # x = self.conv3(x) # x = self.leaky_relu3(x) # # print("c 3x3 2") # # print("%d"%(i), x.shape) # x = self.conv4(x) # # x = self.leaky_relu4(x) # x = self.gdn(x) # # print("d 3x3 1") # # print("%d"%(i), x.shape) # x = x + shortcut_tensor # # print("resblock result: ", x.shape) # if i == 1: # # Attenation # x = self.attention1(x) # # else: # x = self.conv5(x) # x = self.attention2(x) # # return x if __name__ == "__main__": analysis_transform = Analysis_transform() input_image = torch.zeros([1,3,256,256]) feature = analysis_transform(input_image) print(feature.shape)
[ 2, 48443, 23377, 14, 42026, 14, 37906, 13, 30604, 14, 45150, 14, 18, 13, 20, 14, 8800, 14, 29412, 18, 13, 20, 198, 11748, 10688, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 198, 6738, 764, 38, 35504, 1330, 27044, ...
1.67788
1,962
# -*- encoding: utf-8 -*- from app import db
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 598, 1330, 20613, 628 ]
2.35
20
# -*- coding: utf-8 -*- from src.utils.get_data import load_data from src.utils.get_data import get_datasets from src.utils.get_data import concatenate_datasets from src.utils.dataset_balancer import balance_data import os import pandas as pd import unittest if __name__ == "__main__": unittest.main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 12351, 13, 26791, 13, 1136, 62, 7890, 1330, 3440, 62, 7890, 198, 6738, 12351, 13, 26791, 13, 1136, 62, 7890, 1330, 651, 62, 19608, 292, 1039, 198, 6738, 123...
2.195122
164
# # Yinhao Zhu, May 01, 2017 # """ Sparse GP regression, including variational GP and others. """ from __future__ import absolute_import import torch import numpy as np from torch.utils.data import TensorDataset, DataLoader from torch.distributions.transforms import LowerCholeskyTransform from ..model import Param from ..functions import cholesky, trtrs from ..mean_functions import Zero from ..likelihoods import Gaussian from ..util import TensorType, torch_dtype, as_tensor, kmeans_centers from .gpr import GPR from .base import GPModel def minibatch(loss_func): """ Decorator to use minibatching for a loss function (e.g. SVGP) """ return wrapped
[ 2, 198, 2, 37201, 23778, 33144, 11, 1737, 5534, 11, 2177, 198, 2, 198, 37811, 198, 50, 29572, 14714, 20683, 11, 1390, 5553, 864, 14714, 290, 1854, 13, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 1...
3.172897
214
list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"] print list1, list2, list3 # # print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5] # # append() list = [] ## list.append('Google') ## append() list.append('Python') print list # # del list1 = ['Python', 'iOS', 'Java', 'C++'] print list1 del list1[2] print "After deleting value at index 2 : " print list1 # Python # + * + * list1 = ['Python', 'iOS', 'Java', 'C++'] print len(list1) list2 = ['C', 'Ruby', 'Javastript'] print list1 + list2 print ['Python'] * 4 print 'iOS' in list1 for str in list1: print str # Python list1 = ['Python', 'iOS', 'Java', 'C++'] print list1[2] print list1[-2] print list1[1:] # cmp() # cmp() # cmp(list1, list2) # ,, # , # ,, # ,""("") # , # ,"" # ,, 0 list1, list2 = [123, 'xyz'], [456, 'abc'] print cmp(list1, list2); print cmp(list2, list1); list3 = list2 + [786]; list4 = [123, 'xyz'] print cmp(list2, list3) print cmp(list1, list4) # extend() # extend() # list.extend(seq) # aList = [123, 'xyz', 'zara', 'abc', 123]; bList = [2009, 'manni']; aList.extend(bList) print "Extended List : ", aList
[ 4868, 16, 796, 37250, 746, 23154, 3256, 705, 15245, 4592, 3256, 8309, 11, 4751, 60, 198, 4868, 17, 796, 685, 16, 11, 362, 11, 513, 11, 604, 11, 642, 2361, 198, 4868, 18, 796, 14631, 64, 1600, 366, 65, 1600, 366, 66, 1600, 366, 6...
2.130973
565
import tkinter as tk import tkinter.font as tf from tkinter import ttk from tkinter import messagebox from tkinter.filedialog import askopenfilename, askdirectory import time import threading from functools import wraps from xyw_macro.utils import SingletonType from xyw_macro.contants import SLEEP_TIME class InputBox: """ """ def __init__(self, title='', *args): """ :param title: """ self.title = title self.__args = args self.top = None self.vars = [] self.values = [] def show(self): """ :return: """ return self.top_window() def input_box(*ags, title=''): """ :param title: :return: """ return decorator def confirm_box(message=''): """ :param message: :return: """ return decorator if __name__ == '__main__': # notify = Notification() # threading.Thread(target=auto_hide).start() # notify.start() # thd = threading.Thread(target=sub) # thd.start() # def auto_hide(): # time.sleep(2) # # notify.destroy() # # flag = False # notify.hide() notify = Notification('xyw_macro\n') threading.Thread(target=sub).start() notify.run() # notify.show(0.2) # print('end') # time.sleep(2) # notify.set_text('changed') # notify.show() # notify.start() # print('xue') # print(type(notify.get_window())) # notify.start() # flag = True # while flag: # # notify.get_window().update_idletasks() # notify.get_window().update()
[ 11748, 256, 74, 3849, 355, 256, 74, 198, 11748, 256, 74, 3849, 13, 10331, 355, 48700, 198, 6738, 256, 74, 3849, 1330, 256, 30488, 198, 6738, 256, 74, 3849, 1330, 3275, 3524, 198, 6738, 256, 74, 3849, 13, 69, 3902, 498, 519, 1330, ...
2.206391
751
""" Utilities for testing """ import os import json TESTDATADIR = os.path.join(os.path.dirname(__file__), 'testdata') def get_pass(pass_name : str) -> str: """ Returns pass from test_credentials.json """ creds_path = os.path.join(os.path.dirname(__file__), 'test_credentials.json') with open(creds_path, 'r', encoding='utf-8') as f: for line in f.readlines(): creds = json.loads(line) return creds[pass_name] def read_temp_file(filename: str, delete = True, stdout: str = '', stderr: str = '') -> str: """ Reads temp file and returns contents """ # wait for file to be generated print(f'Waiting for {filename} file...') try: while(not os.path.exists(filename)): pass except KeyboardInterrupt as e: error_msg = f'Stdout: {stdout}\nStderr: {stderr}\n' raise Exception(error_msg) # read file with open(filename, 'r', encoding='utf-8') as f: out_str = ''.join([line for line in f.readlines()]) # delete file if delete and os.path.exists(filename): try: os.remove(filename) except: print(f'{filename} file already removed') return out_str
[ 198, 37811, 41086, 329, 4856, 37227, 198, 198, 11748, 28686, 198, 11748, 33918, 198, 198, 51, 6465, 35, 1404, 2885, 4663, 796, 28686, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 828, 705, 9288, 7890, 1...
2.374016
508
from ballistics.collision.dispatch.config import DefaultCollisionConfiguration from ballistics.collision.dispatch.dispatcher import CollisionDispatcher
[ 6738, 2613, 3969, 13, 26000, 1166, 13, 6381, 17147, 13, 11250, 1330, 15161, 22667, 1166, 38149, 198, 6738, 2613, 3969, 13, 26000, 1166, 13, 6381, 17147, 13, 6381, 8071, 2044, 1330, 7778, 1166, 7279, 8071, 2044, 198 ]
4.108108
37
import os from webdriver_manager.driver import ChromeDriver from webdriver_manager.manager import DriverManager from webdriver_manager import utils
[ 11748, 28686, 198, 6738, 3992, 26230, 62, 37153, 13, 26230, 1330, 13282, 32103, 198, 6738, 3992, 26230, 62, 37153, 13, 37153, 1330, 12434, 13511, 198, 6738, 3992, 26230, 62, 37153, 1330, 3384, 4487, 628 ]
4.382353
34
from data_importers.management.commands import BaseDemocracyCountsCsvImporter
[ 6738, 1366, 62, 320, 1819, 1010, 13, 27604, 13, 9503, 1746, 1330, 7308, 11522, 17818, 12332, 82, 34, 21370, 3546, 26634, 628 ]
3.590909
22
MOVIE1 = { "title": "Guardians of the Galaxy", "year": 2014, "ids": { "trakt": 28, "slug": "guardians-of-the-galaxy-2014", "imdb": "tt2015381", "tmdb": 118340, }, } MOVIE2 = { "title": "Guardians of the Galaxy", "year": 2014, "ids": { "trakt": 28, "slug": "guardians-of-the-galaxy-2014", "imdb": "tt2015381", "tmdb": 118340, }, } MOVIE_PREMIERES = [ {"released": "2014-08-01", "movie": MOVIE1}, {"released": "2014-08-01", "movie": MOVIE2}, ] MOVIES = [MOVIE1, MOVIE2] TRENDING_MOVIES = [{"watchers": 21, "movie": MOVIE1}, {"watchers": 17, "movie": MOVIE2}] PLAYED_MOVIES = [ { "watcher_count": 66667, "play_count": 109736, "collected_count": 27584, "movie": MOVIE1, }, { "watcher_count": 76254, "play_count": 104242, "collected_count": 31877, "movie": MOVIE2, }, ] ANTICIPATED_MOVIES = [ {"list_count": 5362, "movie": MOVIE1}, {"list_count": 4405, "movie": MOVIE2}, ] BOX_OFFICE = [ {"revenue": 48464322, "movie": MOVIE1}, {"revenue": 17728313, "movie": MOVIE2}, ] UPDATED_MOVIES = [{"updated_at": "2014-09-22T21:56:03.000Z", "movie": MOVIE1}] EXTENDED_MOVIE = { "title": "TRON: Legacy", "year": 2010, "ids": { "trakt": 343, "slug": "tron-legacy-2010", "imdb": "tt1104001", "tmdb": 20526, }, "tagline": "The Game Has Changed.", "overview": "Sam Flynn, the tech-savvy and daring son of Kevin Flynn, investigates his father's disappearance and is pulled into The Grid. With the help of a mysterious program named Quorra, Sam quests to stop evil dictator Clu from crossing into the real world.", "released": "2010-12-16", "runtime": 125, "country": "us", "updated_at": "2014-07-23T03:21:46.000Z", "trailer": None, "homepage": "http://disney.go.com/tron/", "rating": 8, "votes": 111, "comment_count": 92, "language": "en", "available_translations": ["en"], "genres": ["action"], "certification": "PG-13", } ALIASES = [ {"title": "Batman 1 - Batman Begins", "country": "ca"}, {"title": "Batman 5 Begins", "country": "br"}, ] RELEASES = [ { "country": "us", "certification": "PG", "release_date": "2010-12-16", "release_type": "theatrical", "note": None, }, { "country": "gb", "certification": "PG", "release_date": "2010-12-17", "release_type": "theatrical", "note": None, }, ] TRANSLATIONS = [ { "title": "Batman Begins", "overview": "...", "tagline": "Das Bse frchtet den Ritter.", "language": "de", } ] RATINGS = { "rating": 7.33778, "votes": 7866, "distribution": { "1": 298, "2": 46, "3": 87, "4": 178, "5": 446, "6": 1167, "7": 1855, "8": 1543, "9": 662, "10": 1583, }, } RELATED_MOVIES = [MOVIE1, MOVIE2] MOVIE_STATS = { "watchers": 39204, "plays": 51033, "collectors": 27379, "comments": 36, "lists": 4561, "votes": 7866, }
[ 44, 8874, 10008, 16, 796, 1391, 198, 220, 220, 220, 366, 7839, 1298, 366, 24502, 1547, 286, 262, 9252, 1600, 198, 220, 220, 220, 366, 1941, 1298, 1946, 11, 198, 220, 220, 220, 366, 2340, 1298, 1391, 198, 220, 220, 220, 220, 220, 2...
2.001868
1,606
# coding=utf-8 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- """ shared: Define shared data types(enums) and constant strings. """ from enum import Enum # Retry constants MAX_ADT_CREATE_RETRIES = 5 ADT_CREATE_RETRY_AFTER = 60 MAX_ADT_DH_CREATE_RETRIES = 20 # Data History strings DT_IDENTITY_ERROR = "Digital Twins instance does not have System-Assigned Identity enabled. Please enable and try again." FINISHED_CHECK_RESOURCE_LOG_MSG = "Finished checking the {0} resource." ERROR_PREFIX = "Unable to" FAIL_GENERIC_MSG = ERROR_PREFIX + " assign {0}. Please assign this role manually." FAIL_RBAC_MSG = ERROR_PREFIX + " assign {0}. Please assign this role manually with the command `az {1}`." ABORT_MSG = "Command was aborted." CONT_INPUT_MSG = "Continue with Data History connection creation anyway?" ADX_ROLE_MSG = "'Database Admin' permission on the Digital Twins instance for the Azure Data Explorer database '{0}'" RBAC_ROLE_MSG = "'{0}' role on the Digital Twins instance for the scope '{1}'" # Messages to be used with ADX_ROLE_MSG or RBAC_ROLE_MSG # Example: "Trying to add the '{0}' role on the Digital Twins instance for the scope '{1}'. TRY_ADD_ROLE_LOG_MSG = "Trying to add the {0}." PRESENT_ADD_ROLE_LOG_MSG = "The {0} is already present." FINISHED_ADD_ROLE_LOG_MSG = "Finished adding the {0}." ADD_ROLE_INPUT_MSG = "Add the {0}?" SKIP_ADD_ROLE_MSG = "Skipping addition of the {0}. This may prevent creation of the data history connection." # Enums
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 16529, 1783, 10541, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, ...
3.308411
535
import json import time import uuid from installed_clients.DataFileUtilClient import DataFileUtil from installed_clients.KBaseReportClient import KBaseReport from installed_clients.WorkspaceClient import Workspace as Workspace def log(message, prefix_newline=False): """Logging function, provides a hook to suppress or redirect log messages.""" print(('\n' if prefix_newline else '') + '{0:.2f}'.format(time.time()) + ': ' + str(message))
[ 11748, 33918, 198, 11748, 640, 198, 11748, 334, 27112, 198, 198, 6738, 6589, 62, 565, 2334, 13, 6601, 8979, 18274, 346, 11792, 1330, 6060, 8979, 18274, 346, 198, 6738, 6589, 62, 565, 2334, 13, 42, 14881, 19100, 11792, 1330, 14204, 589, ...
3.316176
136
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import tensorflow as tf def to_tf_tensor(ndarray, dtype = tf.float64): '''Converts the given multidimensional array to a tensorflow tensor. Args: ndarray (ndarray-like): parameter for conversion. dtype (type, optional): defines a type of tensor elements. Defaults to tf.float64. Returns: tensorflow tensor ''' return tf.convert_to_tensor(ndarray, dtype = dtype) def shape(tf_tensor): '''Returns shape of a tensorflow tensor like a list if integers.''' return tf_tensor.get_shape().as_list() def flatten(tf_tensor, column_major = False): '''Returns the flaten tensor.''' if column_major: tf_tensor = tf.transpose(tf_tensor) return tf.reshape(tf_tensor, [-1])
[ 2, 15069, 357, 66, 8, 5413, 10501, 13, 198, 2, 49962, 739, 262, 17168, 5964, 13, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 628, 198, 198, 4299, 284, 62, 27110, 62, 83, 22854, 7, 358, 18747, 11, 288, 4906, 796, 48700, 13, 224...
2.539394
330
# this file describe sets data structures on python thisSet={"Car","Bike","Truk"} # Printing sets on terminal print(thisSet)
[ 2, 428, 2393, 6901, 5621, 1366, 8573, 319, 21015, 220, 198, 198, 5661, 7248, 28, 4895, 9914, 2430, 33, 522, 2430, 51, 622, 74, 20662, 198, 198, 2, 44118, 5621, 319, 12094, 198, 4798, 7, 5661, 7248, 8 ]
3.342105
38
from multiprocessing import Pool import logging
[ 6738, 18540, 305, 919, 278, 1330, 19850, 198, 11748, 18931, 628, 198 ]
4.166667
12
import os import yaml from HTMLScriptExtractor import HTMLScriptExtractor MIME_TYPE_MAP = { '.htm': 'text/html', '.html': 'text/html', '.js': 'text/javascript', '.vbs': 'text/vbscript', '.txt': 'text/plain', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg' } # input: # a function "mime_type_function_dict" a dictionary (mime type -> f) where "f" is a function that accepts the tuple: (string, MetaData) and returns the tuple: (string, MetaData) # output: # a function "g" that accepts a single argument of type list of tuple: (string, MetaData) # # in this function, for each tuple in the list, the function mime_type_function_dict[tuple[1].mime_type] will be called with tuple as the argument # for use with TransformFunctionArgument.content # function(string) -> function(TransformFunctionArgument) # for use with TransformFunctionArgument.metadata.http.normalized_headers # function(list of headers) -> function(TransformFunctionArgument) # for use with TransformFunctionArgument.metadata.http.payload # function(bytes) -> function(TransformFunctionArgument) def IsYaml(filepath): return os.path.splitext(filepath)[-1].lower() == ".yaml" # returns list of baseline # baseline := dictionary of "host", "path", "filepath", "content" # returns list of testcase # testcase := dictionary of "host", "path", "casename"
[ 11748, 28686, 198, 198, 11748, 331, 43695, 198, 198, 6738, 11532, 7391, 11627, 40450, 1330, 11532, 7391, 11627, 40450, 628, 198, 44, 12789, 62, 25216, 62, 33767, 796, 1391, 198, 220, 220, 220, 45302, 19211, 10354, 705, 5239, 14, 6494, 3...
3.115385
442
from rapidtest import Test, Case, TreeNode from solutions.lowest_common_ancestor_of_a_binary_search_tree import Solution with Test(Solution, post_proc=TreeNode.get_val) as test: root = TreeNode.from_iterable([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5]) Case(root, TreeNode(2), TreeNode(4), result=TreeNode(2)) Case(root, TreeNode(4), TreeNode(2), result=TreeNode(2)) Case(root, TreeNode(2), TreeNode(8), result=TreeNode(6)) Case(root, TreeNode(8), TreeNode(2), result=TreeNode(6)) Case(root, TreeNode(3), TreeNode(7), result=TreeNode(6)) Case(root, TreeNode(0), TreeNode(4), result=TreeNode(2)) Case(root, TreeNode(0), TreeNode(5), result=TreeNode(2)) Case(root, TreeNode(2), TreeNode(6), result=TreeNode(6)) Case(root, TreeNode(6), TreeNode(2), result=TreeNode(6)) Case(root, TreeNode(6), TreeNode(2), result=TreeNode(6)) Case(root, TreeNode(0), TreeNode(0), result=TreeNode(0))
[ 6738, 5801, 9288, 1330, 6208, 11, 8913, 11, 12200, 19667, 198, 6738, 8136, 13, 9319, 395, 62, 11321, 62, 1192, 395, 273, 62, 1659, 62, 64, 62, 39491, 62, 12947, 62, 21048, 1330, 28186, 198, 198, 4480, 6208, 7, 46344, 11, 1281, 62, ...
2.519022
368
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: npu_utilization.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() import telemetry_top_pb2 as telemetry__top__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='npu_utilization.proto', package='', syntax='proto2', serialized_options=None, serialized_pb=_b('\n\x15npu_utilization.proto\x1a\x13telemetry_top.proto\"C\n\x1bNetworkProcessorUtilization\x12$\n\x0enpu_util_stats\x18\x01 \x03(\x0b\x32\x0c.Utilization\"q\n\x0bUtilization\x12\x12\n\nidentifier\x18\x01 \x02(\t\x12\x13\n\x0butilization\x18\x02 \x01(\r\x12\x1c\n\x07packets\x18\x03 \x03(\x0b\x32\x0b.PacketLoad\x12\x1b\n\x06memory\x18\x04 \x03(\x0b\x32\x0b.MemoryLoad\"\xba\x01\n\nMemoryLoad\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x61verage_util\x18\x02 \x01(\r\x12\x14\n\x0chighest_util\x18\x03 \x01(\r\x12\x13\n\x0blowest_util\x18\x04 \x01(\r\x12\x1e\n\x16\x61verage_cache_hit_rate\x18\x05 \x01(\r\x12\x1e\n\x16highest_cache_hit_rate\x18\x06 \x01(\r\x12\x1d\n\x15lowest_cache_hit_rate\x18\x07 \x01(\r\"\xa2\x01\n\nPacketLoad\x12\x12\n\nidentifier\x18\x01 \x02(\t\x12\x0c\n\x04rate\x18\x02 \x01(\x04\x12\'\n\x1f\x61verage_instructions_per_packet\x18\x03 \x01(\r\x12&\n\x1e\x61verage_wait_cycles_per_packet\x18\x04 \x01(\r\x12!\n\x19\x61verage_cycles_per_packet\x18\x05 \x01(\r:W\n\x18jnpr_npu_utilization_ext\x12\x17.JuniperNetworksSensors\x18\x0c \x01(\x0b\x32\x1c.NetworkProcessorUtilization') , dependencies=[telemetry__top__pb2.DESCRIPTOR,]) JNPR_NPU_UTILIZATION_EXT_FIELD_NUMBER = 12 jnpr_npu_utilization_ext = _descriptor.FieldDescriptor( name='jnpr_npu_utilization_ext', full_name='jnpr_npu_utilization_ext', index=0, number=12, 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=True, extension_scope=None, serialized_options=None, file=DESCRIPTOR) _NETWORKPROCESSORUTILIZATION = _descriptor.Descriptor( name='NetworkProcessorUtilization', full_name='NetworkProcessorUtilization', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='npu_util_stats', full_name='NetworkProcessorUtilization.npu_util_stats', 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, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=46, serialized_end=113, ) _UTILIZATION = _descriptor.Descriptor( name='Utilization', full_name='Utilization', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='identifier', full_name='Utilization.identifier', index=0, number=1, type=9, cpp_type=9, label=2, 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='utilization', full_name='Utilization.utilization', 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='packets', full_name='Utilization.packets', index=2, number=3, 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='memory', full_name='Utilization.memory', index=3, number=4, 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, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=115, serialized_end=228, ) _MEMORYLOAD = _descriptor.Descriptor( name='MemoryLoad', full_name='MemoryLoad', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='MemoryLoad.name', index=0, number=1, 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='average_util', full_name='MemoryLoad.average_util', 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='highest_util', full_name='MemoryLoad.highest_util', 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='lowest_util', full_name='MemoryLoad.lowest_util', 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='average_cache_hit_rate', full_name='MemoryLoad.average_cache_hit_rate', 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='highest_cache_hit_rate', full_name='MemoryLoad.highest_cache_hit_rate', 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='lowest_cache_hit_rate', full_name='MemoryLoad.lowest_cache_hit_rate', 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, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=231, serialized_end=417, ) _PACKETLOAD = _descriptor.Descriptor( name='PacketLoad', full_name='PacketLoad', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='identifier', full_name='PacketLoad.identifier', index=0, number=1, type=9, cpp_type=9, label=2, 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='rate', full_name='PacketLoad.rate', index=1, number=2, 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='average_instructions_per_packet', full_name='PacketLoad.average_instructions_per_packet', 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='average_wait_cycles_per_packet', full_name='PacketLoad.average_wait_cycles_per_packet', 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='average_cycles_per_packet', full_name='PacketLoad.average_cycles_per_packet', 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, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=420, serialized_end=582, ) _NETWORKPROCESSORUTILIZATION.fields_by_name['npu_util_stats'].message_type = _UTILIZATION _UTILIZATION.fields_by_name['packets'].message_type = _PACKETLOAD _UTILIZATION.fields_by_name['memory'].message_type = _MEMORYLOAD DESCRIPTOR.message_types_by_name['NetworkProcessorUtilization'] = _NETWORKPROCESSORUTILIZATION DESCRIPTOR.message_types_by_name['Utilization'] = _UTILIZATION DESCRIPTOR.message_types_by_name['MemoryLoad'] = _MEMORYLOAD DESCRIPTOR.message_types_by_name['PacketLoad'] = _PACKETLOAD DESCRIPTOR.extensions_by_name['jnpr_npu_utilization_ext'] = jnpr_npu_utilization_ext _sym_db.RegisterFileDescriptor(DESCRIPTOR) NetworkProcessorUtilization = _reflection.GeneratedProtocolMessageType('NetworkProcessorUtilization', (_message.Message,), { 'DESCRIPTOR' : _NETWORKPROCESSORUTILIZATION, '__module__' : 'npu_utilization_pb2' # @@protoc_insertion_point(class_scope:NetworkProcessorUtilization) }) _sym_db.RegisterMessage(NetworkProcessorUtilization) Utilization = _reflection.GeneratedProtocolMessageType('Utilization', (_message.Message,), { 'DESCRIPTOR' : _UTILIZATION, '__module__' : 'npu_utilization_pb2' # @@protoc_insertion_point(class_scope:Utilization) }) _sym_db.RegisterMessage(Utilization) MemoryLoad = _reflection.GeneratedProtocolMessageType('MemoryLoad', (_message.Message,), { 'DESCRIPTOR' : _MEMORYLOAD, '__module__' : 'npu_utilization_pb2' # @@protoc_insertion_point(class_scope:MemoryLoad) }) _sym_db.RegisterMessage(MemoryLoad) PacketLoad = _reflection.GeneratedProtocolMessageType('PacketLoad', (_message.Message,), { 'DESCRIPTOR' : _PACKETLOAD, '__module__' : 'npu_utilization_pb2' # @@protoc_insertion_point(class_scope:PacketLoad) }) _sym_db.RegisterMessage(PacketLoad) jnpr_npu_utilization_ext.message_type = _NETWORKPROCESSORUTILIZATION telemetry__top__pb2.JuniperNetworksSensors.RegisterExtension(jnpr_npu_utilization_ext) # @@protoc_insertion_point(module_scope)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 299, 19944, 62, 22602, 1634, 13, 1676, 1462, 198, 198, 11748, 25064, 198, ...
2.410169
5,015
from annotatelib.models import ( models, class_from_filename, table_name_from_filename, _get_column_description_from_object, _get_indices_description_from_oject ) import sqlite3 from orator import DatabaseManager import os import sys sys.path.insert(0, os.path.abspath( os.path.join(os.path.dirname(__file__), '../')))
[ 6738, 24708, 378, 8019, 13, 27530, 1330, 357, 198, 220, 220, 220, 4981, 11, 1398, 62, 6738, 62, 34345, 11, 198, 220, 220, 220, 3084, 62, 3672, 62, 6738, 62, 34345, 11, 4808, 1136, 62, 28665, 62, 11213, 62, 6738, 62, 15252, 11, 198...
2.730159
126
__version__ = '0.0.1' def flatten_list(input_list): """ Flattens list with many nested lists. >>> flatten_list([1, [2, [3], [4]]]) [1, 2, 3, 4] """ result = [] for item in input_list: if isinstance(item, list): result.extend(flatten_list(item)) # yield from flatten_list(item) else: result.append(item) # yield item return result
[ 834, 9641, 834, 796, 705, 15, 13, 15, 13, 16, 6, 628, 198, 4299, 27172, 268, 62, 4868, 7, 15414, 62, 4868, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1610, 1078, 641, 1351, 351, 867, 28376, 8341, 13, 628, 220, 220, 220...
2.037915
211
import os import keyring from prompt_toolkit import prompt KEY = ('slackcast', 'token') SLACKCAST_INSTALL_URL = os.environ.get( 'SLACKCAST_INSTALL_URL', 'https://slackcast.devtestit.com/install' )
[ 11748, 28686, 198, 11748, 1994, 1806, 198, 6738, 6152, 62, 25981, 15813, 1330, 6152, 198, 198, 20373, 796, 19203, 6649, 441, 2701, 3256, 705, 30001, 11537, 198, 8634, 8120, 44647, 62, 38604, 7036, 62, 21886, 796, 28686, 13, 268, 2268, 1...
2.684211
76
import progressbar from baidupcsapi import PCS pcs = PCS('username','password') test_file = open('bigfile.pdf','rb').read() ret = pcs.upload('/',test_file,'bigfile.pdf',callback=ProgressBar())
[ 11748, 4371, 5657, 198, 6738, 275, 1698, 929, 6359, 15042, 1330, 4217, 50, 628, 198, 79, 6359, 796, 4217, 50, 10786, 29460, 41707, 28712, 11537, 198, 9288, 62, 7753, 796, 1280, 10786, 14261, 7753, 13, 12315, 41707, 26145, 27691, 961, 34...
2.954545
66
""" messages """ from .color import ENDC, FAIL, OKBLUE, YELLOW EXE_SCRIPT_ERR_MSG = '{0}[!]{1} An error occurred while executing script in Pipfile'.format( FAIL, ENDC ) KEYWORD_NOT_FOUND_MSG = "{0}[!]{1} {2}Pipfile{1} in {3}[scripts]{1} keyword not found!".format( FAIL, ENDC, OKBLUE, YELLOW ) FILE_NOT_FOUND_MSG = "{0}[!]{1} {2}Pipfile{1} not found!".format( FAIL, ENDC, OKBLUE ) KEYBOARD_INTERRUPT_MSG = "{0}[!]{1} KeyboardInterrupt".format(FAIL, ENDC) INQUIRER_MSG = "{0}Select Pipfile script to run{1}".format(YELLOW, ENDC)
[ 37811, 198, 37348, 1095, 198, 37811, 198, 6738, 764, 8043, 1330, 23578, 34, 11, 9677, 4146, 11, 7477, 9148, 8924, 11, 575, 23304, 3913, 198, 198, 6369, 36, 62, 6173, 46023, 62, 1137, 49, 62, 5653, 38, 796, 705, 90, 15, 92, 58, 364...
2.181452
248
import sys import logging import pymysql import json import os #rds settings - Lambda role must have RDS access rds_host = os.environ['RDS_HOST'] # Set in Lambda Dashboard name = os.environ['DB_USERNAME'] password = os.environ['DB_PW'] db_name = os.environ['DB_NAME'] db_table = os.environ['DB_TABLE'] logger = logging.getLogger() logger.setLevel(logging.INFO) def handler(event, context): """ This function handles SNS posts from Amazon SNS. Currently it: 1) Inserts the request into an RDS MySQL DB Current Assumptions: 1) Messages don't contain special characters - i.e: ' 2) Requests are correctly formated (contain body and event, and event contains the expected values) """ print("In logevent: ", event) try: slackevent = json.loads(event["Records"][0]["Sns"]["Message"]) writemessagetodb(slackevent) response = response = { "statusCode": 200, "body": event } except Exception as e: ''' Just a stub. Please make this better in real use :) ''' logger.error(f"ERROR: {e}") response = { "statusCode": 400, "body": event } return response
[ 11748, 25064, 198, 11748, 18931, 198, 11748, 279, 4948, 893, 13976, 198, 11748, 33918, 198, 11748, 28686, 198, 198, 2, 4372, 82, 6460, 532, 21114, 6814, 2597, 1276, 423, 371, 5258, 1895, 198, 4372, 82, 62, 4774, 796, 28686, 13, 268, 2...
2.428571
504
# Generated by Django 2.1.5 on 2019-03-29 05:54 import datetime from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 20, 319, 13130, 12, 3070, 12, 1959, 8870, 25, 4051, 198, 198, 11748, 4818, 8079, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.972222
36
from django import forms from .models import Doacao
[ 6738, 42625, 14208, 1330, 5107, 201, 198, 6738, 764, 27530, 1330, 2141, 330, 5488, 201, 198 ]
3.375
16
import requests from elasticsearch import Elasticsearch, client from elasticsearch.exceptions import RequestError es = Elasticsearch() # retrieve all QIDs from the populated reframe ES index body = { "_source": { "includes": ["qid"], }, "query": { "query_string": { "query": "Q*", "fields": ['qid'] } }, "from": 0, "size": 10000, } es.indices.refresh(index="reframe") r = es.search(index="reframe", body=body) bd = { 'mapping': { 'total_fields': { 'limit': 30000 } } } c = client.IndicesClient(es) # check if index exists, otherwise, create if c.exists(index='wikidata'): c.put_settings(index='wikidata', body=bd) else: c.create(index='wikidata', body=bd) session = requests.Session() for count, hit in enumerate(r['hits']['hits']): qid = hit['_source']['qid'] header = { 'Accept': 'application/json' } r = session.get('http://www.wikidata.org/entity/{}'.format(qid), headers=header).json() # print(r) obj = r['entities'][qid] del obj['descriptions'] for claim, value in obj['claims'].items(): # print(claim, value) for x in value: if 'references' in x: del x['references'] if es.exists(index='wikidata', doc_type='compound', id=qid): # print('this exists!!') es.update(index='wikidata', id=qid, doc_type='compound', body={'doc': obj}) # pass else: try: res = es.index(index="wikidata", doc_type='compound', id=qid, body=obj) except RequestError as e: print(e) if count % 100 == 0: print('imported ', count)
[ 11748, 7007, 198, 198, 6738, 27468, 12947, 1330, 48567, 12947, 11, 5456, 198, 6738, 27468, 12947, 13, 1069, 11755, 1330, 19390, 12331, 198, 274, 796, 48567, 12947, 3419, 628, 198, 2, 19818, 477, 1195, 47954, 422, 262, 22331, 1006, 28073, ...
2.219766
769
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.urls import reverse_lazy from django.views.generic import (ListView, CreateView, TemplateView, ) from django.views.generic.detail import DetailView from django.views.generic.edit import (UpdateView, DeleteView, ) from blog.models import Post # def post_detail(request, pk): # post = Post.objects.get(pk=pk) # # # We create empty form when user visits a page # form = CommentForm() # if request.method == 'POST': # form = CommentForm(request.POST) # if form.is_valid(): # comment = Comment( # author=form.cleaned_data['author'], # content=form.cleaned_data['content'], # post=post # ) # comment.save() # # comments = Comment.objects.filter(post=post) # context = { # 'post': post, # 'comments': comments, # 'form': form, # } # return render(request, 'blog/post_detail.html', context)
[ 6738, 42625, 14208, 13, 7295, 13, 79, 363, 20900, 1330, 31525, 20900, 11, 7873, 3673, 2025, 46541, 11, 33523, 9876, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 62, 75, 12582, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, ...
2.329571
443
""" Copyright (c) 2012 Wyss Institute at Harvard University 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. http://www.opensource.org/licenses/mit-license.php """ """ flaskapp.py """ from flask import Flask, g, request, render_template, jsonify, make_response, send_from_directory from werkzeug.exceptions import HTTPException, NotFound from os.path import dirname, basename, split, abspath from os.path import join as op_join import random import sys from experimentcore.exp_dbifc import setupExperiment exp_dict = setupExperiment('evolvulator') app = Flask(__name__) app.config.from_object(__name__) app.wsport = 9000 # default #end def # end def # end def # end def # end def # @app.before_request # def before_request(): # """Make sure we are connected to the database each request.""" # g.db = edb.connectToDB(thedatabase) # # # @app.teardown_request # def teardown_request(exception): # """Closes the database again at the end of the request.""" # if hasattr(g, 'db'): # g.db.close() # # end def
[ 37811, 198, 15269, 357, 66, 8, 2321, 12958, 824, 5136, 379, 11131, 2059, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 1659, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, ...
3.333333
603
# BSD LICENSE # # Copyright(c) 2010-2014 Intel Corporation. All rights reserved. # 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 Intel Corporation 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 # OWNER 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. import os import shutil import re from exception import VerifyFailure """ Generate Rst Test Result Report Example: import rst rst.write_title("Test Case: " + test_case.__name__) out = table.draw() rst.write_text('\n' + out + '\n\n') rst.write_result("PASS") Result: <copyright> <Prerequisites> Test Case: CASE --------------- Result: PASS """ path2Plan = 'test_plans' path2Result = 'output'
[ 2, 347, 10305, 38559, 24290, 198, 2, 198, 2, 15069, 7, 66, 8, 3050, 12, 4967, 8180, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351...
3.238095
630
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_dj-pylti ------------ Tests for `dj-pylti` models module. """ from django.test import TestCase from dj_pylti import models
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 9288, 62, 28241, 12, 9078, 2528, 72, 198, 10541, 198, 198, 51, 3558, 329, 4600, 28241, 12, 9078, 252...
2.506849
73
"""Mutation. Usage: mutation play [--verbose] [--exclude=<globs>] [--only-deadcode-detection] [--include=<globs>] [--sampling=<s>] [--randomly-seed=<n>] [--max-workers=<n>] [<file-or-directory> ...] [-- TEST-COMMAND ...] mutation replay [--verbose] [--max-workers=<n>] mutation list mutation show MUTATION mutation apply MUTATION mutation (-h | --help) mutation --version Options: --verbose Show more information. -h --help Show this screen. --version Show version. """ import asyncio import fnmatch import functools import itertools import os import random import re import shlex import sys import time from ast import Constant from concurrent import futures from contextlib import contextmanager from copy import deepcopy from datetime import timedelta from difflib import unified_diff from uuid import UUID import lexode import parso import pygments import pygments.formatters import pygments.lexers import zstandard as zstd from aiostream import pipe, stream from astunparse import unparse from coverage import Coverage from docopt import docopt from humanize import precisedelta from loguru import logger as log from lsm import LSM from pathlib3x import Path from termcolor import colored from tqdm import tqdm from ulid import ULID __version__ = (0, 4, 4) MINUTE = 60 # seconds HOUR = 60 * MINUTE DAY = 24 * HOUR MONTH = 31 * DAY PRONOTION = "https://youtu.be/ihZEaj9ml4w?list=PLOSNaPJYYhrtliZqyEWDWL0oqeH0hOHnj" log.remove() if os.environ.get("DEBUG", False): log.add( sys.stdout, format="<level>{level}</level> {message}", level="TRACE", colorize=True, enqueue=True, ) else: log.add( sys.stdout, format="<level>{level}</level> {message}", level="INFO", colorize=True, enqueue=True, ) # The function patch was taken somewhere over the rainbow... _hdr_pat = re.compile(r"^@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@$") def patch(diff, source): """Apply unified diff patch to string s to recover newer string. If revert is True, treat s as the newer string, recover older string. """ s = source.splitlines(True) p = diff.splitlines(True) t = "" i = sl = 0 (midx, sign) = (1, "+") while i < len(p) and p[i].startswith(("---", "+++")): i += 1 # skip header lines while i < len(p): m = _hdr_pat.match(p[i]) if not m: raise Exception("Cannot process diff") i += 1 l = int(m.group(midx)) - 1 + (m.group(midx + 1) == "0") t += "".join(s[sl:l]) sl = l while i < len(p) and p[i][0] != "@": if i + 1 < len(p) and p[i + 1][0] == "\\": line = p[i][:-1] i += 2 else: line = p[i] i += 1 if len(line) > 0: if line[0] == sign or line[0] == " ": t += line[1:] sl += line[0] != sign t += "\n" + "".join(s[sl:]) return t def chunks(iterable, n): """Yield successive n-sized chunks from iterable.""" it = iter(iterable) while chunk := tuple(itertools.islice(it, n)): yield chunk def diff(source, target, filename=""): lines = unified_diff( source.split("\n"), target.split("\n"), filename, filename, lineterm="" ) out = "\n".join(lines) return out def mutate(node, index, mutations): for mutation in mutations: if not mutation.predicate(node): continue yield from mutation.mutate(node, index) def mutation_create(item): path, source, coverage, mutation_predicate = item if not coverage: msg = "Ignoring file {} because there is no associated coverage." log.trace(msg, path) return [] log.trace("Mutating file: {}...", path) mutations = [m for m in Mutation.ALL if mutation_predicate(m)] deltas = deltas_compute(source, path, coverage, mutations) # return the compressed deltas to save some time in the # mainthread. out = [(path, zstd.compress(x.encode("utf8"))) for x in deltas] log.trace("There is {} mutations for the file `{}`", len(out), path) return out def install_module_loader(uid): db = LSM(".mutation.okvslite") mutation_show(uid.hex) path, diff = lexode.unpack(db[lexode.pack([1, uid])]) diff = zstd.decompress(diff).decode("utf8") with open(path) as f: source = f.read() patched = patch(diff, source) import imp components = path[:-3].split("/") while components: for pythonpath in sys.path: filepath = os.path.join(pythonpath, "/".join(components)) filepath += ".py" ok = os.path.exists(filepath) if ok: module_path = ".".join(components) break else: components.pop() continue break if module_path is None: raise Exception("sys.path oops!") patched_module = imp.new_module(module_path) try: exec(patched, patched_module.__dict__) except Exception: # TODO: syntaxerror, do not produce those mutations exec("", patched_module.__dict__) sys.modules[module_path] = patched_module def pytest_configure(config): mutation = config.getoption("mutation", default=None) if mutation is not None: uid = UUID(hex=mutation) install_module_loader(uid) PYTEST = "pytest --exitfirst --no-header --tb=no --quiet --assert=plain" PYTEST = shlex.split(PYTEST) # TODO: the `command` is a hack, maybe there is a way to avoid the # following code: `if command is not None. def check_tests(root, seed, arguments, command=None): max_workers = arguments["--max-workers"] or (os.cpu_count() - 1) or 1 max_workers = int(max_workers) log.info("Let's check that the tests are green...") if arguments["<file-or-directory>"] and arguments["TEST-COMMAND"]: log.error("<file-or-directory> and TEST-COMMAND are exclusive!") sys.exit(1) if command is not None: command = list(command) if max_workers > 1: command.extend( [ # Use pytest-xdist to make sure it is possible to run the # tests in parallel "--numprocesses={}".format(max_workers), ] ) else: if arguments["TEST-COMMAND"]: command = list(arguments["TEST-COMMAND"]) else: command = list(PYTEST) command.extend(arguments["<file-or-directory>"]) if max_workers > 1: command.append( # Use pytest-xdist to make sure it is possible to run # the tests in parallel "--numprocesses={}".format(max_workers) ) command.extend( [ # Setup coverage options to only mutate what is tested. "--cov=.", "--cov-branch", "--no-cov-on-fail", # Pass random seed "--randomly-seed={}".format(seed), ] ) with timeit() as alpha: out = run(command) if out == 0: log.info("Tests are green ") alpha = alpha() * max_workers else: msg = "Tests are not green... return code is {}..." log.warning(msg, out) log.warning("I tried the following command: `{}`", " ".join(command)) # Same command without parallelization if arguments["TEST-COMMAND"]: command = list(arguments["TEST-COMMAND"]) else: command = list(PYTEST) command.extend(arguments["<file-or-directory>"]) command += [ # Setup coverage options to only mutate what is tested. "--cov=.", "--cov-branch", "--no-cov-on-fail", # Pass random seed "--randomly-seed={}".format(seed), ] with timeit() as alpha: out = run(command) if out != 0: msg = "Tests are definitly red! Return code is {}!!" log.error(msg, out) log.error("I tried the following command: `{}`", " ".join(command)) sys.exit(2) # Otherwise, it is possible to run the tests but without # parallelization. msg = "Setting max_workers=1 because tests do not pass in parallel" log.warning(msg) max_workers = 1 alpha = alpha() msg = "Time required to run the tests once: {}..." log.info(msg, humanize(alpha)) return alpha, max_workers def mutation_only_deadcode(x): return getattr(x, "deadcode_detection", False) def mutation_all(x): return True def mutation_diff_size(db, uid): _, diff = lexode.unpack(db[lexode.pack([1, uid])]) out = len(zstd.decompress(diff)) return out def replay_mutation(db, uid, alpha, seed, max_workers, command): log.info("* Use Ctrl+C to exit.") command = list(command) command.append("--randomly-seed={}".format(seed)) max_workers = 1 if max_workers > 1: command.append("--numprocesses={}".format(max_workers)) timeout = alpha * 2 while True: ok = mutation_pass((command, uid, timeout)) if not ok: mutation_show(uid.hex) msg = "* Type 'skip' to go to next mutation or just enter to retry." log.info(msg) skip = input().startswith("s") if skip: db[lexode.pack([2, uid])] = b"\x01" return # Otherwise loop to re-test... else: del db[lexode.pack([2, uid])] return if __name__ == "__main__": main()
[ 37811, 44, 7094, 13, 198, 198, 28350, 25, 198, 220, 15148, 711, 685, 438, 19011, 577, 60, 685, 438, 1069, 9152, 28, 27, 4743, 8158, 37981, 685, 438, 8807, 12, 25124, 8189, 12, 15255, 3213, 60, 685, 438, 17256, 28, 27, 4743, 8158, ...
2.224036
4,410
import argparse from ColorDetector import ColorDetector if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 6738, 5315, 11242, 9250, 1330, 5315, 11242, 9250, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
3.096774
31
print('===== DESAFIO 64 =====') num = 0 cont = 0 soma = 0 num = int(input('Digite um nmero [999 para SAIR]: ')) while num != 999: soma += num cont += 1 num = int(input('Digite um nmero [999 para SAIR]: ')) print(f'Voc digitou {cont} nmeros! A soma entre eles {soma}')
[ 4798, 10786, 1421, 28, 22196, 8579, 9399, 5598, 29335, 11537, 198, 22510, 796, 657, 198, 3642, 796, 657, 198, 82, 6086, 796, 657, 198, 22510, 796, 493, 7, 15414, 10786, 19511, 578, 23781, 299, 647, 78, 685, 17032, 31215, 14719, 4663, ...
2.361345
119