content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
import pandas as pd import networkx as nx import matplotlib.pyplot as plt import tqdm,json,math from collections import defaultdict match_path='2020_Problem_D_DATA/matches.csv' passings='2020_Problem_D_DATA/passingevents.csv' fullevents='2020_Problem_D_DATA/fullevents.csv' if __name__=='__main__': conduct_degree()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 3127, 87, 355, 299, 87, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 256, 80, 36020, 11, 17752, 11, 11018, 198, 6738, 17268, 1330, 4277, 11600, 198, 15699, 62, ...
2.807018
114
from __future__ import print_function import time import itertools import click import datetime import os import sys import logging from tabulate import tabulate from . import config from . import projects from . import helpers as h from .projects import Project from . import auth from .path import Path from . import __version__ from .client import RoroClient from firefly.client import FireflyError from requests import ConnectionError @click.group(cls=CatchAllExceptions) @click.version_option(version=__version__) @cli.command() @click.option('--email', prompt='Email address') @click.option('--password', prompt=True, hide_input=True) def login(email, password): """Login to rorodata platform. """ try: auth.login(email, password) click.echo("Login successful.") except ConnectionError: click.echo('unable to connect to the server, try again later') except FireflyError as e: click.echo(e) raise @cli.command() def version(): """Prints the version of roro client.""" cli.main(args=['--version']) @cli.command() def whoami(): """prints the details of current user. """ client = RoroClient(config.SERVER_URL) user = client.whoami() if user: click.echo(user['email']) else: click.echo("You are not logged in yet.") sys.exit(1) @cli.command(name="projects") def _projects(): """Lists all the projects. """ projects = Project.find_all() for p in projects: print(p.name) @cli.command() @click.argument('project') @click.option('--repo-url', help="Initialize the project with a git repo", default=None) def create(project, repo_url=None): """Creates a new Project. """ p = Project(project) if repo_url: task = p.create(repo_url=repo_url) click.echo("Waiting for the project to get created...") response = task.wait() click.echo(response) else: p.create() click.echo("Created project:", project) @cli.command(name="projects:delete") @click.argument('name') def project_delete(name): """Deletes a project """ p = Project(name) p.delete() click.echo("Project {} deleted successfully.".format(name)) @cli.command() def deploy(): """Pushes the local changes to the cloud and restarts all the services. """ # TODO: validate credentials project = projects.current_project(roroyml_required=True) task = project.deploy(async=True) response = task.wait() click.echo(response) @cli.command() @click.argument('src', type=PathType()) @click.argument('dest', type=PathType()) def cp(src, dest): """Copy files to and from volumes to you local disk. Example: $ roro cp volume:/dataset.txt ./dataset.txt downloads the file dataset.txt from the server $ roro cp ./dataset.txt volume:/dataset.txt uploads dataset.txt to the server """ if src.is_volume() is dest.is_volume(): raise Exception('One of the arguments has to be a volume, other a local path') project = projects.current_project() project.copy(src, dest) @cli.command() @click.option('-a', '--all', default=False, is_flag=True) def ps(all): """Shows all the processes running in this project. """ project = projects.current_project() jobs = project.ps(all=all) rows = [] for job in jobs: start = h.parse_time(job['start_time']) end = h.parse_time(job['end_time']) total_time = (end - start) total_time = datetime.timedelta(total_time.days, total_time.seconds) command = " ".join(job["details"]["command"]) rows.append([job['jobid'], job['status'], h.datestr(start), str(total_time), job['instance_type'], h.truncate(command, 50)]) print(tabulate(rows, headers=['JOBID', 'STATUS', 'WHEN', 'TIME', 'INSTANCE TYPE', 'CMD'], disable_numparse=True)) @cli.command(name='ps:restart') @click.argument('name') def ps_restart(name): """Restarts the service specified by name. """ pass @cli.command(name="config") def _config(): """Lists all config vars of this project. """ project = projects.current_project() config = project.get_config() print("=== {} Config Vars".format(project.name)) for k, v in config.items(): print("{}: {}".format(k, v)) @cli.command(name='config:set') @click.argument('vars', nargs=-1) def env_set(vars): """Sets one or more the config vars. """ project = projects.current_project() d = {} for var in vars: if "=" in var: k, v = var.split("=", 1) d[k] = v else: d[var] = "" project.set_config(d) print("Updated config vars") @cli.command(name='config:unset') @click.argument('names', nargs=-1) def env_unset(names): """Unsets one or more config vars. """ project = projects.current_project() project.unset_config(names) print("Updated config vars") @cli.command(context_settings={"allow_interspersed_args": False}) @click.option('-s', '--instance-size', help="size of the instance to run the job on") @click.argument('command', nargs=-1) def run(command, instance_size=None): """Runs the given script in foreground. """ project = projects.current_project() job = project.run(command, instance_size=instance_size) print("Started new job", job["jobid"]) @cli.command(name='run:notebook', context_settings={"allow_interspersed_args": False}) @click.option('-s', '--instance-size', help="size of the instance to run the job on") def run_notebook(instance_size=None): """Runs a notebook. """ project = projects.current_project() job = project.run_notebook(instance_size=instance_size) _logs(project, job["jobid"], follow=True, end_marker="-" * 40) @cli.command() @click.argument('jobid') def stop(jobid): """Stops a job by service name or job id. """ project = projects.current_project() project.stop(jobid) @cli.command() @click.argument('service_name') def start(service_name): """Starts the service specified by the given name. """ project = projects.current_project() project.start_service(service_name) @cli.command() @click.argument('service_name') def restart(service_name): """Restarts the service specified by the given name. """ project = projects.current_project() project.restart_service(service_name) @cli.command() @click.argument('jobid') @click.option('-s', '--show-timestamp', default=False, is_flag=True) @click.option('-f', '--follow', default=False, is_flag=True) def logs(jobid, show_timestamp, follow): """Shows all the logs of the project. """ project = projects.current_project() _logs(project, jobid, follow, show_timestamp) def _logs(project, job_id, follow=False, show_timestamp=False, end_marker=None): """Shows the logs of job_id. """ logs = get_logs(job_id, follow) if end_marker: logs = itertools.takewhile(lambda log: not log['message'].startswith(end_marker), logs) _display_logs(logs, show_timestamp=show_timestamp) @cli.command() @click.argument('project') def project_logs(project): """Shows all the logs of the process with name <project> the project. """ pass @cli.command() def volumes(): """Lists all the volumes. """ project = projects.current_project() volumes = project.list_volumes() if not volumes: click.echo('No volumes are attached to {}'.format(project.name)) for volume in project.list_volumes(): click.echo(volume) @cli.command(name='volumes:add') @click.argument('volume_name') def create_volume(volume_name): """Creates a new volume. """ project = projects.current_project() volume = project.add_volume(volume_name) click.echo('Volume {} added to the project {}'.format(volume, project.name)) @cli.command(name='volumes:remove') @click.argument('volume_name') def remove_volume(volume_name): """Removes a new volume. """ pass @cli.command(name='volumes:ls') @click.argument('path') def ls_volume(path): """Lists you files in a volume. Example: \b roro volume:ls <volume_name> lists all files in volume "volume_name" \b roro volume:ls <volume_name:dir> lists all filies at directory "dir" in volume "volume" """ path = path+':' if ':' not in path else path path = Path(path) project = projects.current_project() stat = project.ls(path) rows = [[item['mode'], item['size'], item['name']] for item in stat] click.echo(tabulate(rows, tablefmt='plain')) @cli.command() @cli.command(name="models:log") @click.argument('name', required=False) @click.option('-a', '--all', default=False, is_flag=True, help="Show all fields") @cli.command(name="models:show") @click.argument('modelref')
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 640, 198, 11748, 340, 861, 10141, 198, 11748, 3904, 198, 11748, 4818, 8079, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 18931, 198, 198, 6738, 7400, 5039, 1330, 7400, 5039, ...
2.666867
3,329
import os import logging from http import HTTPStatus from libtrustbridge.websub.constants import ( TOPIC_ATTR_KEY, MODE_ATTR_KEY, LEASE_SECONDS_ATTR_KEY ) from flask import Flask, request, jsonify HUB_CHALLENGE_ATTR_KEY = 'hub.challenge' PORT = os.environ['PORT'] HOST = '0.0.0.0' app = Flask(__name__) app.config['TESTING'] = True app.config['DEBUG'] = True logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('CALLBACK_SERVER') CALLBACKS_RECORD = [] @app.route('/callback/<result>/<id>', methods=['GET', 'POST']) @app.route('/callback/<result>', methods=['GET', 'POST']) @app.route('/callbacks', methods=['DELETE', 'GET']) @app.route('/callbacks/<index>', methods=['GET']) if __name__ == '__main__': app.run(host=HOST, port=PORT)
[ 11748, 28686, 198, 11748, 18931, 198, 6738, 2638, 1330, 14626, 19580, 198, 6738, 9195, 38087, 9458, 13, 732, 1443, 549, 13, 9979, 1187, 1330, 357, 198, 220, 220, 220, 28662, 2149, 62, 1404, 5446, 62, 20373, 11, 198, 220, 220, 220, 337...
2.468354
316
import argparse import os import random import shutil import warnings import sys warnings.filterwarnings("ignore") from keras import backend as K import numpy as np from PIL import Image, ImageFilter from skimage.measure import compare_ssim as SSIM import keras from util import get_model import tensorflow as tf import os os.environ["CUDA_VISIBLE_DEVICES"] = "0" ####for solving some specific problems, don't care config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True sess = tf.compat.v1.Session(config=config) # the data is in range(-.5, .5) # (row, col, channel) # use PIL Image save instead of guetzli # # (row, col, channel) # def gaussian_blur_transform(AdvSample, radius): # if AdvSample.shape[2] == 3: # sample = np.round(AdvSample) # # image = Image.fromarray(np.uint8(sample)) # gb_image = image.filter(ImageFilter.GaussianBlur(radius=radius)) # gb_image = np.array(gb_image).astype('float32') # # print(gb_image.shape) # # return gb_image # else: # sample = np.round(AdvSample) # sample = np.squeeze(sample, axis=2) # image = Image.fromarray(np.uint8(sample)) # gb_image = image.filter(ImageFilter.GaussianBlur(radius=radius)) # gb_image = np.expand_dims(np.array(gb_image).astype('float32'), axis=-1) # # print(gb_image.shape) # return gb_image # # # # # use PIL Image save instead of guetzli # def image_compress_transform(IndexAdv, AdvSample, dir_name, quality=50): # if AdvSample.shape[2] == 3: # sample = np.round(AdvSample) # image = Image.fromarray(np.uint8(sample)) # saved_adv_image_path = os.path.join(dir_name, '{}th-adv.jpg'.format(IndexAdv)) # image.save(saved_adv_image_path, format='JPEG', quality=quality) # IC_image = Image.open(saved_adv_image_path).convert('RGB') # IC_image = np.array(IC_image).astype('float32') # return IC_image # else: # sample = np.round(AdvSample) # sample = np.squeeze(sample, axis=2) # image = Image.fromarray(np.uint8(sample), mode='L') # saved_adv_image_path = os.path.join(dir_name, '{}th-adv.jpg'.format(IndexAdv)) # image.save(saved_adv_image_path, format='JPEG', quality=quality) # IC_image = Image.open(saved_adv_image_path).convert('L') # IC_image = np.expand_dims(np.array(IC_image).astype('float32'), axis=-1) # return IC_image # model does not have softmax layer # help function # 1 MR:Misclassification Rate # 2 ACAC: average confidence of adversarial class # 3 ACTC: average confidence of true class # 4 ALP: Average L_p Distortion # 5 ASS: Average Structural Similarity # 6: PSD: Perturbation Sensitivity Distance # 7 NTE: Noise Tolerance Estimation # 8 RGB: Robustness to Gaussian Blur # 9 RIC: Robustness to Image Compression if __name__ == '__main__': dataset = 'mnist' model_name = 'lenet1' l = [0, 8] x_train, y_train, x_test, y_test = load_data(dataset) x_test_new = np.load('x_test_new.npy') # ## load mine trained model from keras.models import load_model model = load_model('../data/' + dataset + '_data/model/' + model_name + '.h5') model.summary() T = 1 # for i in range(T): # index = np.load('fuzzing/nc_index_{}.npy'.format(i), allow_pickle=True).item() # for y, x in index.items(): # x_train = np.concatenate((x_train, np.expand_dims(x, axis=0)), axis=0) # y_train = np.concatenate((y_train, np.expand_dims(y_train[y], axis=0)), axis=0) # # retrained_model = retrain(model, x_train, y_train, x_test, y_test, batch_size=512, epochs=30) # retrained_model.save('new_model/' + dataset +'/model_{}.h5'.format(T-1)) retrained_model = load_model('new_model/' + dataset +'/model_{}.h5'.format(T-1)) criteria = AttackEvaluate(retrained_model, x_test, y_test, x_test_new) MR = criteria.misclassification_rate() ACAC = criteria.avg_confidence_adv_class() ACTC = criteria.avg_confidence_true_class() ALP_L0, ALP_L2, ALP_Li = criteria.avg_lp_distortion() ASS = criteria.avg_SSIM() PSD = criteria.avg_PSD() NTE = criteria.avg_noise_tolerance_estimation() _, _, RGB = criteria.robust_gaussian_blur() _, _, RIC = criteria.robust_image_compression(1) with open("attack_evaluate_result.txt", "a") as f: f.write("\n------------------------------------------------------------------------------\n") f.write('the result of {} {} is: \n'.format(dataset, model_name)) f.write('MR: {} \n'.format(MR)) f.write('ACAC: {} \n'.format(ACAC)) f.write('ACTC: {} \n'.format(ACTC)) f.write('ALP_L0: {} \n'.format(ALP_L0)) f.write('ALP_L2: {} \n'.format(ALP_L2)) f.write('ALP_Li: {} \n'.format(ALP_Li)) f.write('ASS: {} \n'.format(ASS)) f.write('PSD: {} \n'.format(PSD)) f.write('NTE: {} \n'.format(NTE)) f.write('RGB: {} \n'.format(RGB)) f.write('RIC: {} \n'.format(RIC))
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 4423, 346, 198, 11748, 14601, 198, 11748, 25064, 198, 198, 40539, 654, 13, 24455, 40539, 654, 7203, 46430, 4943, 198, 198, 6738, 41927, 292, 1330, 30203, 355, 509, 198, ...
2.314622
2,209
# Auto-generated at 2021-09-27T17:12:31.699868+08:00 # from: Justice Iam Service (4.1.0) # Copyright (c) 2018 - 2021 AccelByte Inc. All Rights Reserved. # This is licensed software from AccelByte Inc, for limitations # and restrictions contact your company contract manager. # pylint: disable=duplicate-code # pylint: disable=line-too-long # pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring # pylint: disable=too-many-arguments # pylint: disable=too-many-branches # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-lines # pylint: disable=too-many-locals # pylint: disable=too-many-public-methods # pylint: disable=too-many-return-statements # pylint: disable=too-many-statements # pylint: disable=unused-import from __future__ import annotations from typing import Any, Dict, List, Optional, Tuple, Union from ....core import Model class OauthmodelErrorResponse(Model): """Oauthmodel error response Properties: error: (error) REQUIRED str error_description: (error_description) OPTIONAL str error_uri: (error_uri) OPTIONAL str """ # region fields error: str # REQUIRED error_description: str # OPTIONAL error_uri: str # OPTIONAL # endregion fields # region with_x methods # endregion with_x methods # region to methods # endregion to methods # region static methods @classmethod @classmethod @staticmethod # endregion static methods
[ 2, 11160, 12, 27568, 379, 33448, 12, 2931, 12, 1983, 51, 1558, 25, 1065, 25, 3132, 13, 21, 34808, 3104, 10, 2919, 25, 405, 198, 2, 422, 25, 4796, 314, 321, 4809, 357, 19, 13, 16, 13, 15, 8, 198, 198, 2, 15069, 357, 66, 8, 28...
2.311671
754
""" This module contains all db-related tasks which needs to be executed periodically or as a cron job. The main packages used here to schedule these tasks are `django-apscheduler` and `apscheduler` For reference follow below links: - https://apscheduler.readthedocs.io/en/stable/index.html - https://medium.com/better-programming/introduction-to-apscheduler-86337f3bb4a6 - https://github.com/jcass77/django-apscheduler#quick-start - https://medium.com/@mrgrantanderson/replacing-cron-and-running-background-tasks-in-django-using-apscheduler-and-django-apscheduler-d562646c062e#318c For any specific job, a function should be created which should encapsulate all details of the task, and it should be decoupled from the task scheduler, i.e. it should only do the task required. e.g. `task_dummy` function. All tasks should follow the naming convention as `task_<name of task>`. To execute (schedule) any task, the task should be added as a job in the `add_jobs` function of this module, which schedules and starts these tasks. The add_jobs function either gets automatically executed by the AppConfig with the start of Django (see scheduled_tasks.scheduler.start, backend.apps.BackendConfig), or executed using the runapscheduler-command (backend.management.commands.runapscheduler.Command), which make sure these tasks will be scheduled with start of django application. Further, the tasks will be added to a database-entry which can be managed through the Django-Management-Interface. """ from apscheduler.triggers.cron import CronTrigger from django_apscheduler.models import DjangoJobExecution from django.conf import settings import csv import glob import logging import os from datetime import datetime, timedelta from pathlib import Path import inspect from django.core.exceptions import ValidationError from django.core.validators import URLValidator import backend.models from backend.models import WebResource from settings import BASE_DIR from bert_app import recommender_backbone from recommenders import recommender_functions from dashboard import raw_data from scheduled_tasks import educational_resource_functions def delete_old_job_executions(max_age=604_800): """This job deletes all apscheduler job executions older than `max_age` from the database.""" DjangoJobExecution.objects.delete_old_job_executions(max_age) def add_jobs(scheduler): """ Here new tasks can be added for scheduled execution. """ today = datetime.now().date() tomorrow = today + timedelta(days=1) # Add Jobs here # - replace_existing in combination with the unique ID prevents duplicate copies of the job # scheduler.add_job("core.models.MyModel.my_class_method", "cron", id="my_class_method", hour=0, replace_existing=True) scheduler.add_job(delete_old_job_executions, trigger=CronTrigger(day_of_week="mon", hour="00", minute="00"), id="delete_old_job_executions", max_instances=1, replace_existing=True, ) scheduler.add_job(task_add_backend_resources, 'interval', minutes=10, id="add_backend_resources", replace_existing=True) scheduler.add_job(task_classify_new_resources_bert, 'cron', start_date=today, hour=20, id="classify_new_resources_bert", replace_existing=True) scheduler.add_job(task_execute_recommender_cron_functions,'interval',hours=6, id="execute_recommender_cron_functions", replace_existing=True) scheduler.add_job(task_initialize_templates, id="initialize_templates", replace_existing=True) scheduler.add_job(task_collect_educational_resources, 'cron', start_date=today, hour=20, replace_existing=True) scheduler.add_job(task_create_rawdataexportcsv, 'cron', start_date=today, hour=23, id="create_rawdataexportcsv", replace_existing=True) scheduler.add_job(task_create_rawdataexportcsv, next_run_time=datetime.now() + timedelta(minutes=1), id="create_rawdataexportcsv", replace_existing=True) scheduler.add_job(task_send_admin_report, 'cron', start_date=tomorrow, hour=0, id="send_admin_report", replace_existing=True) def task_dummy(): """ Create the dummy task which you want to accomplish here. This task should be agnostic of scheduled time, i.e. just do the task. :return: """ logger = logging.getLogger("scheduled_tasks.db_tasks.task_dummy") if "LOG_LEVEL" in os.environ and not getattr(settings, "QUIET_SCHEDULER", False): logger.setLevel(int(os.environ["LOG_LEVEL"])) else: logger.setLevel(logging.WARNING) logger.info("I am doing some task.") logger.info(f"Task completed at time: {datetime.now()}") def task_add_backend_resources(): """ This function add new rows in backend_resources table. It will read files from data folder and add all rows from the csv into database if valid, and move file to processed folder. No header is required, but the order of the columns should be as follow: - title;description;url Name of the file should have following extension: - .csv Place of the file: BASE_DIR / 'data' / 'csv_files' / 'database' / 'resources' - :return: """ logger = logging.getLogger("scheduled_tasks.db_tasks.task_add_backend_resources") if "LOG_LEVEL" in os.environ and not getattr(settings, "QUIET_SCHEDULER", False): logger.setLevel(int(os.environ["LOG_LEVEL"])) else: logger.setLevel(logging.WARNING) logger.info("Checking for new files in data folder for new resources.") base_dir = Path(BASE_DIR) data_dir = base_dir.parent / 'data' / 'csv_files' / 'database' / 'resources' # check for all csv files in the current folder csv_files = glob.glob(str(data_dir) + "/*.csv") for file in csv_files: logger.debug(f"processing file: {file}") resource_objs = [] # database objects for resource model with open(file, mode='r') as current_file: csv_reader = csv.reader(current_file, delimiter=';') line_count = 0 for row in csv_reader: # if line_count == 0: # logger.debug(f"Headers/column names are: {', '.join(row)}") # line_count += 1 # continue # # check for validity of values: if row[0] == '': # if there is no title skip the row continue if row[1] == '': # if there is no description, skip the row continue # check for validity of url field: validate = URLValidator() try: # if url is not valid skip the row validate(row[2]) except ValidationError: logger.debug(f"url field is not valid for this row {', '.join(row)}") continue # add row to the database in backend_resources if it is already not there if not WebResource.objects.filter( title=row[0], description=row[1], source=row[2] ).exists(): resource_objs.append( WebResource( title=row[0], description=row[1], source=row[2] )) line_count += 1 logger.debug("Adding rows in backend_resources model") WebResource.objects.bulk_create(resource_objs) # use of bulk create is used for faster execution logger.debug("moving file to old dir") os.rename(file, str(data_dir / 'old' / Path(file).stem) + datetime.now().strftime("%d%m%Y%H%M%S") + ".csv") def task_classify_new_resources_bert(): """ This function is responsible for scheduling the classification of new resources. Resources get classified into a DDC class with the SidBERT app. :return: """ logger = logging.getLogger("scheduled_tasks.db_tasks.task_classify_new_resources_bert") if "LOG_LEVEL" in os.environ and not getattr(settings, "QUIET_SCHEDULER", False): logger.setLevel(int(os.environ["LOG_LEVEL"])) else: logger.setLevel(logging.WARNING) logger.info("Checking for new database resources without ddc label.") classifier = recommender_backbone.ProfessionsRecommenderBackbone() count_updated_resources_bert = classifier.update_resources_bert() if count_updated_resources_bert == 0: logger.info('No new resources to classify for SidBERT') else: msg = 'Updated '+str(count_updated_resources_bert) + 'new resources with DDC labels.' logger.info(msg) #utils.add_report_message(msg, 'BERT Classification')
[ 37811, 198, 1212, 8265, 4909, 477, 20613, 12, 5363, 8861, 543, 2476, 284, 307, 10945, 26034, 393, 355, 257, 1067, 261, 1693, 13, 198, 464, 1388, 10392, 973, 994, 284, 7269, 777, 8861, 389, 4600, 28241, 14208, 12, 499, 1416, 704, 18173...
2.626165
3,325
from django.db import models from ckeditor.fields import RichTextField USER_CHOICES = [ ("a", "Admin"), ("b", "User"), ] INTEGER_CHOICES = [ (0, "Zero"), (1, "One"), (2, "Two"), (3, "Three"), ]
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 269, 9091, 2072, 13, 25747, 1330, 3998, 8206, 15878, 628, 198, 29904, 62, 44899, 34444, 796, 685, 198, 220, 220, 220, 5855, 64, 1600, 366, 46787, 12340, 198, 220, 220, 220, 5855, 65...
2.19802
101
from queue import Queue from threading import Thread, current_thread from time import time from sys import argv from writablecte import WritableCte from normal_style_for_update import LockingAccess from normal_style_wo_explicit_locking import WithoutLockingAccess from db_util import create_pool, get_connection if __name__ == "__main__": print(argv) if len(argv) != 2 or argv[1] not in ['cte', 'lock', 'wolock']: print("Should have 1 argument, whether `cte`, `lock` or `wolock`") exit(1) pool = create_pool() q = Queue() with get_connection(pool) as conn: cursor = conn.cursor() cursor.execute("SELECT code FROM coupons LIMIT 1") code = cursor.fetchone()[0] cursor.execute("SELECT id FROM users") ids = cursor.fetchall() for id in ids: q.put(id[0]) print("Start Inserting") start = time() for _ in range(10): t = WritableCte(q, pool, code) if argv[1] == 'cte' \ else LockingAccess(q, pool, code) if argv[1] == 'lock' \ else WithoutLockingAccess(q, pool, code) t.setDaemon(True) t.start() q.join() print(f"It takes {time()-start} seconds")
[ 6738, 16834, 1330, 4670, 518, 201, 198, 6738, 4704, 278, 1330, 14122, 11, 1459, 62, 16663, 201, 198, 6738, 640, 1330, 640, 201, 198, 6738, 25064, 1330, 1822, 85, 201, 198, 201, 198, 6738, 1991, 540, 310, 68, 1330, 12257, 540, 34, 66...
2.487234
470
from .blend import Blend
[ 6738, 764, 2436, 437, 1330, 41198, 628 ]
3.714286
7
from __future__ import print_function # fn_random.py # A program showing various uses of the "random" function # from the "random" module of Python's standard library. # Author: Vasudev Ram - https://vasudevram.github.io # Copyright 2016 Vasudev Ram from random import random from random import getstate, setstate print("Ex. 1. Plain calls to random():") print("Gives 10 random float values in the interval [0, 1).") for i in range(10): print(random()) print() print("Ex. 2. Calls to random() scaled by 10:") print("Gives 10 random float values in the interval [0, 10).") for i in range(10): print(10.0 * random()) print() print("Ex. 3. Calls to random() scaled by 10 and offset by -5:") print("Gives 10 random float values in the interval [-5, 5).") for i in range(10): print(10.0 * random() - 5.0) print() print("Ex. 4. Calls to random() scaled by 20 and offset by 40:") print("Gives 10 random float values in the interval [40, 60).") for i in range(10): print(20.0 * random() + 40.0)
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 2, 24714, 62, 25120, 13, 9078, 198, 2, 317, 1430, 4478, 2972, 3544, 286, 262, 366, 25120, 1, 2163, 220, 198, 2, 422, 262, 366, 25120, 1, 8265, 286, 11361, 338, 3210, 5888, 1...
3.060423
331
version https://git-lfs.github.com/spec/v1 oid sha256:24c11001f7936158881bbcbcee78db69c9bf8cf58917db2dcb42b87230b682ce size 35959
[ 9641, 3740, 1378, 18300, 12, 1652, 82, 13, 12567, 13, 785, 14, 16684, 14, 85, 16, 198, 1868, 427, 64, 11645, 25, 1731, 66, 1157, 8298, 69, 3720, 2623, 1314, 3459, 6659, 11848, 21101, 344, 68, 3695, 9945, 3388, 66, 24, 19881, 23, 1...
2.063492
63
from flask import Flask, render_template, request, jsonify from nlp_rock import * app = Flask(__name__) # prepare clients lang_client = language.LanguageServiceClient() tran_client = translate.Client() # front @app.route('/') # process # controller @app.route('/nlp_rock', methods=['POST']) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 2581, 11, 33918, 1958, 198, 6738, 299, 34431, 62, 10823, 1330, 1635, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 198, 2, 8335, 7534, 198, 17204, 62, 16366, 796, 3303, 13,...
2.8
130
import asyncio from linguister import loop, run
[ 11748, 30351, 952, 198, 198, 6738, 20280, 1694, 1330, 9052, 11, 1057, 628 ]
3.846154
13
""" Settings for the tests. """ from os.path import abspath, dirname, join import sys from workbench.settings import * # Using the XBlock generic settings for a shorter settings file from django.conf.global_settings import LOGGING # Fix "file not found" with the workbench.settings LOGGING config def root(*args): """ Get the absolute path of the given path relative to the project root. """ return join(abspath(dirname(__file__)), *args) sys.path.append(root('mocks'))
[ 37811, 198, 26232, 329, 262, 5254, 13, 198, 37811, 198, 198, 6738, 28686, 13, 6978, 1330, 2352, 6978, 11, 26672, 3672, 11, 4654, 198, 11748, 25064, 198, 198, 6738, 670, 26968, 13, 33692, 1330, 1635, 220, 1303, 8554, 262, 1395, 12235, ...
3.256579
152
test_list = [17, 5, 1, 7, 9, 12, 6, 4, 2, 19] sort_test = insertion_sort(test_list)
[ 198, 198, 9288, 62, 4868, 796, 685, 1558, 11, 642, 11, 352, 11, 767, 11, 860, 11, 1105, 11, 718, 11, 604, 11, 362, 11, 678, 60, 198, 30619, 62, 9288, 796, 36075, 62, 30619, 7, 9288, 62, 4868, 8, 198 ]
2.097561
41
#!/usr/bin/python if "hummingbot-dist" in __file__: # Dist environment. import os import sys sys.path.append(sys.path.pop(0)) sys.path.insert(0, os.getcwd()) import hummingbot hummingbot.set_prefix_path(os.getcwd()) else: # Dev environment. from os.path import join, realpath import sys sys.path.insert(0, realpath(join(__file__, "../../")))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 361, 366, 17047, 2229, 13645, 12, 17080, 1, 287, 11593, 7753, 834, 25, 198, 220, 220, 220, 1303, 4307, 2858, 13, 198, 220, 220, 220, 1330, 28686, 198, 220, 220, 220, 1330, 25064, 198, ...
2.409938
161
from medicina import Medicina
[ 6738, 6924, 1437, 1330, 5786, 1437, 198 ]
4.285714
7
import falcon from ebl.context import Context from ebl.fragmentarium.application.cropped_annotations_service import ( CroppedAnnotationService, ) from ebl.signs.web.sign_search import SignsSearch from ebl.signs.web.signs import SignsResource from ebl.signs.web.cropped_annotations import CroppedAnnotationsResource
[ 11748, 24215, 1102, 198, 198, 6738, 304, 2436, 13, 22866, 1330, 30532, 198, 6738, 304, 2436, 13, 8310, 363, 434, 17756, 13, 31438, 13, 19915, 1496, 62, 34574, 602, 62, 15271, 1330, 357, 198, 220, 220, 220, 9325, 1496, 2025, 38983, 161...
3.27551
98
# Generated by Django 2.2.19 on 2021-03-06 11:34 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.db.models.manager
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 1129, 319, 33448, 12, 3070, 12, 3312, 1367, 25, 2682, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, ...
3.064516
62
""" Revision ID: 428551b7cf6f Revises: e17533d246ab Create Date: 2021-03-10 12:45:08.022940 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql import os revision = '428551b7cf6f' down_revision = 'e17533d246ab'
[ 37811, 198, 198, 18009, 1166, 4522, 25, 45063, 43697, 65, 22, 12993, 21, 69, 198, 18009, 2696, 25, 304, 17430, 2091, 67, 26912, 397, 198, 16447, 7536, 25, 33448, 12, 3070, 12, 940, 1105, 25, 2231, 25, 2919, 13, 15, 23539, 1821, 198,...
2.457143
105
''' Author: Saijal Shakya Development: > LMS: December 20, 2018 > HRM: Febraury 15, 2019 > CRM: March, 2020 > Inventory Sys: April, 2020 > Analytics: ... License: Credited Contact: https://saijalshakya.com.np '''
[ 7061, 6, 198, 13838, 25, 25251, 73, 282, 35274, 3972, 198, 41206, 25, 198, 220, 220, 220, 1875, 406, 5653, 25, 3426, 1160, 11, 2864, 198, 220, 220, 220, 1875, 15172, 44, 25, 3158, 430, 1601, 1315, 11, 13130, 198, 220, 220, 220, 18...
2.478723
94
"""Standarise SpecArray attributes. attrs (dict): standarised names for spectral variables, standard_names and units """ # from collections import OrderedDict import os import yaml HERE = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(HERE, "attributes.yml")) as stream: attrs = AttrDict(yaml.load(stream, yaml.SafeLoader)) def set_spec_attributes(dset): """ Standarise CF attributes in specarray variables """ for varname, varattrs in attrs.ATTRS.items(): try: dset[varname].attrs = varattrs except Exception: pass
[ 37811, 15480, 283, 786, 18291, 19182, 12608, 13, 198, 198, 1078, 3808, 357, 11600, 2599, 1302, 283, 1417, 3891, 329, 37410, 9633, 11, 3210, 62, 14933, 290, 4991, 198, 37811, 198, 2, 422, 17268, 1330, 14230, 1068, 35, 713, 198, 11748, ...
2.540084
237
#!/usr/bin/python3 import sys import requests import xml.etree.ElementTree as et USAGE = "Usage: ./nmap-hsts.py nmap.xml" proxies = { "http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080" } if __name__ == "__main__": if len(sys.argv) != 2: print(USAGE) sys.exit(1) hosts = parse_services(sys.argv[1]) vulnerable_urls = [] print("Sending requests...") for host in hosts: for port in host.http_ports: for hostname in host.hostnames: r = request_service(hostname, port, False) if r and not check_hsts(r): #TODO: figure out how to reconstruct the pretty, ordered headers that burp's response tab shows vulnerable_urls.append("http://{}:{}/".format(hostname, port)) for port in host.https_ports: for hostname in host.hostnames: r = request_service(hostname, port, True) if r and not check_hsts(r): #TODO: figure out how to reconstruct the pretty, ordered headers that burp's response tab shows vulnerable_urls.append("https://{}:{}/".format(hostname, port)) print() print() print("===== Vulnerable URLs =====") print() for url in vulnerable_urls: print(url)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 25064, 198, 11748, 7007, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 2123, 198, 198, 2937, 11879, 796, 366, 28350, 25, 24457, 77, 8899, 12, 71, 6448, 13, 9078, 2...
2.116822
642
if __name__ == "__main__": main(c="biconditional", i="imagine")
[ 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 7, 66, 2625, 65, 291, 623, 1859, 1600, 1312, 2625, 320, 12756, 4943, 198 ]
2.242424
33
""" Flask-HTMLmin ------------- minimize your flask rendered html """ from setuptools import setup setup( name='Flask-HTMLmin', version='1.3.2', url='https://github.com/hamidfzm/Flask-HTMLmin', license='BSD-3-Clause', author='Hamid FzM', author_email='hamidfzm@gmail.com', description='Minimize render templates html', long_description=__doc__, py_modules=['HTMLMIN'], packages=['flask_htmlmin'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask', 'htmlmin' ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing :: Markup :: HTML', ], setup_requires=['pytest-runner'], test_requires=['pytest'] )
[ 198, 37811, 198, 7414, 2093, 12, 28656, 1084, 198, 32501, 198, 198, 1084, 48439, 534, 42903, 15111, 27711, 198, 37811, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 7414, 2093, 12, ...
2.551948
462
import sys sys.path.append('../') from query import Query from query import Type from query.Type import mechanism_name_dict, wcq_mechanisms, icq_mechanisms, tcq_mechanisms from privacy import PrivacyEngine from query.query_gen import * repeat_times = 1 census_card = 32561 default_workload_size = 100 default_icq_c_ratio = 0.1 default_census_icq_c = default_icq_c_ratio * census_card default_topk = 10 alpha_ratio = 0.02 alpha_census = alpha_ratio * census_card global_foo = 'N/A' ''' Function to run a single query data_set: string of data set, e.g., census q_idx: string of the query wl: workload query_type: WCQ, ICQ, or TCQ icq_threshold: threshold for ICQ mpm_poking: poking times for mpm tcq_k: top k for TCQ m_type: mechanism to use dsize: database size alpha, beta: accuracy parameters ''' re = run_query("census", qw_1, 100, Type.QueryType.WCQ, Type.MechanismType.LM, alpha=0.02*32561) analysis_results(re)
[ 11748, 25064, 201, 198, 17597, 13, 6978, 13, 33295, 10786, 40720, 11537, 201, 198, 201, 198, 6738, 12405, 1330, 43301, 201, 198, 6738, 12405, 1330, 5994, 201, 198, 6738, 12405, 13, 6030, 1330, 9030, 62, 3672, 62, 11600, 11, 266, 66, 8...
2.466165
399
from pydantic import BaseModel, Field, EmailStr from typing import Optional from datetime import datetime, timezone
[ 6738, 279, 5173, 5109, 1330, 7308, 17633, 11, 7663, 11, 9570, 13290, 198, 6738, 19720, 1330, 32233, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 640, 11340, 628, 628 ]
4.103448
29
""" ### `drawio` Automatically includes an svg, based on .drawio file changes. """ import json import subprocess as sp from lcdoc import lp from lcdoc.tools import file_hash, app, dirname, exists, os, read_file, write_file, os multi_line_to_list = True req_kw = ['fn', 'src'] def run(cmd, kw): """ """ D = lp.page_dir(kw) src = kw['abs_src'] if not exists(src): return 'Not found: %s' % src fn = kw['fn'] if not fn or fn[0] == '/': return lp.err('Require relative fn', have=fn) ffn = D + fn os.makedirs(dirname(ffn), exist_ok=True) fn_src_info = ffn + '.src' if exists(fn_src_info): oldmtime, oldhsh = json.loads(read_file(fn_src_info)) else: oldmtime, oldhsh = 0, 0 mtime = os.stat(src).st_mtime have, hsh = False, None if mtime == oldmtime: have = True else: hsh = file_hash(src) if hsh == oldhsh: have = True if not have: create_new_svg(src, ffn, kw) write_file(fn_src_info, json.dumps([mtime, hsh or file_hash(src)])) return {'res': '![](%s)' % fn, 'formatted': True}
[ 37811, 198, 21017, 220, 4600, 19334, 952, 63, 198, 198, 38062, 4142, 3407, 281, 38487, 70, 11, 1912, 319, 764, 19334, 952, 2393, 2458, 13, 198, 37811, 198, 198, 11748, 33918, 198, 11748, 850, 14681, 355, 599, 198, 198, 6738, 300, 1021...
2.113383
538
import tensorflow as tf import numpy as np # refined srnn based on rev8 # try stack CUDNN GRU
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 2, 20449, 19677, 20471, 1912, 319, 2710, 23, 198, 2, 1949, 8931, 327, 8322, 6144, 10863, 52, 628 ]
3.064516
31
# ------------------------------------------------------------------------------ # # Project: EOxServer <http://eoxserver.org> # Authors: Fabian Schindler <fabian.schindler@eox.at> # # ------------------------------------------------------------------------------ # Copyright (C) 2017 EOX IT Services GmbH # # 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 of this Software or works derived from this Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ------------------------------------------------------------------------------ from uuid import uuid4 import ast import _ast import operator import logging import concurrent.futures from functools import wraps import numpy as np from django.utils.six import string_types from eoxserver.render.browse.util import warp_fields from eoxserver.render.browse.functions import get_function, get_buffer from eoxserver.contrib import vrt, gdal, osr, gdal_array logger = logging.getLogger(__name__) class FilenameGenerator(object): """ Utility class to generate filenames after a certain pattern (template) and to keep a list for later cleanup. """ def __init__(self, template, default_extension=None): """ Create a new :class:`FilenameGenerator` from a given template :param template: the template string used to construct the filenames from. Uses the ``.format()`` style language. Keys are ``index``, ``uuid`` and ``extension``. """ self._template = template self._filenames = [] self._default_extension = default_extension def generate(self, extension=None): """ Generate and store a new filename using the specified template. An optional ``extension`` can be passed, when used in the template. """ filename = self._template.format( index=len(self._filenames), uuid=uuid4().hex, extension=extension or self._default_extension, ) self._filenames.append(filename) return filename @property def filenames(self): """ Get a list of all generated filenames. """ return self._filenames ALLOWED_NODE_TYPES = ( _ast.Module, _ast.Expr, _ast.Load, _ast.Name, _ast.Call, _ast.UnaryOp, _ast.BinOp, _ast.Subscript, _ast.Slice, _ast.Load, _ast.Index, _ast.Mult, _ast.Div, _ast.Add, _ast.Sub, _ast.Num if hasattr(_ast, 'Num') else _ast.Constant, _ast.BitAnd, _ast.BitOr, _ast.BitXor, _ast.USub, ) def parse_expression(band_expression): """ Parse and validate the passed band expression """ parsed = ast.parse(band_expression) for node in ast.walk(parsed): if not isinstance(node, ALLOWED_NODE_TYPES): raise BandExpressionError( 'Invalid expression: %s' % type(node).__name__ ) return parsed.body[0].value def extract_fields(band_expression): """ Extract the fields required to generate the output band. :param band_expression: the band expression to extract the fields of :type band_expression: str :return: a list of field names :rtype: list """ if isinstance(band_expression, string_types): root_expr = parse_expression(band_expression) else: root_expr = band_expression return [ node.id for parent, node in parent_walk(root_expr) if isinstance(node, _ast.Name) and not ( isinstance(parent, _ast.Call) and parent.func == node ) ] # make shortcut: if all relevant bands are in one dataset, we # will only return that and give the band numbers def generate_browse(band_expressions, fields_and_coverages, width, height, bbox, crs, generator=None): """ Produce a temporary VRT file describing how transformation of the coverages to browses. :param band_exressions: the band expressions for the various bands :param fields_and_coverages: a dictionary mapping the field names to all coverages with that field :param: band_expressiosn: list of strings :type fields_and_coverages: dict :return: A tuple of the filename of the output file and the generator which was used to generate the filenames. In most cases this is the filename refers to a generated VRT file in very simple cases the file might actually refer to an original file. :rtype: tuple """ generator = generator or FilenameGenerator('/vsimem/{uuid}.vrt') # out_band_filenames = [] parsed_expressions = [ parse_expression(band_expression) for band_expression in band_expressions ] is_simple = all(isinstance(expr, _ast.Name) for expr in parsed_expressions) if not is_simple: return _generate_browse_complex( parsed_expressions, fields_and_coverages, width, height, bbox, crs, generator ), generator, True single_filename, env, bands = single_file_and_indices( band_expressions, fields_and_coverages ) # for single files, we make a shortcut and just return it and the used # bands if single_filename: return ( BrowseCreationInfo(single_filename, env, bands), generator, False ) else: return _generate_browse_complex( parsed_expressions, fields_and_coverages, width, height, bbox, crs, generator ), generator, True # iterate over the input band expressions # for band_expression in band_expressions: # fields = extract_fields(band_expression) # selected_filenames = [] # # iterate over all fields that the output band shall be comprised of # for field in fields: # coverages = fields_and_coverages[field] # # iterate over all coverages for that field to select the single # # field # for coverage in coverages: # location = coverage.get_location_for_field(field) # orig_filename = location.path # orig_band_index = coverage.get_band_index_for_field(field) # # only make a VRT to select the band if band count for the # # dataset > 1 # if location.field_count == 1: # selected_filename = orig_filename # else: # selected_filename = generator.generate() # vrt.select_bands( # orig_filename, location.env, # [orig_band_index], selected_filename # ) # selected_filenames.append(selected_filename) # # if only a single file is required to generate the output band, return # # it. # if len(selected_filenames) == 1: # out_band_filename = selected_filenames[0] # # otherwise mosaic all the input bands to form a composite image # else: # out_band_filename = generator.generate() # vrt.mosaic(selected_filenames, out_band_filename) # out_band_filenames.append(out_band_filename) # # make shortcut here, when we only have one band, just return it # if len(out_band_filenames) == 1: # return ( # BrowseCreationInfo(out_band_filenames[0], None), generator, False # ) # # return the stacked bands as a VRT # else: # stacked_filename = generator.generate() # vrt.stack_bands(out_band_filenames, env or location.env, stacked_filename) # return ( # BrowseCreationInfo(stacked_filename, None), generator, False # ) operator_map = { _ast.Add: wrap_operator(operator.add), _ast.Sub: wrap_operator(operator.sub), _ast.Div: wrap_operator(operator.truediv), _ast.Mult: wrap_operator(operator.mul), }
[ 2, 16529, 26171, 198, 2, 198, 2, 4935, 25, 412, 38208, 10697, 1279, 4023, 1378, 68, 1140, 15388, 13, 2398, 29, 198, 2, 46665, 25, 14236, 666, 3059, 521, 1754, 1279, 36434, 666, 13, 20601, 521, 1754, 31, 68, 1140, 13, 265, 29, 198,...
2.544761
3,541
import numpy as np import cupy as cp import chainer from chainer import functions as F from chainer import links as L class NatureDQNHead(chainer.ChainList): """DQN's head (Nature version)"""
[ 11748, 299, 32152, 355, 45941, 198, 11748, 6508, 88, 355, 31396, 198, 11748, 6333, 263, 198, 6738, 6333, 263, 1330, 5499, 355, 376, 198, 6738, 6333, 263, 1330, 6117, 355, 406, 198, 198, 4871, 10362, 35, 48, 45, 13847, 7, 7983, 263, ...
3.177419
62
#!/usr/bin/python2.7 # _*_ coding: utf-8 _*_ """ @Author: MarkLiu """ import numpy as np def loadSimpData(): """ 加载基本测试数据 :return: """ dataMatrix = np.matrix([[1., 2.1], [2., 1.1], [1.3, 1.], [1., 1.], [2., 1.]]) classLabels = [1, 1, -1, -1, 1] return dataMatrix, classLabels def simpleStumpClassify(dataMatrix, dimen, threshValue, sepOperator): """ 单层决策树分类函数 :param dataMatrix: 输入的样本数据,不包括类别 :param dimen: 从哪一个特征入手 :param threshValue: 该特征分类的阈值 :param sepOperator: 分类的操作符,即大于(greater_than)、小于(lower_than)阈值的情况 :return: 返回预测的类别列向量 """ forecastClasses = np.ones((np.shape(dataMatrix)[0], 1)) if sepOperator == 'lower_than': forecastClasses[dataMatrix[:, dimen] <= threshValue] = -1 else: forecastClasses[dataMatrix[:, dimen] > threshValue] = -1 return forecastClasses def buildDecisionStump(trainDataMatrix, trainClasses, D): """ 通过训练数据创建简单决策树 :param trainDataMatrix: 训练数据集 :param trainClasses: 训练数据集的标签 :param D: 训练数据集各个样本的权重矩阵 :return: 返回创建的简单决策树所需的信息 """ # 保证数据为矩阵 trainDataMatrix = np.matrix(trainDataMatrix) trainClasses = np.matrix(trainClasses).T # 转置,便与计算 D = np.matrix(D) m, n = np.shape(trainDataMatrix) stepsNum = 10 # 在此特征上迭代10次 # 保存最佳分类的加权错误 minWeightedError = np.inf # 初始化设置加权分类错误率为正无穷,type为float bestDecisionStump = {} # 保存最佳决策树 bestPredictValue = np.matrix(np.zeros((m, 1))) # 保存最佳分类结果 # 对数据集的所有样本的特征进行遍历,以便寻找最佳分类的特征 for diem in range(n): # 计算训练数据集在该特征的最大值和最小值的差别,以及每次的步长 featureDatas = trainDataMatrix[:, diem] # print "特征数据:", diem, ":", len(featureDatas) # print featureDatas valueMin = featureDatas.min() valueMax = featureDatas.max() stepSize = (valueMax - valueMin) / stepsNum # 对该特征的min-max之间,以stepSize步进 for j in range(-1, stepsNum + 1): # 由于此简单决策树分类器是二类分类器,所以遍历大于、小于作为分类分界, # 如果类别多于两种,则需要修改 threshValue = valueMin + float(j) * stepSize for sepOperator in ['lower_than', 'greater_than']: # 计算决策树在该特征分类的阈值 # 按照此分类标准(第几个特征diem,阈值threshValue,操作符sepOperator) # 分类的结果 predictValues = simpleStumpClassify(trainDataMatrix, diem, threshValue, sepOperator) # 用于标记分类错误的样本 errArr = np.matrix(np.zeros((m, 1))) errArr[predictValues != trainClasses] = 1 # 结合D的加权分类错误 # D本身为列向量 weightedError = float(D.T * errArr) # 矩阵相乘计算内积 # print '分类:从第 %d 个特征入手,阈值为 %.4f , 操作符为 %s,分类的加权错误率为 %.4f' \ # % (diem, threshValue, sepOperator, weightedError) if weightedError < minWeightedError: minWeightedError = float(weightedError) # 保存最佳的决策树 bestDecisionStump['diem'] = diem bestDecisionStump['threshValue'] = threshValue bestDecisionStump['sepOperator'] = sepOperator bestPredictValue = predictValues.copy() return bestDecisionStump, minWeightedError, bestPredictValue def adaboostTrainDecisionStump(trainDataMatrix, trainClasses, iteratorCount=40): """ 基于单层决策树,对adaBoost算法进行训练 :param trainDataMatrix: 训练数据集 :param trainClasses: 训练数据集的标签 :param iteratorCount: 训练迭代次数 :return: """ trainClasses = np.matrix(trainClasses) # 保存迭代训练获得的决策树 bestDecisionStumps = [] m = np.shape(trainDataMatrix)[0] # 训练数据集样本的权重初始化相等 D = np.matrix(np.ones((m, 1)) / m) # 保存加权的最终预测结果 finalPredictClass = np.matrix(np.zeros((m, 1))) for i in range(0, iteratorCount): print '——————第 %d 轮训练——————' % i print '权重D:', D.T bestDecisionStump, minWeightedError, bestPredictValue = \ buildDecisionStump(trainDataMatrix, trainClasses, D) # 计算当前分类结果的错误率,作为样本的权重alpha alpha = 0.5 * np.log((1 - minWeightedError) / max(minWeightedError, 1e-16)) # 保存当前决策树分类结果的权重 bestDecisionStump['alpha'] = alpha bestDecisionStumps.append(bestDecisionStump) # print "本轮预测结果:", bestPredictValue.T # 根据前一轮预测获得的alpha结果权重更新样本的权重向量D # 前一轮预测结果正确的样本,减小其权重;预测结果错误的样本,增加其权重 # 计算公式: # 前一轮预测结果正确: # Di+1 = ( Di * exp(-alpha) ) / sum(Di) # 前一轮预测结果错误: # Di+1 = ( Di * exp(alpha) ) / sum(Di) print "alpha:", alpha expon = np.multiply(-1 * alpha * trainClasses.T, bestPredictValue) D = np.multiply(D, np.exp(expon)) / D.sum() # 加权预测结果 finalPredictClass += alpha * bestPredictValue # print "加权预测结果:", finalPredictClass.T # 加权后的预测结果错误的数目 weightedErrors = np.multiply(np.sign(finalPredictClass) != trainClasses.T, np.ones((m, 1))) # 计算加权后的错误率 errorRate = weightedErrors.sum() / m print "加权后此次训练的错误率:", errorRate if errorRate == 0.0: break return bestDecisionStumps def adaboostClassify(testDataMatrix, bestDecisionStumps): """ adaboost算法的分类函数 :param testDataMatrix: 测试的数据集 :param bestDecisionStumps: 训练adaboost算法获得的多个决策树策略 :return: """ testDataMatrix = np.matrix(testDataMatrix) m = np.shape(testDataMatrix)[0] weightedForecastClasses = np.matrix(np.zeros((m, 1))) for i in range(len(bestDecisionStumps)): # 用每个决策树算法测试数据 forecastClasses = simpleStumpClassify(testDataMatrix, bestDecisionStumps[i]['diem'], bestDecisionStumps[i]['threshValue'], bestDecisionStumps[i]['sepOperator']) # 计算加权后的类别 weightedForecastClasses += bestDecisionStumps[i]['alpha'] * forecastClasses # print weightedForecastClasses confidence = calConfidence(weightedForecastClasses) return weightedForecastClasses, confidence def calConfidence(weightedForecastClasses): """ 由预测的权重类别,计算分类的把握,计算Sigmoid函数值 :param weightedForecastClasses: 预测的权重类别 :return: """ confidence = 1 / (1 + np.exp(-1 * weightedForecastClasses)) for i in range(0, len(confidence)): if confidence[i] < 0.5: confidence[i] = 1 - confidence[i] return confidence
[ 2, 48443, 14629, 14, 8800, 14, 29412, 17, 13, 22, 198, 2, 4808, 9, 62, 19617, 25, 3384, 69, 12, 23, 4808, 9, 62, 198, 198, 37811, 198, 31, 13838, 25, 2940, 43, 16115, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 628, 198, 429...
1.417601
4,636
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import logging import os import django from applicationinsights.channel import ( AsynchronousSender, NullSender, SenderBase, SynchronousQueue, TelemetryChannel, ) from applicationinsights.channel.SenderBase import ( DEFAULT_ENDPOINT_URL as DEFAULT_ENDPOINT, ) from botbuilder.applicationinsights.django import common from django.test import TestCase, modify_settings, override_settings from rest_framework.test import RequestsClient # Note: MIDDLEWARE_CLASSES for django.VERSION <= (1, 10) MIDDLEWARE_NAME = "MIDDLEWARE" TEST_IKEY = "12345678-1234-5678-9012-123456789abc" TEST_ENDPOINT = "https://test.endpoint/v2/track" PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) @modify_settings( **{ MIDDLEWARE_NAME: { "append": "botbuilder.applicationinsights.django.ApplicationInsightsMiddleware", "prepend": "botbuilder.applicationinsights.django.BotTelemetryMiddleware", } } ) @override_settings( APPLICATION_INSIGHTS={"ikey": TEST_IKEY}, # Templates for 1.7 TEMPLATE_DIRS=(PROJECT_ROOT,), TEMPLATE_LOADERS=("django.template.loaders.filesystem.Loader",), # Templates for 1.8 and up TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [PROJECT_ROOT], } ], ) @modify_settings( **{ MIDDLEWARE_NAME: { "append": "botbuilder.applicationinsights.django.ApplicationInsightsMiddleware" } } ) @override_settings( LOGGING={ "version": 1, "handlers": { "appinsights": { "class": "botbuilder.applicationinsights.django.LoggingHandler", "level": "INFO", } }, "loggers": {__name__: {"handlers": ["appinsights"], "level": "INFO"}}, }, APPLICATION_INSIGHTS={"ikey": TEST_IKEY}, )
[ 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 198, 198, 11748, 18931, 198, 11748, 28686, 198, 198, 11748, 42625, 14208, 198, 6738, 3586, 1040, 2337, 13, 17620, 1330, 357, 198,...
2.325909
853
""" Cpu bound. see: https://docs.python.org/3/library/asyncio-eventloop.html#executing-code-in-thread-or-process-pools """ import os import time from datetime import datetime from logging import getLogger from multiprocessing.connection import Connection from signal import SIGTERM, signal from typing import Any, NoReturn, Optional from tests.testlibraries import SECOND_SLEEP_FOR_TEST_MIDDLE from tests.testlibraries.exceptions import Terminated from tests.testlibraries.local_socket import LocalSocket def cpu_bound(task_id: Optional[int] = None, send_process_id: bool = False) -> str: """ CPU-bound operations will block the event loop: in general it is preferable to run them in a process pool. """ try: logger = getLogger(__name__) signal(SIGTERM, hander) process_id = os.getpid() print(process_id) logger.info("CPU-bound: process id = %d", process_id) if send_process_id: time.sleep(SECOND_SLEEP_FOR_TEST_MIDDLE) logger.info("CPU-bound: Send process id") LocalSocket.send(str(process_id)) logger.info("CPU-bound: Start") result = sum(i * i for i in range(10 ** 7)) logger.debug("CPU-bound: Finish") logger.debug("%d %s", task_id, datetime.now()) return ("" if task_id is None else f"task_id: {task_id}, ") + f"result: {result}" except KeyboardInterrupt: logger.info("CPU-bound: KeyboardInterupt") raise
[ 37811, 198, 34, 19944, 5421, 13, 198, 3826, 25, 3740, 1378, 31628, 13, 29412, 13, 2398, 14, 18, 14, 32016, 14, 292, 13361, 952, 12, 15596, 26268, 13, 6494, 2, 18558, 15129, 12, 8189, 12, 259, 12, 16663, 12, 273, 12, 14681, 12, 774...
2.555172
580
#!/usr/bin/python # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import warnings import time from .metadata_normalizer import MetadataNormalizer import pandas as pd
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 198, 2, 15069, 12131, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287...
3.757895
190
import unittest from aiter import flatten_aiter, map_aiter, push_aiter from .helpers import run, get_n
[ 11748, 555, 715, 395, 628, 198, 6738, 257, 2676, 1330, 27172, 268, 62, 64, 2676, 11, 3975, 62, 64, 2676, 11, 4574, 62, 64, 2676, 628, 198, 6738, 764, 16794, 364, 1330, 1057, 11, 651, 62, 77, 628 ]
2.842105
38
from __future__ import absolute_import, division, print_function from mmtbx.wwpdb import rcsb_web_services def thorough_exercise(): """ This exercises all currently available options, so makes 64 requests. Took 20 minutes, therefore disabled from the general testing. """ lysozyme = """KVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL""" n_good = 0 for po in [True, False]: for do in [True, False]: for sbr in [True, False]: for xro in [True, False]: for d_max in [None, 3.0]: for d_min in [None, 1.0]: print ("ARGUMENTS:", po, do, sbr, xro, d_max, d_min) homologs = rcsb_web_services.sequence_search( lysozyme, xray_only=xro, d_max=d_max, d_min=d_min, protein_only=po, data_only=do, sort_by_resolution=sbr) if len(homologs) > 200: n_good += 1 print ("GOOD:", n_good) print (n_good) assert n_good == 64 if (__name__ == "__main__"): # thorough_exercise() exercise() exercise_2() print("OK")
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 6738, 8085, 83, 65, 87, 13, 1383, 79, 9945, 1330, 374, 6359, 65, 62, 12384, 62, 30416, 198, 198, 4299, 9321, 62, 1069, 23697, 33529, 198, 220, 37227,...
1.945055
637
from Main.AlphaZero.DistributedSelfPlay import Constants as C from Main.Training.Connect4 import SelfPlayWorker from Main import Hyperparameters import multiprocessing as mp
[ 6738, 8774, 13, 38077, 28667, 13, 20344, 6169, 24704, 11002, 1330, 4757, 1187, 355, 327, 201, 198, 6738, 8774, 13, 44357, 13, 13313, 19, 1330, 12189, 11002, 12468, 263, 201, 198, 6738, 8774, 1330, 15079, 17143, 7307, 201, 198, 11748, 18...
3.6
50
from os import system from config import admin_password class PrivilegedHelper: """ Privileged helper tool. Use carefully! """ def execute(self, command: str) -> int: """ Execute shell command with administrator privileges. :param str command: Shell script(command) to be executed. :return int: Return code. """ command_: str = command.replace('"', '\\"') osa_cmd: str = f'do shell script "{command_}" password "{self.admin_password}" with administrator privileges' return system(f"osascript -e '{osa_cmd}' > /dev/null 2>&1") privileged_helper = PrivilegedHelper(admin_password)
[ 6738, 28686, 1330, 1080, 198, 198, 6738, 4566, 1330, 13169, 62, 28712, 628, 198, 4871, 9243, 48446, 47429, 25, 198, 220, 220, 220, 37227, 9243, 48446, 31904, 2891, 13, 5765, 7773, 0, 37227, 628, 220, 220, 220, 825, 12260, 7, 944, 11, ...
2.856522
230
import tarfile from . import *
[ 11748, 13422, 7753, 198, 198, 6738, 764, 1330, 1635, 628 ]
3.3
10
import asyncio import json import ssl import asyncws from .exceptions import AuthenticationError, HomeAssistantError ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE
[ 11748, 30351, 952, 198, 11748, 33918, 198, 11748, 264, 6649, 198, 198, 11748, 30351, 18504, 198, 198, 6738, 764, 1069, 11755, 1330, 48191, 12331, 11, 5995, 48902, 12331, 198, 198, 45163, 62, 22866, 796, 264, 6649, 13, 17953, 62, 12286, ...
3.119048
84
import requests from bs4 import BeautifulSoup from urllib.parse import urljoin import urllib.request import os import ssl import time from PIL import Image import bs4 ssl._create_default_https_context = ssl._create_unverified_context url = 'https://www.foxsports.com/mlb/players?teamId=0&season=2019&position=0&page={}&country=0&grouping=0&weightclass=0' # urlを読み込んで、そのページのhtml要素を返す。 # urlのページから写真のurlと選手の名前を取り出す。 # 選手一覧のページから各選手へ繋がるurlを取得する。 # Half_or_Pure_appフォルダ内に選手画像を保存する。 for i in range(76, 100): url = 'https://www.foxsports.com/mlb/players?teamId=0&season=2019&position=0&page={}&country=0&grouping=0&weightclass=0'.format(i) print(url) save_player_photo(url) time.sleep(10)
[ 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 22179, 198, 11748, 2956, 297, 571, 13, 25927, 198, 11748, 28686, 198, 11748, 264, 6649, 198, 11748, 640, 198, 6738, 350, 4...
1.977778
360
import torch import logging from tame_pytorch import ManifoldModule, Network, L1Linear from grouped_adam import GroupedAdam import math num_inputs = 10 all_X, all_Y = adder_train_set(num_inputs) # all_X, all_Y = prime_train_set(num_inputs) # all_X, all_Y = sum_eq_train_set(num_inputs, 5) # all_X, all_Y = xor_train_set(num_inputs) # train_X, train_Y = rand_train_set(num_inputs) # torch.random.manual_seed(0) # train_mask = torch.rand([all_X.shape[0]]) < 0.5 # torch.random.seed() # train_X = all_X[train_mask, :] # train_Y = all_Y[train_mask, :] # test_X = all_X[~train_mask, :] # test_Y = all_Y[~train_mask, :] train_X = all_X # No separate test set here since we're not trying to generalize train_Y = all_Y test_X = all_X test_Y = all_Y # # print(train_Y) ensemble_size = 1 networks = [Network(widths=[num_inputs] + [128, 128, 128, 128, 64, 32, 16, 8] + [train_Y.shape[1]], pen_lin_coef=0.0, pen_lin_exp=2.0, pen_scale=0.0, arity=4, scale_init=1.0, scale_factor=1e-20, # 0.25, bias_factor=1e-20, # 0.1, act_factor=5.0, dtype=torch.float32, device=torch.device('cpu')) for _ in range(ensemble_size)] noise_factor0 = 0.0 noise_factor1 = 0.0 # 0.001 lr0 = 0.01 lr1 = 0.005 beta0 = 0.9 beta1 = 0.9 pen_act0 = 0.0 pen_act1 = 0.0 pen_lin_coef0 = 0.0 pen_lin_coef1 = 0.0 pen_scale0 = 0.0 # 0.1 pen_scale1 = 0.0 # 0.1 # optimizers = [torch.optim.Adam(networks[i].parameters(), lr=lr0, betas=(beta0, beta0), eps=1e-15) # for i in range(ensemble_size)] optimizers = [GroupedAdam(networks[i].parameters(), lr=lr0, betas=(beta0, beta0), eps=1e-15) for i in range(ensemble_size)] # optimizers = [torch.optim.SGD(networks[i].parameters(), lr=lr0, momentum=0.9) # for i in range(ensemble_size)] average_params = [[torch.zeros_like(p) for p in net.parameters()] for net in networks] # average_batch_norm_running_mean = [[torch.zeros_like(b._buffers['running_mean']) for b in net.bn_layers] for net in networks] # average_batch_norm_running_var = [[torch.zeros_like(b._buffers['running_var']) for b in net.bn_layers] for net in networks] average_param_beta = 0.98 average_param_weight = 0.0 epoch = 1 with torch.no_grad(): for net in networks: for mod in net.modules(): if isinstance(mod, ManifoldModule): mod.project() for _ in range(1, 10001): # if epoch % 100 == 1: # # print(networks[0].act_layers[0].params[:6, :] * networks[0].act_layers[0].act_factor) # print(networks[0].act_layers[0].params[:2, :, :] * networks[0].act_layers[0].act_factor) frac = min(epoch / 3000, 1.0) for net in networks: net.pen_scale = frac * pen_scale1 + (1 - frac) * pen_scale0 for layer in net.lin_layers: layer.pen_coef = frac * pen_lin_coef1 + (1 - frac) * pen_lin_coef0 total_loss = 0.0 total_obj = 0.0 for j, net in enumerate(networks): net.train() net.zero_grad() P = net(train_X) train_loss = compute_loss(P, train_Y) obj = train_loss + net.penalty() obj.backward() gn = torch.nn.utils.clip_grad_norm_(net.parameters(), 1.0) lr = lr0 * (1 - frac) + lr1 * frac beta = beta0 * (1 - frac) + beta1 * frac noise_factor = frac * noise_factor1 + (1 - frac) * noise_factor0 with torch.no_grad(): for mod in net.modules(): if isinstance(mod, L1Linear): noise = torch.rand_like(mod.weights_pos_neg.param) mod.weights_pos_neg.param *= (1 + noise_factor * noise) # mod.weights_pos_neg.param *= (1 + reaper_factor * lr) # optimizers[j].param_groups[0]['lr'] = lr optimizers[j].param_groups[0]['betas'] = (beta, beta) optimizers[j].step() total_loss += train_loss total_obj += obj with torch.no_grad(): for mod in net.modules(): if isinstance(mod, ManifoldModule): mod.project() for i, p in enumerate(net.parameters()): average_params[j][i] = average_param_beta * average_params[j][i] + (1 - average_param_beta) * p average_param_weight = average_param_beta * average_param_weight + (1 - average_param_beta) if epoch % 100 == 0: with torch.no_grad(): saved_params = [[p.data.clone() for p in net.parameters()] for net in networks] for j, net in enumerate(networks): for i, p in enumerate(net.parameters()): p.data = average_params[j][i] / average_param_weight for net in networks: net.eval() test_P = sum(net(test_X) for net in networks) / ensemble_size test_loss = compute_loss(test_P, test_Y) test_acc = torch.mean(torch.all(torch.sgn(test_P) == torch.sgn(test_Y), dim=1).to(torch.float32)) for j, net in enumerate(networks): for i, p in enumerate(net.parameters()): p.data = saved_params[j][i] # act_fracs = [] # for layer in networks[0].act_layers: # act_fracs.append(torch.mean((layer.X >= 0).to(torch.float32))) # act_fracs_fmt = '[{}]'.format(', '.join('{:.3f}'.format(f) for f in act_fracs)) # # act_avgs = [] # for layer in networks[0].act_layers: # act_avgs.append(torch.mean(torch.clamp(layer.X, min=0.0))) # act_avgs_fmt = '[{}]'.format(', '.join('{:.3f}'.format(f) for f in act_avgs)) wt_fracs = [] for layer in networks[0].lin_layers: weights = layer.weights_pos_neg.param[:layer.input_width, :] - layer.weights_pos_neg.param[ layer.input_width:, :] wt_fracs.append(torch.sum(weights != 0).to(torch.float32) / layer.weights_pos_neg.param.shape[1]) # weights = layer.weight # wt_fracs.append(torch.mean((weights != 0).to(torch.float32))) wt_fracs_fmt = '[{}]'.format(', '.join('{:.3f}'.format(f) for f in wt_fracs)) lr = optimizers[0].param_groups[0]['lr'] # lr = optimizers[0].param_groups[0]['lr'] logging.info( "{}: lr={:.6f}, train={:.6f}, obj={:.6f}, test={:.6f}, acc={:.6f}, wt={}, scale={:.3f}, gn={:.3g}".format( epoch, lr, total_loss / ensemble_size / train_X.shape[0], total_obj / ensemble_size / train_X.shape[0], float(test_loss / test_X.shape[0]), float(test_acc), wt_fracs_fmt, torch.max(torch.abs(networks[0].scale) * networks[0].scale_factor).item(), gn)) epoch += 1
[ 11748, 28034, 198, 11748, 18931, 198, 6738, 37812, 62, 9078, 13165, 354, 1330, 1869, 361, 727, 26796, 11, 7311, 11, 406, 16, 14993, 451, 198, 6738, 32824, 62, 324, 321, 1330, 4912, 276, 23159, 198, 11748, 10688, 628, 628, 628, 628, 62...
1.932821
3,647
# -*- coding: utf-8 -*- """ Created on Mon May 16 00:27:50 2016 @author: Hossam Faris """ import random import numpy import math from solution import solution import time
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 1737, 1467, 3571, 25, 1983, 25, 1120, 1584, 198, 198, 31, 9800, 25, 367, 793, 321, 6755, 271, 198, 37811, 198, 198, 11748, 4738, 198, 117...
2.916667
60
# -*- coding: utf-8 -*- if __name__ == '__main__': main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 220, 220, 220, 1388, 3419, 201, 198 ]
1.775
40
import or_gym import numpy as np env_name = 'InvManagement-v3' env = or_gym.make(env_name) action = env.action_space.sample() env.step(action) # z = np.ones(env.num_stages-1) # print(env.base_stock_action(z))
[ 11748, 393, 62, 1360, 76, 198, 11748, 299, 32152, 355, 45941, 198, 198, 24330, 62, 3672, 796, 705, 19904, 48032, 12, 85, 18, 6, 198, 198, 24330, 796, 393, 62, 1360, 76, 13, 15883, 7, 24330, 62, 3672, 8, 198, 2673, 796, 17365, 13, ...
2.370787
89
""" Author: Ibrahim Sherif Date: December, 2021 This script used for ingesting data """ import os import sys import logging import pandas as pd from datetime import datetime from config import DATA_PATH, INPUT_FOLDER_PATH logging.basicConfig(stream=sys.stdout, level=logging.INFO) def merge_multiple_dataframe(): """ Function for data ingestion. Check for datasets, combine them together, drops duplicates and write metadata ingestedfiles.txt and ingested data to finaldata.csv """ df = pd.DataFrame() file_names = [] logging.info(f"Reading files from {INPUT_FOLDER_PATH}") for file in os.listdir(INPUT_FOLDER_PATH): file_path = os.path.join(INPUT_FOLDER_PATH, file) df_tmp = pd.read_csv(file_path) file = os.path.join(*file_path.split(os.path.sep)[-3:]) file_names.append(file) df = df.append(df_tmp, ignore_index=True) logging.info("Dropping duplicates") df = df.drop_duplicates().reset_index(drop=1) logging.info("Saving ingested metadata") with open(os.path.join(DATA_PATH, 'ingestedfiles.txt'), "w") as file: file.write( f"Ingestion date: {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}\n") file.write("\n".join(file_names)) logging.info("Saving ingested data") df.to_csv(os.path.join(DATA_PATH, 'finaldata.csv'), index=False) if __name__ == '__main__': logging.info("Running ingestion.py") merge_multiple_dataframe()
[ 37811, 198, 13838, 25, 30917, 6528, 361, 198, 10430, 25, 3426, 11, 33448, 198, 1212, 4226, 973, 329, 26151, 278, 1366, 198, 37811, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 18931, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738,...
2.53886
579
import serial import time if __name__ == "__main__": while True: # for freq in [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 128000, 230400, 256000, 460800, 500000, 675000, 921600, 1000000]: test_string = b"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*();:'{}[]|,./" for bytesize in [7,8]: for parity in [serial.PARITY_NONE, serial.PARITY_EVEN, serial.PARITY_ODD]: for stopbits in [serial.STOPBITS_ONE, serial.STOPBITS_TWO]: print(freq, end=' ') print(bytesize, end="") if parity == serial.PARITY_NONE: print("N", end="") elif parity == serial.PARITY_EVEN: print("E", end="") else: print("O", end="") if stopbits == serial.STOPBITS_ONE: print("1", end="") else: print("2", end="") print() with serial.Serial('/dev/ttyUSB0', baudrate=freq, timeout=1, parity=parity, stopbits=stopbits, bytesize=bytesize) as ftdi: with serial.Serial('/dev/ttyACM0', baudrate=freq, timeout=1, parity=parity, stopbits=stopbits, bytesize=bytesize) as turtle: turtle.flushInput() ftdi.flushInput() turtle.write(test_string) result = ftdi.read(len(test_string)) print("turtle->ftdi received:", result) assert result == test_string ftdi.write(test_string) result = turtle.read(len(test_string)) print("ftdi->turtle received:", result) assert result == test_string print()
[ 11748, 11389, 198, 11748, 640, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 981, 6407, 25, 198, 220, 220, 220, 220, 220, 220, 220, 1303, 198, 220, 220, 220, 220, 220, 220, 220, 329, 2030, ...
1.601757
1,366
import argparse import config from utils import cwd if __name__ == '__main__': parser = argparse.ArgumentParser('Verify datasets.') parser.add_argument( 'files', nargs='*', default=( config.FILE_TRAINING, config.FILE_VALIDATION, config.FILE_TESTING ), ) parser.add_argument( '--no-debug', dest='debug', action='store_const', const=False, default=True, ) parser.add_argument( '--data-dir', default=config.DATA_DIR ) args = parser.parse_args() with cwd(args.data_dir): for filename in args.files: counter = verify_single(filename) if args.debug: print(f'{filename} has {counter} datapoints')
[ 11748, 1822, 29572, 198, 198, 11748, 4566, 198, 6738, 3384, 4487, 1330, 269, 16993, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 30751, 796, 1822, 29572, 13, 28100, 1713, 46677, 10786, 134...
2.025189
397
""" ******************************************************************************** compas_igs.utilities ******************************************************************************** .. currentmodule:: compas_igs.utilities .. autosummary:: :toctree: generated/ compute_force_drawingscale compute_force_drawinglocation compute_form_forcescale """ from __future__ import absolute_import from .displaysettings import * # noqa: F401 F403 from .equilibrium import * # noqa: F401 F403 __all__ = [name for name in dir() if not name.startswith('_')]
[ 37811, 198, 17174, 17174, 8412, 198, 5589, 292, 62, 9235, 13, 315, 2410, 198, 17174, 17174, 8412, 198, 198, 492, 1459, 21412, 3712, 552, 292, 62, 9235, 13, 315, 2410, 628, 198, 492, 44619, 388, 6874, 3712, 198, 220, 220, 220, 1058, ...
3.781457
151
from __future__ import unicode_literals from djangobmf.apps import ContribTemplate
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 648, 672, 76, 69, 13, 18211, 1330, 2345, 822, 30800, 628 ]
3.4
25
import numpy as np from .variable import VariableScalar from .expression import make_Expression
[ 11748, 299, 32152, 355, 45941, 198, 6738, 764, 45286, 1330, 35748, 3351, 282, 283, 198, 6738, 764, 38011, 1330, 787, 62, 16870, 2234, 198 ]
4
24
# Copyright (c) 2014 Scopely, Inc. # Copyright (c) 2015 Mitch Garnaat # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. import logging import datetime from collections import namedtuple import jmespath import common.awsclient as awsclient from inventory.resources.resource import Resource LOG = logging.getLogger(__name__) class MetricData(object): """ This is a simple object that allows us to compose both the returned data from a call to ``get_metrics_data`` as well as the period that was used when getting the data from CloudWatch. Since the period may be calculated by ``get_metrics_data`` rather than passed explicitly the user would otherwise not how what the period value was. """ class AWSResource(Resource): """ Each Resource class defines a Config variable at the class level. This is a dictionary that gives the specifics about which service the resource belongs to and how to enumerate the resource. Each entry in the dictionary we define: * service - The AWS service in which this resource is defined. * enum_spec - The enumeration configuration. This is a tuple consisting of the name of the operation to call to enumerate the resources, a jmespath query that will be run against the result of the operation to retrieve the list of resources, and a dictionary containing any extra arguments you want to pass in the enumeration call. This can be None if no additional arguments are required. * tags_spec - Some AWS resources return the tags for the resource in the enumeration operation (e.g. DescribeInstances) while others require a second operation to retrieve the tags. If a second operation is required the ``tags_spec`` describes how to make the call. It is a tuple consisting of: * operation name * jmespath query to find the tags in the response * the name of the parameter to send to identify the specific resource (this is not always the same as filter_name, e.g. RDS) * the value of the parameter to send to identify the specific resource (this is not always the same as the id, e.g. RDS) * detail_spec - Some services provide only summary information in the list or describe method and require you to make another request to get the detailed info for a specific resource. If that is the case, this would contain a tuple consisting of the operation to call for the details, the parameter name to pass in to identify the desired resource and the jmespath filter to apply to the results to get the details. * id - The name of the field within the resource data that uniquely identifies the resource. * dimension - The CloudWatch dimension for this resource. A value of None indicates that this resource is not monitored by CloudWatch. * filter_name - By default, the enumerator returns all resources of a given type. But you can also tell it to filter the results by passing in a list of id's. This parameter tells it the name of the parameter to use to specify this list of id's. """ @classmethod @property @property @property def tags(self): """ Convert the ugly Tags JSON into a real dictionary and memorize the result. """ if self._tags is None: LOG.debug('need to build tags') self._tags = {} if hasattr(self.Meta, 'tags_spec'): LOG.debug('have a tags_spec') method, path, param_name, param_value = self.Meta.tags_spec kwargs = {} filter_type = getattr(self.Meta, 'filter_type', None) if filter_type == 'list': kwargs = {param_name: [getattr(self, param_value)]} else: kwargs = {param_name: getattr(self, param_value)} LOG.debug('fetching tags') self.data['Tags'] = self._client.call( method, query=path, **kwargs) LOG.debug(self.data['Tags']) if 'Tags' in self.data: for kvpair in self.data['Tags']: if kvpair['Key'] in self._tags: if not isinstance(self._tags[kvpair['Key']], list): self._tags[kvpair['Key']] = [self._tags[kvpair['Key']]] self._tags[kvpair['Key']].append(kvpair['Value']) else: self._tags[kvpair['Key']] = kvpair['Value'] return self._tags def get_metric_data(self, metric_name=None, metric=None, days=None, hours=1, minutes=None, statistics=None, period=None): """ Get metric data for this resource. You can specify the time frame for the data as either the number of days or number of hours. The maximum window is 14 days. Based on the time frame this method will calculate the correct ``period`` to return the maximum number of data points up to the CloudWatch max of 1440. :type metric_name: str :param metric_name: The name of the metric this data will pertain to. :type days: int :param days: The number of days worth of data to return. You can specify either ``days`` or ``hours``. The default is one hour. The maximum value is 14 days. :type hours: int :param hours: The number of hours worth of data to return. You can specify either ``days`` or ``hours``. The default is one hour. The maximum value is 14 days. :type statistics: list of str :param statistics: The metric statistics to return. The default value is **Average**. Possible values are: * Average * Sum * SampleCount * Maximum * Minimum :returns: A ``MetricData`` object that contains both the CloudWatch data as well as the ``period`` used since this value may have been calculated by skew. """ if not statistics: statistics = ['Average'] if days: delta = datetime.timedelta(days=days) elif hours: delta = datetime.timedelta(hours=hours) else: delta = datetime.timedelta(minutes=minutes) if not period: period = max(60, self._total_seconds(delta) // 1440) if not metric: metric = self.find_metric(metric_name) if metric and self._cloudwatch: end = datetime.datetime.utcnow() start = end - delta data = self._cloudwatch.call( 'get_metric_statistics', Dimensions=metric['Dimensions'], Namespace=metric['Namespace'], MetricName=metric['MetricName'], StartTime=start.isoformat(), EndTime=end.isoformat(), Statistics=statistics, Period=period) return MetricData(jmespath.search('Datapoints', data), period) else: raise ValueError('Metric (%s) not available' % metric_name) ArnComponents = namedtuple('ArnComponents', ['scheme', 'provider', 'service', 'region', 'account', 'resource'])
[ 2, 15069, 357, 66, 8, 1946, 41063, 306, 11, 3457, 13, 198, 2, 15069, 357, 66, 8, 1853, 20472, 402, 28610, 265, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 11074, 921, 198, 2, 743...
2.541078
3,116
from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import FormView from django.contrib.auth.decorators import login_required from .forms import SearchMovieForm, MovieForm from .models import Movie MAX_RETRIES = 3 @login_required()
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 19816, 1040, 1330, 23093, 37374, 35608, 259, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 7343, 7680, 11, 42585, 7680, 198, ...
3.462264
106
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() import datetime """ Base Case: Generate Cumulative Rewards with no battery use """ """ Naive TOU Case: Generate Cumulative Rewards optimized on peak/non-peak TOU nonpeak: lowest tariff price peak: all other prices battery charges/discharges at power rating """ if __name__ == "__main__": df = pd.read_csv(r"load_tariff.csv") # make_base_csv(df) make_naiveTOU_csv(df) # #Plot compare # df1= pd.read_csv(r'naive.csv') # df2 = pd.read_csv(r'base.csv') # times = pd.to_datetime(df1.local_15min) # fig, ax1 = plt.subplots(1, 1, figsize=(10,6)) # #Plot # fig.autofmt_xdate() # plt.gcf().autofmt_xdate() # xfmt = mdates.DateFormatter('%m-%d-%y %H:%M') # ax1.xaxis.set_major_formatter(xfmt) # ax1.set_xlabel('Date') # ax1.set_ylabel('Power, kW') # # p1 = ax1.plot(times, bat_pow) # p2 = ax1.plot(times, df1['R_naive']) # p3 = ax1.plot(times, df2['R_base']) ############ # color = 'tab:red' # ax2 = ax1.twinx() # ax2.set_ylabel('Energy Price, $/kWh', color=color) # # p4 = ax2.plot(times, tariff, color=color) # ax2.tick_params(axis='y', labelcolor=color) # ax2.set_ylim([0,1.1*max(tariff)]) # ax2.xaxis.set_major_formatter(xfmt) # # plt.legend((p1[0], p2[0], p3[0], p4[0]), ('Battery Power', 'Load Power', 'Grid Power', 'Tariff Rate'), loc='best') # fig.tight_layout() # otherwise the right y-label is slightly clipped # # plt.savefig('opt_ex_tariff.png') plt.show() # fig, ax1 = plt.subplots(1, 1, figsize=(10,6)) # fig.autofmt_xdate() # plt.gcf().autofmt_xdate() # xfmt = mdates.DateFormatter('%m-%d-%y %H:%M') # ax1.xaxis.set_major_formatter(xfmt) # ax1.set_xlabel('Date') # ax1.set_ylabel('Power, kW') # p1 = ax1.plot(times, bat_pow) # p2 = ax1.plot(times, load) # p3 = ax1.plot(times, grd_pow.value) # color = 'tab:purple' # ax2 = ax1.twinx() # ax2.set_ylabel('Energy, kWh', color=color) # p4 = ax2.plot(times, bat_eng.value, color=color) # ax2.tick_params(axis='y', labelcolor=color) # ax2.set_ylim([0,BAT_KWH]) # ax2.xaxis.set_major_formatter(xfmt)
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 19581, 355, 285, 19581, 198, 198, 6738, 19798, 292, 13, 29487, ...
2.163004
1,092
import numpy import time
[ 11748, 299, 32152, 198, 11748, 640 ]
4
6
#!/usr/bin/env python3 import unittest from unittest.mock import Mock, patch import sys, os from io import StringIO from rt_runticket_manager import RTManager, AuthorizationError, main RT_SETTINGS = os.path.abspath(os.path.dirname(__file__) + '/rt_settings.ini') if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 11, 8529, 198, 11748, 25064, 11, 28686, 198, 6738, 33245, 1330, 10903, 9399, 198, 198, 6738, 374, 83, 62...
2.745614
114
"""Define function to sort and merge an unsorted array.""" def mergesort(arr): """Define merge sort.""" left = arr[:len(arr)//2] right = arr[len(arr)//2:] if len(left) > 1: left = mergesort(left) if len(right) > 1: right = mergesort(right) lst = [] i, j = 0, 0 while i < len(left) and j < len(right): if left[i] < right[j]: lst.append(left[i]) i += 1 elif left[i] > right[j]: lst.append(right[j]) j += 1 else: lst.append(left[i]) lst.append(right[j]) i += 1 j += 1 for _ in range(i, len(left)): lst.append(left[_]) for _ in range(j, len(right)): lst.append(right[_]) return lst
[ 37811, 7469, 500, 2163, 284, 3297, 290, 20121, 281, 5576, 9741, 7177, 526, 15931, 628, 198, 4299, 4017, 3212, 419, 7, 3258, 2599, 198, 220, 220, 220, 37227, 7469, 500, 20121, 3297, 526, 15931, 198, 220, 220, 220, 1364, 796, 5240, 58, ...
1.850356
421
""" Example of flow control and the case statement """ def flow_control_prime(): """ example of nested loops and break statement """ for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n/x) break else: # loop fell through without finding a factor print(n, 'is a prime number')
[ 37811, 198, 16281, 286, 5202, 1630, 290, 262, 1339, 2643, 198, 37811, 628, 628, 198, 198, 4299, 5202, 62, 13716, 62, 35505, 33529, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1672, 286, 28376, 23607, 290, 2270, 2643, 198, 220, 220,...
2.060465
215
# -*- coding:utf-8 -*- ''' MIT License Copyright (c) 2019 李俊諭 JYUN-YU LI 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 import numpy as np class Config(object): ''' ASR project basic argument settings ''' ''' ----------------------------------------------------------------------------------------------------------------------------------------------------------------- data sources settings ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' # Data sources for wav file settings , directory name and path Audio_Data_Directory_Root = "/home/jyu/Data" Audio_Data_DirectoryName = "audio_data" # Generate a full data sources path Audio_Data_Path = os.path.join( Audio_Data_Directory_Root, Audio_Data_DirectoryName ) # Data sources for prediction file settings , directory name and path Prediction_Audio_Data_Directory_Root = "/home/jyu/Data" Prediction_Audio_Data_DirectoryName = "prediction_data" # Generate a full data sources path Prediction_Audio_Data_Path = os.path.join( Prediction_Audio_Data_Directory_Root, Prediction_Audio_Data_DirectoryName ) ''' ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' ''' ----------------------------------------------------------------------------------------------------------------------------------------------------------------- wav data basic argument settings ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' data_quantity_max = 450 # limit wav data quantity for each class sample_rate = 16000 max_pad_len = 11 class_num = 0 # class number start value channel = 1 # single channel labels = [] MFCC_Data = [] Train_DataSet = [] Train_Labels = [] Test_DataSet = [] Test_Labels = [] Valid_DataSet = [] Valid_Labels = [] data_row = 0 data_column = 0 ''' ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' ''' ----------------------------------------------------------------------------------------------------------------------------------------------------------------- SQLite DB settings ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' SQLite_DB_DirectoryName = "DB" SQLite_name = "class.db3" db_TableName = 'audioclass' column_ClassNum = 'ClassNum' column_Classname = 'ClassName' ''' ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' ''' ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ouput log settings ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' # general ouput log Log_DirectoryName = "log_file" log_file_type = "txt" Log_FeatureData_DirectoryName = "audio_feature" Log_ClassLabelsData_DirectoryName = "audio_classlabels" Log_Recognition_Result_DirectoryName = "recognition_result" Log_ClassLabelsData_name = str( Log_ClassLabelsData_DirectoryName + "." + log_file_type ) # for TensorBoard Log_TensorBoard_DirectoryName = "TensorBoard" Log_TensorBoard_Path = os.path.join( os.getcwd(), Log_DirectoryName, Log_TensorBoard_DirectoryName, "logs" ) # 輸出訓練過程變化圖檔案放置目錄 Plot_Figure_DirectoryName = "plot_figure" ''' ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' ''' ----------------------------------------------------------------------------------------------------------------------------------------------------------------- model settings ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ''' # 訓練後模型儲存參數設置 Model_DirectoryName = "model" Model_Name = "Speech_Recognition_Model.h5" Model_Weight_Name = "Speech_Recognition_Weight.h5" Model_Path = os.path.join( os.getcwd(), Model_DirectoryName, Model_Name ) Model_Weight_Path = os.path.join( os.getcwd(), Model_DirectoryName, Model_Weight_Name ) Model_checkpoints_DirectoryName = "checkpoints" Model_checkpoints_Path = os.path.join( os.getcwd(), Model_checkpoints_DirectoryName, Model_checkpoints_DirectoryName ) # 轉換模型參數設置 Input_Model_Path = os.path.join(os.getcwd(), "model") Output_Model_Name = "ASR_Model.tflite" Output_Model_Path = os.path.join( os.getcwd(), "tflite_model", Output_Model_Name ) # model checkpoint Model_ModelCheckpoint_DirectoryName = "ModelCheckpoint" Model_ModelCheckpoint_Path = os.path.join( os.getcwd(), Model_DirectoryName, Model_ModelCheckpoint_DirectoryName ) # model save path Model_PB_DirectoryName = "model_pb" Model_PB_Name = "frozen_model.pb" Model_PB_Path = os.path.join( os.getcwd(), Model_DirectoryName, Model_PB_DirectoryName, Model_PB_Name ) # model layers name , input layer and ouput layer input_arrays = ["conv2d_input"] output_arrays = ["dense_1/Softmax"] ''' ----------------------------------------------------------------------------------------------------------------------------------------------------------------- '''
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 201, 198, 201, 198, 7061, 6, 201, 198, 36393, 13789, 201, 198, 201, 198, 15269, 357, 66, 8, 13130, 10545, 251, 236, 46479, 232, 164, 104, 255, 449, 56, 4944, 12, 56, 52, 246...
3.297844
2,273
#!/usr/bin/python # Copyright (C) 2012 Ion Torrent Systems, Inc. All Rights Reserved import os import subprocess import traceback import numpy import ConfigParser from ion.reports import beadDensityPlot, plotKey from ion.utils.blockprocessing import printtime, isbadblock """ def mergeRawPeakSignals(dirs): ############################################### # Merge raw_peak_signal files # ############################################### printtime("Merging raw_peak_signal files") try: raw_peak_signal_files = [] for subdir in dirs: printtime("DEBUG: %s:" % subdir) if isbadblock(subdir, "Merging raw_peak_signal files"): continue raw_peak_signal_file = os.path.join(subdir,'raw_peak_signal') if os.path.exists(raw_peak_signal_file): raw_peak_signal_files.append(raw_peak_signal_file) else: printtime("ERROR: Merging raw_peak_signal files: skipped %s" % raw_peak_signal_file) composite_raw_peak_signal_file = "raw_peak_signal" blockprocessing.merge_raw_key_signals(raw_peak_signal_files, composite_raw_peak_signal_file) except: printtime("Merging raw_peak_signal files failed") printtime("Finished mergeRawPeakSignals") """
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 357, 34, 8, 2321, 36404, 43399, 11998, 11, 3457, 13, 1439, 6923, 33876, 198, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 12854, 1891, 198, 11748, 299, 32152, 198, 11748, ...
2.443831
543
# -*- coding: utf-8 -*- """ @Author : captain @time : 18-7-10 下午8:42 @ide : PyCharm """ from .TextCNN import TextCNN from .LSTM import LSTM from .FastText import FastText from .RCNN import RCNN from .RCNN1 import RCNN1 from .AttLSTM import AttLSTM from .GRU import GRU from .Inception import InCNN from .bigru_att import bigru_attention
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 31, 13838, 220, 1058, 10654, 198, 31, 2435, 220, 220, 220, 1058, 1248, 12, 22, 12, 940, 220, 10310, 233, 39355, 230, 23, 25, 3682, 198, 31, 485, 220...
2.423611
144
import os from config import StandardConfig, ArgparseConfig, COPWithModifiableDefaults, ConfigOptionMetadata, \ ConfigDefaultModification, ConfigPackageProvider from config.config_option_packages import NameCOP, SaveDataCOP, OverwriteCOP, VisualizeCOP, ContinueCOP from tracking.face_aabbox_tracking import FaceAABBoxTrackingMethod, face_aabbox_tracker_class from tracking.face_alignment_tracking import FaceAlignmentTrackingMethod, face_alignment_tracker_class if __name__ == '__main__': config = CaptureStandardConfig() config["name"] = 'new_data' config.gather_options() config.print(detailed_package_description=False) print(len(vars(config.options))) args = ['--name', 'new_data'] config = CaptureArgparseConfig(args) config.gather_options() config.print(detailed_package_description=False) print(len(vars(config.options)))
[ 11748, 28686, 198, 198, 6738, 4566, 1330, 8997, 16934, 11, 20559, 29572, 16934, 11, 27975, 3152, 5841, 16823, 7469, 13185, 11, 17056, 19722, 9171, 14706, 11, 3467, 198, 220, 220, 220, 17056, 19463, 5841, 2649, 11, 17056, 27813, 29495, 198...
3.135231
281
#!/usr/bin/env python """Script that produced the test data. """ from pathlib import Path import numpy as np import pandas as pd if __name__ == "__main__": create_test_data()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 7391, 326, 4635, 262, 1332, 1366, 13, 198, 37811, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 628, 19...
2.875
64
# Copyright (C) 2021 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions # and limitations under the License. from attr import attrs from sys import maxsize from ote_sdk.configuration.elements import (ParameterGroup, add_parameter_group, boolean_attribute, configurable_boolean, configurable_float, configurable_integer, selectable, string_attribute) from ote_sdk.configuration.configurable_parameters import ConfigurableParameters from ote_sdk.configuration.enums import ModelLifecycle, AutoHPOState from .configuration_enums import POTQuantizationPreset, Models @attrs
[ 2, 15069, 357, 34, 8, 33448, 8180, 10501, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, ...
2.304422
588
import re from re import match from gluon.contrib.login_methods.email_auth import email_auth #from gluon.contrib.login_methods.gae_google_account import GaeGoogleAccount from gluon.tools import * auth = Auth(globals(), db) auth.define_tables() auth.settings.create_user_groups = False auth.settings.actions_disabled = ['request_reset_password'] auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = False auth.settings.register_next = URL (a = request.application, c = 'default', f = 'user') auth.settings.login_next = URL (scheme = 'http', a = request.application, c = 'default', f = 'index.html') auth.settings.login_methods.append( email_auth("smtp.gmail.com:587", "@gmail.com")) #auth.settings.login_form = GaeGoogleAccount () try: admin_role = auth.id_group ("Administrator") dev_role = auth.id_group ("Developer") auth_role = auth.id_group ("Authenticated") writer_role = auth.id_group ("Writer") editor_role = auth.id_group ("Editor") except: admin_role = None dev_role = None auth_role = None writer_role = None editor_role = None
[ 11748, 302, 198, 6738, 302, 1330, 2872, 198, 6738, 1278, 84, 261, 13, 3642, 822, 13, 38235, 62, 24396, 82, 13, 12888, 62, 18439, 1330, 3053, 62, 18439, 198, 2, 6738, 1278, 84, 261, 13, 3642, 822, 13, 38235, 62, 24396, 82, 13, 2500...
2.722477
436
import unittest from board import Direction, Board import tests.testdata as testdata
[ 11748, 555, 715, 395, 198, 6738, 3096, 1330, 41837, 11, 5926, 198, 11748, 5254, 13, 9288, 7890, 355, 1332, 7890, 198 ]
4.047619
21
""" Tests meant to be run with pytest """ import pytest from moviepy.editor import * @pytest.fixture
[ 37811, 198, 51, 3558, 4001, 284, 307, 1057, 351, 12972, 9288, 198, 37811, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 3807, 9078, 13, 35352, 1330, 1635, 628, 198, 31, 9078, 9288, 13, 69, 9602, 198, 197, 198 ]
2.815789
38
from settings import DB_URL, DB_USER, DB_PASSWORD, DB_NAME from sqlalchemy.ext.automap import automap_base from sqlalchemy import create_engine
[ 6738, 6460, 1330, 20137, 62, 21886, 11, 20137, 62, 29904, 11, 20137, 62, 47924, 54, 12532, 11, 20137, 62, 20608, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 2306, 296, 499, 1330, 3557, 499, 62, 8692, 198, 6738, 44161, 282, 26599, 1330...
3.152174
46
import unittest import uuid import lusid import lusid.models as models from lusid import OrderRequest from lusid import OrderSetRequest from lusid import PerpetualProperty from lusid import PropertyValue from lusid import ResourceId from lusidfeature import lusid_feature from utilities import InstrumentLoader from utilities import TestDataUtilities
[ 11748, 555, 715, 395, 198, 11748, 334, 27112, 198, 11748, 300, 385, 312, 198, 11748, 300, 385, 312, 13, 27530, 355, 4981, 198, 6738, 300, 385, 312, 1330, 8284, 18453, 198, 6738, 300, 385, 312, 1330, 8284, 7248, 18453, 198, 6738, 300, ...
3.815217
92
import unittest from test import support from test.support import check_sanitizer if check_sanitizer(address=True, memory=True): raise unittest.SkipTest("Tests involvin libX11 can SEGFAULT on ASAN/MSAN builds") # Skip test if _tkinter wasn't built. support.import_module('_tkinter') # Skip test if tk cannot be initialized. support.requires('gui') if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 1332, 1330, 1104, 198, 6738, 1332, 13, 11284, 1330, 2198, 62, 12807, 3029, 263, 198, 198, 361, 2198, 62, 12807, 3029, 263, 7, 21975, 28, 17821, 11, 4088, 28, 17821, 2599, 198, 220, 220, 220, 5298, 55...
3.014925
134
import pavilion.sys_vars.base_classes as dumb_system_plugins class DumbSysVar(dumb_system_plugins.SystemPlugin): """An always deferred system variable."""
[ 11748, 45549, 29935, 13, 17597, 62, 85, 945, 13, 8692, 62, 37724, 355, 13526, 62, 10057, 62, 37390, 628, 198, 4871, 42989, 44387, 19852, 7, 67, 2178, 62, 10057, 62, 37390, 13, 11964, 37233, 2599, 198, 220, 220, 220, 37227, 2025, 1464,...
3.354167
48
from os.path import exists from src.distribution_function import ( GaussianProbabilisticDistributionHandler, BetaProbabilisticDistributionHandler ) import cv2 def examine_show_or_save_figure_function(distribution_type: str) -> None: '''Test show_figure, save_figure function. Args: distribution_type: 'gaussian' or 'beta' ''' if distribution_type == 'gaussian': distribution = GaussianProbabilisticDistributionHandler() elif distribution_type == 'beta': distribution = BetaProbabilisticDistributionHandler() else: raise NotImplementedError('Distriution type should be "gaussian" or "beta"') fig_path_all = distribution.save_figure() for fig_path in fig_path_all: assert exists(fig_path), 'File does not exist' assert fig_path.split('.')[-1] == 'png',\ 'File extension should be "png"' fig = cv2.imread(fig_path) assert fig is not None, 'Figure is None'
[ 6738, 28686, 13, 6978, 1330, 7160, 198, 6738, 12351, 13, 17080, 3890, 62, 8818, 1330, 357, 198, 220, 220, 220, 12822, 31562, 2964, 65, 14991, 2569, 20344, 3890, 25060, 11, 198, 220, 220, 220, 17993, 2964, 65, 14991, 2569, 20344, 3890, ...
2.679452
365
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from collections import OrderedDict from torch import Tensor from typing import Any, List, Tuple from spectrai.networks.layers import BasicConv from spectrai.networks.layer_utils import get_normalization, get_pooling # ------------------------------------------------------------ # DenseNet # ------------------------------------------------------------ # This code is adapted from: https://github.com/pytorch/vision/blob/master/torchvision/models/densenet.py # The corresponding paper is: # Gao Huang, Zhuang Liu, Laurens van der Maaten # Deeply Connected Convolutional Networks # IEEE Conference on Computer Vision and Pattern Recognition, 2017 # Available from: https://arxiv.org/abs/1608.06993 class DenseNet(nn.Module): r"""Densenet-BC model class, based on `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_. Args: growth_rate (int) - how many filters to add each layer (`k` in paper) block_config (list of 4 ints) - how many layers in each pooling block num_init_features (int) - the number of filters to learn in the first convolution layer bn_size (int) - multiplicative factor for number of bottle neck layers (i.e. bn_size * k features in the bottleneck layer) drop_rate (float) - dropout rate after each dense layer num_classes (int) - number of classification classes memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient, but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_. """
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 28034, 13, 26791, 13, 9122, 4122, 355, 31396, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 6738, 28034, 1330,...
3.049911
561
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Unittets for S3 objectstore clone. """ import boto from boto import exception as boto_exception from boto.s3 import connection as s3 import fixtures from oslo_config import cfg from oslo_config import fixture as config_fixture from oslotest import base as test_base from ec2api.s3 import s3server CONF = cfg.CONF class S3APITestCase(test_base.BaseTestCase): """Test objectstore through S3 API.""" def setUp(self): """Setup users, projects, and start a test server.""" super(S3APITestCase, self).setUp() tempdir = self.useFixture(fixtures.TempDir()) conf = self.useFixture(config_fixture.Config()) conf.config(buckets_path=tempdir.path, s3_listen='127.0.0.1', s3_listen_port=0) self.server = s3server.get_wsgi_server() # NOTE(ft): this requires eventlet.monkey_patch, which is called in # tests/unit/__init__.py. Remove it out from there if you get these # tests rid of server run self.server.start() self.addCleanup(self.server.stop) if not boto.config.has_section('Boto'): boto.config.add_section('Boto') boto.config.set('Boto', 'num_retries', '0') conn = s3.S3Connection(aws_access_key_id='fake', aws_secret_access_key='fake', host=CONF.s3_listen, port=self.server.port, is_secure=False, calling_format=s3.OrdinaryCallingFormat()) self.conn = conn def get_http_connection(*args): """Get a new S3 connection, don't attempt to reuse connections.""" return self.conn.new_http_connection(*args) self.conn.get_http_connection = get_http_connection
[ 2, 15069, 3050, 1578, 1829, 5070, 355, 7997, 416, 262, 198, 2, 22998, 286, 262, 2351, 15781, 261, 2306, 873, 290, 4687, 8694, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 106...
2.43128
1,055
"""Signals provide a way for applications to loosely couple themselves and respond to different life cycle events. The `blinker`_ library provides the low-level signal implementation. To use the signals you ``connect`` a receiver function to the signals you're interested in: .. code-block:: python from dynamorm.signals import post_save def post_save_receiver(sender, instance, partial, put_kwargs): log.info("Received post_save signal from model %s for instance %s", sender, instance) post_save.connect(post_save_receiver) See the `blinker`_ documentation for more details. .. _blinker: https://pythonhosted.org/blinker/ """ from blinker import signal model_prepared = signal( 'dynamorm.model_prepared', doc='''Sent whenever a model class has been prepared by the metaclass. :param: sender: The model class that is now prepared for use. ''' ) pre_init = signal( 'dynamorm.pre_init', doc='''Sent during model instantiation, before processing the raw data. :param: sender: The model class. :param: instance: The model instance. :param: bool partial: True if this is a partial instantiation, not all data may be present. :param: dict raw: The raw data to be processed by the model schema. ''' ) post_init = signal( 'dynamorm.post_init', doc='''Sent once model instantiation is complete and all raw data has been processed. :param: sender: The model class. :param: instance: The model instance. :param: bool partial: True if this is a partial instantiation, not all data may be present. :param: dict raw: The raw data to be processed by the model schema. ''' ) pre_save = signal( 'dynamorm.pre_save', doc='''Sent before saving (via put) model instances. :param: sender: The model class. :param: instance: The model instance. :param: dict put_kwargs: A dict of the kwargs being sent to the table put method. ''' ) post_save = signal( 'dynamorm.post_save', doc='''Sent after saving (via put) model instances. :param: sender: The model class. :param: instance: The model instance. :param: dict put_kwargs: A dict of the kwargs being sent to the table put method. ''' ) pre_update = signal( 'dynamorm.pre_update', doc='''Sent before saving (via update) model instances. :param: sender: The model class. :param: instance: The model instance. :param: dict conditions: The conditions for the update to succeed. :param: dict update_item_kwargs: A dict of the kwargs being sent to the table put method. :param: dict updates: The fields to update. ''' ) post_update = signal( 'dynamorm.post_update', doc='''Sent after saving (via update) model instances. :param: sender: The model class. :param: instance: The model instance. :param: dict conditions: The conditions for the update to succeed. :param: dict update_item_kwargs: A dict of the kwargs being sent to the table put method. :param: dict updates: The fields to update. ''' ) pre_delete = signal( 'dynamorm.pre_delete', doc='''Sent before deleting model instances. :param: sender: The model class. :param: instance: The model instance. ''' ) post_delete = signal( 'dynamorm.post_delete', doc='''Sent after deleting model instances. :param: sender: The model class. :param: instance: The deleted model instance. ''' )
[ 37811, 11712, 874, 2148, 257, 835, 329, 5479, 284, 28845, 3155, 2405, 290, 3031, 284, 1180, 1204, 6772, 2995, 13, 198, 198, 464, 4600, 2436, 24275, 63, 62, 5888, 3769, 262, 1877, 12, 5715, 6737, 7822, 13, 198, 198, 2514, 779, 262, 1...
3.048845
1,126
# -*- coding: utf-8 -*- import logging logging.getLogger('requests').setLevel(logging.INFO)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 18931, 198, 6404, 2667, 13, 1136, 11187, 1362, 10786, 8897, 3558, 27691, 2617, 4971, 7, 6404, 2667, 13, 10778, 8, 198 ]
2.555556
36
# %% import pandas as pd from matminer.datasets import load_dataset from pymatgen.ext.matproj import MPRester from ml_matrics import ROOT # %% # needs MP API key in ~/.pmgrc.yml available at https://materialsproject.org/dashboard # pmg config --add PMG_MAPI_KEY <your_key> with MPRester() as mpr: formulas = mpr.query({"nelements": {"$lt": 2}}, ["pretty_formula"]) # %% df = pd.DataFrame(formulas).rename(columns={"pretty_formula": "formula"}) df.to_csv(f"{ROOT}/data/mp-n_elements<2.csv", index=False) # %% phonons = load_dataset("matbench_phonons") phonons[["sg_symbol", "sg_number"]] = phonons.apply( lambda row: row.structure.get_space_group_info(), axis=1, result_type="expand" ) phonons.to_csv(f"{ROOT}/data/matbench-phonons.csv", index=False)
[ 2, 43313, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 2603, 1084, 263, 13, 19608, 292, 1039, 1330, 3440, 62, 19608, 292, 316, 198, 6738, 279, 4948, 265, 5235, 13, 2302, 13, 6759, 1676, 73, 1330, 337, 4805, 7834, 198, 198, 6738,...
2.438095
315
import networkx import matplotlib.pyplot as plot import random import math """This module is a graph-based social network model using networkx with a dictionaries of dictionaries implementation. Please make sure to install the following dependencies before running: - networkx: pip3 install networkx - matplotlib: pip3 install matplotlib - tkinter: apt install pyton3-tk or equivalent for non-debian linux or mac - scipy: pip3 install scipy The code is uses Python 3 features. """ class SocialNetwork: """This class models a social network of connected people. This is a graph-based model with each node representing a person and each edge representing a connection between two people. The default instance of this class uses a simple small network of people with random connections. The constructor provides for the ability to specify the people and the connections in two separate lists or sets. A third argument "gov" is provided in the case that no connections are provided and simple designates one of two algorithms for creating connections between people in the network. The two possible values are "random" which creates random connections, this is to be used whenever you want to provide only a list of people and still create a meaningful social network, the other option is "full" which exists only for graph testing purposes and shouldn't be used. If a connections list is provided, a gov argument has no effect""" __test_people = ["Ahmed", "Mohamed", "Mahmoud", "Moaz", "Amr", "Omar", "Mai", "Hoda"] def create_connections_full(self): """Create a list of connections that connect all nodes to all other nodes in the network, not useful for our needs and don't use it for purposes of testing this model as it creates a meaningless social network. Note: This function should not be called from outside but for testing purposes external invocation is allowed""" # This little devilish loop here creates lots of connections for i in self.people: for j in self.people: # self connections are actually handled by networkx by I want a clean connection list if i is j: continue self.connections.append((i, j)) def create_connections_random(self): """Create a list of connections that randomly connect nodes to other nodes in the network, this is the recommended way of creating a meaningful network for our model. Note: This function should not be called from outside but for testing purposes external invocation is allowed""" for i in self.people: for j in self.people: # self connections are actually handled by networkx by I want a clean connection list if i is j: continue # this creates connections at a random boolean-like decision m = random.randint(0, 1) if m == 0: continue else: self.connections.append((i, j)) # this loop only executes one for each person to create less and easier connections break def populate_graph(self): """Populate the graph object with the nodes and the edges. Note: This function should not be called from outside but for testing purposes external invocation is allowed""" # add the nodes to the graph self.graph.add_nodes_from(self.people) # add the edges to the graph self.graph.add_edges_from(self.connections) def draw_graph(self): """Create the plot of the network graph. Note: this function doesn't display the plot, to do that call show_graph() afterwards""" # this is the matplotlib plot object, this subplot full height and left-most occupying self.plot.subplot(121) # draw the network graph on the subplot networkx.draw_networkx(self.graph, with_labels=True, font_weight='bold') def draw_graph_shell(self): """Create the plot of the network graph shell. Note: this function doesn't display the plot, to do that call show_graph() afterwards""" # this is the matplotlib plot object, this subplot full height and right-most occupying self.plot.subplot(122) # draw the shell of network graph on the subplot for an easier outside-in view networkx.draw_shell(self.graph, with_labels=True, font_weight='bold') def show_graph(self): """Show the drawn plots for this network""" self.plot.show() def get_adjacency_with_separation_degree(self, degree): """Get a list of all nodes in the network and for each node a set of nodes that are exactly degree degrees of separation away from the node""" # store the adjacency list adjacency = {} # iterate over the iterable for all shortest path lengths in the graph # each i is a dictionary containing with the person's name and a dictionary # of degrees of separation from each other node in the network for i in networkx.all_pairs_shortest_path_length(self.graph): # holder for the set of people that are exactly degree degrees away from the current node temp = set() # a dictionary to hold the separation dictionary in i dic = dict(i[1]) # iterate over the separation dictionary for the current node for j in dic: # if the current node of the separation dictionary is exactly degree degrees of separation # add it to the current set of nodes if dic.get(j) == degree: temp.add(j) # after iterating over all separations add the person and the set of people that are exactly # degree degrees away from that person adjacency.update({i[0]: temp}) # return the adjacency dictionary return adjacency def get_friends(self): """Friends of a node are the people who are exactly 1 degree of separation away. Note: this notation is not consistent with social theory degree of separation, it is consistent with graph theory degree of separation that uses edges""" return self.get_adjacency_with_separation_degree(1) def get_friends_of_friends(self): """Friends of friends of a node are the people who are exactly 2 degrees of separation away. Note: this notation is not consistent with social theory degree of separation, it is consistent with graph theory degree of separation that uses edges""" return self.get_adjacency_with_separation_degree(2) def get_most_popular(self): """Get a set of all the most popular people in the network, the node(s) with the highest connectivity""" # a unique set of popular people populars = set({}) # a placeholder for a comparable object representing a person person = None for i in self.graph.degree: # this is for the first iteration to cast person from None to a comparable object type if person is None: person = i continue # if the current person object's connectivity level (how many people they're connected to) # is higher than the place holder, replace the placeholder with the current person if i[1] > person[1]: person = i # add the most popular person to the set of most popular people populars.add(person[0]) # this loops adds other people who are equally popular to the most popular person for i in self.graph.degree: # if the current person object's connectivity level is equal than the place holder, # this person is as popular to the most popular person and add them to the set if i[1] == person[1]: populars.add(i[0]) # return the set of most popular people return populars def get_least_popular(self): """Get a set of the least popular people in the network, the node(s) with the least connectivity. Note: Certain variable names contained in this method may trigger people who were triggered by certain historic python terminology. Please open a PEP if you wish to rectify this issue.""" # placeholder for a unique set of least popular people unpopulars = set({}) # placeholder for a comparable person object person = None for i in self.graph.degree: if person is None: person = i continue if i[1] < person[1]: person = i unpopulars.add(person[0]) for i in self.graph.degree: if i[1] == person[1]: unpopulars.add(i[0]) return unpopulars def get_average(self, gov=None): """Get the average level of connectivity in the network. Note: averages are floating points but to be meaningful this function returns an integer, for this reason you may specify a governor for rounding. Possible governors are "ceiling", "floor", "cast" which uses python's int() casting for rounding, or unspecified which returns floating point""" # the summation of all degrees and the count of nodes summation, count = 0, 0 # iterate over the degrees of connectivity of all nodes in the network for i in self.graph.degree: # increase the number of nodes count += 1 # sum the values of node degrees summation += i[1] # do rounding according to the governor argument if gov == "floor": return math.floor(summation/count) elif gov == "ceiling": return math.ceil(summation/count) elif gov == "cast": return int(summation/count) else: return summation/count def get_more_than_four(self): """Get a set of people who have four or more friends in the network""" # a unique set of people with more than four friends populars = set({}) # iterate over the degrees of separation of all nodes in the network for i in self.graph.degree: if i[1] > 4: populars.add(i[0]) if len(populars) == 0: return "No one has more than four friends" return populars # create the social network mode social_network = SocialNetwork() # draw the graph for the network social_network.draw_graph() # draw the network graph shell social_network.draw_graph_shell() # show the graph plots social_network.show_graph() # print the friends of everyone in the network print("Friends:", social_network.get_friends()) # print the friends of friends of everyone in the network print("Friends of friends:", social_network.get_friends_of_friends()) # print the most popular people in the network print("Most popular:", social_network.get_most_popular()) # print the least popular people in the network print("Least popular:", social_network.get_least_popular()) # print the average popularity of people in the network print("Average popularity:", social_network.get_average()) # print people in the network with more than four friends print("More than 4 friends:", social_network.get_more_than_four())
[ 11748, 3127, 87, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 7110, 198, 11748, 4738, 198, 11748, 10688, 198, 198, 37811, 1212, 8265, 318, 257, 4823, 12, 3106, 1919, 3127, 2746, 1262, 3127, 87, 351, 257, 48589, 3166, 286, 48589,...
2.808784
4,121
#!/usr/bin/env python2 from __future__ import print_function import matplotlib from matplotlib import pyplot as plt from scipy.cluster.hierarchy import dendrogram, linkage, cophenet, to_tree import numpy as np import json import sys import os matplotlib.rcParams.update({'font.size': 18}) SHOWPLOT = 0 if len(sys.argv) >= 2 and sys.argv[1] == "showplot": SHOWPLOT = 1 idMap = {} idRevMap = {} cnt = 0 di = {} inp = sys.stdin.read() j = json.loads(inp) for entry in j: if entry[0] not in di: di[entry[0]] = {} if entry[1] not in di: di[entry[1]] = {} di[entry[0]][entry[1]] = entry[2] di[entry[1]][entry[0]] = entry[2] if entry[0] not in idMap: idMap[entry[0]] = cnt idRevMap[cnt] = entry[0] cnt += 1 if entry[1] not in idMap: idMap[entry[1]] = cnt idRevMap[cnt] = entry[1] cnt += 1 matrixNetwork = np.zeros(shape=(cnt, cnt)) for i in range(cnt): for j in range(cnt): if i is not j: matrixNetwork[i][j] = di[idRevMap[i]][idRevMap[j]] print(matrixNetwork, file = sys.stderr) compressedMatrixNetwork = matrixNetwork[np.triu_indices(len(matrixNetwork), 1)] # hcMethods = ['single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward'] # centroid, median, ward will only work if euclidean distance is used that is an embedding of distances between parsetrees is possible in k-dim vector space with l2 norm hcMethods = ['single', 'complete', 'average', 'weighted'] mx = 0.0 method = 'single' for method_ in hcMethods: linked = linkage(compressedMatrixNetwork, method_) coph_var, _ = cophenet(linked, compressedMatrixNetwork) if mx < coph_var: mx = coph_var method = method_ if method in ['centroid', 'median', 'ward']: print('** [warning] ' + method + ' method will work only when euclidean distance exists for set of points', file = sys.stderr) print(method, mx, file = sys.stderr) linked = linkage(compressedMatrixNetwork, method) if SHOWPLOT == 1: plt.figure(figsize=(25,10)) plt.title('Dendrogram: Clusters before running PruneTree') # plt.xlabel('Program ID') plt.ylabel('Distance') dend = fancy_dendrogram(linked, leaf_rotation = 90, leaf_font_size = 8, # truncate_mode = 'lastp', # p = 12, show_contracted = True, annotate_above = 400, max_d = 300) plt.show() hierarchicalTree = to_tree(linked) clusters = [(i, -1) for i in range(0, len(matrixNetwork))] clusterCount = 0 thresholdDist = 400.0 thresholdCount = int(cnt ** 0.5) # (min, max) dfs(hierarchicalTree) print(clusterCount, file = sys.stderr) print(thresholdDist, thresholdCount, file = sys.stderr) print(clusters, file = sys.stderr) finalclusters = [[] for i in range(clusterCount)] for cluster in clusters: finalclusters[cluster[1]].append(idRevMap[cluster[0]]) print(finalclusters, file = sys.stderr) print(json.dumps(map(reorder, finalclusters))) # res = map(lambda x: ','.join(map(str, reorder(x))), finalclusters) # print('|'.join(res))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 2603, 29487, 8019, 198, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 6738, 629, 541, 88...
2.274538
1,406
import FWCore.ParameterSet.Config as cms L1GctConfigProducers = cms.ESProducer("L1GctConfigProducers", JetFinderCentralJetSeed = cms.double(5.0), JetFinderForwardJetSeed = cms.double(5.0), TauIsoEtThreshold = cms.double(2.0), HtJetEtThreshold = cms.double(10.0), MHtJetEtThreshold = cms.double(10.0), RctRegionEtLSB = cms.double(0.5), GctHtLSB = cms.double(0.5), ConvertEtValuesToEnergy = cms.bool(False), # energy sum eta ranges MEtEtaMask = cms.uint32(0x3c000f), TEtEtaMask = cms.uint32(0x3c000f), MHtEtaMask = cms.uint32(0x3c000f), HtEtaMask = cms.uint32(0x3c000f), # The CalibrationStyle should be "None", "PiecewiseCubic", "Simple" or "PF" # "PowerSeries", "ORCAStyle" are also available, but not recommended CalibrationStyle = cms.string('PF'), PFCoefficients = cms.PSet( nonTauJetCalib0 = cms.vdouble(3.01791485,104.05404643,4.37671951,-511.10059192,0.00975609,-17.19462193), nonTauJetCalib1 = cms.vdouble(6.51467316,55.13357477,4.42877284,-75.99041992,0.00574098,-16.07076961), nonTauJetCalib2 = cms.vdouble(2.66631385,59.40320962,3.64453392,-458.28002325,0.00869394,-19.25715247), nonTauJetCalib3 = cms.vdouble(0.71562578,54.71640347,2.72016310,-9009.00062999,0.01044813,-24.07475734), nonTauJetCalib4 = cms.vdouble(1.39149927,31.51196317,2.49437717,-533.64858609,0.01071669,-18.94264462), nonTauJetCalib5 = cms.vdouble(1.56945764,10.19680631,1.61637149,-37.03219196,0.00785145,-17.15336214), nonTauJetCalib6 = cms.vdouble(1.57965654,9.64485987,1.84352989,-53.54520963,0.00818620,-18.04202617), nonTauJetCalib7 = cms.vdouble(1.117,2.382,1.769,0.0,-1.306,-0.4741 ), # OLD HF CALIBS! nonTauJetCalib8 = cms.vdouble(1.634,-1.01,0.7184,1.639,0.6727,-0.2129), nonTauJetCalib9 = cms.vdouble(0.9862,3.138,4.672,2.362,1.55,-0.7154 ), nonTauJetCalib10 = cms.vdouble(1.245,1.103,1.919,0.3054,5.745,0.8622 ), tauJetCalib0 = cms.vdouble(3.01791485,104.05404643,4.37671951,-511.10059192,0.00975609,-17.19462193), tauJetCalib1 = cms.vdouble(6.51467316,55.13357477,4.42877284,-75.99041992,0.00574098,-16.07076961), tauJetCalib2 = cms.vdouble(2.66631385,59.40320962,3.64453392,-458.28002325,0.00869394,-19.25715247), tauJetCalib3 = cms.vdouble(0.71562578,54.71640347,2.72016310,-9009.00062999,0.01044813,-24.07475734), tauJetCalib4 = cms.vdouble(1.39149927,31.51196317,2.49437717,-533.64858609,0.01071669,-18.94264462), tauJetCalib5 = cms.vdouble(1.56945764,10.19680631,1.61637149,-37.03219196,0.00785145,-17.15336214), tauJetCalib6 = cms.vdouble(1.57965654,9.64485987,1.84352989,-53.54520963,0.00818620,-18.04202617) ) )
[ 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 198, 198, 43, 16, 38, 310, 16934, 11547, 7999, 796, 269, 907, 13, 1546, 11547, 2189, 7203, 43, 16, 38, 310, 16934, 11547, 7999, 1600, 198, 220, 220, 220, 19013, 37, 554...
1.862508
1,491
"""Provides access to fulltext content for arXiv papers.""" import json from http import HTTPStatus from functools import wraps from urllib.parse import urljoin import requests from search.domain import Fulltext from search.context import get_application_config, get_application_global class FulltextSession(object): """An HTTP session with the fulltext endpoint.""" def __init__(self, endpoint: str) -> None: """Initialize an HTTP session.""" self._session = requests.Session() self._adapter = requests.adapters.HTTPAdapter(max_retries=2) self._session.mount("https://", self._adapter) if not endpoint[-1] == "/": endpoint += "/" self.endpoint = endpoint def retrieve(self, document_id: str) -> Fulltext: """ Retrieve fulltext content for an arXiv paper. Parameters ---------- document_id : str arXiv identifier, including version tag. E.g. ``"1234.56787v3"``. endpoint : str Base URL for fulltext endpoint. Returns ------- :class:`.Fulltext` Includes the content itself, creation (extraction) date, and extractor version. Raises ------ ValueError Raised when ``document_id`` is not a valid arXiv paper identifier. IOError Raised when unable to retrieve fulltext content. """ if not document_id: # This could use further elaboration. raise ValueError("Invalid value for document_id") try: response = requests.get(urljoin(self.endpoint, document_id)) except requests.exceptions.SSLError as ex: raise IOError("SSL failed: %s" % ex) if response.status_code != HTTPStatus.OK: raise IOError( "%s: could not retrieve fulltext: %i" % (document_id, response.status_code) ) try: data = response.json() except json.decoder.JSONDecodeError as ex: raise IOError( "%s: could not decode response: %s" % (document_id, ex) ) from ex return Fulltext(**data) # type: ignore # See https://github.com/python/mypy/issues/3937 def init_app(app: object = None) -> None: """Set default configuration parameters for an application instance.""" config = get_application_config(app) config.setdefault( "FULLTEXT_ENDPOINT", "https://fulltext.arxiv.org/fulltext/" ) def get_session(app: object = None) -> FulltextSession: """Get a new session with the fulltext endpoint.""" config = get_application_config(app) endpoint = config.get( "FULLTEXT_ENDPOINT", "https://fulltext.arxiv.org/fulltext/" ) return FulltextSession(endpoint) def current_session() -> FulltextSession: """Get/create :class:`.FulltextSession` for this context.""" g = get_application_global() if not g: return get_session() if "fulltext" not in g: g.fulltext = get_session() # type: ignore return g.fulltext # type: ignore @wraps(FulltextSession.retrieve) def retrieve(document_id: str) -> Fulltext: """Retrieve an arxiv document by id.""" return current_session().retrieve(document_id)
[ 37811, 15946, 1460, 1895, 284, 1336, 5239, 2695, 329, 610, 55, 452, 9473, 526, 15931, 198, 198, 11748, 33918, 198, 6738, 2638, 1330, 14626, 19580, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 190...
2.475336
1,338
# Originally written by Kevin Breen (@KevTheHermit): # https://github.com/kevthehermit/RATDecoders/blob/master/DarkComet.py import sys import string from struct import unpack import pefile from binascii import *
[ 2, 19486, 3194, 416, 7939, 347, 1361, 4275, 42, 1990, 464, 9360, 2781, 2599, 198, 2, 3740, 1378, 12567, 13, 785, 14, 365, 85, 1169, 372, 2781, 14, 49, 1404, 10707, 375, 364, 14, 2436, 672, 14, 9866, 14, 17367, 34, 908, 13, 9078, ...
3.042857
70
# -*- coding: utf-8 -*- from mfr.core import FileHandler, get_file_extension from .render import render_pdf EXTENSIONS = ['.pdf'] class Handler(FileHandler): """FileHandler for Portable Document Format files.""" renderers = { 'html': render_pdf, } exporters = {}
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 285, 8310, 13, 7295, 1330, 9220, 25060, 11, 651, 62, 7753, 62, 2302, 3004, 198, 6738, 764, 13287, 1330, 8543, 62, 12315, 628, 198, 13918, 16938, 11053, 796, 685, ...
2.754717
106
#! python3 # Author: Elsaid Salem # Credits: Gabor Szabo, GeeksForGeeks, Andrew Krcatovich # Notes: use .xls format for the excel, make sure to add a no_images dir to the output location in -o param #tahsine: x 23, y 445 # Known Issues: ''' - two files are created, need to delete image-less one, for now sort by .pdf extension - add more args for options, but keep them optional ? - find a way to reduce the number of needed paramters to execute - need better error / exception handling ''' from reportlab.pdfgen import canvas import argparse import xlrd import pdfrw from PyPDF2 import PdfFileWriter, PdfFileReader import io # need to add in argparse and assign variables to parameters parser = argparse.ArgumentParser() parser.add_argument("--excel", dest="excel_path", help="Path to your excel file, required") parser.add_argument("--sheet", dest="sheet_index", help="Index of the sheet to load data from, 0 being the first sheet. Default value is 0", default=0) parser.add_argument("--pdf", dest="pdf_path", help="Path to your pdf template file, required") parser.add_argument("--fill-images", dest="fill_images", help="whether or not to fill images, default is yes", default="y") parser.add_argument("--images", dest="image_path", help="Path to the directory of your images, don't include terminal / , required if filling images . default value is ./excel_to_pdf", default="./excel_to_pdf") parser.add_argument("--img-field", dest="name_field", help="Which field in your excel corresponds to the image names, required if filling images") parser.add_argument("--img-extension", dest="img_ext", help="What extension does your image use (eg png, jpg), required if filling images, don't include the '.' - default value is .jpg", default=".jpg") parser.add_argument("--output", "-o", dest="pdf_output", help="fixed name of your output file (the part that doesn't change, don't include terminal /). Default value is ./excel_to_pdf", default="./excel_to_pdf/") parser.add_argument("--x-axis", "-x", dest="x_loc", help="image location on x (0,0 is bottom left of page). Default value is 23", type=int, default=23) parser.add_argument("--y-axis", "-y", dest="y_loc", help="image location on x (0,0 is bottom left of page). Default value is 445", type=int, default=445) parser.add_argument("--width", "-w", dest="img_width", help="Image size based on width, keeps aspect ration", type=int, default=100) # make sure your excel columns and pdf fields have the same names # loads the excel data to fill the pdf # adds the image to the file # Note: fill the pdf first, then add the image # use this by calling fill_pdf in a for each of load_excel if __name__ == "__main__": main() print("\n\nDone!")
[ 2, 0, 21015, 18, 198, 198, 2, 6434, 25, 2574, 30079, 31988, 198, 2, 29501, 25, 402, 4820, 27974, 34748, 11, 402, 32201, 1890, 38, 32201, 11, 6858, 509, 6015, 265, 18198, 198, 2, 11822, 25, 779, 764, 87, 7278, 5794, 329, 262, 27336...
3.35049
816
#!/usr/bin/env python from website import app # Build logger if doesn't exist import os if not os.path.exists('/tmp/log.csv'): os.mknod('/tmp/log.csv') app.run(debug=True)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 3052, 1330, 598, 198, 198, 2, 10934, 49706, 611, 1595, 470, 2152, 198, 11748, 28686, 198, 198, 361, 407, 28686, 13, 6978, 13, 1069, 1023, 10786, 14, 22065, 14, 6404, 13, 40664, ...
2.486111
72
import time from django.forms import Widget from django.urls import reverse from django.utils import baseconv from django.core.signing import Signer signer = Signer()
[ 11748, 640, 198, 198, 6738, 42625, 14208, 13, 23914, 1330, 370, 17484, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 6738, 42625, 14208, 13, 26791, 1330, 2779, 42946, 198, 6738, 42625, 14208, 13, 7295, 13, 12683, 278, 1330, 58...
3.36
50
# vim: set encoding=utf-8 # Copyright (c) 2016 Intel Corporation  # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #       http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Type checking for arguments, including the implicit argument """ __all__ = ['implicit', 'affirm_type', 'require_type', 'validate_call'] class implicit(object): """ Type which acts a singleton value indicating that an argument should be implicitly filled Usage: def mult(a, b=2, base=implicit): if base is implicit: implicit.error('base') return base(a*b) """ @staticmethod def error(arg_name): """Raises an error that the arg with the given name was found equal to implicit (i.e. its value was not provided, implicitly or explicitly)""" raise ValueError("Missing value for arg '%s'. This value is normally filled implicitly, however, if this method is called standalone, it must be set explicitly" % arg_name) def type_error(expected_type, x_type, x_name, extra_msg=None): """returns a commonly formatted type error which can then be raised by individual methods""" extra_msg = '' if extra_msg is None else ' ' + extra_msg return TypeError("Value for %s is of type %s. Expected type %s.%s" % (x_name, x_type, expected_type, extra_msg)) def value_error(expected_value_description, x_value, x_name, extra_msg=None): """returns a commonly formatted value error which can then be raised by individual methods""" extra_msg = '' if extra_msg is None else ' ' + extra_msg return ValueError("Found %s = %s. Expected %s.%s" % (x_name, x_value, expected_value_description, extra_msg)) class _AffirmType(object): """ Holds methods which affirm the value is of a particular type, returning it as that type after possible conversion Raises ValueError otherwise """ def list_of_str(self, value, name, extra_msg=None, length=None, allow_none=False): """Note: converts str to list of str""" values = self.list_of_anything(value, name, extra_msg, length, allow_none) if values and not all(isinstance(c, basestring) for c in values): raise value_error("str or list of str", values, name, extra_msg) return values @staticmethod def _allow_none(value, name, extra_msg, allow_none): """private none-checker, reduces boilerplate code, called on value is None""" if allow_none: return value if value is not None: # sanity check for programmer's usage raise RuntimeError("Internal error: _allow_none always expects value is None, but it is not") raise value_error("a non-None value", value, name, extra_msg) affirm_type = _AffirmType() # singleton instance of the _AffirmType class class _RequireType(object): """ raises a TypeError or ValueError if the given x_value not does meet the requirements (accounts for implicit) :param required_type: (type) what type x is supposed to be :param value: the value in question :param name: (str) the name of the variable for the possible error message :param extra_msg: (Optional) extra message text for the possible error Example ------- >>> a = 1 >>> require_type(int, a, 'a') """ # **please update unit tests (test_arguments.py) if you add methods to this class require_type = _RequireType() #singleton instance of the _RequireType class def is_name_private(name, public=None): """ Answers whether the name is considered private, by checking the leading underscore. A ist of public names can be provided which would override the normal check """ if public and name in public: return False return name.startswith('_') def default_value_to_str(value): """renders value to be printed in a function signature""" return value if value is None or type(value) not in [str, unicode] else "'%s'" % value def get_args_spec_from_function(function, ignore_self=False, ignore_private_args=False): """ Returns the spec of the arguments as a tuple :param function: the function to interrogate :param ignore_self: whether to ignore a 'self' argument :param ignore_private_args: whether to ignore arguments which start with an '_' :return: tuple of args, kwargs, varargs, varkwargs args - list of strings the names of the required arguments. None if not defined kwargs - list of tuples of (name, default value). None if not defined varargs - name of a var args (e.g. "args" for "*args). None if not defined varkwargs - name of a var kwargs (e.g. "kwargs" for "**kwargs). None if not defined """ import inspect args, varargs, varkwargs, defaults = inspect.getargspec(function) if ignore_self: args = [a for a in args if a != 'self'] num_defaults = len(defaults) if defaults else 0 if num_defaults: kwargs = zip(args[-num_defaults:], defaults) args = args[:-num_defaults] else: kwargs = [] if ignore_private_args: args = [name for name in args if not is_name_private(name)] kwargs = [(name, value) for name, value in kwargs if not is_name_private(name)] return args, kwargs, varargs, varkwargs # todo - make nametuple def get_args_text_from_function(function, ignore_self=False, ignore_private_args=False): """Returns a string which is the familiar python representation of the function's argument signature""" args, kwargs, varargs, varkwargs = get_args_spec_from_function(function, ignore_self, ignore_private_args) args.extend(["%s=%s" % (name, default_value_to_str(value)) for name, value in kwargs]) if varargs: args.append('*' + varargs) if varkwargs: args.append('**' + varkwargs) text = ", ".join(args) return text def validate_call(function, arguments, ignore_self=False): """Validates the a dict of arguments can be used to call the given function""" require_type(dict, arguments, "arguments") args, kwargs, varargs, varkwargs = get_args_spec_from_function(function, ignore_self=ignore_self) if varargs: signature = get_args_text_from_function(function) raise ValueError("function %s(%s) cannot be validated against a dict of parameters because of the '*%s' in its signature" % (function.__name__, signature, varargs)) missing_args = list(args) invalid_args = [] valid_kwarg_names = [name for name, default_val in kwargs] for name in arguments: if name in args: missing_args.remove(name) elif name not in valid_kwarg_names: if not varkwargs: invalid_args.append(name) if missing_args or invalid_args: signature = get_args_text_from_function(function) # todo - add Levenshtein distance calc's and helpful messages if invalid_args: raise ValueError("call to function %s(%s) included one or more unknown args named: %s" % (function.__name__, signature, ', '.join(invalid_args))) else: raise ValueError("call to function %s(%s) is missing the following required arguments: %s" % (function.__name__, signature, ', '.join(missing_args))) def extract_call(function, arguments, ignore_self=False): """Validates the a dict of arguments can be used to call the given function""" require_type(dict, arguments, "arguments") args, kwargs, varargs, varkwargs = get_args_spec_from_function(function, ignore_self=ignore_self) if varargs: signature = get_args_text_from_function(function) raise ValueError("function %s(%s) cannot be validated against a dict of parameters because of the '*%s' in its signature" % (function.__name__, signature, varargs)) missing_args = list(args) invalid_args = [] call_kwargs = {} valid_kwarg_names = [name for name, default_val in kwargs] for name in arguments: if name in args: missing_args.remove(name) call_kwargs[name] = arguments[name] elif name in valid_kwarg_names: call_kwargs[name] = arguments[name] else: if varkwargs: print "adding %s" % name call_kwargs[name] = arguments[name] if missing_args or invalid_args: signature = get_args_text_from_function(function) # todo - add Levenshtein distance calc's and helpful messages if invalid_args: raise ValueError("call to function %s(%s) included one or more unknown args named: %s" % (function.__name__, signature, ', '.join(invalid_args))) else: raise ValueError("call to function %s(%s) is missing the following required arguments: %s" % (function.__name__, signature, ', '.join(missing_args))) #print "call_kwargs=%s" % call_kwargs return call_kwargs
[ 2, 43907, 25, 900, 21004, 28, 40477, 12, 23, 198, 198, 2, 220, 15069, 1849, 7, 66, 8, 1849, 5304, 8180, 1849, 10606, 1819, 341, 1849, 198, 2, 198, 2, 220, 49962, 1849, 4625, 1849, 1169, 1849, 25189, 4891, 1849, 34156, 11, 1849, 14...
2.749707
3,412
import os, sys import PIL from PIL import Image import argparse import glob # TODO Change the image resize method to be more dynamic. As in add a loop to do the given sizes instead of the presets default_sizes = ['18', '36', '72'] # Twitchs required Sub Badge sizes if __name__ == '__main__': parser = argparse.ArgumentParser( description='Make Twitch Sub Badges. Takes in an image and outputs the correct sizes. Names them too.') parser.add_argument('-f', '--folder', action='store', dest='foldername', help='The folder name where the original files and the output files are contained', nargs="*") parser.add_argument('-r', '--recursive', action='store_true', default=False, dest='recursive', help='Should it look for files in the folders withing the folder that the program is running?') parser.add_argument('-s', '--sizes', action='store', dest='sizes', help='Use your own sizes for the resizing proccess. If this is not provided it will use the defualt sizes. Example: -s 18 36 72', nargs='*') results = parser.parse_args() if results.recursive == True and results.foldername == None: print("Running the recursive code") allfiles = [] subdirs = next(os.walk('.'))[1] for s in subdirs: f = glob.glob(s + "\\*.png") if len(f) == 1: allfiles.append([s, f[0]]) else: print("Too many files in directory: {}".format(str(s))) for x in range(len(allfiles)): if results.sizes != None: for size in results.sizes: resize_image(input_image_path=str(allfiles[x][1]), output_image_path="{}\\{}px - {}.png".format( str(allfiles[x][0]), str(size), str(allfiles[x][0])), size=(int(size), int(size))) else: for size in default_sizes: resize_image(input_image_path=str(allfiles[x][1]), output_image_path="{}\\{}px - {}.png".format( str(allfiles[x][0]), str(size), str(allfiles[x][0])), size=(int(size), int(size))) elif results.recursive == False and results.foldername != None: # print("Running NON-Recursive code") dr = os.path.abspath(str(results.foldername[0])) files = os.listdir(dr + "\\") for x in range(len(files)): if results.sizes != None: for size in results.sizes: resize_image(input_image_path="{}\\{}".format(str(dr), str(files[x])), output_image_path="{}\\{}px - {}".format( str(dr), str(size), str(files[x])), size=(int(size), int(size))) else: for size in default_sizes: resize_image(input_image_path="{}\\{}".format(str(dr), str(files[x])), output_image_path="{}\\{}px - {}".format( str(dr), str(size), str(files[x])), size=(int(size), int(size))) else: print("Something went wrong!")
[ 11748, 28686, 11, 25064, 201, 198, 11748, 350, 4146, 201, 198, 6738, 350, 4146, 1330, 7412, 201, 198, 11748, 1822, 29572, 201, 198, 11748, 15095, 201, 198, 201, 198, 201, 198, 2, 16926, 46, 9794, 262, 2939, 47558, 2446, 284, 307, 517,...
2.000594
1,684
#!/usr/bin/env python # # Copyright (c) 2018, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from wpan import verify import wpan import time #----------------------------------------------------------------------------------------------------------------------- # Test description: Orphaned node attach through MLE Announcement test_name = __file__[:-3] if __file__.endswith('.py') else __file__ print '-' * 120 print 'Starting \'{}\''.format(test_name) def verify_channel(nodes, new_channel, wait_time=20): """ This function checks the channel on a given list of `nodes` and verifies that all nodes switch to a given `new_channel` (as int) within certain `wait_time` (int and in seconds) """ start_time = time.time() while not all([ (new_channel == int(node.get(wpan.WPAN_CHANNEL), 0)) for node in nodes ]): if time.time() - start_time > wait_time: print 'Took too long to switch to channel {} ({}>{} sec)'.format(new_channel, time.time() - start_time, wait_time) exit(1) time.sleep(0.1) #----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances router = wpan.Node() c1 = wpan.Node() c2 = wpan.Node() all_nodes = [router, c1, c2] #----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() #----------------------------------------------------------------------------------------------------------------------- # Build network topology router.form('announce-tst', channel=11) c1.join_node(router, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE) c2.join_node(router, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE) c1.set(wpan.WPAN_POLL_INTERVAL, '500') c2.set(wpan.WPAN_POLL_INTERVAL, '500') c1.set(wpan.WPAN_THREAD_DEVICE_MODE,'5') c2.set(wpan.WPAN_THREAD_DEVICE_MODE,'5') #----------------------------------------------------------------------------------------------------------------------- # Test implementation # Reset c2 and keep it in detached state c2.set('Daemon:AutoAssociateAfterReset', 'false') c2.reset(); # Switch the rest of network to channel 26 router.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '26') verify_channel([router, c1], 26) # Now re-enable c2 and verify that it does attach to router and is on channel 26 # c2 would go through the ML Announce recovery. c2.set('Daemon:AutoAssociateAfterReset', 'true') c2.reset(); verify(int(c2.get(wpan.WPAN_CHANNEL), 0) == 11) # wait for 20s for c2 to be attached/associated start_time = time.time() wait_time = 20 while not c2.is_associated(): if time.time() - start_time > wait_time: print 'Took too long to recover through ML Announce ({}>{} sec)'.format(time.time() - start_time, wait_time) exit(1) time.sleep(0.1) # Check that c2 did attach and is on channel 26. verify(int(c2.get(wpan.WPAN_CHANNEL), 0) == 26) #----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() print '\'{}\' passed.'.format(test_name)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 220, 15069, 357, 66, 8, 2864, 11, 383, 4946, 16818, 46665, 13, 198, 2, 220, 1439, 2489, 10395, 13, 198, 2, 198, 2, 220, 2297, 396, 3890, 290, 779, 287, 2723, 290, 1393...
3.117992
1,534
from collections import deque from tkinter import *
[ 6738, 17268, 1330, 390, 4188, 198, 6738, 256, 74, 3849, 1330, 1635, 198 ]
4
13
#Personal message: Personel_name = "Tony" message = "You are doing great in coding." print(Personel_name + "! " + message)
[ 2, 30228, 3275, 25, 220, 198, 198, 15439, 417, 62, 3672, 796, 366, 29387, 1, 198, 198, 20500, 796, 366, 1639, 389, 1804, 1049, 287, 19617, 526, 198, 198, 4798, 7, 15439, 417, 62, 3672, 1343, 366, 0, 366, 1343, 3275, 8, 198 ]
2.953488
43
from Blocktrace.Protobufs.bstream.v1 import bstream_pb2_grpc, bstream_pb2 from Blocktrace.Protobufs.eosio.codec.v1 import codec_pb2_grpc, codec_pb2
[ 6738, 9726, 40546, 13, 19703, 672, 3046, 82, 13, 65, 5532, 13, 85, 16, 1330, 275, 5532, 62, 40842, 17, 62, 2164, 14751, 11, 275, 5532, 62, 40842, 17, 198, 6738, 9726, 40546, 13, 19703, 672, 3046, 82, 13, 68, 418, 952, 13, 19815, ...
2.387097
62
from rest_framework import generics, filters, permissions, viewsets, mixins, serializers, status from rest_framework.response import Response from django_pyowm.models import Location, Forecast from weather_api.weather.utils import fetch_forecast_for_location from .serializers import LocationSerializer, ForecastSerializer class LocationsView(generics.ListAPIView): """ Search available locations """ queryset = Location.objects.order_by('name') serializer_class = LocationSerializer filter_backends = (filters.SearchFilter,) search_fields = ('name', ) class UserLocationsView(generics.ListAPIView): """ List of user locations """ serializer_class = LocationSerializer permission_classes = (permissions.IsAuthenticated,) class ForecastsView(generics.ListAPIView): """ List of user location forecasts """ serializer_class = ForecastSerializer permission_classes = (permissions.IsAuthenticated,) class UserLocationAddDeleteViewSet(mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): """ update: Add location for track destroy: Remove location from track """ queryset = Location.objects.all() permission_classes = (permissions.IsAuthenticated,) serializer_class = serializers.Serializer
[ 6738, 1334, 62, 30604, 1330, 1152, 873, 11, 16628, 11, 21627, 11, 5009, 1039, 11, 5022, 1040, 11, 11389, 11341, 11, 3722, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 6738, 42625, 14208, 62, 9078, 322, 76, 13, 27530, 1330,...
3.229268
410
#!/usr/bin/env python from collections import defaultdict from re import compile if __name__ == "__main__": import sys output(xref(sys.argv[1] if sys.argv[1:] else "xref.py"))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 302, 1330, 17632, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1330, 25064, 198, 220, 220...
2.661972
71
# encoding: utf-8 import argparse import logging import os from solr_tasks.lib import utils from solr_tasks.lib.solr import SolrCollection, solr_collections if '__main__' == __name__: main()
[ 2, 21004, 25, 3384, 69, 12, 23, 628, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 28686, 198, 6738, 1540, 81, 62, 83, 6791, 13, 8019, 1330, 3384, 4487, 198, 6738, 1540, 81, 62, 83, 6791, 13, 8019, 13, 34453, 81, 1330, 4...
2.701299
77
import unittest from pyalink.alink import * import numpy as np import pandas as pd
[ 11748, 555, 715, 395, 198, 6738, 12972, 282, 676, 13, 282, 676, 1330, 1635, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67 ]
3.037037
27
from . import points, graph, biomes, elevation, land, rivers, regions __all__ = ['points', 'graph', 'biomes', 'elevation', 'land', 'rivers', 'regions']
[ 6738, 764, 1330, 2173, 11, 4823, 11, 3182, 2586, 11, 22910, 11, 1956, 11, 18180, 11, 7652, 198, 198, 834, 439, 834, 796, 37250, 13033, 3256, 705, 34960, 3256, 705, 8482, 2586, 3256, 705, 68, 2768, 341, 3256, 705, 1044, 3256, 705, 38...
3.06
50
begin_unit comment|'# Copyright (c) 2012 Rackspace Hosting' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#' nl|'\n' comment|'# http://www.apache.org/licenses/LICENSE-2.0' nl|'\n' comment|'#' nl|'\n' comment|'# Unless required by applicable law or agreed to in writing, software' nl|'\n' comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT' nl|'\n' comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the' nl|'\n' comment|'# License for the specific language governing permissions and limitations' nl|'\n' comment|'# under the License.' nl|'\n' nl|'\n' string|'"""\nCells Service Manager\n"""' newline|'\n' name|'import' name|'datetime' newline|'\n' name|'import' name|'time' newline|'\n' nl|'\n' name|'from' name|'oslo_log' name|'import' name|'log' name|'as' name|'logging' newline|'\n' name|'import' name|'oslo_messaging' newline|'\n' name|'from' name|'oslo_service' name|'import' name|'periodic_task' newline|'\n' name|'from' name|'oslo_utils' name|'import' name|'importutils' newline|'\n' name|'from' name|'oslo_utils' name|'import' name|'timeutils' newline|'\n' name|'import' name|'six' newline|'\n' name|'from' name|'six' op|'.' name|'moves' name|'import' name|'range' newline|'\n' nl|'\n' name|'from' name|'nova' op|'.' name|'cells' name|'import' name|'messaging' newline|'\n' name|'from' name|'nova' op|'.' name|'cells' name|'import' name|'state' name|'as' name|'cells_state' newline|'\n' name|'from' name|'nova' op|'.' name|'cells' name|'import' name|'utils' name|'as' name|'cells_utils' newline|'\n' name|'import' name|'nova' op|'.' name|'conf' newline|'\n' name|'from' name|'nova' name|'import' name|'context' newline|'\n' name|'from' name|'nova' name|'import' name|'exception' newline|'\n' name|'from' name|'nova' op|'.' name|'i18n' name|'import' name|'_LW' newline|'\n' name|'from' name|'nova' name|'import' name|'manager' newline|'\n' name|'from' name|'nova' name|'import' name|'objects' newline|'\n' name|'from' name|'nova' op|'.' name|'objects' name|'import' name|'base' name|'as' name|'base_obj' newline|'\n' name|'from' name|'nova' op|'.' name|'objects' name|'import' name|'instance' name|'as' name|'instance_obj' newline|'\n' nl|'\n' nl|'\n' DECL|variable|CONF name|'CONF' op|'=' name|'nova' op|'.' name|'conf' op|'.' name|'CONF' newline|'\n' nl|'\n' DECL|variable|LOG name|'LOG' op|'=' name|'logging' op|'.' name|'getLogger' op|'(' name|'__name__' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|CellsManager name|'class' name|'CellsManager' op|'(' name|'manager' op|'.' name|'Manager' op|')' op|':' newline|'\n' indent|' ' string|'"""The nova-cells manager class. This class defines RPC\n methods that the local cell may call. This class is NOT used for\n messages coming from other cells. That communication is\n driver-specific.\n\n Communication to other cells happens via the nova.cells.messaging module.\n The MessageRunner from that module will handle routing the message to\n the correct cell via the communications driver. Most methods below\n create \'targeted\' (where we want to route a message to a specific cell)\n or \'broadcast\' (where we want a message to go to multiple cells)\n messages.\n\n Scheduling requests get passed to the scheduler class.\n """' newline|'\n' nl|'\n' DECL|variable|target name|'target' op|'=' name|'oslo_messaging' op|'.' name|'Target' op|'(' name|'version' op|'=' string|"'1.37'" op|')' newline|'\n' nl|'\n' DECL|member|__init__ name|'def' name|'__init__' op|'(' name|'self' op|',' op|'*' name|'args' op|',' op|'**' name|'kwargs' op|')' op|':' newline|'\n' indent|' ' name|'LOG' op|'.' name|'warning' op|'(' name|'_LW' op|'(' string|"'The cells feature of Nova is considered experimental '" nl|'\n' string|"'by the OpenStack project because it receives much '" nl|'\n' string|"'less testing than the rest of Nova. This may change '" nl|'\n' string|"'in the future, but current deployers should be aware '" nl|'\n' string|"'that the use of it in production right now may be '" nl|'\n' string|"'risky. Also note that cells does not currently '" nl|'\n' string|"'support rolling upgrades, it is assumed that cells '" nl|'\n' string|"'deployments are upgraded lockstep so n-1 cells '" nl|'\n' string|"'compatibility does not work.'" op|')' op|')' newline|'\n' comment|'# Mostly for tests.' nl|'\n' name|'cell_state_manager' op|'=' name|'kwargs' op|'.' name|'pop' op|'(' string|"'cell_state_manager'" op|',' name|'None' op|')' newline|'\n' name|'super' op|'(' name|'CellsManager' op|',' name|'self' op|')' op|'.' name|'__init__' op|'(' name|'service_name' op|'=' string|"'cells'" op|',' nl|'\n' op|'*' name|'args' op|',' op|'**' name|'kwargs' op|')' newline|'\n' name|'if' name|'cell_state_manager' name|'is' name|'None' op|':' newline|'\n' indent|' ' name|'cell_state_manager' op|'=' name|'cells_state' op|'.' name|'CellStateManager' newline|'\n' dedent|'' name|'self' op|'.' name|'state_manager' op|'=' name|'cell_state_manager' op|'(' op|')' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'=' name|'messaging' op|'.' name|'MessageRunner' op|'(' name|'self' op|'.' name|'state_manager' op|')' newline|'\n' name|'cells_driver_cls' op|'=' name|'importutils' op|'.' name|'import_class' op|'(' nl|'\n' name|'CONF' op|'.' name|'cells' op|'.' name|'driver' op|')' newline|'\n' name|'self' op|'.' name|'driver' op|'=' name|'cells_driver_cls' op|'(' op|')' newline|'\n' name|'self' op|'.' name|'instances_to_heal' op|'=' name|'iter' op|'(' op|'[' op|']' op|')' newline|'\n' nl|'\n' DECL|member|post_start_hook dedent|'' name|'def' name|'post_start_hook' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' string|'"""Have the driver start its servers for inter-cell communication.\n Also ask our child cells for their capacities and capabilities so\n we get them more quickly than just waiting for the next periodic\n update. Receiving the updates from the children will cause us to\n update our parents. If we don\'t have any children, just update\n our parents immediately.\n """' newline|'\n' comment|"# FIXME(comstud): There's currently no hooks when services are" nl|'\n' comment|'# stopping, so we have no way to stop servers cleanly.' nl|'\n' name|'self' op|'.' name|'driver' op|'.' name|'start_servers' op|'(' name|'self' op|'.' name|'msg_runner' op|')' newline|'\n' name|'ctxt' op|'=' name|'context' op|'.' name|'get_admin_context' op|'(' op|')' newline|'\n' name|'if' name|'self' op|'.' name|'state_manager' op|'.' name|'get_child_cells' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'msg_runner' op|'.' name|'ask_children_for_capabilities' op|'(' name|'ctxt' op|')' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'ask_children_for_capacities' op|'(' name|'ctxt' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'_update_our_parents' op|'(' name|'ctxt' op|')' newline|'\n' nl|'\n' dedent|'' dedent|'' op|'@' name|'periodic_task' op|'.' name|'periodic_task' newline|'\n' DECL|member|_update_our_parents name|'def' name|'_update_our_parents' op|'(' name|'self' op|',' name|'ctxt' op|')' op|':' newline|'\n' indent|' ' string|'"""Update our parent cells with our capabilities and capacity\n if we\'re at the bottom of the tree.\n """' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'tell_parents_our_capabilities' op|'(' name|'ctxt' op|')' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'tell_parents_our_capacities' op|'(' name|'ctxt' op|')' newline|'\n' nl|'\n' dedent|'' op|'@' name|'periodic_task' op|'.' name|'periodic_task' newline|'\n' DECL|member|_heal_instances name|'def' name|'_heal_instances' op|'(' name|'self' op|',' name|'ctxt' op|')' op|':' newline|'\n' indent|' ' string|'"""Periodic task to send updates for a number of instances to\n parent cells.\n\n On every run of the periodic task, we will attempt to sync\n \'CONF.cells.instance_update_num_instances\' number of instances.\n When we get the list of instances, we shuffle them so that multiple\n nova-cells services aren\'t attempting to sync the same instances\n in lockstep.\n\n If CONF.cells.instance_update_at_threshold is set, only attempt\n to sync instances that have been updated recently. The CONF\n setting defines the maximum number of seconds old the updated_at\n can be. Ie, a threshold of 3600 means to only update instances\n that have modified in the last hour.\n """' newline|'\n' nl|'\n' name|'if' name|'not' name|'self' op|'.' name|'state_manager' op|'.' name|'get_parent_cells' op|'(' op|')' op|':' newline|'\n' comment|'# No need to sync up if we have no parents.' nl|'\n' indent|' ' name|'return' newline|'\n' nl|'\n' dedent|'' name|'info' op|'=' op|'{' string|"'updated_list'" op|':' name|'False' op|'}' newline|'\n' nl|'\n' DECL|function|_next_instance name|'def' name|'_next_instance' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'try' op|':' newline|'\n' indent|' ' name|'instance' op|'=' name|'next' op|'(' name|'self' op|'.' name|'instances_to_heal' op|')' newline|'\n' dedent|'' name|'except' name|'StopIteration' op|':' newline|'\n' indent|' ' name|'if' name|'info' op|'[' string|"'updated_list'" op|']' op|':' newline|'\n' indent|' ' name|'return' newline|'\n' dedent|'' name|'threshold' op|'=' name|'CONF' op|'.' name|'cells' op|'.' name|'instance_updated_at_threshold' newline|'\n' name|'updated_since' op|'=' name|'None' newline|'\n' name|'if' name|'threshold' op|'>' number|'0' op|':' newline|'\n' indent|' ' name|'updated_since' op|'=' name|'timeutils' op|'.' name|'utcnow' op|'(' op|')' op|'-' name|'datetime' op|'.' name|'timedelta' op|'(' nl|'\n' name|'seconds' op|'=' name|'threshold' op|')' newline|'\n' dedent|'' name|'self' op|'.' name|'instances_to_heal' op|'=' name|'cells_utils' op|'.' name|'get_instances_to_sync' op|'(' nl|'\n' name|'ctxt' op|',' name|'updated_since' op|'=' name|'updated_since' op|',' name|'shuffle' op|'=' name|'True' op|',' nl|'\n' name|'uuids_only' op|'=' name|'True' op|')' newline|'\n' name|'info' op|'[' string|"'updated_list'" op|']' op|'=' name|'True' newline|'\n' name|'try' op|':' newline|'\n' indent|' ' name|'instance' op|'=' name|'next' op|'(' name|'self' op|'.' name|'instances_to_heal' op|')' newline|'\n' dedent|'' name|'except' name|'StopIteration' op|':' newline|'\n' indent|' ' name|'return' newline|'\n' dedent|'' dedent|'' name|'return' name|'instance' newline|'\n' nl|'\n' dedent|'' name|'rd_context' op|'=' name|'ctxt' op|'.' name|'elevated' op|'(' name|'read_deleted' op|'=' string|"'yes'" op|')' newline|'\n' nl|'\n' name|'for' name|'i' name|'in' name|'range' op|'(' name|'CONF' op|'.' name|'cells' op|'.' name|'instance_update_num_instances' op|')' op|':' newline|'\n' indent|' ' name|'while' name|'True' op|':' newline|'\n' comment|'# Yield to other greenthreads' nl|'\n' indent|' ' name|'time' op|'.' name|'sleep' op|'(' number|'0' op|')' newline|'\n' name|'instance_uuid' op|'=' name|'_next_instance' op|'(' op|')' newline|'\n' name|'if' name|'not' name|'instance_uuid' op|':' newline|'\n' indent|' ' name|'return' newline|'\n' dedent|'' name|'try' op|':' newline|'\n' indent|' ' name|'instance' op|'=' name|'objects' op|'.' name|'Instance' op|'.' name|'get_by_uuid' op|'(' name|'rd_context' op|',' nl|'\n' name|'instance_uuid' op|')' newline|'\n' dedent|'' name|'except' name|'exception' op|'.' name|'InstanceNotFound' op|':' newline|'\n' indent|' ' name|'continue' newline|'\n' dedent|'' name|'self' op|'.' name|'_sync_instance' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' name|'break' newline|'\n' nl|'\n' DECL|member|_sync_instance dedent|'' dedent|'' dedent|'' name|'def' name|'_sync_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Broadcast an instance_update or instance_destroy message up to\n parent cells.\n """' newline|'\n' name|'if' name|'instance' op|'.' name|'deleted' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'instance_destroy_at_top' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'instance_update_at_top' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|build_instances dedent|'' dedent|'' name|'def' name|'build_instances' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'build_inst_kwargs' op|')' op|':' newline|'\n' indent|' ' string|'"""Pick a cell (possibly ourselves) to build new instance(s) and\n forward the request accordingly.\n """' newline|'\n' comment|'# Target is ourselves first.' nl|'\n' name|'filter_properties' op|'=' name|'build_inst_kwargs' op|'.' name|'get' op|'(' string|"'filter_properties'" op|')' newline|'\n' name|'if' op|'(' name|'filter_properties' name|'is' name|'not' name|'None' name|'and' nl|'\n' name|'not' name|'isinstance' op|'(' name|'filter_properties' op|'[' string|"'instance_type'" op|']' op|',' nl|'\n' name|'objects' op|'.' name|'Flavor' op|')' op|')' op|':' newline|'\n' comment|'# NOTE(danms): Handle pre-1.30 build_instances() call. Remove me' nl|'\n' comment|'# when we bump the RPC API version to 2.0.' nl|'\n' indent|' ' name|'flavor' op|'=' name|'objects' op|'.' name|'Flavor' op|'(' op|'**' name|'filter_properties' op|'[' string|"'instance_type'" op|']' op|')' newline|'\n' name|'build_inst_kwargs' op|'[' string|"'filter_properties'" op|']' op|'=' name|'dict' op|'(' nl|'\n' name|'filter_properties' op|',' name|'instance_type' op|'=' name|'flavor' op|')' newline|'\n' dedent|'' name|'instances' op|'=' name|'build_inst_kwargs' op|'[' string|"'instances'" op|']' newline|'\n' name|'if' name|'not' name|'isinstance' op|'(' name|'instances' op|'[' number|'0' op|']' op|',' name|'objects' op|'.' name|'Instance' op|')' op|':' newline|'\n' comment|'# NOTE(danms): Handle pre-1.32 build_instances() call. Remove me' nl|'\n' comment|'# when we bump the RPC API version to 2.0' nl|'\n' indent|' ' name|'build_inst_kwargs' op|'[' string|"'instances'" op|']' op|'=' name|'instance_obj' op|'.' name|'_make_instance_list' op|'(' nl|'\n' name|'ctxt' op|',' name|'objects' op|'.' name|'InstanceList' op|'(' op|')' op|',' name|'instances' op|',' op|'[' string|"'system_metadata'" op|',' nl|'\n' string|"'metadata'" op|']' op|')' newline|'\n' dedent|'' name|'our_cell' op|'=' name|'self' op|'.' name|'state_manager' op|'.' name|'get_my_state' op|'(' op|')' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'build_instances' op|'(' name|'ctxt' op|',' name|'our_cell' op|',' name|'build_inst_kwargs' op|')' newline|'\n' nl|'\n' DECL|member|get_cell_info_for_neighbors dedent|'' name|'def' name|'get_cell_info_for_neighbors' op|'(' name|'self' op|',' name|'_ctxt' op|')' op|':' newline|'\n' indent|' ' string|'"""Return cell information for our neighbor cells."""' newline|'\n' name|'return' name|'self' op|'.' name|'state_manager' op|'.' name|'get_cell_info_for_neighbors' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|run_compute_api_method dedent|'' name|'def' name|'run_compute_api_method' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'cell_name' op|',' name|'method_info' op|',' name|'call' op|')' op|':' newline|'\n' indent|' ' string|'"""Call a compute API method in a specific cell."""' newline|'\n' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'run_compute_api_method' op|'(' name|'ctxt' op|',' nl|'\n' name|'cell_name' op|',' nl|'\n' name|'method_info' op|',' nl|'\n' name|'call' op|')' newline|'\n' name|'if' name|'call' op|':' newline|'\n' indent|' ' name|'return' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|instance_update_at_top dedent|'' dedent|'' name|'def' name|'instance_update_at_top' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Update an instance at the top level cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'instance_update_at_top' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|instance_destroy_at_top dedent|'' name|'def' name|'instance_destroy_at_top' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Destroy an instance at the top level cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'instance_destroy_at_top' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|instance_delete_everywhere dedent|'' name|'def' name|'instance_delete_everywhere' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'delete_type' op|')' op|':' newline|'\n' indent|' ' string|'"""This is used by API cell when it didn\'t know what cell\n an instance was in, but the instance was requested to be\n deleted or soft_deleted. So, we\'ll broadcast this everywhere.\n """' newline|'\n' name|'if' name|'isinstance' op|'(' name|'instance' op|',' name|'dict' op|')' op|':' newline|'\n' indent|' ' name|'instance' op|'=' name|'objects' op|'.' name|'Instance' op|'.' name|'_from_db_object' op|'(' name|'ctxt' op|',' nl|'\n' name|'objects' op|'.' name|'Instance' op|'(' op|')' op|',' name|'instance' op|')' newline|'\n' dedent|'' name|'self' op|'.' name|'msg_runner' op|'.' name|'instance_delete_everywhere' op|'(' name|'ctxt' op|',' name|'instance' op|',' nl|'\n' name|'delete_type' op|')' newline|'\n' nl|'\n' DECL|member|instance_fault_create_at_top dedent|'' name|'def' name|'instance_fault_create_at_top' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance_fault' op|')' op|':' newline|'\n' indent|' ' string|'"""Create an instance fault at the top level cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'instance_fault_create_at_top' op|'(' name|'ctxt' op|',' name|'instance_fault' op|')' newline|'\n' nl|'\n' DECL|member|bw_usage_update_at_top dedent|'' name|'def' name|'bw_usage_update_at_top' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'bw_update_info' op|')' op|':' newline|'\n' indent|' ' string|'"""Update bandwidth usage at top level cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'bw_usage_update_at_top' op|'(' name|'ctxt' op|',' name|'bw_update_info' op|')' newline|'\n' nl|'\n' DECL|member|sync_instances dedent|'' name|'def' name|'sync_instances' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'project_id' op|',' name|'updated_since' op|',' name|'deleted' op|')' op|':' newline|'\n' indent|' ' string|'"""Force a sync of all instances, potentially by project_id,\n and potentially since a certain date/time.\n """' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'sync_instances' op|'(' name|'ctxt' op|',' name|'project_id' op|',' name|'updated_since' op|',' nl|'\n' name|'deleted' op|')' newline|'\n' nl|'\n' DECL|member|service_get_all dedent|'' name|'def' name|'service_get_all' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'filters' op|')' op|':' newline|'\n' indent|' ' string|'"""Return services in this cell and in all child cells."""' newline|'\n' name|'responses' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'service_get_all' op|'(' name|'ctxt' op|',' name|'filters' op|')' newline|'\n' name|'ret_services' op|'=' op|'[' op|']' newline|'\n' comment|'# 1 response per cell. Each response is a list of services.' nl|'\n' name|'for' name|'response' name|'in' name|'responses' op|':' newline|'\n' indent|' ' name|'services' op|'=' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' name|'for' name|'service' name|'in' name|'services' op|':' newline|'\n' indent|' ' name|'service' op|'=' name|'cells_utils' op|'.' name|'add_cell_to_service' op|'(' nl|'\n' name|'service' op|',' name|'response' op|'.' name|'cell_name' op|')' newline|'\n' name|'ret_services' op|'.' name|'append' op|'(' name|'service' op|')' newline|'\n' dedent|'' dedent|'' name|'return' name|'ret_services' newline|'\n' nl|'\n' dedent|'' op|'@' name|'oslo_messaging' op|'.' name|'expected_exceptions' op|'(' name|'exception' op|'.' name|'CellRoutingInconsistency' op|')' newline|'\n' DECL|member|service_get_by_compute_host name|'def' name|'service_get_by_compute_host' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'host_name' op|')' op|':' newline|'\n' indent|' ' string|'"""Return a service entry for a compute host in a certain cell."""' newline|'\n' name|'cell_name' op|',' name|'host_name' op|'=' name|'cells_utils' op|'.' name|'split_cell_and_item' op|'(' name|'host_name' op|')' newline|'\n' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'service_get_by_compute_host' op|'(' name|'ctxt' op|',' nl|'\n' name|'cell_name' op|',' nl|'\n' name|'host_name' op|')' newline|'\n' name|'service' op|'=' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' name|'service' op|'=' name|'cells_utils' op|'.' name|'add_cell_to_service' op|'(' name|'service' op|',' name|'response' op|'.' name|'cell_name' op|')' newline|'\n' name|'return' name|'service' newline|'\n' nl|'\n' DECL|member|get_host_uptime dedent|'' name|'def' name|'get_host_uptime' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'host_name' op|')' op|':' newline|'\n' indent|' ' string|'"""Return host uptime for a compute host in a certain cell\n\n :param host_name: fully qualified hostname. It should be in format of\n parent!child@host_id\n """' newline|'\n' name|'cell_name' op|',' name|'host_name' op|'=' name|'cells_utils' op|'.' name|'split_cell_and_item' op|'(' name|'host_name' op|')' newline|'\n' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'get_host_uptime' op|'(' name|'ctxt' op|',' name|'cell_name' op|',' nl|'\n' name|'host_name' op|')' newline|'\n' name|'return' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|service_update dedent|'' name|'def' name|'service_update' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'host_name' op|',' name|'binary' op|',' name|'params_to_update' op|')' op|':' newline|'\n' indent|' ' string|'"""Used to enable/disable a service. For compute services, setting to\n disabled stops new builds arriving on that host.\n\n :param host_name: the name of the host machine that the service is\n running\n :param binary: The name of the executable that the service runs as\n :param params_to_update: eg. {\'disabled\': True}\n :returns: the service reference\n """' newline|'\n' name|'cell_name' op|',' name|'host_name' op|'=' name|'cells_utils' op|'.' name|'split_cell_and_item' op|'(' name|'host_name' op|')' newline|'\n' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'service_update' op|'(' nl|'\n' name|'ctxt' op|',' name|'cell_name' op|',' name|'host_name' op|',' name|'binary' op|',' name|'params_to_update' op|')' newline|'\n' name|'service' op|'=' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' name|'service' op|'=' name|'cells_utils' op|'.' name|'add_cell_to_service' op|'(' name|'service' op|',' name|'response' op|'.' name|'cell_name' op|')' newline|'\n' name|'return' name|'service' newline|'\n' nl|'\n' DECL|member|service_delete dedent|'' name|'def' name|'service_delete' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'cell_service_id' op|')' op|':' newline|'\n' indent|' ' string|'"""Deletes the specified service."""' newline|'\n' name|'cell_name' op|',' name|'service_id' op|'=' name|'cells_utils' op|'.' name|'split_cell_and_item' op|'(' nl|'\n' name|'cell_service_id' op|')' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'service_delete' op|'(' name|'ctxt' op|',' name|'cell_name' op|',' name|'service_id' op|')' newline|'\n' nl|'\n' dedent|'' op|'@' name|'oslo_messaging' op|'.' name|'expected_exceptions' op|'(' name|'exception' op|'.' name|'CellRoutingInconsistency' op|')' newline|'\n' DECL|member|proxy_rpc_to_manager name|'def' name|'proxy_rpc_to_manager' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'topic' op|',' name|'rpc_message' op|',' name|'call' op|',' name|'timeout' op|')' op|':' newline|'\n' indent|' ' string|'"""Proxy an RPC message as-is to a manager."""' newline|'\n' name|'compute_topic' op|'=' name|'CONF' op|'.' name|'compute_topic' newline|'\n' name|'cell_and_host' op|'=' name|'topic' op|'[' name|'len' op|'(' name|'compute_topic' op|')' op|'+' number|'1' op|':' op|']' newline|'\n' name|'cell_name' op|',' name|'host_name' op|'=' name|'cells_utils' op|'.' name|'split_cell_and_item' op|'(' name|'cell_and_host' op|')' newline|'\n' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'proxy_rpc_to_manager' op|'(' name|'ctxt' op|',' name|'cell_name' op|',' nl|'\n' name|'host_name' op|',' name|'topic' op|',' name|'rpc_message' op|',' name|'call' op|',' name|'timeout' op|')' newline|'\n' name|'return' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|task_log_get_all dedent|'' name|'def' name|'task_log_get_all' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'task_name' op|',' name|'period_beginning' op|',' nl|'\n' name|'period_ending' op|',' name|'host' op|'=' name|'None' op|',' name|'state' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' string|'"""Get task logs from the DB from all cells or a particular\n cell.\n\n If \'host\' is not None, host will be of the format \'cell!name@host\',\n with \'@host\' being optional. The query will be directed to the\n appropriate cell and return all task logs, or task logs matching\n the host if specified.\n\n \'state\' also may be None. If it\'s not, filter by the state as well.\n """' newline|'\n' name|'if' name|'host' name|'is' name|'None' op|':' newline|'\n' indent|' ' name|'cell_name' op|'=' name|'None' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'cell_name' op|',' name|'host' op|'=' name|'cells_utils' op|'.' name|'split_cell_and_item' op|'(' name|'host' op|')' newline|'\n' comment|'# If no cell name was given, assume that the host name is the' nl|'\n' comment|'# cell_name and that the target is all hosts' nl|'\n' name|'if' name|'cell_name' name|'is' name|'None' op|':' newline|'\n' indent|' ' name|'cell_name' op|',' name|'host' op|'=' name|'host' op|',' name|'cell_name' newline|'\n' dedent|'' dedent|'' name|'responses' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'task_log_get_all' op|'(' name|'ctxt' op|',' name|'cell_name' op|',' nl|'\n' name|'task_name' op|',' name|'period_beginning' op|',' name|'period_ending' op|',' nl|'\n' name|'host' op|'=' name|'host' op|',' name|'state' op|'=' name|'state' op|')' newline|'\n' comment|'# 1 response per cell. Each response is a list of task log' nl|'\n' comment|'# entries.' nl|'\n' name|'ret_task_logs' op|'=' op|'[' op|']' newline|'\n' name|'for' name|'response' name|'in' name|'responses' op|':' newline|'\n' indent|' ' name|'task_logs' op|'=' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' name|'for' name|'task_log' name|'in' name|'task_logs' op|':' newline|'\n' indent|' ' name|'cells_utils' op|'.' name|'add_cell_to_task_log' op|'(' name|'task_log' op|',' nl|'\n' name|'response' op|'.' name|'cell_name' op|')' newline|'\n' name|'ret_task_logs' op|'.' name|'append' op|'(' name|'task_log' op|')' newline|'\n' dedent|'' dedent|'' name|'return' name|'ret_task_logs' newline|'\n' nl|'\n' dedent|'' op|'@' name|'oslo_messaging' op|'.' name|'expected_exceptions' op|'(' name|'exception' op|'.' name|'CellRoutingInconsistency' op|')' newline|'\n' DECL|member|compute_node_get name|'def' name|'compute_node_get' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'compute_id' op|')' op|':' newline|'\n' indent|' ' string|'"""Get a compute node by ID in a specific cell."""' newline|'\n' name|'cell_name' op|',' name|'compute_id' op|'=' name|'cells_utils' op|'.' name|'split_cell_and_item' op|'(' nl|'\n' name|'compute_id' op|')' newline|'\n' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'compute_node_get' op|'(' name|'ctxt' op|',' name|'cell_name' op|',' nl|'\n' name|'compute_id' op|')' newline|'\n' name|'node' op|'=' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' name|'node' op|'=' name|'cells_utils' op|'.' name|'add_cell_to_compute_node' op|'(' name|'node' op|',' name|'cell_name' op|')' newline|'\n' name|'return' name|'node' newline|'\n' nl|'\n' DECL|member|compute_node_get_all dedent|'' name|'def' name|'compute_node_get_all' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'hypervisor_match' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' string|'"""Return list of compute nodes in all cells."""' newline|'\n' name|'responses' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'compute_node_get_all' op|'(' name|'ctxt' op|',' nl|'\n' name|'hypervisor_match' op|'=' name|'hypervisor_match' op|')' newline|'\n' comment|'# 1 response per cell. Each response is a list of compute_node' nl|'\n' comment|'# entries.' nl|'\n' name|'ret_nodes' op|'=' op|'[' op|']' newline|'\n' name|'for' name|'response' name|'in' name|'responses' op|':' newline|'\n' indent|' ' name|'nodes' op|'=' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' name|'for' name|'node' name|'in' name|'nodes' op|':' newline|'\n' indent|' ' name|'node' op|'=' name|'cells_utils' op|'.' name|'add_cell_to_compute_node' op|'(' name|'node' op|',' nl|'\n' name|'response' op|'.' name|'cell_name' op|')' newline|'\n' name|'ret_nodes' op|'.' name|'append' op|'(' name|'node' op|')' newline|'\n' dedent|'' dedent|'' name|'return' name|'ret_nodes' newline|'\n' nl|'\n' DECL|member|compute_node_stats dedent|'' name|'def' name|'compute_node_stats' op|'(' name|'self' op|',' name|'ctxt' op|')' op|':' newline|'\n' indent|' ' string|'"""Return compute node stats totals from all cells."""' newline|'\n' name|'responses' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'compute_node_stats' op|'(' name|'ctxt' op|')' newline|'\n' name|'totals' op|'=' op|'{' op|'}' newline|'\n' name|'for' name|'response' name|'in' name|'responses' op|':' newline|'\n' indent|' ' name|'data' op|'=' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' name|'for' name|'key' op|',' name|'val' name|'in' name|'six' op|'.' name|'iteritems' op|'(' name|'data' op|')' op|':' newline|'\n' indent|' ' name|'totals' op|'.' name|'setdefault' op|'(' name|'key' op|',' number|'0' op|')' newline|'\n' name|'totals' op|'[' name|'key' op|']' op|'+=' name|'val' newline|'\n' dedent|'' dedent|'' name|'return' name|'totals' newline|'\n' nl|'\n' DECL|member|actions_get dedent|'' name|'def' name|'actions_get' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'cell_name' op|',' name|'instance_uuid' op|')' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'actions_get' op|'(' name|'ctxt' op|',' name|'cell_name' op|',' name|'instance_uuid' op|')' newline|'\n' name|'return' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|action_get_by_request_id dedent|'' name|'def' name|'action_get_by_request_id' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'cell_name' op|',' name|'instance_uuid' op|',' nl|'\n' name|'request_id' op|')' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'action_get_by_request_id' op|'(' name|'ctxt' op|',' name|'cell_name' op|',' nl|'\n' name|'instance_uuid' op|',' nl|'\n' name|'request_id' op|')' newline|'\n' name|'return' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|action_events_get dedent|'' name|'def' name|'action_events_get' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'cell_name' op|',' name|'action_id' op|')' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'action_events_get' op|'(' name|'ctxt' op|',' name|'cell_name' op|',' nl|'\n' name|'action_id' op|')' newline|'\n' name|'return' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|consoleauth_delete_tokens dedent|'' name|'def' name|'consoleauth_delete_tokens' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance_uuid' op|')' op|':' newline|'\n' indent|' ' string|'"""Delete consoleauth tokens for an instance in API cells."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'consoleauth_delete_tokens' op|'(' name|'ctxt' op|',' name|'instance_uuid' op|')' newline|'\n' nl|'\n' DECL|member|validate_console_port dedent|'' name|'def' name|'validate_console_port' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance_uuid' op|',' name|'console_port' op|',' nl|'\n' name|'console_type' op|')' op|':' newline|'\n' indent|' ' string|'"""Validate console port with child cell compute node."""' newline|'\n' name|'instance' op|'=' name|'objects' op|'.' name|'Instance' op|'.' name|'get_by_uuid' op|'(' name|'ctxt' op|',' name|'instance_uuid' op|')' newline|'\n' name|'if' name|'not' name|'instance' op|'.' name|'cell_name' op|':' newline|'\n' indent|' ' name|'raise' name|'exception' op|'.' name|'InstanceUnknownCell' op|'(' name|'instance_uuid' op|'=' name|'instance_uuid' op|')' newline|'\n' dedent|'' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'validate_console_port' op|'(' name|'ctxt' op|',' nl|'\n' name|'instance' op|'.' name|'cell_name' op|',' name|'instance_uuid' op|',' name|'console_port' op|',' nl|'\n' name|'console_type' op|')' newline|'\n' name|'return' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|get_capacities dedent|'' name|'def' name|'get_capacities' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'cell_name' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'state_manager' op|'.' name|'get_capacities' op|'(' name|'cell_name' op|')' newline|'\n' nl|'\n' DECL|member|bdm_update_or_create_at_top dedent|'' name|'def' name|'bdm_update_or_create_at_top' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'bdm' op|',' name|'create' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' string|'"""BDM was created/updated in this cell. Tell the API cells."""' newline|'\n' comment|'# TODO(ndipanov): Move inter-cell RPC to use objects' nl|'\n' name|'bdm' op|'=' name|'base_obj' op|'.' name|'obj_to_primitive' op|'(' name|'bdm' op|')' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'bdm_update_or_create_at_top' op|'(' name|'ctxt' op|',' name|'bdm' op|',' name|'create' op|'=' name|'create' op|')' newline|'\n' nl|'\n' DECL|member|bdm_destroy_at_top dedent|'' name|'def' name|'bdm_destroy_at_top' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance_uuid' op|',' name|'device_name' op|'=' name|'None' op|',' nl|'\n' name|'volume_id' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' string|'"""BDM was destroyed for instance in this cell. Tell the API cells."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'bdm_destroy_at_top' op|'(' name|'ctxt' op|',' name|'instance_uuid' op|',' nl|'\n' name|'device_name' op|'=' name|'device_name' op|',' nl|'\n' name|'volume_id' op|'=' name|'volume_id' op|')' newline|'\n' nl|'\n' DECL|member|get_migrations dedent|'' name|'def' name|'get_migrations' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'filters' op|')' op|':' newline|'\n' indent|' ' string|'"""Fetch migrations applying the filters."""' newline|'\n' name|'target_cell' op|'=' name|'None' newline|'\n' name|'if' string|'"cell_name"' name|'in' name|'filters' op|':' newline|'\n' indent|' ' name|'_path_cell_sep' op|'=' name|'cells_utils' op|'.' name|'PATH_CELL_SEP' newline|'\n' name|'target_cell' op|'=' string|"'%s%s%s'" op|'%' op|'(' name|'CONF' op|'.' name|'cells' op|'.' name|'name' op|',' name|'_path_cell_sep' op|',' nl|'\n' name|'filters' op|'[' string|"'cell_name'" op|']' op|')' newline|'\n' nl|'\n' dedent|'' name|'responses' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'get_migrations' op|'(' name|'ctxt' op|',' name|'target_cell' op|',' nl|'\n' name|'False' op|',' name|'filters' op|')' newline|'\n' name|'migrations' op|'=' op|'[' op|']' newline|'\n' name|'for' name|'response' name|'in' name|'responses' op|':' newline|'\n' indent|' ' name|'migrations' op|'+=' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' dedent|'' name|'return' name|'migrations' newline|'\n' nl|'\n' DECL|member|instance_update_from_api dedent|'' name|'def' name|'instance_update_from_api' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'expected_vm_state' op|',' nl|'\n' name|'expected_task_state' op|',' name|'admin_state_reset' op|')' op|':' newline|'\n' indent|' ' string|'"""Update an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'instance_update_from_api' op|'(' name|'ctxt' op|',' name|'instance' op|',' nl|'\n' name|'expected_vm_state' op|',' nl|'\n' name|'expected_task_state' op|',' nl|'\n' name|'admin_state_reset' op|')' newline|'\n' nl|'\n' DECL|member|start_instance dedent|'' name|'def' name|'start_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Start an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'start_instance' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|stop_instance dedent|'' name|'def' name|'stop_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'do_cast' op|'=' name|'True' op|',' nl|'\n' name|'clean_shutdown' op|'=' name|'True' op|')' op|':' newline|'\n' indent|' ' string|'"""Stop an instance in its cell."""' newline|'\n' name|'response' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'stop_instance' op|'(' name|'ctxt' op|',' name|'instance' op|',' nl|'\n' name|'do_cast' op|'=' name|'do_cast' op|',' nl|'\n' name|'clean_shutdown' op|'=' name|'clean_shutdown' op|')' newline|'\n' name|'if' name|'not' name|'do_cast' op|':' newline|'\n' indent|' ' name|'return' name|'response' op|'.' name|'value_or_raise' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|cell_create dedent|'' dedent|'' name|'def' name|'cell_create' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'values' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'state_manager' op|'.' name|'cell_create' op|'(' name|'ctxt' op|',' name|'values' op|')' newline|'\n' nl|'\n' DECL|member|cell_update dedent|'' name|'def' name|'cell_update' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'cell_name' op|',' name|'values' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'state_manager' op|'.' name|'cell_update' op|'(' name|'ctxt' op|',' name|'cell_name' op|',' name|'values' op|')' newline|'\n' nl|'\n' DECL|member|cell_delete dedent|'' name|'def' name|'cell_delete' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'cell_name' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'state_manager' op|'.' name|'cell_delete' op|'(' name|'ctxt' op|',' name|'cell_name' op|')' newline|'\n' nl|'\n' DECL|member|cell_get dedent|'' name|'def' name|'cell_get' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'cell_name' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'state_manager' op|'.' name|'cell_get' op|'(' name|'ctxt' op|',' name|'cell_name' op|')' newline|'\n' nl|'\n' DECL|member|reboot_instance dedent|'' name|'def' name|'reboot_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'reboot_type' op|')' op|':' newline|'\n' indent|' ' string|'"""Reboot an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'reboot_instance' op|'(' name|'ctxt' op|',' name|'instance' op|',' name|'reboot_type' op|')' newline|'\n' nl|'\n' DECL|member|pause_instance dedent|'' name|'def' name|'pause_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Pause an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'pause_instance' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|unpause_instance dedent|'' name|'def' name|'unpause_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Unpause an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'unpause_instance' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|suspend_instance dedent|'' name|'def' name|'suspend_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Suspend an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'suspend_instance' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|resume_instance dedent|'' name|'def' name|'resume_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Resume an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'resume_instance' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|terminate_instance dedent|'' name|'def' name|'terminate_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'delete_type' op|'=' string|"'delete'" op|')' op|':' newline|'\n' indent|' ' string|'"""Delete an instance in its cell."""' newline|'\n' comment|'# NOTE(rajesht): The `delete_type` parameter is passed so that it will' nl|'\n' comment|'# be routed to destination cell, where instance deletion will happen.' nl|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'terminate_instance' op|'(' name|'ctxt' op|',' name|'instance' op|',' nl|'\n' name|'delete_type' op|'=' name|'delete_type' op|')' newline|'\n' nl|'\n' DECL|member|soft_delete_instance dedent|'' name|'def' name|'soft_delete_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Soft-delete an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'soft_delete_instance' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|resize_instance dedent|'' name|'def' name|'resize_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'flavor' op|',' nl|'\n' name|'extra_instance_updates' op|',' nl|'\n' name|'clean_shutdown' op|'=' name|'True' op|')' op|':' newline|'\n' indent|' ' string|'"""Resize an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'resize_instance' op|'(' name|'ctxt' op|',' name|'instance' op|',' nl|'\n' name|'flavor' op|',' name|'extra_instance_updates' op|',' nl|'\n' name|'clean_shutdown' op|'=' name|'clean_shutdown' op|')' newline|'\n' nl|'\n' DECL|member|live_migrate_instance dedent|'' name|'def' name|'live_migrate_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'block_migration' op|',' nl|'\n' name|'disk_over_commit' op|',' name|'host_name' op|')' op|':' newline|'\n' indent|' ' string|'"""Live migrate an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'live_migrate_instance' op|'(' name|'ctxt' op|',' name|'instance' op|',' nl|'\n' name|'block_migration' op|',' nl|'\n' name|'disk_over_commit' op|',' nl|'\n' name|'host_name' op|')' newline|'\n' nl|'\n' DECL|member|revert_resize dedent|'' name|'def' name|'revert_resize' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Revert a resize for an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'revert_resize' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|confirm_resize dedent|'' name|'def' name|'confirm_resize' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Confirm a resize for an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'confirm_resize' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|reset_network dedent|'' name|'def' name|'reset_network' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Reset networking for an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'reset_network' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|inject_network_info dedent|'' name|'def' name|'inject_network_info' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' string|'"""Inject networking for an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'inject_network_info' op|'(' name|'ctxt' op|',' name|'instance' op|')' newline|'\n' nl|'\n' DECL|member|snapshot_instance dedent|'' name|'def' name|'snapshot_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'image_id' op|')' op|':' newline|'\n' indent|' ' string|'"""Snapshot an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'snapshot_instance' op|'(' name|'ctxt' op|',' name|'instance' op|',' name|'image_id' op|')' newline|'\n' nl|'\n' DECL|member|backup_instance dedent|'' name|'def' name|'backup_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'image_id' op|',' name|'backup_type' op|',' name|'rotation' op|')' op|':' newline|'\n' indent|' ' string|'"""Backup an instance in its cell."""' newline|'\n' name|'self' op|'.' name|'msg_runner' op|'.' name|'backup_instance' op|'(' name|'ctxt' op|',' name|'instance' op|',' name|'image_id' op|',' nl|'\n' name|'backup_type' op|',' name|'rotation' op|')' newline|'\n' nl|'\n' DECL|member|rebuild_instance dedent|'' name|'def' name|'rebuild_instance' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'image_href' op|',' name|'admin_password' op|',' nl|'\n' name|'files_to_inject' op|',' name|'preserve_ephemeral' op|',' name|'kwargs' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'msg_runner' op|'.' name|'rebuild_instance' op|'(' name|'ctxt' op|',' name|'instance' op|',' name|'image_href' op|',' nl|'\n' name|'admin_password' op|',' name|'files_to_inject' op|',' nl|'\n' name|'preserve_ephemeral' op|',' name|'kwargs' op|')' newline|'\n' nl|'\n' DECL|member|set_admin_password dedent|'' name|'def' name|'set_admin_password' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'instance' op|',' name|'new_pass' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'msg_runner' op|'.' name|'set_admin_password' op|'(' name|'ctxt' op|',' name|'instance' op|',' name|'new_pass' op|')' newline|'\n' nl|'\n' DECL|member|get_keypair_at_top dedent|'' name|'def' name|'get_keypair_at_top' op|'(' name|'self' op|',' name|'ctxt' op|',' name|'user_id' op|',' name|'name' op|')' op|':' newline|'\n' indent|' ' name|'responses' op|'=' name|'self' op|'.' name|'msg_runner' op|'.' name|'get_keypair_at_top' op|'(' name|'ctxt' op|',' name|'user_id' op|',' name|'name' op|')' newline|'\n' name|'keypairs' op|'=' op|'[' name|'resp' op|'.' name|'value' name|'for' name|'resp' name|'in' name|'responses' name|'if' name|'resp' op|'.' name|'value' name|'is' name|'not' name|'None' op|']' newline|'\n' nl|'\n' name|'if' name|'len' op|'(' name|'keypairs' op|')' op|'==' number|'0' op|':' newline|'\n' indent|' ' name|'return' name|'None' newline|'\n' dedent|'' name|'elif' name|'len' op|'(' name|'keypairs' op|')' op|'>' number|'1' op|':' newline|'\n' indent|' ' name|'cell_names' op|'=' string|"', '" op|'.' name|'join' op|'(' op|'[' name|'resp' op|'.' name|'cell_name' name|'for' name|'resp' name|'in' name|'responses' nl|'\n' name|'if' name|'resp' op|'.' name|'value' name|'is' name|'not' name|'None' op|']' op|')' newline|'\n' name|'LOG' op|'.' name|'warning' op|'(' name|'_LW' op|'(' string|'"The same keypair name \'%(name)s\' exists in the "' nl|'\n' string|'"following cells: %(cell_names)s. The keypair "' nl|'\n' string|'"value from the first cell is returned."' op|')' op|',' nl|'\n' op|'{' string|"'name'" op|':' name|'name' op|',' string|"'cell_names'" op|':' name|'cell_names' op|'}' op|')' newline|'\n' nl|'\n' dedent|'' name|'return' name|'keypairs' op|'[' number|'0' op|']' newline|'\n' dedent|'' dedent|'' endmarker|'' end_unit
[ 27471, 62, 20850, 198, 23893, 91, 6, 2, 15069, 357, 66, 8, 2321, 37927, 13200, 14504, 278, 6, 198, 21283, 91, 6, 59, 77, 6, 198, 23893, 91, 6, 2, 1439, 6923, 33876, 2637, 198, 21283, 91, 6, 59, 77, 6, 198, 23893, 91, 6, 2, 6...
1.973076
25,442
# -*- coding: utf-8 -*- """ jishaku.modules ~~~~~~~~~~~~~~ Functions for managing and searching modules. :copyright: (c) 2021 Devon (Gorialis) R :license: MIT, see LICENSE for more details. """ import pathlib import typing import pkg_resources from braceexpand import UnbalancedBracesError, braceexpand from diskord.ext import commands __all__ = ('find_extensions_in', 'resolve_extensions', 'package_version', 'ExtensionConverter') def find_extensions_in(path: typing.Union[str, pathlib.Path]) -> list: """ Tries to find things that look like bot extensions in a directory. """ if not isinstance(path, pathlib.Path): path = pathlib.Path(path) if not path.is_dir(): return [] extension_names = [] # Find extensions directly in this folder for subpath in path.glob('*.py'): parts = subpath.with_suffix('').parts if parts[0] == '.': parts = parts[1:] extension_names.append('.'.join(parts)) # Find extensions as subfolder modules for subpath in path.glob('*/__init__.py'): parts = subpath.parent.parts if parts[0] == '.': parts = parts[1:] extension_names.append('.'.join(parts)) return extension_names def resolve_extensions(bot: commands.Bot, name: str) -> list: """ Tries to resolve extension queries into a list of extension names. """ exts = [] for ext in braceexpand(name): if ext.endswith('.*'): module_parts = ext[:-2].split('.') path = pathlib.Path(*module_parts) exts.extend(find_extensions_in(path)) elif ext == '~': exts.extend(bot.extensions) else: exts.append(ext) return exts def package_version(package_name: str) -> typing.Optional[str]: """ Returns package version as a string, or None if it couldn't be found. """ try: return pkg_resources.get_distribution(package_name).version except (pkg_resources.DistributionNotFound, AttributeError): return None class ExtensionConverter(commands.Converter): # pylint: disable=too-few-public-methods """ A converter interface for resolve_extensions to match extensions from users. """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 73, 680, 8719, 13, 18170, 198, 15116, 8728, 4907, 198, 198, 24629, 2733, 329, 11149, 290, 10342, 13103, 13, 198, 198, 25, 22163, 4766, 25, 357, 66, 8,...
2.565415
879