id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
108514
# ====================================================================== # Disk Defragmenter # Advent of Code 2017 Day 14 -- <NAME> -- https://adventofcode.com # # Computer simulation by Dr. <NAME> III # ====================================================================== # ====================================================================== # d e f r a g . p y # ====================================================================== "A solver for Disk Defragmenter for Advent of Code 2017 Day 14" # ---------------------------------------------------------------------- # import # ---------------------------------------------------------------------- import knots # ---------------------------------------------------------------------- # constants # ---------------------------------------------------------------------- HEX_TO_BITS = { '0': [0, 0, 0, 0], '1': [0, 0, 0, 1], '2': [0, 0, 1, 0], '3': [0, 0, 1, 1], '4': [0, 1, 0, 0], '5': [0, 1, 0, 1], '6': [0, 1, 1, 0], '7': [0, 1, 1, 1], '8': [1, 0, 0, 0], '9': [1, 0, 0, 1], 'a': [1, 0, 1, 0], 'b': [1, 0, 1, 1], 'c': [1, 1, 0, 0], 'd': [1, 1, 0, 1], 'e': [1, 1, 1, 0], 'f': [1, 1, 1, 1], } DELTA = [(0, -1), (0, 1), (1, 0), (-1, 0)] # ====================================================================== # Defrag # ====================================================================== class Defrag(object): # pylint: disable=R0902, R0205 """Object for a disk defragmenter""" def __init__(self, size=128, text=None, part2=False): # 1. Set the initial values self.part2 = part2 self.text = text self.size = size self.bits = [[0 for _ in range(size)] for _ in range(size)] self.region = None # 2. if there is text, use key to populate bits if text is not None: self.populate_bits() def __getitem__(self, key): return self.bits[key[1]][key[0]] def __setitem__(self, key, value): self.bits[key[1]][key[0]] = value def is_key_valid(self, key): "Check if the key is valid for getting a bit" if key[0] < 0 or key[0] >= self.size or key[1] < 0 or key[1] >= self.size: return False return True def populate_bits(self): "Populate the bits from the knot hash" # 0. Precondition axiom assert self.size <= 128 # 1. loop for each row of bits for rnum in range(self.size): # 2. Generate row key row_key = self.text + '-%d' % rnum # 3. Get the dense hash knot = knots.Knots(length=256, part2=True) # 4. Get the dense hash dense_hash = knot.process_knots(text=row_key, verbose=False) # 5. Convert the dense_hash to bits bits = self.hash_to_bits(dense_hash) # 6. Save the bits self.bits[rnum] = bits def hash_to_bits(self, dense_hash): "Turn a dense hash into bits" # 0. Precondition axiom assert self.size <= 128 # 1. Start with nothing result = [] # 2. Loop for all of the hex digits for digit in dense_hash: # 3. Add the bits to the result result.extend(HEX_TO_BITS[digit]) # 4. Return the bits return result[0:self.size] def bits_to_regions(self, verbose=False): "Group the bits into regions" # 1. Set initial region number self.region = 2 # 2. Loop for every row and every column for rnum in range(self.size): for cnum in range(self.size): # 3. Ignore unused squares or one already in regions if self[(cnum, rnum)] != 1: continue # 4. This square is now a region if verbose: print("Starting region %d at (%d, %d" % (self.region, cnum, rnum)) self[(cnum, rnum)] = self.region # 5. Add neighbors of this square to the region self.add_neighbors(cnum, rnum) # 6. Increment region number self.region += 1 def add_neighbors(self, cnum, rnum): "Add neighboring squares to an existing region" # 1. Add the neighbors of the given square for delta in DELTA: # 2. Determine the square of the neighbot ncol = cnum + delta[0] nrow = rnum + delta[1] # 3. Ignore the neighbor if invalid location if not self.is_key_valid((ncol, nrow)): continue # 4. Ignore the neighbor if empty or already in region if self[(ncol, nrow)] != 1: continue # 5. This square is now in the region self[(ncol, nrow)] = self.region # 6. Add the neighbors of this square self.add_neighbors(ncol, nrow) def part_one(self, verbose=False, limit=0): "Returns the number of squares used" # 1. Start with nothing result = 0 # 2. Loop for all of the rows for row in self.bits: # 3. Add up the bits in the row and accumulate the result result += sum(row) # 4. Return the number of bits used return result def part_two(self, verbose=False, limit=0): "Returns the number of squares used" # 1. Convert bits to regions self.bits_to_regions(verbose=verbose) # 2. Return the number of regions return self.region - 2 # ---------------------------------------------------------------------- # module initialization # ---------------------------------------------------------------------- if __name__ == '__main__': pass # ====================================================================== # end d e f r a g . p y end # ======================================================================
StarcoderdataPython
1747130
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "LICENSE.txt" file accompanying this file. # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. # See the License for the specific language governing permissions and limitations under the License. import logging import os as os_lib from shutil import copyfile import boto3 import pytest import yaml from assertpy import assert_that from remote_command_executor import RemoteCommandExecutor from s3_common_utils import check_s3_read_resource, check_s3_read_write_resource, get_policy_resources from tests.common.assertions import assert_no_errors_in_logs from tests.common.schedulers_common import get_scheduler_commands from tests.schedulers.test_awsbatch import _test_job_submission as test_job_submission_awsbatch from tests.schedulers.test_slurm import _wait_for_computefleet_changed as wait_for_computefleet_changed @pytest.mark.usefixtures("os", "instance") def test_iam_roles( region, scheduler, create_roles_stack, pcluster_config_reader, clusters_factory, test_datadir, ): is_awsbatch = scheduler == "awsbatch" cfn_client, ec2_client, iam_client, lambda_client = _create_boto3_clients(region) compute_instance_profile, compute_instance_role, head_instance_role, lambda_role = _create_cluster_roles( create_roles_stack, "integ-tests-iam-cluster-roles", "cluster-roles.cfn.yaml", is_awsbatch ) create_config, update_config = _get_config_create_and_update(test_datadir) cluster = _test_cluster_create( cfn_client, clusters_factory, compute_instance_profile, compute_instance_role, create_config, ec2_client, head_instance_role, iam_client, is_awsbatch, lambda_client, lambda_role, pcluster_config_reader, ) _test_cluster_update( cfn_client, cluster, compute_instance_profile, compute_instance_role, create_roles_stack, ec2_client, head_instance_role, iam_client, is_awsbatch, lambda_client, lambda_role, pcluster_config_reader, update_config, ) _test_cluster_scaling(cluster, is_awsbatch, region, scheduler) def _get_config_create_and_update(test_datadir): # Copy the config file template for reuse in update. config_file_name = "pcluster.config.yaml" config_file_path = os_lib.path.join(str(test_datadir), config_file_name) updated_config_file_name = "pcluster.config.update.yaml" updated_config_file_path = os_lib.path.join(str(test_datadir), updated_config_file_name) copyfile(config_file_path, updated_config_file_path) return config_file_name, updated_config_file_name def _create_boto3_clients(region): # Create boto3 client cfn_client = boto3.client("cloudformation", region_name=region) ec2_client = boto3.client("ec2", region_name=region) iam_client = boto3.client("iam", region_name=region) lambda_client = boto3.client("lambda", region_name=region) return cfn_client, ec2_client, iam_client, lambda_client def _test_cluster_create( cfn_client, clusters_factory, compute_instance_profile, compute_instance_role, config_file_name, ec2_client, head_instance_role, iam_client, is_awsbatch, lambda_client, lambda_role, pcluster_config_reader, ): cluster_config = pcluster_config_reader( config_file=config_file_name, head_instance_role=head_instance_role, compute_instance_role=compute_instance_role, compute_instance_profile=compute_instance_profile, iam_lambda_role=lambda_role, min_count=1, ) cluster = clusters_factory(cluster_config) # Check roles are attached to the resources # If scheduler is awsbatch, there will still be IAM roles created. _check_roles( cfn_client, ec2_client, iam_client, lambda_client, cluster.name, head_instance_role, compute_instance_role, lambda_role, not is_awsbatch, ) return cluster def _test_cluster_scaling(cluster, is_awsbatch, region, scheduler): remote_command_executor = RemoteCommandExecutor(cluster) if is_awsbatch: timeout = ( 120 if region.startswith("cn-") else 60 ) # Longer timeout in china regions due to less reliable networking test_job_submission_awsbatch( remote_command_executor, f"awsbsub --vcpus 2 --memory 256 --timeout {timeout} sleep 1" ) else: scheduler_commands = get_scheduler_commands(scheduler, remote_command_executor) job_id = scheduler_commands.submit_command_and_assert_job_accepted( submit_command_args={"command": "sleep 1", "nodes": 1} ) scheduler_commands.wait_job_completed(job_id) def _test_cluster_update( cfn_client, cluster, compute_instance_profile, compute_instance_role, create_roles_stack, ec2_client, head_instance_role, iam_client, is_awsbatch, lambda_client, lambda_role, pcluster_config_reader, updated_config_file_name, ): ( another_compute_instance_profile, another_compute_instance_role, another_head_instance_role, another_lambda_role, ) = _create_cluster_roles( create_roles_stack, "integ-tests-iam-cluster-roles", "cluster-roles.cfn.yaml", is_awsbatch ) assert_that(another_lambda_role == lambda_role).is_false() assert_that(another_head_instance_role == head_instance_role).is_false() if not is_awsbatch: assert_that(another_compute_instance_profile == compute_instance_profile).is_false() assert_that(another_compute_instance_role == compute_instance_role).is_false() # Update cluster with new roles cluster.stop() wait_for_computefleet_changed(cluster, "DISABLED" if is_awsbatch else "STOPPED") cluster.update( str( pcluster_config_reader( config_file=updated_config_file_name, head_instance_role=another_head_instance_role, compute_instance_role=another_compute_instance_role, compute_instance_profile=another_compute_instance_profile, iam_lambda_role=another_lambda_role, min_count=0, ) ) ) cluster.start() wait_for_computefleet_changed(cluster, "ENABLED" if is_awsbatch else "RUNNING") # Check new roles are attached to the resources _check_roles( cfn_client, ec2_client, iam_client, lambda_client, cluster.name, another_head_instance_role, another_compute_instance_role, another_lambda_role, not is_awsbatch, ) def _create_cluster_roles(create_roles_stack, stack_prefix, roles_file, is_awsbatch): cluster_roles_stack = create_roles_stack(stack_prefix=stack_prefix, roles_file=roles_file) if is_awsbatch: head_instance_role = cluster_roles_stack.cfn_outputs["HeadNodeRoleBatch"] lambda_role = cluster_roles_stack.cfn_outputs["CustomLambdaResourcesRoleBatch"] compute_instance_role = "" compute_instance_profile = "" else: head_instance_role = cluster_roles_stack.cfn_outputs["HeadNodeRoleSlurm"] compute_instance_profile = cluster_roles_stack.cfn_outputs["ComputeNodeInstanceProfileSlurm"] compute_instance_role = cluster_roles_stack.cfn_outputs["ComputeNodeRoleSlurm"] lambda_role = cluster_roles_stack.cfn_outputs["CustomLambdaResourcesRoleSlurm"] return compute_instance_profile, compute_instance_role, head_instance_role, lambda_role def _check_roles( cfn_client, ec2_client, iam_client, lambda_client, stack_name, head_instance_role, compute_instance_role, lambda_role, check_no_role_is_created, ): """Test roles are attached to EC2 instances and Lambda functions.""" resources = cfn_client.describe_stack_resources(StackName=stack_name)["StackResources"] for resource in resources: resource_type = resource["ResourceType"] if check_no_role_is_created: # If check_no_role_is_created, check that there is no role created in the stack. assert_that(resource_type).is_not_equal_to("AWS::IAM::Role") if resource_type == "AWS::Lambda::Function": # Check the role is attached to the Lambda function lambda_function = lambda_client.get_function(FunctionName=resource["PhysicalResourceId"])["Configuration"] assert_that(lambda_function["Role"]).is_equal_to(lambda_role) if resource_type == "AWS::EC2::Instance": # Check the role is attached to the EC2 instance instance_profile_arn = ( ec2_client.describe_instances(InstanceIds=[resource["PhysicalResourceId"]]) .get("Reservations")[0] .get("Instances")[0] .get("IamInstanceProfile") .get("Arn") ) instance_roles_list = [ role.get("Arn") for role in ( iam_client.get_instance_profile( InstanceProfileName=_get_resource_name_from_resource_arn(instance_profile_arn) ) .get("InstanceProfile") .get("Roles") ) ] if resource["LogicalResourceId"] == "HeadNode": assert_that(instance_roles_list).contains(head_instance_role) elif resource["LogicalResourceId"] == "ComputeNode": assert_that(instance_roles_list).contains(compute_instance_role) def _get_resource_name_from_resource_arn(resource_arn): return resource_arn.rsplit("/", 1)[-1] if resource_arn else "" @pytest.mark.usefixtures("os", "instance") def test_iam_policies(region, scheduler, pcluster_config_reader, clusters_factory): """Test IAM Policies""" cluster_config = pcluster_config_reader( iam_policies=["arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess", "arn:aws:iam::aws:policy/AWSBatchFullAccess"] ) cluster = clusters_factory(cluster_config) remote_command_executor = RemoteCommandExecutor(cluster) _test_s3_access(remote_command_executor, region) if scheduler == "awsbatch": _test_batch_access(remote_command_executor, region) assert_no_errors_in_logs(remote_command_executor, scheduler) def _test_s3_access(remote_command_executor, region): logging.info("Testing S3 Access") result = remote_command_executor.run_remote_command(f"AWS_DEFAULT_REGION={region} sudo aws s3 ls").stdout # An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied assert_that(result).does_not_contain("AccessDenied") def _test_batch_access(remote_command_executor, region): logging.info("Testing AWS Batch Access") result = remote_command_executor.run_remote_command( f"AWS_DEFAULT_REGION={region} aws batch describe-compute-environments" ).stdout # An error occurred (AccessDeniedException) when calling the DescribeComputeEnvironments operation: ... assert_that(result).does_not_contain("AccessDeniedException") @pytest.mark.usefixtures("os", "instance", "scheduler") def test_s3_read_write_resource(region, pcluster_config_reader, s3_bucket_factory, clusters_factory, test_datadir): # Create S3 bucket for testing s3_read_resource and s3_read_write_resource bucket_name = s3_bucket_factory() bucket = boto3.resource("s3", region_name=region).Bucket(bucket_name) logging.info("bucket is {0}".format(bucket_name)) bucket.upload_file(str(test_datadir / "s3_test_file"), "read_only/s3_test_file") bucket.upload_file(str(test_datadir / "s3_test_file"), "read_and_write/s3_test_file") cluster_config = pcluster_config_reader(bucket=bucket_name) cluster = clusters_factory(cluster_config) with open(cluster_config, encoding="utf-8") as conf_file: config = yaml.safe_load(conf_file) # Check S3 resources check_s3_read_resource(region, cluster, get_policy_resources(config, enable_write_access=False)) check_s3_read_write_resource(region, cluster, get_policy_resources(config, enable_write_access=True))
StarcoderdataPython
3265423
import logging import math import os import numpy as np import torch from torch import nn from torch.autograd import Variable as Var from archive.genut import msk_list_to_mat from archive.genut import Trainer class LMTrainer(Trainer): def __init__(self, opt, model, data): super().__init__(opt, model, data) # self.logger = Logger(opt.print_every, self.n_batch) # weight = torch.ones(opt.full_dict_size) # weight[0] = 0 # assert 0 == opt.word_dict.fword2idx('<pad>') self.crit = nn.CrossEntropyLoss(size_average=True, reduce=True, ignore_index=0) self.crit_test = nn.CrossEntropyLoss(size_average=False, reduce=False, ignore_index=0) self.opt = opt self.model = model self.train_bag = data[0] self.test_bag = data[1] self.n_batch = len(self.train_bag) # parameters = filter(lambda p: p.requires_grad, self.model.parameters()) # self.optimizer = torch.optim.Adagrad(parameters, lr=opt.lr) # TODO self.optimizer = torch.optim.SGD(self.model.parameters(), lr=opt.lr, momentum=0.9) # self.optimizer = torch.optim.SGD(parameters,lr=opt.lr) # self.mul_loss = opt.mul_loss # self.add_loss = opt.add_loss # dicts = [word_dict, pos_dict, ner_dict] self.word_dict = opt.word_dict self.clip = opt.clip def func_train(self, inp_var, inp_msk): self.optimizer.zero_grad() # clear grad aux = {} batch_size = inp_var.size()[0] batch_size_ = len(inp_msk) assert batch_size == batch_size_ target_len = inp_msk[0] decoder_outputs_prob, decoder_outputs = self.model.forward(inp_var, inp_msk, inp_var, inp_msk, aux) valid_pos_mask = Var(msk_list_to_mat(inp_msk), requires_grad=False).view(target_len * batch_size, 1) if self.opt.use_cuda: valid_pos_mask = valid_pos_mask.cuda() # Compulsory NLL loss part pred_prob = decoder_outputs_prob.view(target_len * batch_size, -1) # print(inp_var) seq_first_inp_var = inp_var.transpose(1, 0).contiguous() gold_dist = seq_first_inp_var.view(target_len * batch_size) gold_dist = Var(gold_dist) if self.opt.use_cuda: gold_dist = gold_dist.cuda() loss = self.crit(pred_prob, gold_dist) loss.backward() torch.nn.utils.clip_grad_norm(self.model.parameters(), self.clip) self.optimizer.step() return loss.data[0], math.exp(loss.data[0]) def func_test(self, inp_var, inp_msk): target_len = inp_msk[0] batch_size = inp_var.size()[0] decoder_outputs_prob, decoder_outputs = self.model.forward(inp_var, inp_msk, tgt_var=inp_var, tgt_msk=inp_msk, aux=None) # Compulsory NLL loss part pred_prob = decoder_outputs_prob.view(target_len * batch_size, -1) seq_first_inp_var = inp_var.transpose(1, 0).contiguous() gold_dist = Var(seq_first_inp_var.view(target_len * batch_size)) if self.opt.use_cuda: gold_dist = gold_dist.cuda() loss = self.crit_test(pred_prob, gold_dist) loss = torch.sum(loss) return loss.data[0], decoder_outputs def train_iters(self): """ Training function called from main.py. :return: """ for epo in range(self.opt.start_epo, self.opt.n_epo + 1): self.model.train() batch_order = np.arange(self.n_batch) np.random.shuffle(batch_order) for idx, batch_idx in enumerate(batch_order): # self.logger.init_new_batch(batch_idx) current_batch = self.train_bag[batch_idx] # current_batch = copy.deepcopy(tmp_cur_batch) inp_var = current_batch['txt'] inp_msk = current_batch['txt_msk'] # out_var = current_batch['cur_out_var'] # out_mask = current_batch['cur_out_mask'] # scatter_msk = current_batch['cur_scatter_mask'].cuda() # replacement = current_batch['replacement'] # max_oov_len = len(replacement) # self.logger.set_oov(max_oov_len) # inp_var = Var(inp_var) if self.opt.use_cuda: # inp_var = [x.contiguous().cuda() for x in inp_var] inp_var = inp_var.contiguous().cuda() nll, ppl = self.func_train(inp_var, inp_msk) if idx % self.opt.print_every == 0: logging.info('NLL:%.2f \tPPL:%s' % (nll, str(ppl))) if idx % self.opt.save_every == 0: ppl = self.evaluate() os.chdir(self.opt.save_dir) name_string = '%d_%.2f'.lower() % (epo, ppl) logging.info("Saving in epo %s" % name_string) torch.save(self.model.emb.state_dict(), name_string + '_emb') # torch.save(self.model.enc.state_dict(), name_string + '_enc') torch.save(self.model.dec.state_dict(), name_string + '_dec') torch.save(self.model.opt, name_string + '_opt') os.chdir('..') def evaluate(self): self.model.eval() n_batch = len(self.test_bag) test_len = 0 accumulated_ppl = 0 for idx in range(n_batch): current_batch = self.test_bag[idx] inp_var = current_batch['txt'] inp_mask = current_batch['txt_msk'] batch_size = inp_var.size()[0] test_len += inp_mask[0] * batch_size nll, decoder_output = self.func_test(inp_var, inp_mask) accumulated_ppl += nll final_ppl = accumulated_ppl / test_len final_ppl = math.exp(final_ppl) logging.info('PPL: %f' % final_ppl) return final_ppl
StarcoderdataPython
3375167
import random MEMBER_SIZES = 3 with open("fp_profiling", "r") as fh: lines = [line.strip().split() for line in fh.readlines()] totals = {} lasts = {} for stamp, stage, token, module in lines: stamp = float(stamp) if token not in totals: totals[token] = (0, 0, 9999999999, 0, []) if stage == "START": lasts[token] = stamp elif stage == "STOP": accum, count, min_delta, max_delta, hits = totals[token] delta = stamp - lasts[token] totals[token] = ( accum + delta, count + 1, min(delta, min_delta), max(delta, max_delta), hits + [(delta, module)], ) for token, pair in totals.items(): accum, count, min_delta, max_delta, hits = totals[token] if count == 0: continue print( "{} {:.6f} ({:.6f}, {:.6f}, {:.6f}) {}".format( token, accum, min_delta, accum / count, max_delta, hits[int(count / 2)][0] ) ) hist = {index: (0, []) for index in range(0, 1000)} for item, module in hits: index = int(int(item * 1000) / 10) * 10 if index not in hist: hist[index] = (0, []) hist[index] = (hist[index][0] + 1, hist[index][1] + [module]) for index, pair in hist.items(): count, members = pair random.shuffle(members) if count != 0: print( " {:3} ms: {:4} -- {}".format( index, count, " ".join(members[:MEMBER_SIZES]) + ("" if len(members) <= MEMBER_SIZES else " ..."), ) )
StarcoderdataPython
22832
# known contracts from protocol CONTRACTS = [ # NFT - Meteor Dust "<KEY>", # NFT - Eggs "<KEY>", # NFT - Dragons "<KEY>", # NFT - Loot "<KEY>", ] def handle(exporter, elem, txinfo, contract): print(f"Levana! {contract}") #print(elem)
StarcoderdataPython
3348392
import datetime import os import re from dateutil import tz import sqlalchemy as sa from sqlalchemy.engine.reflection import Inspector from alembic import autogenerate from alembic import command from alembic import util from alembic.environment import EnvironmentContext from alembic.operations import ops from alembic.script import ScriptDirectory from alembic.testing import assert_raises_message from alembic.testing import assertions from alembic.testing import eq_ from alembic.testing import is_ from alembic.testing import mock from alembic.testing import ne_ from alembic.testing.env import _get_staging_directory from alembic.testing.env import _multi_dir_testing_config from alembic.testing.env import _multidb_testing_config from alembic.testing.env import _no_sql_testing_config from alembic.testing.env import _sqlite_file_db from alembic.testing.env import _sqlite_testing_config from alembic.testing.env import _testing_config from alembic.testing.env import clear_staging_env from alembic.testing.env import env_file_fixture from alembic.testing.env import script_file_fixture from alembic.testing.env import staging_env from alembic.testing.env import three_rev_fixture from alembic.testing.env import write_script from alembic.testing.fixtures import TestBase from alembic.util import CommandError env, abc, def_ = None, None, None class GeneralOrderedTests(TestBase): def setUp(self): global env env = staging_env() def tearDown(self): clear_staging_env() def test_steps(self): self._test_001_environment() self._test_002_rev_ids() self._test_003_api_methods_clean() self._test_004_rev() self._test_005_nextrev() self._test_006_from_clean_env() self._test_007_long_name() self._test_008_long_name_configurable() def _test_001_environment(self): assert_set = set(["env.py", "script.py.mako", "README"]) eq_(assert_set.intersection(os.listdir(env.dir)), assert_set) def _test_002_rev_ids(self): global abc, def_ abc = util.rev_id() def_ = util.rev_id() ne_(abc, def_) def _test_003_api_methods_clean(self): eq_(env.get_heads(), []) eq_(env.get_base(), None) def _test_004_rev(self): script = env.generate_revision(abc, "this is a message", refresh=True) eq_(script.doc, "this is a message") eq_(script.revision, abc) eq_(script.down_revision, None) assert os.access( os.path.join(env.dir, "versions", "%s_this_is_a_message.py" % abc), os.F_OK, ) assert callable(script.module.upgrade) eq_(env.get_heads(), [abc]) eq_(env.get_base(), abc) def _test_005_nextrev(self): script = env.generate_revision( def_, "this is the next rev", refresh=True ) assert os.access( os.path.join( env.dir, "versions", "%s_this_is_the_next_rev.py" % def_ ), os.F_OK, ) eq_(script.revision, def_) eq_(script.down_revision, abc) eq_(env.get_revision(abc).nextrev, set([def_])) assert script.module.down_revision == abc assert callable(script.module.upgrade) assert callable(script.module.downgrade) eq_(env.get_heads(), [def_]) eq_(env.get_base(), abc) def _test_006_from_clean_env(self): # test the environment so far with a # new ScriptDirectory instance. env = staging_env(create=False) abc_rev = env.get_revision(abc) def_rev = env.get_revision(def_) eq_(abc_rev.nextrev, set([def_])) eq_(abc_rev.revision, abc) eq_(def_rev.down_revision, abc) eq_(env.get_heads(), [def_]) eq_(env.get_base(), abc) def _test_007_long_name(self): rid = util.rev_id() env.generate_revision( rid, "this is a really long name with " "lots of characters and also " "I'd like it to\nhave\nnewlines", ) assert os.access( os.path.join( env.dir, "versions", "%s_this_is_a_really_long_name_with_lots_of_.py" % rid, ), os.F_OK, ) def _test_008_long_name_configurable(self): env.truncate_slug_length = 60 rid = util.rev_id() env.generate_revision( rid, "this is a really long name with " "lots of characters and also " "I'd like it to\nhave\nnewlines", ) assert os.access( os.path.join( env.dir, "versions", "%s_this_is_a_really_long_name_with_lots_" "of_characters_and_also_.py" % rid, ), os.F_OK, ) class ScriptNamingTest(TestBase): @classmethod def setup_class(cls): _testing_config() @classmethod def teardown_class(cls): clear_staging_env() def test_args(self): script = ScriptDirectory( _get_staging_directory(), file_template="%(rev)s_%(slug)s_" "%(year)s_%(month)s_" "%(day)s_%(hour)s_" "%(minute)s_%(second)s", ) create_date = datetime.datetime(2012, 7, 25, 15, 8, 5) eq_( script._rev_path( script.versions, "12345", "this is a message", create_date ), os.path.abspath( "%s/versions/12345_this_is_a_" "message_2012_7_25_15_8_5.py" % _get_staging_directory() ), ) def _test_tz(self, timezone_arg, given, expected): script = ScriptDirectory( _get_staging_directory(), file_template="%(rev)s_%(slug)s_" "%(year)s_%(month)s_" "%(day)s_%(hour)s_" "%(minute)s_%(second)s", timezone=timezone_arg, ) with mock.patch( "alembic.script.base.datetime", mock.Mock( datetime=mock.Mock(utcnow=lambda: given, now=lambda: given) ), ): create_date = script._generate_create_date() eq_(create_date, expected) def test_custom_tz(self): self._test_tz( "EST5EDT", datetime.datetime(2012, 7, 25, 15, 8, 5), datetime.datetime( 2012, 7, 25, 11, 8, 5, tzinfo=tz.gettz("EST5EDT") ), ) def test_custom_tz_lowercase(self): self._test_tz( "est5edt", datetime.datetime(2012, 7, 25, 15, 8, 5), datetime.datetime( 2012, 7, 25, 11, 8, 5, tzinfo=tz.gettz("EST5EDT") ), ) def test_custom_tz_utc(self): self._test_tz( "utc", datetime.datetime(2012, 7, 25, 15, 8, 5), datetime.datetime(2012, 7, 25, 15, 8, 5, tzinfo=tz.gettz("UTC")), ) def test_custom_tzdata_tz(self): self._test_tz( "Europe/Berlin", datetime.datetime(2012, 7, 25, 15, 8, 5), datetime.datetime( 2012, 7, 25, 17, 8, 5, tzinfo=tz.gettz("Europe/Berlin") ), ) def test_default_tz(self): self._test_tz( None, datetime.datetime(2012, 7, 25, 15, 8, 5), datetime.datetime(2012, 7, 25, 15, 8, 5), ) def test_tz_cant_locate(self): assert_raises_message( CommandError, "Can't locate timezone: fake", self._test_tz, "fake", datetime.datetime(2012, 7, 25, 15, 8, 5), datetime.datetime(2012, 7, 25, 15, 8, 5), ) class RevisionCommandTest(TestBase): def setUp(self): self.env = staging_env() self.cfg = _sqlite_testing_config() self.a, self.b, self.c = three_rev_fixture(self.cfg) def tearDown(self): clear_staging_env() def test_create_script_basic(self): rev = command.revision(self.cfg, message="some message") script = ScriptDirectory.from_config(self.cfg) rev = script.get_revision(rev.revision) eq_(rev.down_revision, self.c) assert "some message" in rev.doc def test_create_script_splice(self): rev = command.revision( self.cfg, message="some message", head=self.b, splice=True ) script = ScriptDirectory.from_config(self.cfg) rev = script.get_revision(rev.revision) eq_(rev.down_revision, self.b) assert "some message" in rev.doc eq_(set(script.get_heads()), set([rev.revision, self.c])) def test_create_script_missing_splice(self): assert_raises_message( util.CommandError, "Revision %s is not a head revision; please specify --splice " "to create a new branch from this revision" % self.b, command.revision, self.cfg, message="some message", head=self.b, ) def test_illegal_revision_chars(self): assert_raises_message( util.CommandError, r"Character\(s\) '-' not allowed in " "revision identifier 'no-dashes'", command.revision, self.cfg, message="some message", rev_id="no-dashes", ) assert not os.path.exists( os.path.join(self.env.dir, "versions", "no-dashes_some_message.py") ) assert_raises_message( util.CommandError, r"Character\(s\) '@' not allowed in " "revision identifier 'no@atsigns'", command.revision, self.cfg, message="some message", rev_id="no@atsigns", ) assert_raises_message( util.CommandError, r"Character\(s\) '-, @' not allowed in revision " "identifier 'no@atsigns-ordashes'", command.revision, self.cfg, message="some message", rev_id="no@atsigns-ordashes", ) assert_raises_message( util.CommandError, r"Character\(s\) '\+' not allowed in revision " r"identifier 'no\+plussignseither'", command.revision, self.cfg, message="some message", rev_id="no+plussignseither", ) def test_create_script_branches(self): rev = command.revision( self.cfg, message="some message", branch_label="foobar" ) script = ScriptDirectory.from_config(self.cfg) rev = script.get_revision(rev.revision) eq_(script.get_revision("foobar"), rev) def test_create_script_branches_old_template(self): script = ScriptDirectory.from_config(self.cfg) with open(os.path.join(script.dir, "script.py.mako"), "w") as file_: file_.write( "<%text>#</%text> ${message}\n" "revision = ${repr(up_revision)}\n" "down_revision = ${repr(down_revision)}\n\n" "def upgrade():\n" " ${upgrades if upgrades else 'pass'}\n\n" "def downgrade():\n" " ${downgrade if downgrades else 'pass'}\n\n" ) # works OK if no branch names command.revision(self.cfg, message="some message") assert_raises_message( util.CommandError, r"Version \w+ specified branch_labels foobar, " r"however the migration file .+?\b does not have them; have you " "upgraded your script.py.mako to include the 'branch_labels' " r"section\?", command.revision, self.cfg, message="some message", branch_label="foobar", ) class CustomizeRevisionTest(TestBase): def setUp(self): self.env = staging_env() self.cfg = _multi_dir_testing_config() self.cfg.set_main_option("revision_environment", "true") script = ScriptDirectory.from_config(self.cfg) self.model1 = util.rev_id() self.model2 = util.rev_id() self.model3 = util.rev_id() for model, name in [ (self.model1, "model1"), (self.model2, "model2"), (self.model3, "model3"), ]: script.generate_revision( model, name, refresh=True, version_path=os.path.join(_get_staging_directory(), name), head="base", ) write_script( script, model, """\ "%s" revision = '%s' down_revision = None branch_labels = ['%s'] from alembic import op def upgrade(): pass def downgrade(): pass """ % (name, model, name), ) def tearDown(self): clear_staging_env() def _env_fixture(self, fn, target_metadata): self.engine = engine = _sqlite_file_db() def run_env(self): from alembic import context with engine.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, process_revision_directives=fn, ) with context.begin_transaction(): context.run_migrations() return mock.patch( "alembic.script.base.ScriptDirectory.run_env", run_env ) def test_new_locations_no_autogen(self): m = sa.MetaData() def process_revision_directives(context, rev, generate_revisions): generate_revisions[:] = [ ops.MigrationScript( util.rev_id(), ops.UpgradeOps(), ops.DowngradeOps(), version_path=os.path.join( _get_staging_directory(), "model1" ), head="model1@head", ), ops.MigrationScript( util.rev_id(), ops.UpgradeOps(), ops.DowngradeOps(), version_path=os.path.join( _get_staging_directory(), "model2" ), head="model2@head", ), ops.MigrationScript( util.rev_id(), ops.UpgradeOps(), ops.DowngradeOps(), version_path=os.path.join( _get_staging_directory(), "model3" ), head="model3@head", ), ] with self._env_fixture(process_revision_directives, m): revs = command.revision(self.cfg, message="some message") script = ScriptDirectory.from_config(self.cfg) for rev, model in [ (revs[0], "model1"), (revs[1], "model2"), (revs[2], "model3"), ]: rev_script = script.get_revision(rev.revision) eq_( rev_script.path, os.path.abspath( os.path.join( _get_staging_directory(), model, "%s_.py" % (rev_script.revision,), ) ), ) assert os.path.exists(rev_script.path) def test_renders_added_directives_no_autogen(self): m = sa.MetaData() def process_revision_directives(context, rev, generate_revisions): generate_revisions[0].upgrade_ops.ops.append( ops.CreateIndexOp("some_index", "some_table", ["a", "b"]) ) with self._env_fixture(process_revision_directives, m): rev = command.revision( self.cfg, message="some message", head="model1@head", sql=True ) with mock.patch.object(rev.module, "op") as op_mock: rev.module.upgrade() eq_( op_mock.mock_calls, [ mock.call.create_index( "some_index", "some_table", ["a", "b"], unique=False ) ], ) def test_autogen(self): m = sa.MetaData() sa.Table("t", m, sa.Column("x", sa.Integer)) def process_revision_directives(context, rev, generate_revisions): existing_upgrades = generate_revisions[0].upgrade_ops existing_downgrades = generate_revisions[0].downgrade_ops # model1 will run the upgrades, e.g. create the table, # model2 will run the downgrades as upgrades, e.g. drop # the table again generate_revisions[:] = [ ops.MigrationScript( util.rev_id(), existing_upgrades, ops.DowngradeOps(), version_path=os.path.join( _get_staging_directory(), "model1" ), head="model1@head", ), ops.MigrationScript( util.rev_id(), ops.UpgradeOps(ops=existing_downgrades.ops), ops.DowngradeOps(), version_path=os.path.join( _get_staging_directory(), "model2" ), head="model2@head", ), ] with self._env_fixture(process_revision_directives, m): command.upgrade(self.cfg, "heads") eq_( Inspector.from_engine(self.engine).get_table_names(), ["alembic_version"], ) command.revision( self.cfg, message="some message", autogenerate=True ) command.upgrade(self.cfg, "model1@head") eq_( Inspector.from_engine(self.engine).get_table_names(), ["alembic_version", "t"], ) command.upgrade(self.cfg, "model2@head") eq_( Inspector.from_engine(self.engine).get_table_names(), ["alembic_version"], ) def test_programmatic_command_option(self): def process_revision_directives(context, rev, generate_revisions): generate_revisions[0].message = "test programatic" generate_revisions[0].upgrade_ops = ops.UpgradeOps( ops=[ ops.CreateTableOp( "test_table", [ sa.Column("id", sa.Integer(), primary_key=True), sa.Column("name", sa.String(50), nullable=False), ], ) ] ) generate_revisions[0].downgrade_ops = ops.DowngradeOps( ops=[ops.DropTableOp("test_table")] ) with self._env_fixture(None, None): rev = command.revision( self.cfg, head="model1@head", process_revision_directives=process_revision_directives, ) with open(rev.path) as handle: result = handle.read() assert ( ( """ def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('test_table', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=50), nullable=False), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### """ ) in result ) class ScriptAccessorTest(TestBase): def test_upgrade_downgrade_ops_list_accessors(self): u1 = ops.UpgradeOps(ops=[]) d1 = ops.DowngradeOps(ops=[]) m1 = ops.MigrationScript("somerev", u1, d1) is_(m1.upgrade_ops, u1) is_(m1.downgrade_ops, d1) u2 = ops.UpgradeOps(ops=[]) d2 = ops.DowngradeOps(ops=[]) m1._upgrade_ops.append(u2) m1._downgrade_ops.append(d2) assert_raises_message( ValueError, "This MigrationScript instance has a multiple-entry list for " "UpgradeOps; please use the upgrade_ops_list attribute.", getattr, m1, "upgrade_ops", ) assert_raises_message( ValueError, "This MigrationScript instance has a multiple-entry list for " "DowngradeOps; please use the downgrade_ops_list attribute.", getattr, m1, "downgrade_ops", ) eq_(m1.upgrade_ops_list, [u1, u2]) eq_(m1.downgrade_ops_list, [d1, d2]) class ImportsTest(TestBase): def setUp(self): self.env = staging_env() self.cfg = _sqlite_testing_config() def tearDown(self): clear_staging_env() def _env_fixture(self, target_metadata, **kw): self.engine = engine = _sqlite_file_db() def run_env(self): from alembic import context with engine.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, **kw ) with context.begin_transaction(): context.run_migrations() return mock.patch( "alembic.script.base.ScriptDirectory.run_env", run_env ) def test_imports_in_script(self): from sqlalchemy import MetaData, Table, Column from sqlalchemy.dialects.mysql import VARCHAR type_ = VARCHAR(20, charset="utf8", national=True) m = MetaData() Table("t", m, Column("x", type_)) def process_revision_directives(context, rev, generate_revisions): generate_revisions[0].imports.add( "from sqlalchemy.dialects.mysql import TINYINT" ) with self._env_fixture( m, process_revision_directives=process_revision_directives ): rev = command.revision( self.cfg, message="some message", autogenerate=True ) with open(rev.path) as file_: contents = file_.read() assert "from sqlalchemy.dialects import mysql" in contents assert "from sqlalchemy.dialects.mysql import TINYINT" in contents class MultiContextTest(TestBase): """test the multidb template for autogenerate front-to-back""" def setUp(self): self.engine1 = _sqlite_file_db(tempname="eng1.db") self.engine2 = _sqlite_file_db(tempname="eng2.db") self.engine3 = _sqlite_file_db(tempname="eng3.db") self.env = staging_env(template="multidb") self.cfg = _multidb_testing_config( { "engine1": self.engine1, "engine2": self.engine2, "engine3": self.engine3, } ) def _write_metadata(self, meta): path = os.path.join(_get_staging_directory(), "scripts", "env.py") with open(path) as env_: existing_env = env_.read() existing_env = existing_env.replace("target_metadata = {}", meta) with open(path, "w") as env_: env_.write(existing_env) def tearDown(self): clear_staging_env() def test_autogen(self): self._write_metadata( """ import sqlalchemy as sa m1 = sa.MetaData() m2 = sa.MetaData() m3 = sa.MetaData() target_metadata = {"engine1": m1, "engine2": m2, "engine3": m3} sa.Table('e1t1', m1, sa.Column('x', sa.Integer)) sa.Table('e2t1', m2, sa.Column('y', sa.Integer)) sa.Table('e3t1', m3, sa.Column('z', sa.Integer)) """ ) rev = command.revision( self.cfg, message="some message", autogenerate=True ) with mock.patch.object(rev.module, "op") as op_mock: rev.module.upgrade_engine1() eq_( op_mock.mock_calls[-1], mock.call.create_table("e1t1", mock.ANY), ) rev.module.upgrade_engine2() eq_( op_mock.mock_calls[-1], mock.call.create_table("e2t1", mock.ANY), ) rev.module.upgrade_engine3() eq_( op_mock.mock_calls[-1], mock.call.create_table("e3t1", mock.ANY), ) rev.module.downgrade_engine1() eq_(op_mock.mock_calls[-1], mock.call.drop_table("e1t1")) rev.module.downgrade_engine2() eq_(op_mock.mock_calls[-1], mock.call.drop_table("e2t1")) rev.module.downgrade_engine3() eq_(op_mock.mock_calls[-1], mock.call.drop_table("e3t1")) class RewriterTest(TestBase): def test_all_traverse(self): writer = autogenerate.Rewriter() mocker = mock.Mock(side_effect=lambda context, revision, op: op) writer.rewrites(ops.MigrateOperation)(mocker) addcolop = ops.AddColumnOp("t1", sa.Column("x", sa.Integer())) directives = [ ops.MigrationScript( util.rev_id(), ops.UpgradeOps(ops=[ops.ModifyTableOps("t1", ops=[addcolop])]), ops.DowngradeOps(ops=[]), ) ] ctx, rev = mock.Mock(), mock.Mock() writer(ctx, rev, directives) eq_( mocker.mock_calls, [ mock.call(ctx, rev, directives[0]), mock.call(ctx, rev, directives[0].upgrade_ops), mock.call(ctx, rev, directives[0].upgrade_ops.ops[0]), mock.call(ctx, rev, addcolop), mock.call(ctx, rev, directives[0].downgrade_ops), ], ) def test_double_migrate_table(self): writer = autogenerate.Rewriter() idx_ops = [] @writer.rewrites(ops.ModifyTableOps) def second_table(context, revision, op): return [ op, ops.ModifyTableOps( "t2", ops=[ops.AddColumnOp("t2", sa.Column("x", sa.Integer()))], ), ] @writer.rewrites(ops.AddColumnOp) def add_column(context, revision, op): idx_op = ops.CreateIndexOp("ixt", op.table_name, [op.column.name]) idx_ops.append(idx_op) return [op, idx_op] directives = [ ops.MigrationScript( util.rev_id(), ops.UpgradeOps( ops=[ ops.ModifyTableOps( "t1", ops=[ ops.AddColumnOp( "t1", sa.Column("x", sa.Integer()) ) ], ) ] ), ops.DowngradeOps(ops=[]), ) ] ctx, rev = mock.Mock(), mock.Mock() writer(ctx, rev, directives) eq_( [d.table_name for d in directives[0].upgrade_ops.ops], ["t1", "t2"] ) is_(directives[0].upgrade_ops.ops[0].ops[1], idx_ops[0]) is_(directives[0].upgrade_ops.ops[1].ops[1], idx_ops[1]) def test_chained_ops(self): writer1 = autogenerate.Rewriter() writer2 = autogenerate.Rewriter() @writer1.rewrites(ops.AddColumnOp) def add_column_nullable(context, revision, op): if op.column.nullable: return op else: op.column.nullable = True return [ op, ops.AlterColumnOp( op.table_name, op.column.name, modify_nullable=False, existing_type=op.column.type, ), ] @writer2.rewrites(ops.AddColumnOp) def add_column_idx(context, revision, op): idx_op = ops.CreateIndexOp("ixt", op.table_name, [op.column.name]) return [op, idx_op] directives = [ ops.MigrationScript( util.rev_id(), ops.UpgradeOps( ops=[ ops.ModifyTableOps( "t1", ops=[ ops.AddColumnOp( "t1", sa.Column( "x", sa.Integer(), nullable=False ), ) ], ) ] ), ops.DowngradeOps(ops=[]), ) ] ctx, rev = mock.Mock(), mock.Mock() writer1.chain(writer2)(ctx, rev, directives) eq_( autogenerate.render_python_code(directives[0].upgrade_ops), "# ### commands auto generated by Alembic - please adjust! ###\n" " op.add_column('t1', " "sa.Column('x', sa.Integer(), nullable=True))\n" " op.create_index('ixt', 't1', ['x'], unique=False)\n" " op.alter_column('t1', 'x',\n" " existing_type=sa.Integer(),\n" " nullable=False)\n" " # ### end Alembic commands ###", ) def test_no_needless_pass(self): writer1 = autogenerate.Rewriter() @writer1.rewrites(ops.AlterColumnOp) def rewrite_alter_column(context, revision, op): return [] directives = [ ops.MigrationScript( util.rev_id(), ops.UpgradeOps( ops=[ ops.ModifyTableOps( "t1", ops=[ ops.AlterColumnOp( "foo", "bar", modify_nullable=False, existing_type=sa.Integer(), ), ops.AlterColumnOp( "foo", "bar", modify_nullable=False, existing_type=sa.Integer(), ), ], ), ops.ModifyTableOps( "t1", ops=[ ops.AlterColumnOp( "foo", "bar", modify_nullable=False, existing_type=sa.Integer(), ) ], ), ] ), ops.DowngradeOps(ops=[]), ) ] ctx, rev = mock.Mock(), mock.Mock() writer1(ctx, rev, directives) eq_( autogenerate.render_python_code(directives[0].upgrade_ops), "# ### commands auto generated by Alembic - please adjust! ###\n" " pass\n" " # ### end Alembic commands ###", ) def test_multiple_passes_with_mutations(self): writer1 = autogenerate.Rewriter() @writer1.rewrites(ops.CreateTableOp) def rewrite_alter_column(context, revision, op): op.table_name += "_pass" return op directives = [ ops.MigrationScript( util.rev_id(), ops.UpgradeOps( ops=[ ops.CreateTableOp( "test_table", [sa.Column("id", sa.Integer(), primary_key=True)], ) ] ), ops.DowngradeOps(ops=[]), ) ] ctx, rev = mock.Mock(), mock.Mock() writer1(ctx, rev, directives) directives[0].upgrade_ops_list.extend( [ ops.UpgradeOps( ops=[ ops.CreateTableOp( "another_test_table", [sa.Column("id", sa.Integer(), primary_key=True)], ) ] ), ops.UpgradeOps( ops=[ ops.CreateTableOp( "third_test_table", [sa.Column("id", sa.Integer(), primary_key=True)], ) ] ), ] ) writer1(ctx, rev, directives) eq_( autogenerate.render_python_code(directives[0].upgrade_ops_list[0]), "# ### commands auto generated by Alembic - please adjust! ###\n" " op.create_table('test_table_pass',\n" " sa.Column('id', sa.Integer(), nullable=False),\n" " sa.PrimaryKeyConstraint('id')\n" " )\n" " # ### end Alembic commands ###", ) eq_( autogenerate.render_python_code(directives[0].upgrade_ops_list[1]), "# ### commands auto generated by Alembic - please adjust! ###\n" " op.create_table('another_test_table_pass',\n" " sa.Column('id', sa.Integer(), nullable=False),\n" " sa.PrimaryKeyConstraint('id')\n" " )\n" " # ### end Alembic commands ###", ) eq_( autogenerate.render_python_code(directives[0].upgrade_ops_list[2]), "# ### commands auto generated by Alembic - please adjust! ###\n" " op.create_table('third_test_table_pass',\n" " sa.Column('id', sa.Integer(), nullable=False),\n" " sa.PrimaryKeyConstraint('id')\n" " )\n" " # ### end Alembic commands ###", ) class MultiDirRevisionCommandTest(TestBase): def setUp(self): self.env = staging_env() self.cfg = _multi_dir_testing_config() def tearDown(self): clear_staging_env() def test_multiple_dir_no_bases(self): assert_raises_message( util.CommandError, "Multiple version locations present, please specify " "--version-path", command.revision, self.cfg, message="some message", ) def test_multiple_dir_no_bases_invalid_version_path(self): assert_raises_message( util.CommandError, "Path foo/bar/ is not represented in current version locations", command.revision, self.cfg, message="x", version_path=os.path.join("foo/bar/"), ) def test_multiple_dir_no_bases_version_path(self): script = command.revision( self.cfg, message="x", version_path=os.path.join(_get_staging_directory(), "model1"), ) assert os.access(script.path, os.F_OK) def test_multiple_dir_chooses_base(self): command.revision( self.cfg, message="x", head="base", version_path=os.path.join(_get_staging_directory(), "model1"), ) script2 = command.revision( self.cfg, message="y", head="base", version_path=os.path.join(_get_staging_directory(), "model2"), ) script3 = command.revision( self.cfg, message="y2", head=script2.revision ) eq_( os.path.dirname(script3.path), os.path.abspath(os.path.join(_get_staging_directory(), "model2")), ) assert os.access(script3.path, os.F_OK) class TemplateArgsTest(TestBase): def setUp(self): staging_env() self.cfg = _no_sql_testing_config( directives="\nrevision_environment=true\n" ) def tearDown(self): clear_staging_env() def test_args_propagate(self): config = _no_sql_testing_config() script = ScriptDirectory.from_config(config) template_args = {"x": "x1", "y": "y1", "z": "z1"} env = EnvironmentContext(config, script, template_args=template_args) env.configure( dialect_name="sqlite", template_args={"y": "y2", "q": "q1"} ) eq_(template_args, {"x": "x1", "y": "y2", "z": "z1", "q": "q1"}) def test_tmpl_args_revision(self): env_file_fixture( """ context.configure(dialect_name='sqlite', template_args={"somearg":"somevalue"}) """ ) script_file_fixture( """ # somearg: ${somearg} revision = ${repr(up_revision)} down_revision = ${repr(down_revision)} """ ) command.revision(self.cfg, message="some rev") script = ScriptDirectory.from_config(self.cfg) rev = script.get_revision("head") with open(rev.path) as f: text = f.read() assert "somearg: somevalue" in text def test_bad_render(self): env_file_fixture( """ context.configure(dialect_name='sqlite', template_args={"somearg":"somevalue"}) """ ) script_file_fixture( """ <% z = x + y %> """ ) try: command.revision(self.cfg, message="some rev") except CommandError as ce: m = re.match( r"^Template rendering failed; see (.+?) " "for a template-oriented", str(ce), ) assert m, "Command error did not produce a file" with open(m.group(1)) as handle: contents = handle.read() os.remove(m.group(1)) assert "<% z = x + y %>" in contents class DuplicateVersionLocationsTest(TestBase): def setUp(self): self.env = staging_env() self.cfg = _multi_dir_testing_config( # this is a duplicate of one of the paths # already present in this fixture extra_version_location="%(here)s/model1" ) script = ScriptDirectory.from_config(self.cfg) self.model1 = util.rev_id() self.model2 = util.rev_id() self.model3 = util.rev_id() for model, name in [ (self.model1, "model1"), (self.model2, "model2"), (self.model3, "model3"), ]: script.generate_revision( model, name, refresh=True, version_path=os.path.join(_get_staging_directory(), name), head="base", ) write_script( script, model, """\ "%s" revision = '%s' down_revision = None branch_labels = ['%s'] from alembic import op def upgrade(): pass def downgrade(): pass """ % (name, model, name), ) def tearDown(self): clear_staging_env() def test_env_emits_warning(self): with assertions.expect_warnings( "File %s loaded twice! ignoring. " "Please ensure version_locations is unique" % ( os.path.realpath( os.path.join( _get_staging_directory(), "model1", "%s_model1.py" % self.model1, ) ) ) ): script = ScriptDirectory.from_config(self.cfg) script.revision_map.heads eq_( [rev.revision for rev in script.walk_revisions()], [self.model1, self.model2, self.model3], ) class NormPathTest(TestBase): def setUp(self): self.env = staging_env() def test_script_location(self): config = _no_sql_testing_config() script = ScriptDirectory.from_config(config) def normpath(path): return path.replace("/", ":NORM:") normpath = mock.Mock(side_effect=normpath) with mock.patch("os.path.normpath", normpath): eq_( script._version_locations, ( os.path.abspath( os.path.join( _get_staging_directory(), "scripts", "versions" ) ).replace("/", ":NORM:"), ), ) eq_( script.versions, os.path.abspath( os.path.join( _get_staging_directory(), "scripts", "versions" ) ).replace("/", ":NORM:"), ) def test_script_location_muliple(self): config = _multi_dir_testing_config() script = ScriptDirectory.from_config(config) def normpath(path): return path.replace("/", ":NORM:") normpath = mock.Mock(side_effect=normpath) with mock.patch("os.path.normpath", normpath): eq_( script._version_locations, [ os.path.abspath( os.path.join(_get_staging_directory(), "model1/") ).replace("/", ":NORM:"), os.path.abspath( os.path.join(_get_staging_directory(), "model2/") ).replace("/", ":NORM:"), os.path.abspath( os.path.join(_get_staging_directory(), "model3/") ).replace("/", ":NORM:"), ], )
StarcoderdataPython
56213
<filename>assistance_arbitration/assistance_arbitrator/src/assistance_arbitrator/monitors/octomap_monitor.py #!/usr/bin/env python # Monitor the octomap and check if the threshold of clutter in the octomap is # too high. This is almost never likely to be the actual cause of issues from __future__ import print_function, division import numpy as np from threading import Lock import rospy from assistance_msgs.msg import MonitorMetadata from moveit_msgs.msg import PlanningSceneComponents, PlanningScene from moveit_msgs.srv import GetPlanningScene from assistance_arbitrator.monitoring import AbstractFaultMonitor # The class definition class OctomapMonitor(AbstractFaultMonitor): """ Monitor the octomap and return an indication of the amount of free space. This is a dumb algorithm for now """ OCTOMAP_MONITOR_EVENT_NAME = "octomap_update" OCTOMAP_TOPIC = "/planning_scene" OCTOMAP_SERVICE = "/get_planning_scene" MONITOR_DURATION = rospy.Duration(5.0) # Duration at which to check the octomap OCTOMAP_OCCUPIED_PROBABILITY_THRESHOLD = 0.5 FREE_PERC_FAULT_THRESHOLD = 0.7 # Pretty arbitrary number def __init__(self): super(OctomapMonitor, self).__init__() self.set_metadata(topics=[OctomapMonitor.OCTOMAP_TOPIC]) self._octomap = None self._octomap_lock = Lock() # The service for getting the octomap self._get_octomap = rospy.ServiceProxy(OctomapMonitor.OCTOMAP_SERVICE, GetPlanningScene) # The topic for listening to the planning scene self._octomap_sub = rospy.Subscriber( OctomapMonitor.OCTOMAP_TOPIC, PlanningScene, self._on_planning_scene ) # Start the timer to periodically self._monitor_timer = rospy.Timer( OctomapMonitor.MONITOR_DURATION, self._monitor_func, oneshot=False ) def _on_planning_scene(self, scene_msg): if len(scene_msg.world.octomap.octomap.data) > 0: with self._octomap_lock: self._octomap = np.array(scene_msg.world.octomap.octomap.data) def _monitor_func(self, evt): try: planning_scene = self._get_octomap(components=PlanningSceneComponents(PlanningSceneComponents.OCTOMAP)) except rospy.ServiceException as e: rospy.logerr("Error fetching planning scene: {}".format(e)) return # Update the octomap and then check the threshold new_octomap = np.array(planning_scene.scene.world.octomap.octomap.data) free_space_num = np.sum( (1 - (1 / (1 + np.exp(new_octomap)))) # Convert Log-Odds to Probabilities <= OctomapMonitor.OCTOMAP_OCCUPIED_PROBABILITY_THRESHOLD ) free_space_perc = free_space_num / len(new_octomap) # Update the trace self.update_trace( OctomapMonitor.OCTOMAP_MONITOR_EVENT_NAME, free_space_perc < OctomapMonitor.FREE_PERC_FAULT_THRESHOLD, { 'free_space_perc': free_space_perc } ) # Update the pointer to the octomap with self._octomap_lock: self._octomap = new_octomap # When running the monitor in standalone mode if __name__ == '__main__': rospy.init_node('global_plan_monitor') monitor = OctomapMonitor() rospy.spin()
StarcoderdataPython
3203335
import uspider class MSUSpider(uspider.USpider): name = "msuspider" allowed_domains = ["msu.ru"] download_delay = 1 extract_text = "db" def __init__(self, **kwargs): super().__init__(**kwargs) self.start_urls.insert(0, "https://msu.ru")
StarcoderdataPython
3245861
class Vertex(object): def __init__(self, key): self.id = key self.connected_to = {} def add_neighbor(self, nbr, weight=0): self.connected_to[nbr] = weight def get_connections(self): return self.connected_to.keys() def get_id(self): return self.id def get_weight(self, nbr): return self.connected_to[nbr] def __str__(self): return "{} connected to: {}".format( self.id, [x.id for x in self.connected_to] ) class Graph(object): def __init__(self): self.vertices_list = {} self.num_vertices = 0 def add_vertex(self, key): self.num_vertices += 1 new_vertex = Vertex(key) self.vertices_list[key] = new_vertex return new_vertex def get_vertex(self, key): if key in self.vertices_list: return self.vertices_list[key] else: return None def add_edge(self, f, t, cost=0): """ :param f: From vertex :param t: To vertex :param cost: Weight of vertex = """ if f not in self.vertices_list: new_vertex = self.add_vertex(f) if t not in self.vertices_list: new_vertex = self.add_vertex(t) self.vertices_list[f].add_neighbor(self.vertices_list[t], cost) def get_vertices(self): return self.vertices_list.keys() def __iter__(self): return iter(self.vertices_list.values()) def __contains__(self, key): return key in self.vertices_list if __name__ == '__main__': g = Graph() for i in range(6): g.add_vertex(i) print(g.vertices_list) g.add_edge(0, 1, 2) g.add_edge(0, 5, 3) g.add_edge(2, 4, 3) g.add_edge(4, 2, 2) g.add_edge(1, 4, 2) for v in g: print(v)
StarcoderdataPython
3243993
<reponame>brunocroh/wifidog-auth-flask import os from auth import create_app app = create_app() if __name__ == '__main__': app.run(debug=app.config['DEBUG'], host=app.config['HOST'], port=int(app.config['PORT']))
StarcoderdataPython
1646031
<filename>traxee/flipkart/api/serializers.py from rest_framework import serializers from django.db.models.fields import EmailField from django.db.models.fields import PositiveIntegerField class SignUpSerializers(serializers.Serializer): email = serializers.EmailField() name = serializers.CharField() password = serializers.CharField() isPremium = serializers.BooleanField() class SignInSerializers(serializers.Serializer): email = serializers.CharField() password = serializers.CharField() class TokenSerializer(serializers.Serializer): token = serializers.CharField() class ForgotPasswordSerializer(serializers.Serializer): email = serializers.EmailField() class SearchItemSerializer(serializers.Serializer): item = serializers.CharField()
StarcoderdataPython
1669009
<filename>deleteRows.py import os import csv def deleteKeys(folder, keys): for fil in os.listdir(folder): if os.path.splitext(fil)[1] == '.csv': with open(os.path.join(folder, fil)) as f: rows = [row for row in csv.reader(f)] origLength = len(rows) rows = [row for row in rows if not row or row[0] not in keys] if origLength == len(rows): continue with open(os.path.join(folder, fil), 'w') as f: writer = csv.writer(f) writer.writerows(rows) print(' '.join(keys)) if __name__ == '__main__': import sys folder = sys.argv[1] keys = sys.argv[2:] deleteKeys(folder, keys)
StarcoderdataPython
1721254
""" Entradas contraseña-->int-->contraseña Salidas correcto-->str-->Acesso Permitido incorrecto-->str-->Senha Invalida """ #Caja negra while True: #Entrada contraseña=int(input()) #Caja negra if(contraseña==2002): #Salida print("Acesso Permitido") break else: #Salida print("Senha Invalida")
StarcoderdataPython
129040
<reponame>kozakusek/ipp-2020-testy from part1 import ( gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new, ) """ scenario: test_random_actions uuid: 239604592 """ """ random actions, total chaos """ board = gamma_new(2, 2, 2, 3) assert board is not None assert gamma_move(board, 2, 1, 0) == 1 assert gamma_move(board, 2, 0, 0) == 1 assert gamma_move(board, 1, 0, 1) == 1 assert gamma_move(board, 1, 0, 1) == 0 assert gamma_move(board, 2, 1, 1) == 1 assert gamma_move(board, 2, 1, 0) == 0 assert gamma_move(board, 1, 1, 0) == 0 assert gamma_move(board, 1, 1, 1) == 0 assert gamma_free_fields(board, 1) == 0 assert gamma_move(board, 2, 0, 0) == 0 assert gamma_move(board, 2, 0, 0) == 0 assert gamma_golden_possible(board, 2) == 1 gamma_delete(board)
StarcoderdataPython
1785397
<reponame>izmirli/modern-python-projects-course from calculator import Calculator def test_calculator(): calc = Calculator() calc.add(10) calc.subtract(5) calc.multiply(5) assert str(calc) == "Calculator(25)" def test_calculator_initial_value(): calc = Calculator(10) assert str(calc) == "Calculator(10)" calc.add(5) assert str(calc) == "Calculator(15)" def test_chaining_operations(): calc = Calculator() calc.add(5).add(10).subtract(15) assert str(calc) == "Calculator(0)"
StarcoderdataPython
3361264
<reponame>elliotbrandwein/discord_options_chain_bot # # written by me, <NAME> # No rights are granted to anyone without the express written consent of me or the National Football League import datetime from collections import defaultdict import robin_stocks as r import keyring import getpass ########### THINGS YOU MIGHT WANNA CHANGE #################### MY_RH_USERNAME = "<EMAIL>" tickers = ['UAL', 'AAL', 'JETS', 'GME', 'NOK', 'F', 'GE', 'OPK'] MIN_PREMIUM_PERCENTAGE = 1 # MAX_PREMIUM_PERCENTAGE = 2 # to use you must also uncomment code below ############################################################## pwd = keyring.get_password("<PASSWORD>", "my_very_own_rh_username") if pwd is None: print("First time? Securely type in your Robinhood Password please:") # Stores password in local system using keyring keyring.set_password("<PASSWORD>", "my_very_own_rh_username", getpass.getpass()) pwd = keyring.get_password("<PASSWORD>", "my_very_own_rh_username") login = r.login(MY_RH_USERNAME, pwd) latest_prices = r.get_latest_price(tickers) prices = dict(zip(tickers, list(map(float, latest_prices)))) today = datetime.date.today() friday = today + datetime.timedelta((4 - today.weekday()) % 7) # If it's late in the week and you want to look at next week, uncomment the below line # friday = friday + datetime.timedelta(7) expiration = "{}-{}-{}".format(friday.year, friday.month, friday.day) putData = r.find_options_by_expiration(tickers, expirationDate=expiration, optionType='put') putsToLookAt = defaultdict(lambda: []) for put in putData: tick = put["chain_symbol"] curr_stock_price = prices[tick] strike = float(put["strike_price"]) if strike > curr_stock_price: # We don't sell puts for strikes above the current stock price continue premium = float(put["bid_price"]) # only the bid price is guaranteed, rest is theoretical if premium < strike * (MIN_PREMIUM_PERCENTAGE / 100): # Not worth it continue # if premium > strike * (MAX_PREMIUM_PERCENTAGE / 100): # # Probably too risky to consider # continue putsToLookAt[tick].append("${} strike for ${} = {:.2%}".format(strike, premium, premium / strike)) print("Puts expiring on {} for strikes below current stock price with profitability above {}%:" .format(expiration, MIN_PREMIUM_PERCENTAGE)) for tick in tickers: print("*" * 50) print("{}: Current Price: {}".format(tick, prices[tick])) puts = putsToLookAt[tick] if not puts: print("No puts are worth it this week for this guy") else: puts.sort() for put in puts: print("\t{}".format(put))
StarcoderdataPython
176380
<gh_stars>1-10 import time,opt import RPi.GPIO as GPIO def DistanceMeasure(distance_limit=0.2,time_limit=1,time_delay=10): GPIO.setmode(GPIO.BCM) trig=27;GPIO.setup(trig,GPIO.OUT) echo=22;GPIO.setup(echo,GPIO.IN) count=0 while 39: GPIO.output(trig,1) time.sleep(0.00001) GPIO.output(trig,0) # while GPIO.input(echo)==0: pass pulse_start=time.time() while GPIO.input(echo)==1: pass pulse_end=time.time() pulse_time=pulse_end-pulse_start distance=pulse_time*171.5 if distance>distance_limit: count=0 else: count+=1 if count>distance_limit*1000: stp=opt.CameraJudge() if stp==0: # print "shibieshibai" time.sleep(time_delay) else: return 1 count=0 # DistanceMeasure()
StarcoderdataPython
3268342
class Group: def __init__(self, name: object, header: object, footer: object) -> object: self.name = name self.header = header self.footer = footer
StarcoderdataPython
1629067
<gh_stars>0 from Models import VehcleDriver from time import sleep from random import randint import random from faker import Faker import json from kafka import KafkaProducer def publish_message(producer_instance, topic_name, key, value): try: key_bytes = bytes(key, encoding='utf-8') value_bytes = bytes(value, encoding='utf-8') producer_instance.send(topic_name, key=key_bytes, value=value_bytes) producer_instance.flush() print('Message published successfully.') except Exception as ex: print('Exception in publishing message') print(str(ex)) def connect_kafka_producer(): _producer = None try: _producer = KafkaProducer(bootstrap_servers=['localhost:9092'], api_version=(0, 10)) except Exception as ex: print('Exception while connecting Kafka') print(str(ex)) finally: return _producer def simulateVehicleData(x): # dictionary driver_data =[] vehcle_list = ["Tata Pickup", "Tata Turbo xls", "Eicher Motor Turbo", "Gati Transport"] state_list = ["UP", "BR", "DL", "KA","UK"] fake = Faker(['en_IN']) for i in range(0, x): driver= VehcleDriver() driver.id= randint(1, 100) driver.driverName= fake.name() driver.driverTempreture= randint(20,60) driver.driverBloodPressure= str(randint(0,200))+'/'+ str(randint(60,90))+'mmHg' driver.address= fake.city() driver.latitude= str(fake.latitude()) driver.longitude= str(fake.longitude()) driver.vechileModel= str(random.choice(vehcle_list)) driver.vechileLiecense= str(random.choice(state_list))+'-'+str(randint(10, 99))+'-'+str(randint(1000, 9999)) # UP-60-9999 driver.vechileTempreture= randint(30, 150) driver.vechileFuelLevel= randint(1, 100) driver.vechileTyrePressure= str(randint(50, 130))+'psi' driver.vechileSpeed=randint(1, 100) driver_data.append(driver) if len(driver_data) > 0: kafka_producer = connect_kafka_producer() for data in driver_data: publish_message(kafka_producer, 'topic-vehicle-data', 'raw',json.dumps(data.__dict__)) sleep(5) if kafka_producer is not None: kafka_producer.close() if __name__ == '__main__': while True: simulateVehicleData(1) sleep(2)
StarcoderdataPython
3352135
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from .work_item_tracking_resource import WorkItemTrackingResource class FieldDependentRule(WorkItemTrackingResource): """FieldDependentRule. :param url: :type url: str :param _links: :type _links: :class:`ReferenceLinks <work-item-tracking.v4_0.models.ReferenceLinks>` :param dependent_fields: :type dependent_fields: list of :class:`WorkItemFieldReference <work-item-tracking.v4_0.models.WorkItemFieldReference>` """ _attribute_map = { 'url': {'key': 'url', 'type': 'str'}, '_links': {'key': '_links', 'type': 'ReferenceLinks'}, 'dependent_fields': {'key': 'dependentFields', 'type': '[WorkItemFieldReference]'} } def __init__(self, url=None, _links=None, dependent_fields=None): super(FieldDependentRule, self).__init__(url=url, _links=_links) self.dependent_fields = dependent_fields
StarcoderdataPython
3268430
<reponame>ved93/deliberate-practice-challenges<gh_stars>0 def binary_search(a,k): left, right = 0, len(a)-1 while left <= right: mid = (left + right) // 2 if a[mid] == k: return True elif a[mid] < k: left = mid +1 else: right = mid - 1 return -1 if __name__ == "__main__": a = [1,3, 4,5, 8,9,10] k = 10 print(binary_search(a,k))
StarcoderdataPython
3383678
from hwt.hdl.constants import DIRECTION from hwt.interfaces.std import VectSignal, Signal from hwt.synthesizer.param import Param from hwtLib.amba.axi3Lite import Axi3Lite_addr, Axi3Lite, Axi3Lite_r, Axi3Lite_b,\ IP_Axi3Lite from hwtLib.amba.axi_intf_common import AxiMap, Axi_id, Axi_hs, Axi_strb from hwtLib.amba.axis import AxiStream, AxiStreamAgent from hwtLib.amba.sim.agentCommon import BaseAxiAgent from hwt.serializer.ip_packager import IpPackager from ipCorePackager.component import Component from hwtSimApi.hdlSimulator import HdlSimulator from hwtLib.amba.constants import BYTES_IN_TRANS, BURST_INCR, CACHE_DEFAULT,\ LOCK_DEFAULT, PROT_DEFAULT _DEFAULT = object() ##################################################################### class Axi3_addr(Axi3Lite_addr, Axi_id): """ Axi3 address channel interface .. hwt-autodoc:: """ LEN_WIDTH = 4 LOCK_WIDTH = 2 def _config(self): Axi3Lite_addr._config(self) Axi_id._config(self, default_id_width=6) self.USER_WIDTH = Param(0) def _declr(self): Axi3Lite_addr._declr(self) Axi_id._declr(self) self.burst = VectSignal(2) self.cache = VectSignal(4) self.len = VectSignal(self.LEN_WIDTH) self.lock = VectSignal(self.LOCK_WIDTH) self.prot = VectSignal(3) self.size = VectSignal(3) if self.USER_WIDTH: self.user = VectSignal(self.USER_WIDTH) def _initSimAgent(self, sim: HdlSimulator): self._ag = Axi3_addrAgent(sim, self) class Axi3_addrAgent(AxiStreamAgent): """ Simulation agent for :class:`.Axi3_addr` interface input/output data stored in list under "data" property data contains tuples (id, addr, burst, cache, len, lock, prot, size, qos, optionally user) """ def __init__(self, sim: HdlSimulator, intf: Axi3_addr, allowNoReset=False): BaseAxiAgent.__init__(self, sim, intf, allowNoReset=allowNoReset) signals = [ intf.id, intf.addr, intf.burst, intf.cache, intf.len, intf.lock, intf.prot, intf.size, ] if hasattr(intf, "user"): signals.append(intf.user) self._signals = tuple(signals) self._sigCnt = len(signals) def create_addr_req(self, addr, _len, _id=0, burst=BURST_INCR, cache=CACHE_DEFAULT, lock=LOCK_DEFAULT, prot=PROT_DEFAULT, size=_DEFAULT, user=None): """ Create a default AXI address transaction :note: transaction is created and returned but it is not added to a agent data """ if size is _DEFAULT: D_B = self.intf._parent.DATA_WIDTH // 8 size = BYTES_IN_TRANS(D_B) if self.intf.USER_WIDTH: return (_id, addr, burst, cache, _len, lock, prot, size, user) else: assert user is None return (_id, addr, burst, cache, _len, lock, prot, size) ##################################################################### class Axi3_w(Axi_hs, Axi_strb): """ Axi3 write channel interface (simplified AxiStream) .. hwt-autodoc:: """ def _config(self): self.ID_WIDTH = Param(0) self.DATA_WIDTH = Param(64) def _declr(self): if self.ID_WIDTH: self.id = VectSignal(self.ID_WIDTH) self.data = VectSignal(self.DATA_WIDTH) Axi_strb._declr(self) self.last = Signal() Axi_hs._declr(self) def _initSimAgent(self, sim: HdlSimulator): AxiStream._initSimAgent(self, sim) ##################################################################### class Axi3_r(Axi3Lite_r, Axi_id): """ Axi 3 read channel interface .. hwt-autodoc:: """ def _config(self): Axi_id._config(self, default_id_width=6) Axi3Lite_r._config(self) def _declr(self): Axi_id._declr(self) Axi3Lite_r._declr(self) self.last = Signal() def _initSimAgent(self, sim: HdlSimulator): self._ag = Axi3_rAgent(sim, self) class Axi3_rAgent(BaseAxiAgent): """ Simulation agent for :class:`.Axi4_r` interface input/output data stored in list under "data" property data contains tuples (id, data, resp, last) """ def get_data(self): intf = self.intf _id = intf.id.read() data = intf.data.read() resp = intf.resp.read() last = intf.last.read() return (_id, data, resp, last) def set_data(self, data): intf = self.intf if data is None: data = [None for _ in range(4)] _id, data, resp, last = data intf.id.write(_id) intf.data.write(data) intf.resp.write(resp) intf.last.write(last) ##################################################################### class Axi3_b(Axi3Lite_b, Axi_id): """ Axi3 write response channel interface .. hwt-autodoc:: """ def _config(self): Axi_id._config(self) Axi3Lite_b._config(self) def _declr(self): Axi_id._declr(self) Axi3Lite_b._declr(self) def _initSimAgent(self, sim: HdlSimulator): self._ag = Axi3_bAgent(sim, self) class Axi3_bAgent(BaseAxiAgent): """ Simulation agent for :class:`.Axi3_b` interface input/output data stored in list under "data" property data contains tuples (id, resp) """ def get_data(self): intf = self.intf return intf.id.read(), intf.resp.read() def set_data(self, data): intf = self.intf if data is None: data = [None for _ in range(2)] _id, resp = data intf.id.write(_id) intf.resp.write(resp) ##################################################################### class Axi3(Axi3Lite): """ AMBA Axi3 bus interface https://static.docs.arm.com/ihi0022/d/IHI0022D_amba_axi_protocol_spec.pdf .. hwt-autodoc:: """ LOCK_WIDTH = Axi3_addr.LOCK_WIDTH LEN_WIDTH = Axi3_addr.LEN_WIDTH AW_CLS = Axi3_addr AR_CLS = Axi3_addr W_CLS = Axi3_w R_CLS = Axi3_r B_CLS = Axi3_b def _config(self): Axi3Lite._config(self) Axi_id._config(self, default_id_width=6) self.ADDR_USER_WIDTH = Param(0) # self.DATA_USER_WIDTH = Param(0) def _declr(self): with self._paramsShared(): if self.HAS_R: self.ar = self.AR_CLS() self.ar.USER_WIDTH = self.ADDR_USER_WIDTH self.r = self.R_CLS(masterDir=DIRECTION.IN) if self.HAS_W: self.aw = self.AW_CLS() self.aw.USER_WIDTH = self.ADDR_USER_WIDTH self.w = self.W_CLS() self.b = self.B_CLS(masterDir=DIRECTION.IN) # for d in [self.w, self.r, self.b]: # d.USER_WIDTH = self.DATA_USER_WIDTH def _getIpCoreIntfClass(self): return IP_Axi3 class IP_Axi3(IP_Axi3Lite): """ IP core interface meta for Axi3 interface """ def __init__(self,): super(IP_Axi3, self).__init__() self.quartus_name = "axi" self.xilinx_protocol_name = "AXI3" A_SIGS = ['id', 'burst', 'cache', 'len', 'lock', 'prot', 'size', 'qos', 'user'] AxiMap('ar', A_SIGS, self.map['ar']) AxiMap('r', ['id', 'last'], self.map['r']) AxiMap('aw', A_SIGS, self.map['aw']) AxiMap('w', ['id', 'last'], self.map['w']) AxiMap('b', ['id'], self.map['b']) def postProcess(self, component: Component, packager: IpPackager, thisIf: Axi3): self.endianness = "little" thisIntfName = packager.getInterfaceLogicalName(thisIf) def param(name, val): return self.addSimpleParam(thisIntfName, name, str(val)) # [TODO] width as expression instead of int param("ADDR_WIDTH", thisIf.aw.addr._dtype.bit_length()) param("MAX_BURST_LENGTH", int(2 ** thisIf.aw.len._dtype.bit_length())) param("NUM_READ_OUTSTANDING", 5) param("NUM_WRITE_OUTSTANDING", 5) param("PROTOCOL", self.xilinx_protocol_name) param("READ_WRITE_MODE", "READ_WRITE") param("SUPPORTS_NARROW_BURST", 0) A_U_W = int(thisIf.ADDR_USER_WIDTH) if A_U_W: param("AWUSER_WIDTH", A_U_W) param("ARUSER_WIDTH", A_U_W)
StarcoderdataPython
59131
from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from .forms import UserLoginForm def home_view(request): context = {'name': 'Dave'} return render(request, 'home.html',context) def login_view(request): form = UserLoginForm(request.POST or None) next_ = request.GET.get('next') if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username.strip(), password=password.strip()) login(request, user) next_post = request.POST.get('next') redirect_path = next_ or next_post or '/' return redirect(redirect_path) return render(request, 'login.html', {'form':form}) def logout_view(request): logout(request) return redirect('lista:home')
StarcoderdataPython
1628743
from PyPowerStore.utils import constants from PyPowerStore.tests.unit_tests.base_test import TestBase from PyPowerStore.utils.exception import PowerStoreException import mock class TestVolume(TestBase): def test_get_volumes(self): vol_list = self.provisioning.get_volumes() self.assertListEqual(vol_list, self.data.volume_list) def test_get_volume_detail(self): vol_details = self.provisioning.get_volume_details(self.data.vol_id1) self.assertEqual(vol_details, self.data.volume1) def test_create_volume(self): vol = self.provisioning.create_volume(self.data.vol_name1, self.data.size) self.assertIsNone(vol) def test_modify_volume(self): vol = self.provisioning.modify_volume(self.data.vol_id1, self.data.vol_name1) self.assertIsNone(vol) def test_delete_volume(self): vol = self.provisioning.delete_volume(self.data.vol_id1) self.assertIsNone(vol) def test_get_volumes_with_filter(self): querystring = {'name': 'ilike.*test*'} querystring.update(constants.SELECT_ID_AND_NAME) with mock.patch.object(self.provisioning.client, 'request') as mock_request: self.provisioning.get_volumes(filter_dict=querystring, all_pages=True) mock_request.assert_called_with( constants.GET, constants.GET_VOLUME_LIST_URL.format( self.provisioning.server_ip), all_pages=True, payload=None, querystring=querystring) def test_add_protection_policy_for_volume(self): resp = self.provisioning.add_protection_policy_for_volume( self.data.vol_id1, self.data.pol_id) self.assertIsNone(resp) def test_add_invalid_protection_policy_for_volume(self): self.assertRaises(PowerStoreException, self.provisioning.add_protection_policy_for_volume, self.data.vol_id1, self.data.invalid_pol_id) def test_remove_protection_policy_for_volume(self): resp = self.provisioning.remove_protection_policy_for_volume( self.data.vol_id1) self.assertIsNone(resp) def test_get_volume_by_name(self): vol_details = self.provisioning.get_volume_by_name( self.data.vol_name1) self.assertEqual(vol_details, [self.data.volume1]) def test_map_volume_to_host(self): resp = self.provisioning.map_volume_to_host( self.data.vol_id1, self.data.host_id1, self.data.lun) self.assertIsNone(resp) def test_unmap_volume_from_host(self): resp = self.provisioning.unmap_volume_from_host( self.data.vol_id1, self.data.host_id1) self.assertIsNone(resp) def test_map_volume_to_hg(self): resp = self.provisioning.map_volume_to_host_group( self.data.vol_id1, self.data.hg_id1, self.data.lun) self.assertIsNone(resp) def test_unmap_volume_from_host_group(self): resp = self.provisioning.unmap_volume_from_host_group( self.data.vol_id1, self.data.hg_id1) self.assertIsNone(resp) def test_create_volume_snapshot(self): vol_snap_detail = self.protection.create_volume_snapshot( self.data.vol_id1, description='vol snap description') self.assertEqual(vol_snap_detail, self.data.vol_snap_detail) def test_get_volume_snapshots(self): snap = self.protection.get_volume_snapshots(self.data.vol_id1) self.assertListEqual(snap, self.data.volume_snap_list) def test_get_volume_snapshot_details(self): snap = self.protection.get_volume_snapshot_details( self.data.vol_snap_id) self.assertEqual(snap, self.data.vol_snap_detail) def test_modify_volume_snapshot(self): snap = self.protection.modify_volume_snapshot( self.data.vol_snap_id, name='vol_snap') self.assertEqual(snap, self.data.vol_snap_detail) def test_delete_volume_snapshot(self): resp = self.protection.delete_volume_snapshot(self.data.vol_snap_id) self.assertIsNone(resp)
StarcoderdataPython
3273848
""" Methods for drawing from the sunspot latitude and radius distribution """ import numpy as np import astropy.units as u __all__ = ['draw_random_sunspot_latitudes', 'draw_random_sunspot_radii'] @u.quantity_input(theta=u.rad, phi=u.rad) def rtp_to_edge(radius, theta, phi, n_points=1000): """ Use the haversine formula to compute the boundary lat/lon coordinates for a circular spot centered on ``(theta, phi)``, with radius ``radius` in units of the stellar radius. Parameters ---------- radius : float Spot radius [R_star] theta : `~astropy.units.Quantity` Spot theta coord (90 deg - latitude) phi : `~astropy.units.Quantity` Spot phi coord (longitude) n_points : int Number of points to include in the circle boundary Returns ------- lat : `~astropy.units.Quantity` Latitudes of spot boundary lon : `~astropy.units.Quantity` Longitudes of spot boundary """ lat1 = np.pi/2 - theta.to(u.rad).value lon1 = phi.to(u.rad).value d = radius thetas = np.linspace(0, -2*np.pi, n_points)[:, np.newaxis] lat = np.arcsin(np.sin(lat1) * np.cos(d) + np.cos(lat1) * np.sin(d) * np.cos(thetas)) dlon = np.arctan2(np.sin(thetas) * np.sin(d) * np.cos(lat1), np.cos(d) - np.sin(lat1) * np.sin(lat)) lon = ((lon1 - dlon + np.pi) % (2*np.pi)) - np.pi return lat*u.rad, lon*u.rad def generate_random_coord(n=1): """ Generate random latitude/longitude pairs, of length ``n``. """ random_longitude = 2*np.pi*np.random.rand(n) random_z = 2*np.random.rand(n) - 1 random_latitude = np.arcsin(random_z) result = np.vstack([random_latitude, random_longitude]).T * u.rad if result.shape[0] == 1: return result[0] return result def sunspot_distribution(latitude, mean_latitude=15): """ Approximate un-normalized probability distribution of sunspots at ``latitude`` near activity maximum on the Sun. Parameters ---------- latitude : `~numpy.ndarray` Latitude mean_latitude : float Mean active latitude in degrees Returns ------- p : `~numpy.ndarray Probability (un-normalized) """ return np.exp(-0.5 * (abs(latitude) - mean_latitude)**2 / 6**2) def sunspot_latitude_inverse_transform(x, mean_latitude=15): """ Use inverse transform sampling to randomly draw spot latitudes from the sunspot latitude distribution, for a uniform random variate ``x`` on the range [0,1). Parameters ---------- x : `~np.ndarray` or float Uniform random variate on [0, 1) Returns ------- lat : `~astropy.units.Quantity` Latitude of a sunspot drawn from the sunspot latitude distribution. """ lats = np.linspace(-88, 88, 1000) prob = np.cumsum(sunspot_distribution(lats, mean_latitude=mean_latitude)) prob /= np.max(prob) return np.interp(x, prob, lats) * u.deg def draw_random_sunspot_latitudes(n, mean_latitude=15): """ Draw one or more random samples from the sunspot latitude distribution. Parameters ---------- n : int Number of random sunspot latitudes to draw Returns ------- lat : `~astropy.units.Quantity` Latitude of a sunspot drawn from the sunspot latitude distribution. """ return sunspot_latitude_inverse_transform(np.random.rand(n), mean_latitude=mean_latitude) def sunspot_umbral_area_distribution(log_area_uhem): """ Approximate log-normal distribution of sunspot umbral areas """ return np.exp(-0.5 * (log_area_uhem - 4.1)**2 / 1.0**2) def sunspot_umbral_area_inverse_transform(x): """ Use inverse transform sampling to randomly draw spot areas from the sunspot umbral area distribution, for a uniform random variate ``x`` on the range [0,1). Parameters ---------- x : `~np.ndarray` or float Uniform random variate on [0, 1) Returns ------- umbral_areas : `~numpy.ndarray` Umbral area(s) of sunspot(s) drawn from the sunspot umbral area distribution. """ log_areas_uhem = np.linspace(0, 9, 1000) prob = np.cumsum(sunspot_umbral_area_distribution(log_areas_uhem)) prob /= np.max(prob) return np.interp(x, prob, log_areas_uhem) def draw_random_sunspot_radii(n): """ Draw one or more random samples from the sunspot radius distribution. Parameters ---------- n : int Number of random sunspot radii to draw Returns ------- rspot_rstar : `~numpy.ndarray` Radii of a sunspots drawn from the sunspot radius distribution, in units of stellar radii. """ umbral_areas_uhem = sunspot_umbral_area_inverse_transform(np.random.rand(n)) total_to_umbral_area = 5 # ratio of total spot area to area in umbra rspot_rstar = np.sqrt(1e-6 * 2 * total_to_umbral_area * umbral_areas_uhem) return rspot_rstar
StarcoderdataPython
42957
<reponame>PublicMapping/districtbuilder-classic from __future__ import absolute_import, unicode_literals import os from celery import Celery from . import REDIS_URL os.environ.setdefault("DJANGO_SETTINGS_MODULE", "publicmapping.settings") # Configure Celery app to use Redis as both the results backend and the message broker. app = Celery('publicmapping', backend=REDIS_URL, broker=REDIS_URL) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks()
StarcoderdataPython
116432
<reponame>Telefonica/clipspy from .rules_engines import RulesEngine import logging import os from typing import Text logger = logging.getLogger(__name__) class RulesEnginesStore(object): """ Base class for rules engine stores. """ def load_persistent_state(self, rules_engine: RulesEngine, id: Text): """ Loads a persisted state into a rules engine. :param rules_engine: The rules engine. :param id: The id of the persisted state. """ raise NotImplementedError("This method should be implemented by subclasses!") def save_persistent_state(self, rules_engine: RulesEngine, id: Text): """ Save the current state of a rules engine and associates it to a given id. :param rules_engine: The rules engine. :param id: The identifier to persist to. """ raise NotImplementedError("This method should be implemented by subclasses!") def clear_persistent_state(self, id: Text): """ Clears the persisted state identified by a give id. :param id: The identifier to clear. """ raise NotImplementedError("This method should be implemented by subclasses!") class LocalFileRulesEngineStore(RulesEnginesStore): """ This rules engine stores persistent states into a folder into the local machine. Each persistent state is stored as file into this folder. The name of the files follow this format: <floder_path>/<id>.persist """ def __init__(self, folder_path: Text, binary: bool= True): """ :param folder_path: The path to the persistence folder. :param binary: If True the state is saved as a binary file. Default: True. """ self.folder_path = folder_path self.binary = binary def _build_path(self, id: Text): return os.path.join(self.folder_path, "{}.persist".format(id)) def load_persistent_state(self, rules_engine: RulesEngine, id: Text): _path = self._build_path(id) if os.path.exists(_path): rules_engine.env.eval("(load-facts {})".format(self._build_path(id))) # Clear all activations in agenda logger.debug("Clearing agenda after facts load") # Debug rules_engine.env._agenda.clear() else: logger.warn('No persisted state found for id="{}"'.format(id)) def save_persistent_state(self, rules_engine: RulesEngine, id: Text): rules_engine.env.eval("(save-facts {})".format(self._build_path(id))) def clear_persistent_state(self, id: Text): _path = self._build_path(id) if os.path.exists(_path): os.remove(self._build_path(id)) else: logger.warn('No persisted state found for id="{}"'.format(id))
StarcoderdataPython
44560
from openprocurement.tender.core.procedure.serializers.base import ListSerializer from openprocurement.tender.core.procedure.serializers.document import ConfidentialDocumentSerializer from openprocurement.tender.core.procedure.serializers.parameter import ParameterSerializer from openprocurement.tender.esco.procedure.serializers.lot_value import LotValueSerializer from openprocurement.tender.esco.procedure.serializers.value import ValueSerializer from openprocurement.tender.openeu.procedure.serializers import BidSerializer as BaseBidSerializer class BidSerializer(BaseBidSerializer): serializers = { "value": ValueSerializer, "lotValues": ListSerializer(LotValueSerializer), "documents": ListSerializer(ConfidentialDocumentSerializer), "parameters": ListSerializer(ParameterSerializer), }
StarcoderdataPython
195178
from enum import Enum class MerossEventType(Enum): # Fired when the MQTT client connects/disconnects to the MQTT broker CLIENT_CONNECTION = 10 DEVICE_ONLINE_STATUS = 100 DEVICE_BIND = 200 DEVICE_UNBIND = 201 DEVICE_SWITCH_STATUS = 1000 DEVICE_BULB_SWITCH_STATE = 2000 DEVICE_BULB_STATE = 2001 GARAGE_DOOR_STATUS = 3000 THERMOSTAT_TEMPERATURE_CHANGE = 5000 THERMOSTAT_MODE_CHANGE = 5001 HUMIDIFIER_SPRY_EVENT = 6000 HUMIDIFIER_LIGHT_EVENT = 6001 class MerossEvent(object): event_type = None # type: MerossEventType def __init__(self, event_type): self.event_type = event_type class DeviceBindEvent(MerossEvent): def __init__(self, device, bind_data): super(DeviceBindEvent, self).__init__(MerossEventType.DEVICE_BIND) self.device = device self.bind_data = bind_data class DeviceUnbindEvent(MerossEvent): def __init__(self, device): super(DeviceUnbindEvent, self).__init__(MerossEventType.DEVICE_UNBIND) self.device = device class ClientConnectionEvent(MerossEvent): status = None def __init__(self, current_status): super(ClientConnectionEvent, self).__init__(MerossEventType.CLIENT_CONNECTION) self.status = current_status class DeviceOnlineStatusEvent(MerossEvent): # Pointer to the device object device = None # Current status of the device status = None def __init__(self, dev, current_status): super(DeviceOnlineStatusEvent, self).__init__(MerossEventType.DEVICE_ONLINE_STATUS) self.device = dev self.status = "online" if current_status else "offline" class DeviceSwitchStatusEvent(MerossEvent): # Pointer to the device object device = None # Channel ID where the event occurred channel_id = None # Current state of the switch where the event occurred switch_state = None # Indicates id the event was generated by a command issued by the library itself. # This is particularly useful in the case the user handler wants only to react # to events generated by third parties. generated_by_myself = None def __init__(self, dev, channel_id, switch_state, generated_by_myself): super(DeviceSwitchStatusEvent, self).__init__(MerossEventType.DEVICE_SWITCH_STATUS) self.device = dev self.channel_id = channel_id self.switch_state = switch_state self.generated_by_myself = generated_by_myself class DeviceDoorStatusEvent(MerossEvent): # Pointer to the device object device = None # Current state of the door door_state = None # Channel related to the door controller channel = None # Indicates id the event was generated by a command issued by the library itself. # This is particularly useful in the case the user handler wants only to react # to events generated by third parties. generated_by_myself = None def __init__(self, dev, channel_id, door_state, generated_by_myself): super(DeviceDoorStatusEvent, self).__init__(MerossEventType.GARAGE_DOOR_STATUS) self.device = dev self.channel = channel_id self.door_state = "open" if door_state else "closed" self.generated_by_myself = generated_by_myself class BulbSwitchStateChangeEvent(MerossEvent): def __init__(self, dev, channel_id, is_on, generated_by_myself): super(BulbSwitchStateChangeEvent, self).__init__(MerossEventType.DEVICE_BULB_SWITCH_STATE) self.device = dev self.channel = channel_id self.is_on = is_on self.generated_by_myself = generated_by_myself class BulbLightStateChangeEvent(MerossEvent): def __init__(self, dev, channel_id, light_state, generated_by_myself): super(BulbLightStateChangeEvent, self).__init__(MerossEventType.DEVICE_BULB_STATE) self.device = dev self.channel = channel_id self.light_state = light_state self.generated_by_myself = generated_by_myself class ThermostatTemperatureChange(MerossEvent): def __init__(self, device, temperature_state, generated_by_myself): super(ThermostatTemperatureChange, self).__init__(MerossEventType.THERMOSTAT_TEMPERATURE_CHANGE) self.device = device self.temperature = temperature_state self.generated_by_myself = generated_by_myself class ThermostatModeChange(MerossEvent): def __init__(self, device, mode, generated_by_myself): super(ThermostatModeChange, self).__init__(MerossEventType.THERMOSTAT_MODE_CHANGE) self.device = device self.mode = mode self.generated_by_myself = generated_by_myself class HumidifierSpryEvent(MerossEvent): def __init__(self, device, spry_mode, channel, generated_by_myself): super(HumidifierSpryEvent, self).__init__(MerossEventType.HUMIDIFIER_SPRY_EVENT) self.device = device self.spry_mode = spry_mode self.channel = channel self.generated_by_myself = generated_by_myself class HumidifierLightEvent(MerossEvent): def __init__(self, dev, channel, onoff, rgb, luminance, generated_by_myself): super(HumidifierLightEvent, self).__init__(MerossEventType.HUMIDIFIER_LIGHT_EVENT) self.device = dev self.channel = channel self.is_on = onoff == 1 self.rgb = rgb self.luminance = luminance self.generated_by_myself = generated_by_myself
StarcoderdataPython
3390950
from researchutils.chainer.functions import average_k_step_squared_error from chainer.link import Chain from chainer import reporter import chainer import chainer.functions as F class FFPredictionEvaluator(Chain): def __init__(self, predictor, loss_fun=average_k_step_squared_error, k_step=1): super(FFPredictionEvaluator, self).__init__() self.loss_fun = loss_fun self.k_step = k_step self.loss = None with self.init_scope(): self.predictor = predictor def __call__(self, *args, **kwargs): self.loss = 0 (train_frame, train_actions) = kwargs['input'] target_frames = kwargs['target'] for step in range(self.k_step): predicted_frame = self.predictor( (train_frame, train_actions[:, step, :, :])) expected_frame = target_frames[:, step, :, :, :] self.loss += self.loss_fun(predicted_frame, expected_frame, self.k_step) if not self.k_step == 1: predicted_frame = chainer.Variable(predicted_frame.array) train_frame = F.concat((train_frame, predicted_frame), axis=1)[ :, 3:, :, :] reporter.report({'loss':self.loss}, self) return self.loss
StarcoderdataPython
1662830
<reponame>preranaandure/wildlifecompliance # -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-12-24 05:49 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wildlifecompliance', '0357_auto_20191224_1345'), ] operations = [ migrations.RemoveField( model_name='remediationactiontaken', name='remediation_action', ), migrations.RemoveField( model_name='remediationactiontakendocument', name='remediation_action_taken', ), migrations.DeleteModel( name='RemediationActionTaken', ), migrations.DeleteModel( name='RemediationActionTakenDocument', ), ]
StarcoderdataPython
3256480
<gh_stars>100-1000 # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def drughiv(path): """data from Exercise 7.6, p222 The `drughiv` data frame has 34 rows and 3 columns. This data frame contains the following columns: drug Drug combination (1=AZT + zalcitabine, 2=AZT + zalcitabine + saquinavir) time Time after drug administration to CD4 count at a specified level, days delta Indicator of CD4 count reaching specified level (1=yes, 0=no) <NAME> Moeschberger (1997) *Survival Analysis Techniques for Censored and truncated data*, Springer. Args: path: str. Path to directory which either stores file or otherwise file will be downloaded and extracted there. Filename is `drughiv.csv`. Returns: Tuple of np.ndarray `x_train` with 34 rows and 3 columns and dictionary `metadata` of column headers (feature names). """ import pandas as pd path = os.path.expanduser(path) filename = 'drughiv.csv' if not os.path.exists(os.path.join(path, filename)): url = 'http://dustintran.com/data/r/KMsurv/drughiv.csv' maybe_download_and_extract(path, url, save_file_name='drughiv.csv', resume=False) data = pd.read_csv(os.path.join(path, filename), index_col=0, parse_dates=True) x_train = data.values metadata = {'columns': data.columns} return x_train, metadata
StarcoderdataPython
1641993
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: self.ans = 0 def depth(p): if not p: return 0 left, right = depth(p.left), depth(p.right) self.ans = max(self.ans, left+right) return 1 + max(left, right) depth(root) return self.ans
StarcoderdataPython
1780176
<filename>esphome/components/modbus_controller/__init__.py import binascii import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import modbus from esphome.const import CONF_ADDRESS, CONF_ID, CONF_NAME, CONF_LAMBDA, CONF_OFFSET from esphome.cpp_helpers import logging from .const import ( CONF_BITMASK, CONF_BYTE_OFFSET, CONF_COMMAND_THROTTLE, CONF_CUSTOM_COMMAND, CONF_FORCE_NEW_RANGE, CONF_MODBUS_CONTROLLER_ID, CONF_REGISTER_COUNT, CONF_REGISTER_TYPE, CONF_RESPONSE_SIZE, CONF_SKIP_UPDATES, CONF_VALUE_TYPE, ) CODEOWNERS = ["@martgras"] AUTO_LOAD = ["modbus"] MULTI_CONF = True # pylint: disable=invalid-name modbus_controller_ns = cg.esphome_ns.namespace("modbus_controller") ModbusController = modbus_controller_ns.class_( "ModbusController", cg.PollingComponent, modbus.ModbusDevice ) SensorItem = modbus_controller_ns.struct("SensorItem") ModbusFunctionCode_ns = modbus_controller_ns.namespace("ModbusFunctionCode") ModbusFunctionCode = ModbusFunctionCode_ns.enum("ModbusFunctionCode") MODBUS_FUNCTION_CODE = { "read_coils": ModbusFunctionCode.READ_COILS, "read_discrete_inputs": ModbusFunctionCode.READ_DISCRETE_INPUTS, "read_holding_registers": ModbusFunctionCode.READ_HOLDING_REGISTERS, "read_input_registers": ModbusFunctionCode.READ_INPUT_REGISTERS, "write_single_coil": ModbusFunctionCode.WRITE_SINGLE_COIL, "write_single_register": ModbusFunctionCode.WRITE_SINGLE_REGISTER, "write_multiple_coils": ModbusFunctionCode.WRITE_MULTIPLE_COILS, "write_multiple_registers": ModbusFunctionCode.WRITE_MULTIPLE_REGISTERS, } ModbusRegisterType_ns = modbus_controller_ns.namespace("ModbusRegisterType") ModbusRegisterType = ModbusRegisterType_ns.enum("ModbusRegisterType") MODBUS_WRITE_REGISTER_TYPE = { "custom": ModbusRegisterType.CUSTOM, "coil": ModbusRegisterType.COIL, "holding": ModbusRegisterType.HOLDING, } MODBUS_REGISTER_TYPE = { **MODBUS_WRITE_REGISTER_TYPE, "discrete_input": ModbusRegisterType.DISCRETE_INPUT, "read": ModbusRegisterType.READ, } SensorValueType_ns = modbus_controller_ns.namespace("SensorValueType") SensorValueType = SensorValueType_ns.enum("SensorValueType") SENSOR_VALUE_TYPE = { "RAW": SensorValueType.RAW, "U_WORD": SensorValueType.U_WORD, "S_WORD": SensorValueType.S_WORD, "U_DWORD": SensorValueType.U_DWORD, "U_DWORD_R": SensorValueType.U_DWORD_R, "S_DWORD": SensorValueType.S_DWORD, "S_DWORD_R": SensorValueType.S_DWORD_R, "U_QWORD": SensorValueType.U_QWORD, "U_QWORD_R": SensorValueType.U_QWORD_R, "S_QWORD": SensorValueType.S_QWORD, "S_QWORD_R": SensorValueType.S_QWORD_R, "FP32": SensorValueType.FP32, "FP32_R": SensorValueType.FP32_R, } TYPE_REGISTER_MAP = { "RAW": 1, "U_WORD": 1, "S_WORD": 1, "U_DWORD": 2, "U_DWORD_R": 2, "S_DWORD": 2, "S_DWORD_R": 2, "U_QWORD": 4, "U_QWORD_R": 4, "S_QWORD": 4, "S_QWORD_R": 4, "FP32": 2, "FP32_R": 2, } MULTI_CONF = True _LOGGER = logging.getLogger(__name__) CONFIG_SCHEMA = cv.All( cv.Schema( { cv.GenerateID(): cv.declare_id(ModbusController), cv.Optional( CONF_COMMAND_THROTTLE, default="0ms" ): cv.positive_time_period_milliseconds, } ) .extend(cv.polling_component_schema("60s")) .extend(modbus.modbus_device_schema(0x01)) ) ModbusItemBaseSchema = cv.Schema( { cv.GenerateID(CONF_MODBUS_CONTROLLER_ID): cv.use_id(ModbusController), cv.Optional(CONF_ADDRESS): cv.positive_int, cv.Optional(CONF_CUSTOM_COMMAND): cv.ensure_list(cv.hex_uint8_t), cv.Exclusive( CONF_OFFSET, "offset", f"{CONF_OFFSET} and {CONF_BYTE_OFFSET} can't be used together", ): cv.positive_int, cv.Exclusive( CONF_BYTE_OFFSET, "offset", f"{CONF_OFFSET} and {CONF_BYTE_OFFSET} can't be used together", ): cv.positive_int, cv.Optional(CONF_BITMASK, default=0xFFFFFFFF): cv.hex_uint32_t, cv.Optional(CONF_SKIP_UPDATES, default=0): cv.positive_int, cv.Optional(CONF_FORCE_NEW_RANGE, default=False): cv.boolean, cv.Optional(CONF_LAMBDA): cv.returning_lambda, cv.Optional(CONF_RESPONSE_SIZE, default=0): cv.positive_int, }, ) def validate_modbus_register(config): if CONF_CUSTOM_COMMAND not in config and CONF_ADDRESS not in config: raise cv.Invalid( f" {CONF_ADDRESS} is a required property if '{CONF_CUSTOM_COMMAND}:' isn't used" ) if CONF_CUSTOM_COMMAND in config and CONF_REGISTER_TYPE in config: raise cv.Invalid( f"can't use '{CONF_REGISTER_TYPE}:' together with '{CONF_CUSTOM_COMMAND}:'", ) if CONF_CUSTOM_COMMAND not in config and CONF_REGISTER_TYPE not in config: raise cv.Invalid( f" {CONF_REGISTER_TYPE} is a required property if '{CONF_CUSTOM_COMMAND}:' isn't used" ) return config def modbus_calc_properties(config): byte_offset = 0 reg_count = 0 if CONF_OFFSET in config: byte_offset = config[CONF_OFFSET] # A CONF_BYTE_OFFSET setting overrides CONF_OFFSET if CONF_BYTE_OFFSET in config: byte_offset = config[CONF_BYTE_OFFSET] if CONF_REGISTER_COUNT in config: reg_count = config[CONF_REGISTER_COUNT] if CONF_VALUE_TYPE in config: value_type = config[CONF_VALUE_TYPE] if reg_count == 0: reg_count = TYPE_REGISTER_MAP[value_type] if CONF_CUSTOM_COMMAND in config: if CONF_ADDRESS not in config: # generate a unique modbus address using the hash of the name # CONF_NAME set even if only CONF_ID is used. # a modbus register address is required to add the item to sensormap value = config[CONF_NAME] if isinstance(value, str): value = value.encode() config[CONF_ADDRESS] = binascii.crc_hqx(value, 0) config[CONF_REGISTER_TYPE] = ModbusRegisterType.CUSTOM config[CONF_FORCE_NEW_RANGE] = True return byte_offset, reg_count async def add_modbus_base_properties( var, config, sensor_type, lamdba_param_type=cg.float_, lamdba_return_type=float ): if CONF_CUSTOM_COMMAND in config: cg.add(var.set_custom_data(config[CONF_CUSTOM_COMMAND])) if config[CONF_RESPONSE_SIZE] > 0: cg.add(var.set_register_size(config[CONF_RESPONSE_SIZE])) if CONF_LAMBDA in config: template_ = await cg.process_lambda( config[CONF_LAMBDA], [ (sensor_type.operator("ptr"), "item"), (lamdba_param_type, "x"), ( cg.std_vector.template(cg.uint8).operator("const").operator("ref"), "data", ), ], return_type=cg.optional.template(lamdba_return_type), ) cg.add(var.set_template(template_)) async def to_code(config): var = cg.new_Pvariable(config[CONF_ID], config[CONF_COMMAND_THROTTLE]) cg.add(var.set_command_throttle(config[CONF_COMMAND_THROTTLE])) await register_modbus_device(var, config) async def register_modbus_device(var, config): cg.add(var.set_address(config[CONF_ADDRESS])) await cg.register_component(var, config) return await modbus.register_modbus_device(var, config) def function_code_to_register(function_code): FUNCTION_CODE_TYPE_MAP = { "read_coils": ModbusRegisterType.COIL, "read_discrete_inputs": ModbusRegisterType.DISCRETE, "read_holding_registers": ModbusRegisterType.HOLDING, "read_input_registers": ModbusRegisterType.READ, "write_single_coil": ModbusRegisterType.COIL, "write_single_register": ModbusRegisterType.HOLDING, "write_multiple_coils": ModbusRegisterType.COIL, "write_multiple_registers": ModbusRegisterType.HOLDING, } return FUNCTION_CODE_TYPE_MAP[function_code]
StarcoderdataPython
156024
# -*- coding: UTF8 -*- from pupylib.PupyModule import * from pupylib.PupyCompleter import * from rpyc.utils.classic import download import os import os.path import time __class_name__="DownloaderScript" @config(category="manage") class DownloaderScript(PupyModule): """ download a file/directory from a remote system """ def init_argparse(self): self.arg_parser = PupyArgumentParser(prog='download', description=self.__doc__) self.arg_parser.add_argument('remote_file', metavar='<remote_path>') self.arg_parser.add_argument('local_file', nargs='?', metavar='<local_path>', completer=path_completer) def run(self, args): remote_file=self.client.conn.modules['os.path'].expandvars(args.remote_file) rep=os.path.join("data","downloads",self.client.short_name()) if not args.local_file: try: os.makedirs(rep) except Exception: pass args.local_file=os.path.join(rep, os.path.basename(remote_file.replace("\\",os.sep).replace("/",os.sep).rstrip("/\\"))) self.info("downloading %s ..."%remote_file) start_time=time.time() download(self.client.conn, remote_file, args.local_file) self.success("file downloaded from remote:%s to local:%s"%(remote_file, args.local_file)) size=os.path.getsize(args.local_file) total_time=round(time.time()-start_time, 2) self.info("%s bytes downloaded in: %ss. average %sKB/s"%(size, total_time, round((size/total_time)/10**3, 2)))
StarcoderdataPython
3345773
# -*- coding: utf-8 -*- from Particion import Particion from Particionado import Particionado from src.Instances import Instances import random class DivisionPorcentual(Particionado): """docstring for DivisionPorcentual""" def __init__(self): super(DivisionPorcentual, self).__init__() self.porcentaje = 0.0 def setPorcentajeTrain(self, porcentaje): self.porcentaje = porcentaje def generaParticiones(self, instances): #una sola particion particion = Particion() #generar las instacias para la particion instanceTrain = Instances() instanceTest = Instances() # set clases instanceTrain.setClases(instances.getClases()) instanceTest.setClases(instances.getClases()) # set columns instanceTrain.setColumnas(instances.getColumnasList(), instances.getColumnasTipo()) instanceTest.setColumnas(instances.getColumnasList(), instances.getColumnasTipo()) #generar las instancias listInstances = list(instances.getListInstances()) random.shuffle(listInstances) n_instances = len(listInstances) n_instances_train = int(round(n_instances * self.porcentaje)) n_instances_test = n_instances - n_instances_train #instancias de train for i in range(0, n_instances_train): instanceTrain.addInstance(listInstances[i]) #instancias de test for i in range(n_instances_train, n_instances): instanceTest.addInstance(listInstances[i]) #añadir a la particion las instancias particion.setTrain(instanceTrain) particion.setTest(instanceTest) return particion def generaParticionesProporcional(self, instances, aleatorio = False): #una sola particion particion = Particion() #generar las instacias para la particion instanceTrain = Instances() instanceTest = Instances() # set clases instanceTrain.setClases(instances.getClases()) instanceTest.setClases(instances.getClases()) # set columns instanceTrain.setColumnas(instances.getColumnasList(), instances.getColumnasTipo()) instanceTest.setColumnas(instances.getColumnasList(), instances.getColumnasTipo()) #generar las instancias listInstances = list(instances.getListInstances()) if aleatorio: random.shuffle(listInstances) n_instances = len(listInstances) n_instances_train = int(round(n_instances * self.porcentaje)) n_instances_test = n_instances - n_instances_train #conteo de instancias en cada clase conteoClases = {} conteoIntroducido = {} listaClases = instances.getClases() for clase in listaClases: conteoClases[clase] = {} conteoClases[clase]['cont'] = 0 conteoClases[clase]['instaces_id'] = [] conteoIntroducido[clase] = 0 i = 0 for instancia in listInstances: clase = instancia.getClase() conteoClases[clase]['cont'] += 1 conteoClases[clase]['instaces_id'].append(i) i+=1 for clase in listaClases: print 'instancias de la clase ' + str(clase) + ': ' + str(conteoClases[clase]['cont']) + ' porcentaje: '+ str(conteoClases[clase]['cont']/float(len(listInstances))) #instancias de train #por cada clase busca se ha de introducir una instancia for i in range(0, n_instances_train): for clase in listaClases: if conteoIntroducido[clase] < ((conteoClases[clase]['cont'] / float(n_instances)) * n_instances_train): identificador = conteoClases[clase]['instaces_id'][conteoIntroducido[clase]] conteoIntroducido[clase] += 1 instanceTrain.addInstance(listInstances[identificador]) #instanceTrain.addInstance(listInstances[i]) #instancias de test for clase in listaClases: desde = conteoIntroducido[clase] hasta = conteoClases[clase]['cont'] for i in range(desde, hasta): identificador = conteoClases[clase]['instaces_id'][i] instanceTest.addInstance(listInstances[identificador]) conteoIntroducido[clase] += 1 #for i in range(n_instances_train, n_instances): # instanceTest.addInstance(listInstances[i]) #añadir a la particion las instancias if aleatorio: instanceTrain.shuffle() particion.setTrain(instanceTrain) particion.setTest(instanceTest) return particion
StarcoderdataPython
3287536
<reponame>pesh1983/exercises """Implementations calculation of Fibonacci numbers.""" def fib1(amount): """ Calculate Fibonacci numbers. The second variable is used to store the result. :param amount: Amount of numbers to produce. :return: Generator. >>> list(fib1(0)) [] >>> list(fib1(1)) [0] >>> list(fib1(3)) [0, 1, 1] >>> list(fib1(9)) [0, 1, 1, 2, 3, 5, 8, 13, 21] """ first, second = 0, 1 for _ in range(amount): yield first first, second = second + first, first def fib2(amount): """ Calculate Fibonacci numbers. The first variable is used to store the result. :param amount: Amount of numbers to produce. :return: Generator. >>> list(fib2(0)) [] >>> list(fib2(1)) [0] >>> list(fib2(3)) [0, 1, 1] >>> list(fib2(9)) [0, 1, 1, 2, 3, 5, 8, 13, 21] """ first, second = 1, 0 for _ in range(amount): first, second = second, first + second yield first if __name__ == '__main__': import doctest doctest.testmod()
StarcoderdataPython
64301
"""This module contains the general information for AaaTacacsPlusEpFsmStage ManagedObject.""" from ...ucscmo import ManagedObject from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta from ...ucscmeta import VersionMeta class AaaTacacsPlusEpFsmStageConsts(): LAST_UPDATE_TIME_ = "" NAME_NOP = "nop" NAME_UPDATE_EP_BEGIN = "updateEpBegin" NAME_UPDATE_EP_FAIL = "updateEpFail" NAME_UPDATE_EP_SET_EP_LOCAL = "updateEpSetEpLocal" NAME_UPDATE_EP_SUCCESS = "updateEpSuccess" STAGE_STATUS_FAIL = "fail" STAGE_STATUS_IN_PROGRESS = "inProgress" STAGE_STATUS_NOP = "nop" STAGE_STATUS_PENDING = "pending" STAGE_STATUS_SKIP = "skip" STAGE_STATUS_SUCCESS = "success" STAGE_STATUS_THROTTLED = "throttled" class AaaTacacsPlusEpFsmStage(ManagedObject): """This is AaaTacacsPlusEpFsmStage class.""" consts = AaaTacacsPlusEpFsmStageConsts() naming_props = set([u'name']) mo_meta = MoMeta("AaaTacacsPlusEpFsmStage", "aaaTacacsPlusEpFsmStage", "stage-[name]", VersionMeta.Version141a, "OutputOnly", 0xf, [], [""], [u'aaaTacacsPlusEpFsm'], [], [None]) prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version141a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "descr": MoPropertyMeta("descr", "descr", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, None, None, r"""[ !#$%&\(\)\*\+,\-\./:;\?@\[\]_\{\|\}~a-zA-Z0-9]{0,256}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, 0x2, 0, 256, None, [], []), "last_update_time": MoPropertyMeta("last_update_time", "lastUpdateTime", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, None, None, r"""([0-9]){4}-([0-9]){2}-([0-9]){2}T([0-9]){2}:([0-9]){2}:([0-9]){2}((\.([0-9]){3})){0,1}""", [""], []), "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version141a, MoPropertyMeta.NAMING, None, None, None, None, ["nop", "updateEpBegin", "updateEpFail", "updateEpSetEpLocal", "updateEpSuccess"], []), "order": MoPropertyMeta("order", "order", "ushort", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []), "retry": MoPropertyMeta("retry", "retry", "byte", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "stage_status": MoPropertyMeta("stage_status", "stageStatus", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["fail", "inProgress", "nop", "pending", "skip", "success", "throttled"], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version141a, MoPropertyMeta.READ_WRITE, 0x8, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), } prop_map = { "childAction": "child_action", "descr": "descr", "dn": "dn", "lastUpdateTime": "last_update_time", "name": "name", "order": "order", "retry": "retry", "rn": "rn", "stageStatus": "stage_status", "status": "status", } def __init__(self, parent_mo_or_dn, name, **kwargs): self._dirty_mask = 0 self.name = name self.child_action = None self.descr = None self.last_update_time = None self.order = None self.retry = None self.stage_status = None self.status = None ManagedObject.__init__(self, "AaaTacacsPlusEpFsmStage", parent_mo_or_dn, **kwargs)
StarcoderdataPython
3379931
from yaml import safe_load from handler import Context, Arguments, CommandResult from rpg.items.item import Item async def run(ctx: Context, args: Arguments) -> CommandResult: item = args[0] items_data = Item._read_objects_from_file(item.__class__) item_data = items_data.get(item.id) if item_data is None: return "Предмет с таким id не найден в файле конфига" add_attribute = False del_attribute = False attributes = args[1].lower() if attributes.startswith("+"): attributes = attributes[1:] add_attribute = True elif attributes.startswith("-"): attributes = attributes[1:] del_attribute = True attribute_chain = attributes.split(".") current_level = item_data for attribute in attribute_chain[:-1]: try: current_level = current_level[attribute] except KeyError: if add_attribute: current_level[attribute] = {} current_level = current_level[attribute] continue return f"Атрибут `{attribute}` не найден. Доступные атрибуты: **{', '.join(a for a in current_level)}**" if attribute_chain[-1] not in current_level: return f"Атрибут `{attribute_chain[-1]}` не найден. Доступные атрибуты: **{', '.join(a for a in current_level)}**" if del_attribute: del current_level[attribute_chain[-1]] else: if len(args) == 2: return "Необходим аргумент со значением" current_level[attribute_chain[-1]] = safe_load(args[2]) new_item = item.from_data(item_data) # inject new item del new_item._storage_by_id[item.id] del new_item._storage_by_name[item.name.lower()] new_item._storage_by_id[new_item.id] = new_item new_item._storage_by_name[new_item.name.lower()] = new_item return f"Предмет: **{new_item!r}**\nЗначения: **{item_data}**"
StarcoderdataPython
3319600
<gh_stars>0 # -*- coding: utf-8 -*- print('Olá Python!') # Resposta do desafio: salario = 3450.45 despesas = 2456.2 percentaul_comprometido = despesas / salario * 100 print(percentaul_comprometido) # Desafio: Operadores Lógicos trabalho_terca = True trabalho_quinta = True ''' - Confirmando os 2: TV 50" + Sorvete - Confirmando apenas 1: TV 32" + Sorvete - Nenhum confirmado: Ficar em casa ''' tv_50 = trabalho_terca and trabalho_quinta sorvete = trabalho_terca or trabalho_quinta tv_32 = trabalho_terca != trabalho_quinta mais_saudavel = not sorvete print("TV50={} TV32={} Sorvete={} Saudável={}" .format(tv_50, tv_32, sorvete, mais_saudavel)) # Operadores ternários esta_chovendo = True print('Hoje estou com as roupas ' + ('secas.', 'molhadas.')[esta_chovendo]) print('Hoje estou com as roupas ' + ('molhadas.' if esta_chovendo else 'secas.'))
StarcoderdataPython
3371481
""" Defines the model used for generating index and compression @<NAME> """ import time import numpy as np from eva_storage.models.sdae_wrapper import SDAE_wrapper from logger import Logger, LoggingLevel import torch import torch.utils.data import argparse parser = argparse.ArgumentParser(description='Define arguments for loader') parser.add_argument('--learning_rate', type=int, default=0.0001, help='Learning rate for UNet') parser.add_argument('--total_epochs', type=int, default=800, help='Number of epoch for training') parser.add_argument('--l2_reg', type=int, default=1e-6, help='Regularization constaint for training') parser.add_argument('--batch_size', type=int, default=64, help='Batch size used for training') parser.add_argument('--compressed_size', type=int, default=100, help='Number of features the compressed image format has') parser.add_argument('--checkpoint_name', type=str, default='unet_uadetrac', help='name of the file that will be used to save checkpoints') args = parser.parse_args() ### TODO: Need to fix the train / execute methods!!! class Network: def __init__(self, type=0): self.model = None self.dataset = None self.data_dimensions = None self.logger = Logger() self.network_type = type ## for now, type will denoting whether we are using a compressed or full network def debugMode(self, mode=False): if mode: self.logger.setLogLevel(LoggingLevel.DEBUG) else: self.logger.setLogLevel(LoggingLevel.INFO) def _parse_dir(self, directory_string): """ This function is called by other methods in UNET to parse the directory string to extract model name and epoch We will assume the format of the string is /dir/name/whatever/{model_name}-{epoch}.pth :param directory_string: string of interest :return: """ tmp = directory_string.split('/') tmp = tmp[-1] model_name, epoch_w_pth = tmp.split('-') epoch = int(epoch_w_pth.split('.')[0]) assert (type(epoch) == int) assert (type(model_name) == str) return model_name, epoch def train(self, train_images: np.ndarray, target_images: np.ndarray, save_name, load_dir = None, model_type = 'sdae', cuda=True): """ Trains the network with given images :param images: original images :param segmented_images: tmp_data :return: None """ if cuda: torch.set_default_tensor_type('torch.cuda.FloatTensor') ### all types of dataset here if model_type == 'sdae': self.model = SDAE_wrapper() assert(self.model is not None) ### we could be training the network from a starting point if load_dir is not None: self.model.load(load_dir) ## delegate the train step to the specific model st = time.perf_counter() ## give the model the training dataset self.model.train(train_images, target_images, save_name, args.total_epochs, lr = args.learning_rate, batch_size = args.batch_size, weight_decay = args.l2_reg, cuda = cuda) self.logger.info(f"Trained the model {self.model} in {time.perf_counter() - st} (sec)") return def execute(self, test_images: np.ndarray = None, model_type = 'dae', load_dir=None, cuda = True): """ We will overload this function to take in no parameters when we are just executing on the given image.. :return: compressed, segmented images that are output of the network """ st = time.perf_counter() if self.model is None: if model_type == 'dae': self.model = SDAE_wrapper() else: raise ValueError if load_dir is None: raise ValueError else: self.model.load(load_dir) assert (self.model is not None) self.logger.info("Images are given, creating dataset object and executing... ") return self.model.execute(test_images) if __name__ == "__main__": network = Network() from loaders.uadetrac_loader import UADetracLoader loader = UADetracLoader() images = loader.load_images()
StarcoderdataPython
3407
"""Collection of tests.""" import pytest import dblib.lib f0 = dblib.lib.Finding('CD spook', 'my_PC', 'The CD drive is missing.') f1 = dblib.lib.Finding('Unplugged', 'my_PC', 'The power cord is unplugged.') f2 = dblib.lib.Finding('Monitor switched off', 'my_PC', 'The monitor is switched off.') def test_add_remove(): """Test function.""" db = dblib.lib.BackyardDB() # regular cases db.add(f0) assert f0 in db.findings assert len(db.findings) == 1 db.add(f1) assert f1 in db.findings assert len(db.findings) == 2 db.add(f2) assert f2 in db.findings assert len(db.findings) == 3 db.add(None) assert len(db.findings) == 3 db.remove(f1) assert f1 not in db.findings assert len(db.findings) == 2 # test exceptions with pytest.raises(TypeError): db.add(1) def test_update(): """Test function.""" db = dblib.lib.BackyardDB() db.add(f0) db.add(f1) db.update(f1, f2) assert f2 in db.findings assert len(db.findings) == 2
StarcoderdataPython
85929
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 18}) def cut_by_item(dataframe, key, step): item_range = np.arange(0, dataframe[key].max(), step) grouped = dataframe.groupby(pd.cut(dataframe[key], item_range)) keys = [key for key, _ in grouped] dataframes = [group for _, group in grouped] return keys, dataframes def plot_delays_by_rules(dataframe): print 'Plotting by rules' bounds = [31000, 64000, 85000, 105000] #group_by_switches = dataframe.groupby(pd.cut(dataframe['network_size'], np.arange(0, 301, 100))) group_by_switches = dataframe.groupby(pd.cut(dataframe['network_size'], [0, 100, 200, 250, 300])) labels = [l for l, _ in group_by_switches] delays = [d for _, d in group_by_switches] #fig, axes = plt.subplots(2, 2)#, sharey=True) ax_indices = [(0, 0), (0, 1), (1, 0), (1, 1)] for label, delay, bound, idx in zip(labels, delays, bounds, ax_indices): rule_interval = 100 grouped_by_rules = delay.groupby(pd.cut( delay['graph_size'], np.arange(0, bound, rule_interval)) #np.arange(0, max(delay['graph_size']), rule_interval)) )['duration'] mean = grouped_by_rules.mean() #median = grouped_by_rules.median() lower = grouped_by_rules.quantile(0.05) upper = grouped_by_rules.quantile(0.95) #mean = mean.rolling(window=5, min_periods=1).mean() ##median = median.rolling(window=5, min_periods=1).mean() #lower = lower.rolling(window=5, min_periods=1).mean() #upper = upper.rolling(window=5, min_periods=1).mean() keys = [(k.left + k.right)/2.0 for k in mean.keys()] plt.figure(figsize=(8, 6)) plt.ylim(0, 450) plt.plot(keys, mean, 'green') plt.fill_between(keys, lower, upper, color='green', alpha='0.15') plt.xlabel(u'Количество правил')#('Rule number') plt.ylabel(u'Задержка, мс')#('Delay, ms') #plt.title('Delay by rule number') plt.grid() plt.tight_layout() plt.savefig(data_dir + '/plot/' + 'delay_by_rules_%i_%i.pdf' % (label.left, label.right), fmt='pdf') #plt.show() plt.gcf().clear() #ax = axes[idx[0]][idx[1]] #ax.plot(keys, mean, 'green') #ax.fill_between(keys, lower, upper, color='green', alpha='0.15') #ax.set_xlabel(u'Количество правил')#('Rule number') #ax.set_ylabel(u'Задержка, мс')#('Delay, ms') #ax.set_title(u'От %i до %i коммутаторов' % (label.left, label.right))#('Delay by rule number') #ax.grid() #fig.savefig(data_dir + '/plot/' + 'Delay by rule number', fmt='pdf') ##plt.show() #plt.gcf().clear() print 'Done' def plot_delays_by_switches(dataframe): print 'Plotting by switches' switch_interval = 10 switch_bound = 301 dataframe = dataframe.sort_values(['graph_size']) dataframe['duration'] = dataframe['duration'].rolling(window=3, min_periods=1).mean() grouped_by_switches = dataframe.groupby(pd.cut( dataframe['network_size'], np.arange(0, switch_bound, switch_interval)) )['duration'] mean = grouped_by_switches.mean() #median = grouped_by_switches.median() #std = grouped_by_switches.std() lower = grouped_by_switches.quantile(0.05) upper = grouped_by_switches.quantile(0.95) keys = [(k.left + k.right)/2.0 for k in mean.keys()] mean = pd.Series(mean).reset_index(drop=True) #median = pd.Series(median).reset_index(drop=True) #std = pd.Series(std).reset_index(drop=True) lower = pd.Series(lower).reset_index(drop=True) upper = pd.Series(upper).reset_index(drop=True) #mean = mean.rolling(window=5, min_periods=1).mean() ##median = median.rolling(window=5, min_periods=1).mean() #lower = lower.rolling(window=5, min_periods=1).mean() #upper = upper.rolling(window=5, min_periods=1).mean() #plt.boxplot(data) #plt.plot(keys, median, yerr=std, color='blue') #plt.plot(keys, mean, 'ro') plt.figure(figsize=(14, 6)) plt.errorbar(keys, mean, yerr=[lower, upper], color='blue', fmt='o', markersize=9, capsize=6, elinewidth=3, capthick=2) #plt.fill_between(keys, lower, upper, color='blue', alpha='0.15') plt.xlabel(u'Количество коммутаторов')#('Network size') plt.ylabel(u'Задержка, мс')#('Delay, ms') #plt.title('Delay by network size') plt.grid() plt.tight_layout() plt.savefig(data_dir + '/plot/' + 'delay_by_switches.pdf', fmt='pdf') #plt.show() plt.gcf().clear() # By mean table size #delays_table = delays print 'Done' def process_delays(delays): delays = delays[delays['network_size'] % 5 == 0] delays = delays[delays['network_size'] <= 305] plot_delays_by_rules(delays) plot_delays_by_switches(delays) def predictions_boxplot(dataframe, delay): #dataframe['packet_error'] = np.abs(dataframe['real_packets'] - dataframe['pred_packets']) #dataframe['byte_error'] = np.abs(dataframe['real_bytes'] - dataframe['pred_bytes']) #labels = list(reversed(['100 Kbps', '1 Mbps', '10 Mbps', '100 Mbps', '1 Gbps'])) labels = list(reversed([u'100 Кбит/с', u'1 Мбит/с', u'10 Мбит/с', u'100 Мбит/с', u'1 Гбит/с'])) bandwidths = reversed([int(b*1000000) for b in [0.1, 1, 10, 100, 1000]]) packet_data = [] byte_data = [] for bandwidth in bandwidths: packet_data.append(dataframe[dataframe['bandwidth'] == bandwidth]['packet_error']) byte_data.append(dataframe[dataframe['bandwidth'] == bandwidth]['byte_error']) adjust_left = 0.21 packet_xlabel = u'Ошибка предсказания (количество пакетов)'#'Packet error' byte_xlabel = u'Ошибка предсказания (количество байт)'#'Byte error' #b = plt.boxplot(packet_data, showfliers=False, vert=False) #print('Delay:', delay, '| Quantile:', [p.quantile(0.95) for p in packet_data]) #print 'Delay:', delay, '| Quantile:', [item.get_xdata() for item in b['whiskers']] #return None # DEBUG # Plot in normal scale plt.figure(figsize=(8, 6)) plt.boxplot(packet_data, showfliers=False, vert=False) plt.yticks([1, 2, 3, 4, 5], labels) plt.xlabel(packet_xlabel) plt.tight_layout() plt.gcf().subplots_adjust(left=adjust_left) plt.savefig(data_dir + '/plot/' + 'packet_error_%d.pdf' % delay, fmt='pdf') #plt.show() plt.gcf().clear() # Plot in logarithmic scale ax = plt.gca() ax.set_xscale('log') plt.boxplot(packet_data, showfliers=False, vert=False) plt.yticks([1, 2, 3, 4, 5], labels) plt.xlabel(packet_xlabel) plt.tight_layout() plt.gcf().subplots_adjust(left=adjust_left) plt.savefig(data_dir + '/plot/' + 'packet_error_%d_log.pdf' % delay, fmt='pdf') #plt.show() plt.gcf().clear() # Plot in normal scale plt.boxplot(byte_data, showfliers=False, vert=False) plt.yticks([1, 2, 3, 4, 5], labels) plt.xlabel(byte_xlabel) plt.tight_layout() plt.gcf().subplots_adjust(left=adjust_left) plt.savefig(data_dir + '/plot/' + 'byte_error_%d.pdf' % delay, fmt='pdf') #plt.show() plt.gcf().clear() # Plot in logarithmic scale ax = plt.gca() ax.set_xscale('log') plt.boxplot(byte_data, showfliers=False, vert=False) plt.yticks([1, 2, 3, 4, 5], labels) plt.xlabel(byte_xlabel) plt.tight_layout() plt.gcf().subplots_adjust(left=adjust_left) plt.savefig(data_dir + '/plot/' + 'byte_error_%d_log.pdf' % delay, fmt='pdf') #plt.show() plt.gcf().clear() def process_predictions(dataframe): dataframe = dataframe[dataframe['real_packets'] > 0] dataframe['packet_error'] = np.abs(dataframe['real_packets'] - dataframe['pred_packets']) dataframe['byte_error'] = np.abs(dataframe['real_bytes'] - dataframe['pred_bytes']) for delay in [0, 1, 33, 66, 333, 666, 2000]: predictions_boxplot(dataframe[dataframe['delay'] == delay], delay) def load(files): dataframe_list = [] for dataframe_file in files: df = pd.read_csv(dataframe_file, index_col=None, header=0) dataframe_list.append(df) return pd.concat(dataframe_list, ignore_index=True) if __name__ == '__main__': data_dir = './experiments' delay_files = [data_dir + '/delay.csv'] #delay_files = [data_dir + '/no_delay_prediction'] prediction_files = [data_dir + '/prediction.csv'] #print 'Loading delays' #delays = load(delay_files) #process_delays(delays) print 'Loading predictions' predictions = load(prediction_files) process_predictions(predictions)
StarcoderdataPython
4820254
"""RAK811 CLI interface. Provides a command line interface for the RAK811 module (Firmware V3.0). Copyright 2021 <NAME> 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. SPDX-License-Identifier: Apache-2.0 """ from json import dumps import logging import click from .rak811_v3 import Rak811 from .rak811_v3 import Rak811Error from .rak811_v3 import Rak811ResponseError, Rak811TimeoutError def print_exception(e): """Print exception raised by the Rak811 library.""" if isinstance(e, Rak811ResponseError): click.echo('RAK811 response error {}: {}'.format(e.errno, e.strerror)) elif isinstance(e, Rak811TimeoutError): click.echo('RAK811 timeout: {}'.format(e)) else: click.echo('RAK811 unexpected exception {}'.format(e)) @click.group() @click.option( '-v', '--verbose', is_flag=True, help='Verbose mode' ) @click.option( '-d', '--debug', is_flag=True, help='Debug mode' ) @click.version_option() @click.pass_context def cli(ctx, verbose, debug): """Command line interface for the RAK811 module.""" ctx.ensure_object(dict) ctx.obj['VERBOSE'] = verbose logging.basicConfig(level=logging.DEBUG if debug else logging.INFO) @cli.command(name='hard-reset') @click.pass_context def hard_reset(ctx): """Hardware reset of the module. Hard reset should not be required in normal operation. It needs to be issued once after host boot, or module restart. """ lora = Rak811() lora.hard_reset() if ctx.obj['VERBOSE']: click.echo('Hard reset complete') lora.close() """Get / set commands.""" @cli.command() @click.argument( 'config_item', required=True ) @click.pass_context def set_config(ctx, config_item): """Execute set_config RAK811 command. \b Config items are in the format <type>:<topic>[:<param>]... Supported types and topics: - device: restart, sleep, boot, status, uart, uart_mode, gpio - lora: region, channel, dev_eui, app_eui, app_key, dev_addr, apps_key, nwks_key, join_mode, work_mode, ch_mask, class, confirm, dr, tx_power, adr, send_interval - lorap2p: transfer_mode, channel configuration """ lora = Rak811() try: responses = lora.set_config(config_item) if ctx.obj['VERBOSE']: click.echo('Configuration done') for response in responses: if response.strip(): click.echo(response) except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.argument( 'config_item', required=True ) @click.pass_context def get_config(ctx, config_item): """Execute get_config RAK811 command. \b Config items are in the format <type>:<topic>[:<param>] Supported types and topics: - device: status, gpio, adc - lora: channel, status """ lora = Rak811() try: responses = lora.get_config(config_item) for response in responses: if response.strip(): click.echo(response) except Rak811Error as e: print_exception(e) lora.close() """General AT commands.""" @cli.command() @click.pass_context def version(ctx): """Get module version.""" lora = Rak811() click.echo(lora.version) lora.close() @cli.command() @click.pass_context def help(ctx): """Print module help.""" lora = Rak811() for response in lora.help: click.echo(response) lora.close() @cli.command() @click.pass_context def run(ctx): """Exit boot mode and enter normal mode.""" lora = Rak811() lora.run() lora.close() """ Interface commands.""" @cli.command() @click.option( '-i', '--index', default='3', type=click.Choice(['1', '3']), help='UART Index (1 or 3, default 3)' ) @click.option( '--binary', is_flag=True, help='Data is binary (hex encoded)' ) @click.argument( 'data', required=True ) @click.pass_context def send_uart(ctx, index, binary, data): """Send data to UART. UART1 is the AT Command interface, so you probably want to use UART3! """ if binary: try: data = bytes.fromhex(data) except ValueError: click.echo('Invalid binary data') return lora = Rak811() try: lora.send_uart(data, int(index)) except Rak811Error as e: print_exception(e) lora.close() return if ctx.obj['VERBOSE']: click.echo('Data sent.') """LoRaWan commands.""" @cli.command() @click.pass_context def join(ctx): """Join the configured network. \b ABP requires the following parameters to be set prior join: - dev_addr - nwks_key - apps_key OTAA requires the following parameters to be set prior join: - dev_eui - app_eui - app_key """ lora = Rak811() try: lora.join() if ctx.obj['VERBOSE']: click.echo('Joined!') except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.option( '-p', '--port', default=1, type=click.IntRange(1, 223), help='port number to use (1-223)' ) @click.option( '--binary', is_flag=True, help='Data is binary (hex encoded)' ) @click.argument( 'data', required=True ) @click.option( '--json', is_flag=True, help='Output downlink in JSON format' ) @click.pass_context def send(ctx, port, binary, data, json): """Send LoRaWan message and check for downlink.""" if binary: try: data = bytes.fromhex(data) except ValueError: click.echo('Invalid binary data') return lora = Rak811() try: lora.send(data, port=port) except Rak811Error as e: print_exception(e) lora.close() return if ctx.obj['VERBOSE']: click.echo('Message sent.') if lora.nb_downlinks: downlink = lora.get_downlink() if downlink['len']: downlink['data'] = downlink['data'].hex() if json: click.echo(dumps(downlink, indent=4)) elif ctx.obj['VERBOSE']: click.echo('Downlink received:') click.echo('Port: {}'.format(downlink['port'])) click.echo('RSSI: {}'.format(downlink['rssi'])) click.echo('SNR: {}'.format(downlink['snr'])) click.echo('Data: {}'.format(downlink['data'])) else: click.echo(downlink['data']) elif ctx.obj['VERBOSE']: click.echo('Send confirmed.') click.echo('RSSI: {}'.format(downlink['rssi'])) click.echo('SNR: {}'.format(downlink['snr'])) elif ctx.obj['VERBOSE']: click.echo('No downlink available.') lora.close() @cli.command() @click.option( '--binary', is_flag=True, help='Data is binary (hex encoded)' ) @click.argument( 'data', required=True ) @click.pass_context def send_p2p(ctx, binary, data): """Send LoRa P2P message.""" if binary: try: data = bytes.fromhex(data) except ValueError: click.echo('Invalid binary data') return lora = Rak811() try: lora.send_p2p(data) except Rak811Error as e: print_exception(e) lora.close() return if ctx.obj['VERBOSE']: click.echo('Message sent.') @cli.command() @click.argument( 'timeout', required=False, default=60, type=click.INT ) @click.option( '--json', is_flag=True, help='Output message in JSON format' ) @click.pass_context def receive_p2p(ctx, timeout, json): """Get LoraP2P message.""" lora = Rak811() lora.receive_p2p(timeout) if lora.nb_downlinks: rx = lora.get_downlink() rx['data'] = rx['data'].hex() if json: click.echo(dumps(rx, indent=4)) elif ctx.obj['VERBOSE']: click.echo('Message received:') click.echo('RSSI: {}'.format(rx['rssi'])) click.echo('SNR: {}'.format(rx['snr'])) click.echo('Data: {}'.format(rx['data'])) else: click.echo(rx['data']) elif ctx.obj['VERBOSE']: click.echo('No message available.') lora.close() if __name__ == '__main__': cli()
StarcoderdataPython
4818930
<reponame>malteos/explirefit from __future__ import division import codecs from os import listdir from os.path import isfile, join import pickle import numpy as np from helpers import data_helper ################################################################################################################################ def serialize(item, path): pickle.dump(item, open(path, "wb" )) def deserialize(path): return pickle.load(open(path, "rb" )) def load_file(filepath): return (codecs.open(filepath, 'r', encoding = 'utf8', errors = 'replace')).read() def load_lines(filepath): return [l.strip() for l in list(codecs.open(filepath, "r", encoding = 'utf8', errors = 'replace').readlines())] ################################################################################################################################ def store_embeddings(path, embeddings, language, print_progress = True): f = codecs.open(path,'w',encoding='utf8') vocab = embeddings.lang_vocabularies[language] embs = embeddings.lang_embeddings[language] cnt = 0 for word in vocab: cnt += 1 if print_progress and cnt % 1000 == 0: print("Storing embeddings " + str(cnt)) f.write(word + " ") for i in range(len(embs[vocab[word]])): f.write(str(embs[vocab[word]][i]) + " ") f.write("\n") f.close() def load_embeddings_dict_with_norms(filepath, limit = None, special_tokens = None, print_load_progress = False, min_one_letter = False, skip_first_line = False): norms = [] vocabulary = {} embeddings = [] cnt = 0 cnt_dict = 0 emb_size = -1 with codecs.open(filepath,'r',encoding='utf8', errors='replace') as f: for line in f: try: cnt += 1 if limit and cnt > limit: break if print_load_progress and (cnt % 1000 == 0): print("Loading embeddings: " + str(cnt)) if cnt > 1 or not skip_first_line: splt = line.split() word = splt[0] if word.startswith("en_"): word = word.replace("en_", "").strip() if min_one_letter and not any(c.isalpha() for c in word): continue vec = [np.float32(x) for x in splt[1:]] if emb_size < 0 and len(vec) > 10: emb_size = len(vec) if emb_size > 0 and len(vec) == emb_size: vocabulary[word] = cnt_dict cnt_dict += 1 norms.append(np.linalg.norm(vec, 2)) embeddings.append(vec) except(ValueError,IndexError,UnicodeEncodeError): print("Incorrect format line!") if special_tokens is not None: for st in special_tokens: vocabulary[st] = cnt_dict cnt_dict += 1 vec = np.array([0.1 * (special_tokens.index(st) + 1)] * emb_size) #np.random.uniform(-1.0, 1.0, size = [emb_size]) norms.append(np.linalg.norm(vec, 2)) embeddings.append(vec) return vocabulary, np.array(embeddings, dtype = np.float32), norms ############################################################################################################################ def load_whitespace_separated_data(filepath): lines = list(codecs.open(filepath,'r',encoding='utf8', errors='replace').readlines()) return [[x.strip() for x in l.strip().split()] for l in lines] def load_tab_separated_data(filepath): lines = list(codecs.open(filepath,'r',encoding='utf8', errors='replace').readlines()) return [[x.strip() for x in l.strip().split('\t')] for l in lines] def load_wn_concepts_dict(path): lines = list(codecs.open(path,'r',encoding='utf8', errors='replace').readlines()) lcols = {x[0] : ' '.join((x[1].split('_'))[2:-2]) for x in [l.strip().split() for l in lines]} return lcols def load_bless_dataset(path): lines = list(codecs.open(path,'r',encoding='utf8', errors='replace').readlines()) lcols = [(x[0].split('-')[0], x[3].split('-')[0], "1" if x[2] == "hyper" else "0") for x in [l.strip().split() for l in lines]] return lcols def write_list(path, list): f = codecs.open(path,'w',encoding='utf8') for l in list: f.write(l + "\n") f.close() def write_dictionary(path, dictionary): f = codecs.open(path,'w',encoding='utf8') for k in dictionary: f.write(str(k) + "\t" + str(dictionary[k]) + "\n") f.close() def load_translation_pairs(filepath): lines = list(codecs.open(filepath,'r',encoding='utf8', errors='replace').readlines()) dataset = []; for line in lines: spl = line.split(',') srcword = spl[0].strip() trgword = spl[1].strip(); if (" " not in srcword.strip()) and (" " not in trgword.strip()): dataset.append((srcword, trgword)); return dataset def write_list_tuples_separated(path, list, delimiter = '\t'): f = codecs.open(path,'w',encoding='utf8') for i in range(len(list)): for j in range(len(list[i])): if j == len(list[i]) - 1: f.write(str(list[i][j]) + '\n') else: f.write(str(list[i][j]) + delimiter) f.close() def store_wordnet_rels(dirpath, relname, pos, lang, instances): f = codecs.open(dirpath + "/" + lang + "_" + relname + "_" + pos + ".txt",'w',encoding='utf8') for i in instances: splt = i.split('::') f.write(splt[0].replace("_", " ") + "\t" + splt[1].replace("_", " ") + "\t" + str(instances[i]) + "\n") f.close() def load_csv_lines(path, delimiter = ',', indices = None): f = codecs.open(path,'r',encoding='utf8') lines = [l.strip().split(delimiter) for l in f.readlines()] if indices is None: return lines else: return [sublist(l, indices) for l in lines] def load_csv_lines_line_by_line(path, delimiter = ',', indices = None, limit = None): lines = [] f = codecs.open(path,'r',encoding='utf8') line = f.readline().strip() cnt = 1 while line is not None: lines.append(sublist(line, indices) if indices is not None else line.split(delimiter)) line = f.readline().strip() cnt += 1 if limit is not None and cnt > limit: break return lines def sublist(list, indices): sublist = [] for i in indices: sublist.append(list[i]) return sublist ######################################################## def load_sequence_labelling_data(path, delimiter = '\t', indices = None, line_start_skip = None): f = codecs.open(path,'r',encoding='utf8') lines = [[t.strip() for t in l.split(delimiter)] for l in f.readlines()] instances = [] instance = [] for i in range(len(lines)): if line_start_skip is not None and lines[i][0].startswith(line_start_skip): continue if len(lines[i]) == 1 and lines[i][0] == "": instances.append(instance) instance = [] else: if indices is None: instance.append(lines[i]) else: instance.append(sublist(lines[i], indices)) if len(instance) > 0: instances.append(instance) return instances def load_classification_data(path, delimiter_text_labels = '\t', delimiter_labels = '\t', line_start_skip = None): f = codecs.open(path,'r',encoding='utf8') lines = [[t.strip() for t in l.split(delimiter_text_labels)] for l in f.readlines()] instances = [] for i in range(len(lines)): if line_start_skip is not None and lines[i][0].startswith(line_start_skip): continue text = data_helper.clean_str(lines[i][0].strip()).split() if delimiter_text_labels == delimiter_labels: labels = lines[i][1:] else: labels = lines[i][1].strip().split(delimiter_labels) instances.append((text, labels)) return instances
StarcoderdataPython
184698
<gh_stars>1-10 /usr/lib/python2.7/encodings/cp1258.py
StarcoderdataPython
1697461
import os PACKAGEDIR = os.path.abspath(os.path.dirname(__file__)) from .correct import * from .planetsystem import * from .transitfit import * from .utils import *
StarcoderdataPython
1521
<filename>image_aug.py # coding=UTF-8 # This Python file uses the following encoding: utf-8 import cv2 import numpy as np import xml.etree.cElementTree as ET from random import sample #default args: default_args = {'noise_prob': 0.1, 'gasuss_mean': 0, 'gasuss_var': 0.001, 'rand_hug': 30, 'rand_saturation':30, 'rand_light': 30, 'rot_angle': 15, 'bordervalue': (127, 127, 127), 'zoom_out_value': 0.7, 'output_shape': (416, 416), 'take_value' : 5 } #添加黑色noise def sp_noise(image, box_loc=None, **kwargs): h, w = image.shape[0:2] noise = np.random.rand(h,w) out_img = image.copy() out_img[noise < kwargs['noise_prob']] = 0 if box_loc is None: return out_img else: return out_img, box_loc #高斯noise def gasuss_noise(image, box_loc=None, **kwargs): out_img = (image / 255.) - 0.5 noise = np.random.normal(kwargs['gasuss_mean'], kwargs['gasuss_var']** 0.5, image.shape) out_img = out_img + noise + 0.5 out_img[out_img < 0] = 0 out_img[out_img > 1] = 1 out_img = (out_img * 255).astype(np.uint8) if box_loc is None: return out_img else: return out_img, box_loc #調整彩度(彩度通道加上隨機-N~N之值) def mod_hue(image, box_loc=None, **kwargs): out_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV).astype(np.float32) out_img[:,:,0] += np.random.randint(-kwargs['rand_hug'], kwargs['rand_hug']) out_img = cv2.cvtColor(np.clip(out_img, 0, 180).astype(np.uint8), cv2.COLOR_HSV2BGR) if box_loc is None: return out_img else: return out_img, box_loc #調整飽和度(飽和度通道加上隨機-N~N之值) def mod_saturation(image, box_loc=None, **kwargs): out_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV).astype(np.float32) out_img[:,:,1] += np.random.randint(-kwargs['rand_saturation'], kwargs['rand_saturation']) out_img = cv2.cvtColor(np.clip(out_img, 0, 255).astype(np.uint8), cv2.COLOR_HSV2BGR) if box_loc is None: return out_img else: return out_img, box_loc #調整亮度(亮度通道加上隨機-N~N之值) def mod_light(image, box_loc=None, **kwargs): out_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV).astype(np.float32) out_img[:,:,2] += np.random.randint(-kwargs['rand_light'], kwargs['rand_light']) out_img = cv2.cvtColor(np.clip(out_img, 0, 255).astype(np.uint8), cv2.COLOR_HSV2BGR) if box_loc is None: return out_img else: return out_img, box_loc #水平翻轉 def horizontal_flip(image, box_loc=None, **kwargs): ''' Args: box_loc: bounding box location(x_min, y_min, x_max, y_max) ''' if box_loc is None: return cv2.flip(image, 1) else: w = image.shape[1] for i in box_loc: if i[2] == 0: break else: x_min, x_max = i[0], i[2] i[0] = w - x_max i[2] = w - x_min return cv2.flip(image, 1), box_loc #垂直翻轉 def vertical_flip(image, box_loc=None, **kwargs): ''' Args: box_loc: bounding box location(num box,(x_min, y_min, x_max, y_max, label)) ''' if box_loc is None: return cv2.flip(image, 0) else: h = image.shape[0] for i in box_loc: if i[3] == 0: break else: y_min, y_max = i[1], i[3] i[1] = h - y_max i[3] = h - y_min return cv2.flip(image, 0), box_loc #旋轉-n~n度 def rot_image(image, box_loc=None, **kwargs): ''' Args: box_loc: bounding box location(num box,(x_min, y_min, x_max, y_max, label)) rot: 要選轉的範圍 bordervalue: 空白處補的值 ''' h, w, _ = image.shape center = ( w // 2, h // 2) angle = np.random.randint(-kwargs['rot_angle'], kwargs['rot_angle']) M = cv2.getRotationMatrix2D(center, angle, 1) out_img = cv2.warpAffine(image, M, (w, h), borderValue = kwargs['bordervalue']) if box_loc is None: return out_img else: loc = box_loc[:,0:4].copy() loc = np.append(loc, loc[:, 0:1], axis=-1) loc = np.append(loc, loc[:, 3:4], axis=-1) loc = np.append(loc, loc[:, 2:3], axis=-1) loc = np.append(loc, loc[:, 1:2], axis=-1) loc = loc.reshape(-1, 4, 2) loc = loc - np.array(center) rot_loc = loc.dot(np.transpose(M[:,0:2])) rot_loc = rot_loc + np.array(center) rot_box = np.hstack([np.min(rot_loc, axis=-2), np.max(rot_loc, axis=-2), box_loc[:, 4:5]]) rot_box = np.floor(rot_box) rot_box[...,0:4] = np.clip(rot_box[...,0:4], [0,0,0,0], [w-1, h-1, w-1, h-1]) return out_img, rot_box #等比例縮放影像 def resize_img(image, box_loc=None, **kwargs): h, w, _ = image.shape max_edge = max(kwargs['output_shape'][0], kwargs['output_shape'][1]) scale = min( max_edge / h, max_edge / w) h = int(h * scale) w = int(w * scale) if box_loc is None: return cv2.resize(image, (w, h)) else: box_loc[:,0] = box_loc[:,0] * scale box_loc[:,1] = box_loc[:,1] * scale box_loc[:,2] = box_loc[:,2] * scale box_loc[:,3] = box_loc[:,3] * scale return cv2.resize(image, (w, h)), box_loc.astype(np.int32) #將樸片補至指定大小 def padding_img(image, box_loc=None, **kwargs): h, w, _ = image.shape dx = int((kwargs['output_shape'][1] - w) / 2) dy = int((kwargs['output_shape'][0] - h) / 2) out_img = np.ones((kwargs['output_shape'][0], kwargs['output_shape'][1], 3), np.uint8) * kwargs['bordervalue'][0] out_img[dy: dy + h, dx: dx + w] = cv2.resize(image, (w, h)) if box_loc is None: return out_img else: box_loc[:,0] = box_loc[:,0] + dx box_loc[:,1] = box_loc[:,1] + dy box_loc[:,2] = box_loc[:,2] + dx box_loc[:,3] = box_loc[:,3] + dy return out_img, box_loc.astype(np.int32) #隨機縮小 value~1倍 def random_zoom_out(image, box_loc=None, **kwargs): h, w, _ = image.shape scale = np.random.uniform(kwargs['zoom_out_value'], 1) h = int(h * scale) w = int(w * scale) dx = int((image.shape[1] - w) / 2) dy = int((image.shape[0] - h) / 2) out_img = np.ones(image.shape, np.uint8) * kwargs['bordervalue'][0] out_img[dy: dy + h, dx: dx + w] = cv2.resize(image, (w, h)) if box_loc is None: return out_img else: box_loc[:,0] = box_loc[:,0] * scale + dx box_loc[:,1] = box_loc[:,1] * scale + dy box_loc[:,2] = box_loc[:,2] * scale + dx box_loc[:,3] = box_loc[:,3] * scale + dy return out_img, box_loc.astype(np.int32) #load csv data def load_csv(xml_path, max_boxes=4): tree = ET.parse(xml_path) root = tree.getroot() #location list loc_list = np.zeros((0, 5)) box_count = 0 for obj in root.iter('object'): if box_count >= max_boxes: break ''' difficult = obj.find('difficult').text cls = obj.find('name').text if cls not in classes or int(difficult) == 1: continue cls_id = classes.index(cls) ''' loc = obj.find('bndbox') x_min = int(loc.find('xmin').text) y_min = int(loc.find('ymin').text) x_max = int(loc.find('xmax').text) y_max = int(loc.find('ymax').text) loc_list = np.vstack([loc_list, np.array([x_min, y_min, x_max, y_max, 0])]) box_count += 1 return loc_list.astype(np.float32) #draw rectangle def draw_rect(image, box_loc): for i in box_loc: cv2.rectangle(image, (int(i[0]), int(i[1])), (int(i[2]), int(i[3])), (0, 255, 0), 4) def print_args(**kwargs): for key, value in kwargs.items(): print('key name: {}\nvalue:{}\n'.format(key, value)) #隨機選擇0~N個 image augmentation方法 def rand_aug_image(image, box_loc=None, **kwargs): if box_loc is None: out_img = resize_img(image, **kwargs) else: out_img, box_loc = resize_img(image, box_loc, **kwargs) #total augmentation function func_list = [sp_noise, gasuss_noise, mod_hue, mod_saturation, mod_light, horizontal_flip, vertical_flip, rot_image, random_zoom_out] #rand take function take_func = sample(func_list, np.random.randint(kwargs['take_value'])) for func in take_func: if box_loc is None: out_img = func(out_img, **kwargs) else: out_img, box_loc = func(out_img, box_loc, **kwargs) if box_loc is None: out_img = padding_img(out_img, **kwargs) return out_img else: out_img, box_loc = padding_img(out_img, box_loc, **kwargs) return out_img, box_loc if __name__ == "__main__": img = cv2.imread('./00002.jpg') bbox = load_csv('./00002.xml') #黑點noise #aug_img = sp_noise(img, **default_args) #aug_img, bbox = sp_noise(img, bbox, **default_args) #gasuss_noise #aug_img = gasuss_noise(img, **default_args) #aug_img, bbox = gasuss_noise(img, bbox, **default_args) #調整Hue #aug_img = mod_hue(img, **default_args) #aug_img, bbox = mod_hue(img, bbox, **default_args) #調整saturation #aug_img = mod_saturation(img, **default_args) #aug_img, bbox = mod_saturation(img, bbox, **default_args) #調整light #aug_img = mod_light(img, **default_args) #aug_img, bbox = mod_light(img, bbox, **default_args) #水平翻轉 #aug_img = horizontal_flip(img, **default_args) #aug_img, bbox = horizontal_flip(img, bbox, **default_args) #垂直翻轉 #aug_img = vertical_flip(img, **default_args) #aug_img, bbox = vertical_flip(img, bbox, **default_args) #旋轉角度 #aug_img = rot_image(img, **default_args) #aug_img, bbox = rot_image(img, bbox, **default_args) #等比例resize至指定大小 #aug_img = resize_img(img, **default_args) #aug_img, bbox = resize_img(img, bbox, **default_args) #補形狀至指定大小 #aug_img = padding_img(aug_img, **default_args) #aug_img, bbox = padding_img(aug_img, bbox, **default_args) #隨機縮小 N~1倍 #aug_img = random_zoom_out(img, **default_args) #aug_img, bbox = random_zoom_out(img, bbox, **default_args) #隨機選擇augmentation方法 aug_img = rand_aug_image(img, **default_args) #aug_img, bbox = rand_aug_image(img, bbox, **default_args) print(bbox) draw_rect(aug_img, bbox) cv2.imshow('img', img) cv2.imshow('aug img', aug_img) cv2.waitKey(0) cv2.destroyAllWindows()
StarcoderdataPython
61181
import numpy as np from scipy.stats import chi2 from tqdm import tqdm as tqdm from ...common import ( Gaussian, GaussianDensity, HypothesisReduction, normalize_log_weights, ) from ...configs import SensorModelConfig from ...measurement_models import MeasurementModel from ...motion_models import MotionModel from .base_single_object_tracker import SingleObjectTracker class GaussSumTracker(SingleObjectTracker): def __init__( self, meas_model: MeasurementModel, sensor_model: SensorModelConfig, motion_model: MotionModel, M, merging_threshold, P_G, w_min, *args, **kwargs, ) -> None: self.meas_model = meas_model self.sensor_model = sensor_model self.motion_model = motion_model self.w_min = w_min self.P_G = P_G self.gating_size = chi2.ppf(P_G, df=self.meas_model.d) self.M = M self.merging_threshold = merging_threshold self.hypotheses_weight = None self.multi_hypotheses_bank = None super(GaussSumTracker).__init__() def estimate(self, initial_state: Gaussian, measurements, verbose=False): """Tracks a single object using Gauss sum filtering For each filter recursion iteration implemented next steps: 1) for each hypothesis, create missed detection hypothesis 2) for each hypothesis, perform ellipsoidal gating and only create object detection hypotheses for detections inside the gate 3) normalise hypotheses weights 4) prune hypotheses with small weights and then re-normalise the weights 5) hypothese merging 6) cap the number of the hypotheses and then re-normalise the weights 7) extract object state estimate using the most probably hypothesis estimation 8) for each hypothesis, perform prediction """ prev_state = initial_state estimations = [None for x in range(len(measurements))] self.hypotheses_weight = [np.log(1.0)] self.multi_hypotheses_bank = [initial_state] for timestep, measurements_in_scene in tqdm(enumerate(measurements)): estimations[timestep] = self.estimation_step( predicted_state=prev_state, current_measurements=np.array(measurements_in_scene), ) prev_state = GaussianDensity.predict(state=estimations[timestep], motion_model=self.motion_model) return tuple(estimations) def estimation_step(self, predicted_state: Gaussian, current_measurements: np.ndarray): new_hypotheses, new_weights = [], [] w_theta_factor = np.log(self.sensor_model.P_D / self.sensor_model.intensity_c) w_theta_0 = np.log(1 - self.sensor_model.P_D) # misdetection for _old_idx, (curr_weight, curr_hypothesis) in enumerate( zip(self.hypotheses_weight, self.multi_hypotheses_bank) ): # 1) for each hypothesis, create missed detection hypothesis new_hypotheses.append(curr_hypothesis) new_weights.append(w_theta_0 + curr_weight) # 2) for each hypothesis, perform ellipsoidal gating # and only create object detection hypotheses for detection # inside the gate z_ingate, _ = GaussianDensity.ellipsoidal_gating( curr_hypothesis, current_measurements, self.meas_model, self.gating_size, ) predicted_likelihood = GaussianDensity.predicted_likelihood(curr_hypothesis, z_ingate, self.meas_model) # for each measurement create detection hypotheses for idx, meausurement in z_ingate: new_hypotheses.append(GaussianDensity.update(curr_hypothesis, meausurement, self.meas_model)) new_weights.append(predicted_likelihood[idx] + w_theta_factor) self.hypotheses_weight.extend(new_weights) self.multi_hypotheses_bank.extend(new_hypotheses) assert len(self.hypotheses_weight) == len(self.multi_hypotheses_bank) # 3.normalise hypotheses weights self.hypotheses_weight, _ = normalize_log_weights(self.hypotheses_weight) # 4. Prune hypotheses with small weights and then re-normalise the weights self.hypotheses_weight, self.multi_hypotheses_bank = HypothesisReduction.prune( self.hypotheses_weight, self.multi_hypotheses_bank, threshold=self.w_min ) self.hypotheses_weight, _ = normalize_log_weights(self.hypotheses_weight) # 5. Hypotheses merging and normalize self.hypotheses_weight, self.multi_hypotheses_bank = HypothesisReduction.merge( self.hypotheses_weight, self.multi_hypotheses_bank, threshold=self.merging_threshold, ) self.hypotheses_weight, _ = normalize_log_weights(self.hypotheses_weight) # 6. Cap the number of the hypotheses and then re-normalise the weights self.hypotheses_weight, self.multi_hypotheses_bank = HypothesisReduction.cap( self.hypotheses_weight, self.multi_hypotheses_bank, top_k=self.M ) self.hypotheses_weight, _ = normalize_log_weights(self.hypotheses_weight) # 7. Get object state from the most probable hypothesis if self.multi_hypotheses_bank: current_step_state = self.multi_hypotheses_bank[np.argmax(self.hypotheses_weight)] estimation = current_step_state else: estimation = predicted_state # 8. For each hypotheses do prediction self.updated_states = [ GaussianDensity.predict(hypothesis, self.motion_model) for hypothesis in self.multi_hypotheses_bank ] self.multi_hypotheses_bank = self.updated_states return estimation @property def method(self): return "gauss sum filter"
StarcoderdataPython
1714263
<reponame>gaocegege/treadmill """Runs the Treadmill application runner. """ import logging import os import click from treadmill import appenv from treadmill import runtime as app_runtime from treadmill.appcfg import abort as app_abort _LOGGER = logging.getLogger(__name__) def init(): """Top level command handler.""" @click.command() @click.option('--approot', type=click.Path(exists=True), envvar='TREADMILL_APPROOT', required=True) @click.option('--runtime', default=app_runtime.DEFAULT_RUNTIME) @click.argument('container_dir', type=click.Path(exists=True)) def run(approot, runtime, container_dir): """Runs container given a container dir.""" # Make sure container_dir is a fully resolved path. container_dir = os.path.realpath(container_dir) _LOGGER.info('run %r %r', approot, container_dir) tm_env = appenv.AppEnvironment(approot) try: app_runtime.get_runtime(runtime, tm_env, container_dir).run() except Exception as exc: # pylint: disable=W0703 _LOGGER.exception('Failed to start, app will be aborted.') app_abort.flag_aborted(tm_env, container_dir, exc) return run
StarcoderdataPython
1690635
import networkx as nx import csv import pandas as pd import itertools import json import dedupe from itertools import combinations,product import sys import os import numpy as np from affinegap import normalizedAffineGapDistance import simplejson from tqdm import tqdm import tempfile from dedupe.clustering import cluster as dedupe_cluster import dm_file_checker def get_deduper_probs_and_threshold(deduper, unlabeled_data, blocked_data = None, recall_weight = 1): if blocked_data is None: pairs = deduper.pairs(unlabeled_data) else: pairs = itertools.chain.from_iterable(get_blocked_pairs(deduper, blocked_data)) probs = dedupe.core.scoreDuplicates(pairs, deduper.data_model, deduper.classifier, deduper.num_cores)['score'] # the memory mapped file location of the scored records temp_filename = probs.filename probs = probs.copy() probs.sort() probs = probs[::-1] # delete the memory mapped file so it won't clog the disk os.remove(temp_filename) expected_dupes = np.cumsum(probs) recall = expected_dupes / expected_dupes[-1] precision = expected_dupes / np.arange(1, len(expected_dupes) + 1) score = recall * precision / (recall + recall_weight ** 2 * precision) i = np.argmax(score) print('Maximum expected recall and precision') print('recall: {:.2f}%'.format(recall[i]*100)) print('precision: {:.2f}%'.format(precision[i]*100)) print('With threshold: {:.2f}%'.format(probs[i]*100)) return probs, probs[i] def get_linker_probs_and_threshold(linker, unlabeled_data_1, unlabeled_data_2, blocked_data = None, recall_weight = 1): if blocked_data is None: pairs = linker.pairs(unlabeled_data_1, unlabeled_data_2) else: pairs = itertools.chain.from_iterable(get_blocked_pairs(linker, blocked_data)) probs = dedupe.core.scoreDuplicates(pairs, linker.data_model, linker.classifier, linker.num_cores)['score'] # the memory mapped file location of the scored records temp_filename = probs.filename probs = probs.copy() probs.sort() probs = probs[::-1] # delete the memory mapped file so it won't clog the disk os.remove(temp_filename) expected_dupes = np.cumsum(probs) recall = expected_dupes / expected_dupes[-1] precision = expected_dupes / np.arange(1, len(expected_dupes) + 1) score = recall * precision / (recall + recall_weight ** 2 * precision) i = np.argmax(score) print('Maximum expected recall and precision') print('recall: {:.2f}%'.format(recall[i]*100)) print('precision: {:.2f}%'.format(precision[i]*100)) print('With threshold: {:.2f}%'.format(probs[i]*100)) return probs, probs[i] def get_model_weights(deduper_or_linker): fields = [field.name for field in deduper_or_linker.data_model._variables] model_weights = sorted(list(zip(fields, deduper_or_linker.classifier.weights)), key = lambda x: x[1], reverse = False) model_weights = pd.DataFrame(model_weights, columns = ["variable", "logistic_reg_weight"]) return model_weights def map_cluster_ids(deduper, unlabeled_data, threshold, hard_threshold = 0.0, blocked_data = None, canonicalize = True, numeric_fields = None, cluster_id_tag = None, mapped_records_filepath = None, cluster_canonical_filepath = None): # BADLY NEED TO REFACTOR THIS """ Function that maps record ids to cluster ids Parameters ---------- deduper : dedupe.Deduper A trained instance of dedupe. unlabeled_data : dict The dedupe formatted data dictionary. threshold : dedupe.Threshold The threshold used for clustering. hard_threshold: float Threshold for record pair scores that will be included in the clustering canonicalize : bool or list, default False Option that provides the canonical records as additional columns. Specifying a list of column names only canonicalizes those columns. numeric_fields: list of str, default None Specify which fields are numeric cluster_id_tag: str, default None Additional tag for distinguishing the cluster id of different datasets Returns ------- mapped_records A dataframe storing the mapping from cluster_id to record_id cluster_canonicals A dataframe storing the canonical representation per cluster_id """ assert (hard_threshold < 1) and (hard_threshold >= 0), "hard_threshold should less than 1 at at least 0.0" if mapped_records_filepath is not None: with open(mapped_records_filepath, "w", newline = "") as f: mapped_records_header = ["record id", "cluster id", "confidence score", "cluster type"] writer = csv.DictWriter(f, fieldnames = mapped_records_header, quoting = csv.QUOTE_ALL) writer.writeheader() if canonicalize: if cluster_canonical_filepath is not None: with open(cluster_canonical_filepath, "w", newline = "") as f: cluster_canonical_header = [field.field for field in deduper.data_model.primary_fields] cluster_canonical_header.append("cluster id") writer = csv.DictWriter(f, fieldnames = cluster_canonical_header, quoting = csv.QUOTE_ALL) writer.writeheader() else: assert cluster_canonical_filepath is None, "can't have canonicalize be False if cluster_canonical_filepath exists" # ## Clustering if blocked_data is None: pairs = deduper.pairs(unlabeled_data) else: pairs = itertools.chain.from_iterable(get_blocked_pairs(deduper, blocked_data)) pair_scores = deduper.score(pairs) pair_scores = pair_scores[pair_scores["score"] > hard_threshold] clustered_dupes = deduper.cluster(pair_scores, threshold) if numeric_fields is not None: assert isinstance(numeric_fields, list) mapped_records = [] cluster_canonicals = [] record_ids_in_clusters = [] # assign cluster ids to record ids i = 0 print("Mapping cluster ids...") for cluster in tqdm(clustered_dupes): i += 1 cluster_id = "cl-{}".format(i) if cluster_id_tag is not None: cluster_id = "{}-{}".format(cluster_id_tag, cluster_id) id_set, scores = cluster if canonicalize: cluster_data = [unlabeled_data[i] for i in id_set] canonical_rep = get_canonical_rep(cluster_data, numeric_fields = numeric_fields) canonical_rep["cluster id"] = cluster_id if cluster_canonical_filepath is not None: with open(cluster_canonical_filepath, "a") as f: writer = csv.DictWriter(f, fieldnames = cluster_canonical_header, quoting = csv.QUOTE_ALL) writer.writerow(canonical_rep) else: cluster_canonicals.append(canonical_rep) for record_id, score in zip(id_set, scores): record_dict = { "record id": record_id, "cluster id": cluster_id, "confidence score": score, "cluster type":'dup' } if mapped_records_filepath is not None: with open(mapped_records_filepath, "a", newline = "") as f: writer = csv.DictWriter(f, fieldnames = mapped_records_header, quoting = csv.QUOTE_ALL) writer.writerow(record_dict) else: mapped_records.append(record_dict) record_ids_in_clusters.append(record_id) record_ids_in_clusters = set(record_ids_in_clusters) solo_ids = list(set(unlabeled_data.keys()).difference(record_ids_in_clusters)) # assign solo ids to record ids print("Mapping solo record ids...") for record_id in tqdm(solo_ids): i += 1 cluster_id = "cl-{}".format(i) if cluster_id_tag is not None: cluster_id = "{}-{}".format(cluster_id_tag, cluster_id) record_dict = { "record id":record_id, "cluster id":cluster_id, "confidence score":None, "cluster type":'solo' } mapped_records.append(record_dict) if mapped_records_filepath is None: mapped_records = pd.DataFrame(mapped_records) else: with open(mapped_records_filepath, "a", newline = "") as f: writer = csv.DictWriter(f, fieldnames = mapped_records_header, quoting = csv.QUOTE_ALL) writer.writerows(mapped_records) mapped_records = None if cluster_canonical_filepath is None: cluster_canonicals = pd.DataFrame(cluster_canonicals) else: cluster_canonicals = None # delete temporary file generated for pair_scores try: mmap_file = pair_scores.filename del pair_scores os.remove(mmap_file) except AttributeError: pass if canonicalize: return mapped_records, cluster_canonicals else: return mapped_records def abs_distance(x,y): return np.abs(x-y) def get_canonical_rep(record_cluster, numeric_fields = None): """ Given a list of records within a duplicate cluster, constructs a canonical representation of the cluster by finding canonical values for each field """ canonical_rep = {} keys = record_cluster[0].keys() if numeric_fields is None: numeric_fields = [] for key in keys: key_values = [] # difference distance functions for numeric and non-numeric fields if key in numeric_fields: comparator = abs_distance else: comparator = normalizedAffineGapDistance for record in record_cluster: # assume non-empty values always better than empty value # for canonical record if record[key]: key_values.append(record[key]) if key_values: canonical_rep[key] = dedupe.canonical.getCentroid(key_values, comparator) else: canonical_rep[key] = '' return canonical_rep def get_linked_ids(linker, unlabeled_data_1, unlabeled_data_2, threshold, hard_threshold = 0.0, blocked_data = None, mapped_records_filepath = None, constraint = "one-to-one"): # BADLY NEED TO REFACTOR THIS """ constraint: What type of constraint to put on a join. 'one-to-one' Every record in data_1 can match at most one record from data_2 and every record from data_2 can match at most one record from data_1. This is good for when both data_1 and data_2 are from different sources and you are interested in matching across the sources. If, individually, data_1 or data_2 have many duplicates you will not get good matches. 'many-to-one' Every record in data_1 can match at most one record from data_2, but more than one record from data_1 can match to the same record in data_2. This is good for when data_2 is a lookup table and data_1 is messy, such as geocoding or matching against golden records. 'many-to-many' Every record in data_1 can match multiple records in data_2 and vice versa. This is like a SQL inner join. """ if mapped_records_filepath is not None: with open(mapped_records_filepath, "w", newline = "") as f: mapped_records_header = ["record id 1", "record id 2", "confidence score", "link type"] writer = csv.DictWriter(f, fieldnames = mapped_records_header, quoting = csv.QUOTE_ALL) writer.writeheader() ## link matching if blocked_data is None: pairs = linker.pairs(unlabeled_data_1, unlabeled_data_2) else: pairs = itertools.chain.from_iterable(get_blocked_pairs(linker, blocked_data)) pair_scores = linker.score(pairs) pair_scores = pair_scores[pair_scores["score"] > hard_threshold] assert constraint in {'one-to-one', 'many-to-one', 'many-to-many'}, ( '%s is an invalid constraint option. Valid options include ' 'one-to-one, many-to-one, or many-to-many' % constraint) if constraint == 'one-to-one': links = linker.one_to_one(pair_scores, threshold) elif constraint == 'many-to-one': links = linker.many_to_one(pair_scores, threshold) elif constraint == 'many-to-many': links = pair_scores[pair_scores['score'] > threshold] links = list(links) # delete temporary file generated for pair_scores try: mmap_file = pair_scores.filename del pair_scores os.remove(mmap_file) except AttributeError: pass mapped_records = [] ids_with_links_1 = [] ids_with_links_2 = [] print("Mapping linked pairs...") for record_pair in tqdm(links): record_ids, score = record_pair pair_dict = { "record id 1":record_ids[0], "record id 2":record_ids[1], "confidence score":score, "link type":"dup", } if mapped_records_filepath is not None: with open(mapped_records_filepath, "a", newline = "") as f: mapped_records_header = ["record id 1", "record id 2", "confidence score", "link type"] writer = csv.DictWriter(f, fieldnames = mapped_records_header, quoting = csv.QUOTE_ALL) writer.writerow(pair_dict) else: mapped_records.append(pair_dict) ids_with_links_1.append(record_ids[0]) ids_with_links_2.append(record_ids[1]) ids_with_links_1 = set(ids_with_links_1) ids_with_links_2 = set(ids_with_links_2) # include the records without found links ids_without_links_1 = list(set(unlabeled_data_1.keys()).difference(ids_with_links_1)) ids_without_links_2 = list(set(unlabeled_data_2.keys()).difference(ids_with_links_2)) print("Mapping unlinked records in dataset 1...") for record_id in tqdm(ids_without_links_1): pair_dict = { "record id 1":record_id, "record id 2":None, "confidence score":None, "link type":"solo", } mapped_records.append(pair_dict) print("Mapping unlinked records in dataset 2...") for record_id in tqdm(ids_without_links_2): pair_dict = { "record id 1":None, "record id 2":record_id, "confidence score":None, "link type":"solo", } mapped_records.append(pair_dict) if mapped_records_filepath is None: mapped_records = pd.DataFrame(mapped_records) else: with open(mapped_records_filepath, "a", newline = "") as f: mapped_records_header = ["record id 1", "record id 2", "confidence score", "link type"] writer = csv.DictWriter(f, fieldnames = mapped_records_header, quoting = csv.QUOTE_ALL) writer.writerows(mapped_records) mapped_records = None return mapped_records def get_uncertain_clusters(mapped_records_df, threshold = 0.9): cluster_means_df = mapped_records_df\ .groupby("cluster id")\ .mean()\ .sort_values(by = "confidence score", ascending = True) cluster_means_bool = (cluster_means_df["confidence score"] < threshold) print("There are {} clusters with mean confidence score lower than {:.1f}% threshold".format(cluster_means_bool.sum(), threshold*100)) uncertain_clusters_dict = cluster_means_df.loc[cluster_means_bool,:].to_dict()["confidence score"] return uncertain_clusters_dict def get_pairs_from_uncertain_clusters(mapped_records_df, labeled_id_pairs, threshold = 0.9): assert isinstance(labeled_id_pairs, list) uncertain_clusters = get_uncertain_clusters(mapped_records_df, threshold = threshold) n_uncertain_clusters = len(uncertain_clusters) nth_cluster = 0 for cluster_id, mean_conf_score in uncertain_clusters.items(): nth_cluster += 1 pairs_in_cluster = [] # get record ids in cluster ids_in_cluster = mapped_records_df.loc[mapped_records_df["cluster id"] == cluster_id,"record id"].values.tolist() # generating record pairs from cluster for id_1, id_2 in combinations(ids_in_cluster, 2): id_pair = tuple(sorted((id_1,id_2))) # if pair is not already tagged, grab data of records if id_pair not in labeled_id_pairs: pairs_in_cluster.append(id_pair) yield ids_in_cluster, pairs_in_cluster, nth_cluster, n_uncertain_clusters, mean_conf_score def find_ids_of_labeled_data(labeled_data, unlabeled_data): labeled_pair_ids = [] for label in labeled_data.keys(): assert label in ["distinct", "match"] print("Finding ids for {} pairs".format(label)) data_pairs_list = labeled_data[label] for data_pair in tqdm(data_pairs_list): try: # for backwards compatibility record_1, record_2 = data_pair["__value__"] except: record_1, record_2 = data_pair record_1_id = [key for key,val in unlabeled_data.items() if unlabeled_data[key] == record_1] record_2_id = [key for key,val in unlabeled_data.items() if unlabeled_data[key] == record_2] if len(record_1_id) > 1: print("Multiple record ids ({}) found for {}".format(len(record_1_id),record_1)) record_1_id = record_1_id[0] if len(record_2_id) > 1: print("Multiple record ids ({}) found for {}".format(len(record_2_id),record_2)) record_2_id = record_2_id[0] labeled_pair = {"record id 1":record_1_id, "record id 2":record_2_id, "label":label} labeled_pair_ids.append(labeled_pair) labeled_pair_ids = pd.DataFrame(labeled_pair_ids, dtype = "str") return labeled_pair_ids def find_ids_of_labeled_data_rl(labeled_data, unlabeled_data_1, unlabeled_data_2): labeled_pair_ids = [] for label in labeled_data.keys(): assert label in ["distinct", "match"] print("Finding ids for {} pairs".format(label)) data_pairs_list = labeled_data[label] for data_pair in tqdm(data_pairs_list): record_1, record_2 = data_pair record_1_id = [key for key,val in unlabeled_data_1.items() if unlabeled_data_1[key] == record_1] record_2_id = [key for key,val in unlabeled_data_2.items() if unlabeled_data_2[key] == record_2] if len(record_1_id) > 1: print("Multiple record ids ({}) found for {}".format(len(record_1_id),record_1)) record_1_id = record_1_id[0] if len(record_2_id) > 1: print("Multiple record ids ({}) found for {}".format(len(record_2_id),record_2)) record_2_id = record_2_id[0] labeled_pair = {"record id 1":record_1_id, "record id 2":record_2_id, "label":label} labeled_pair_ids.append(labeled_pair) labeled_pair_ids = pd.DataFrame(labeled_pair_ids, dtype = "str") return labeled_pair_ids def consoleLabel_cluster_old(deduper, mapped_records_df, labeled_id_pairs, unlabeled_data, threshold = 0.9): ''' Command line interface for presenting and labeling uncertain clusters by the user Argument : A deduper object ''' finished = False fields = [field.field for field in deduper.data_model.primary_fields] assert len(fields) == len(list(set(fields))) labeled_pairs = {"distinct":[], "match":[]} uncertain_pair_generator = get_pairs_from_uncertain_clusters(mapped_records_df, labeled_id_pairs, threshold = threshold) while not finished: try: ids_in_cluster, pairs_in_cluster, nth_cluster, n_uncertain_clusters, mean_conf_score = next(uncertain_pair_generator) records_in_cluster = {i:unlabeled_data[i] for i in ids_in_cluster} except StopIteration: print("Already tagged all {} uncertain clusters.".format(n_uncertain_clusters)) print("Finished labeling") break print("Viewing {} out of {} uncertain clusters".format(nth_cluster, n_uncertain_clusters), file = sys.stderr) print("Cluster contains {} records".format(len(ids_in_cluster))) print("Mean Cluster Score {:.1f}%\n".format(mean_conf_score*100), file = sys.stderr) for record_id, record in records_in_cluster.items(): print("Record {}".format(record_id), file=sys.stderr) for field in fields: line = "{} : {}".format(field, record[field]) print(line, file=sys.stderr) print(file=sys.stderr) user_input = _prompt_records_same() if user_input == "y": for id_1, id_2 in pairs_in_cluster: record_pair = (unlabeled_data[id_1], unlabeled_data[id_2]) labeled_pairs["match"].append(record_pair) elif user_input == "n": print("Reviewing pairs in cluster", file=sys.stderr) for id_1, id_2 in pairs_in_cluster: record_pair = (unlabeled_data[id_1], unlabeled_data[id_2]) for record in record_pair: for field in fields: line = "{} : {}".format(field, record[field]) print(line, file=sys.stderr) print(file=sys.stderr) user_input = _prompt_records_same() if user_input == "y": labeled_pairs["match"].append(record_pair) elif user_input == "n": labeled_pairs["distinct"].append(record_pair) elif user_input == "f": print("Finished labeling", file=sys.stderr) finished = True break elif user_input == "f": print("Finished labeling", file=sys.stderr) finished = True deduper.markPairs(labeled_pairs) def consoleLabel_cluster(deduper, mapped_records_df, labeled_id_pairs, unlabeled_data, recall = 1.0, threshold = 0.9): ''' Command line interface for presenting and labeling uncertain clusters by the user Argument : A deduper object ''' finished = False fields = [field.field for field in deduper.data_model.primary_fields] assert len(fields) == len(list(set(fields))) labeled_pairs = {"distinct":[], "match":[]} uncertain_pair_generator = get_pairs_from_uncertain_clusters(mapped_records_df, labeled_id_pairs, threshold = threshold) while not finished: try: ids_in_cluster, pairs_in_cluster, nth_cluster, n_uncertain_clusters, mean_conf_score = next(uncertain_pair_generator) records_in_cluster = {i:unlabeled_data[i] for i in ids_in_cluster} except StopIteration: print("Already tagged all {} uncertain clusters.".format(n_uncertain_clusters)) print("Finished labeling") break print("Viewing {} out of {} uncertain clusters".format(nth_cluster, n_uncertain_clusters), file = sys.stderr) print("Cluster contains {} records".format(len(ids_in_cluster)), file = sys.stderr) print("Mean Cluster Score {:.1f}%\n".format(mean_conf_score*100), file = sys.stderr) for record_id, record in records_in_cluster.items(): print("Record {}".format(record_id), file=sys.stderr) for field in fields: line = "{} : {}".format(field, record[field]) print(line, file=sys.stderr) print(file=sys.stderr) user_input = _prompt_records_same() if user_input == "y": for id_1, id_2 in pairs_in_cluster: record_pair = (unlabeled_data[id_1], unlabeled_data[id_2]) labeled_pairs["match"].append(record_pair) labeled_id_pairs.append((id_1, id_2)) elif user_input == "n": print("Reviewing pairs in cluster", file=sys.stderr) for id_1, id_2 in pairs_in_cluster: record_pair = (unlabeled_data[id_1], unlabeled_data[id_2]) for record in record_pair: for field in fields: line = "{} : {}".format(field, record[field]) print(line, file=sys.stderr) print(file=sys.stderr) pair_user_input = _prompt_records_same() if pair_user_input == "y": labeled_pairs["match"].append(record_pair) labeled_id_pairs.append((id_1,id_2)) elif pair_user_input == "n": labeled_pairs["distinct"].append(record_pair) labeled_id_pairs.append((id_1,id_2)) elif pair_user_input == "f": print("Finished labeling", file=sys.stderr) finished = True break elif user_input == "f": print("Finished labeling", file=sys.stderr) finished = True if (user_input == "y") or (user_input == "n"): deduper.markPairs(labeled_pairs) deduper.train(recall = recall) clustering_threshold = deduper.threshold(unlabeled_data, recall_weight=1) mapped_records_df = map_cluster_ids(deduper, unlabeled_data, clustering_threshold, canonicalize=False) print("Resampling uncertain clusters based on retrained model", file=sys.stderr) labeled_pairs = {"distinct":[], "match":[]} uncertain_pair_generator = get_pairs_from_uncertain_clusters(mapped_records_df, labeled_id_pairs, threshold = threshold) def _prompt_records_same(): print("Do these records refer to the same thing?", file = sys.stderr) valid_response = False user_input = "" valid_responses = {"y", "n", "u", "f"} while not valid_response: prompt = "(y)es / (n)o / (u)nsure / (f)inished" print(prompt, file=sys.stderr) user_input = input() if user_input in valid_responses: valid_response = True return user_input def get_clusters_from_links(links, solo_records): assert isinstance(links, pd.Index) assert isinstance(solo_records, pd.Index) clusters = nx.Graph(links.tolist()) clusters = list(nx.connected_components(clusters)) clusters.extend(solo_records.tolist()) return clusters def get_deduper_candidate_pairs(deduper, unlabeled_data): # gets candidate pairs after indexing candidate_records = deduper.pairs(unlabeled_data) candidate_records = [(candidate[0][0], candidate[1][0]) for candidate in candidate_records] candidate_records = pd.MultiIndex.from_tuples(candidate_records) # some candidate records can be placed in more than 1 block, so let's drop duplicates candidate_records = candidate_records.drop_duplicates() return candidate_records def get_linker_candidate_pairs(linker, unlabeled_data_1, unlabeled_data_2): # gets candidate pairs after indexing candidate_records = linker.pairs(unlabeled_data_1, unlabeled_data_2) candidate_records = [(candidate[0][0], candidate[1][0]) for candidate in candidate_records] candidate_records = pd.MultiIndex.from_tuples(candidate_records) # some candidate records can be placed in more than 1 block, so let's drop duplicates candidate_records = candidate_records.drop_duplicates() return candidate_records # converts multindex to format preferred by dedupe method def convert_rl_to_dedupe_candidate_pair(candidate_pairs, unlabeled_data): assert isinstance(candidate_pairs, pd.Index) output = [] for rec_id_1, rec_id_2 in candidate_pairs: # dedupe candidate pairs must be in the format (record_id, record) candidate_1 = (rec_id_1, unlabeled_data[rec_id_1]) candidate_2 = (rec_id_2, unlabeled_data[rec_id_2]) candidate_pair = (candidate_1, candidate_2) output.append(candidate_pair) return output # converts multiindex to format preferred by linker method def convert_rl_to_linker_candidate_pair(candidate_pairs, unlabeled_data_1, unlabeled_data_2): assert isinstance(candidate_pairs, pd.Index) output = [] for rec_id_1, rec_id_2 in candidate_pairs: if rec_id_1 in unlabeled_data_1.keys(): rec_data_1 = unlabeled_data_1[rec_id_1] rec_data_2 = unlabeled_data_2[rec_id_2] assert rec_id_1 not in unlabeled_data_2.keys(), "{} key found in both datasets. Keys must be unique".format(rec_id_1) assert rec_id_2 not in unlabeled_data_1.keys(), "{} key found in both datasets. Keys must be unique".format(rec_id_2) else: rec_data_1 = unlabeled_data_2[rec_id_1] rec_data_2 = unlabeled_data_1[rec_id_2] assert rec_id_2 not in unlabeled_data_2.keys(), "{} found in both datasets. Keys must be unique".format(rec_id_2) # record linker candidate pairs must be in the format (record_id, record) candidate_1 = (rec_id_1, rec_data_1) candidate_2 = (rec_id_2, rec_data_2) candidate_pair = (candidate_1, candidate_2) output.append(candidate_pair) return output def read_unlabeled_data_json(unlabeled_data_filepath, empty_str_to_none = True, numeric_fields = None): with open(unlabeled_data_filepath, "r") as json_file: unlabeled_data = json.load(json_file) unlabeled_data = pd.DataFrame.from_dict(unlabeled_data, orient = "index") if numeric_fields is not None: assert isinstance(numeric_fields, list) for col in numeric_fields: unlabeled_data[col] = unlabeled_data[col].apply(lambda x: x if x == "" else float(x)) if empty_str_to_none: for col in unlabeled_data.columns.tolist(): empty_str_bool = (unlabeled_data[col] == "") print("converting {} empty string values of column {} to None".format(empty_str_bool.sum(), col)) unlabeled_data.loc[empty_str_bool,col] = None # converting NaNs of numeric columns (NaNs introduced because of the previous line) to None if numeric_fields is not None: for col in numeric_fields: not_nan_bool = unlabeled_data[col].notnull() print("converting {} NaN values of column {} to None".format((~not_nan_bool).sum(), col)) unlabeled_data[col] = unlabeled_data[col].where((not_nan_bool), None) unlabeled_data = unlabeled_data.to_dict(orient = "index") return unlabeled_data def write_canonical_w_solo_unlabeled_data(canonicals_df, mapped_records_df, unlabeled_data, canonical_w_solo_unlabeled_filepath): # will be used for post cluster review, specifically on matching solos to clusters and merging clusters # those two steps are based on the cluster canonicals # remember to read in this written file using read_unlabeled_data_json later on canonical_w_solo_data = canonicals_df.set_index("cluster id")\ .to_dict(orient = "index") mapped_records_df = mapped_records_df.set_index("record id") solo_records = mapped_records_df.loc[mapped_records_df["cluster type"] == "solo",:]\ .index.tolist() for record_id in solo_records: record = unlabeled_data[record_id] cluster_id = mapped_records_df.loc[record_id,"cluster id"] canonical_w_solo_data[cluster_id] = record with open(canonical_w_solo_unlabeled_filepath, 'w') as outfile: json.dump(canonical_w_solo_data, outfile) def prepare_training_deduper(deduper, unlabeled_data, labeled_data_filepath, blocked_proportion = 0.5, sample_size = 15_000): # If we have training data saved from a previous run of dedupe, # look for it and load it in. # __Note:__ if you want to train from scratch, delete the labeled_data_filepath if os.path.exists(labeled_data_filepath): print('reading labeled examples from ', labeled_data_filepath) with open(labeled_data_filepath, 'rb') as labeled_data: deduper.prepare_training(data = unlabeled_data, training_file = labeled_data, blocked_proportion = blocked_proportion, sample_size = sample_size) else: deduper.prepare_training(data = unlabeled_data, blocked_proportion = blocked_proportion, sample_size = sample_size) def save_trained_deduper(deduper, labeled_data_filepath, settings_filepath): # When finished, save our training to disk with open(labeled_data_filepath, 'w') as tf: deduper.write_training(tf) # Save our weights and predicates to disk. If the settings file # exists, we will skip all the training and learning next time we run # this file. with open(settings_filepath, 'wb') as sf: deduper.write_settings(sf) def prepare_training_linker(linker, unlabeled_data_1, unlabeled_data_2, labeled_data_filepath, blocked_proportion = 0.5, sample_size = 15_000): # If we have training data saved from a previous run of linker, # look for it and load it in. # __Note:__ if you want to train from scratch, delete the labeled_data_filepath if os.path.exists(labeled_data_filepath): print('reading labeled examples from ', labeled_data_filepath) with open(labeled_data_filepath, 'rb') as labeled_data: linker.prepare_training(data_1 = unlabeled_data_1, data_2 = unlabeled_data_2, training_file = labeled_data, blocked_proportion = blocked_proportion, sample_size = sample_size) else: linker.prepare_training(data_1 = unlabeled_data_1, data_2 = unlabeled_data_2, blocked_proportion = blocked_proportion, sample_size = sample_size) def save_trained_linker(linker, labeled_data_filepath, settings_filepath): # When finished, save our training to disk with open(labeled_data_filepath, 'w') as tf: linker.write_training(tf) # Save our weights and predicates to disk. If the settings file # exists, we will skip all the training and learning next time we run # this file. with open(settings_filepath, 'wb') as sf: linker.write_settings(sf) def get_data_of_labeled_pairs(labeled_pairs_df, unlabeled_data): df = pd.DataFrame.from_dict(unlabeled_data, orient = "index") df_left = df.loc[labeled_pairs_df["record id 1"],:] df_left.columns = ["{}_1".format(col) for col in df_left.columns] df_left.index.name = "record id 1" df_left = df_left.reset_index() df_right = df.loc[labeled_pairs_df["record id 2"],:] df_right.columns = ["{}_2".format(col) for col in df_right.columns] df_right.index.name = "record id 2" df_right = df_right.reset_index() output = pd.concat([df_left, df_right], axis = 1, sort = False) # sort columns output = output.sort_index(axis = 1) output = output.set_index(["record id 1", "record id 2"]) label_df = labeled_pairs_df.set_index(["record id 1", "record id 2"]) output = pd.merge(left = label_df, right = output, left_index = True, right_index = True, how = "inner") return output def get_deduped_data(mapped_records_df, canonicals_df, unlabeled_data, none_to_empty_str = True): mapped_records_df = mapped_records_df.set_index("record id") solo_record_ids = mapped_records_df.loc[mapped_records_df["cluster type"] == "solo","cluster id"].to_dict() deduped_data = {cluster_id:unlabeled_data[record_id] for record_id,cluster_id in solo_record_ids.items()} deduped_data = pd.DataFrame.from_dict(deduped_data, orient = "index") deduped_data.index.name = "cluster id" canonicals_df = canonicals_df.set_index("cluster id") # appending the canonicalized cluster representations to the solo records deduped_data = deduped_data.append(canonicals_df) if none_to_empty_str: deduped_data = deduped_data.where((deduped_data.notnull()), "") return deduped_data def write_deduper_blocks(deduper, unlabeled_data, blocks_filepath): """ simplify blocks by not writing the record entries, only the ids """ blocks = deduper.pairs(unlabeled_data) with open(blocks_filepath, "w", newline = "") as csv_file: writer = csv.writer(csv_file, quoting = csv.QUOTE_ALL) header = ["block_id", "record_id"] writer.writerow(header) block_id = 1 for block in blocks: """ from dedupe source code: Each item in a block must be a sequence of record_id, record and the records also must be dictionaries but we're only keeping the record_id, not the record here """ for record in block: record_id, _, = record block_entry = [block_id, record_id] writer.writerow(block_entry) block_id += 1 def read_deduper_blocks(unlabeled_data, blocks_filepath): # assumes that the records are sorted by block number current_block_id = None block_records = [] """ from dedupe source code: Each item in a block must be a sequence of record_id, record, and the records also must be dictionaries """ with open(blocks_filepath, "r") as csv_file: reader = csv.DictReader(csv_file) for row in reader: block_id, record_id = row["block_id"], row["record_id"] if current_block_id == block_id: block_records.append((record_id, unlabeled_data[record_id])) else: if current_block_id is not None: yield block_records current_block_id = block_id block_records = [(record_id, unlabeled_data[record_id])] yield block_records def write_linker_blocks(linker, unlabeled_data_1, unlabeled_data_2, blocks_filepath): """ simplify blocks by not writing the record entries, only the ids """ blocks = linker.pairs(unlabeled_data_1, unlabeled_data_2) block_id = 1 with open(blocks_filepath, "w", newline = "") as csv_file: writer = csv.writer(csv_file, quoting = csv.QUOTE_ALL) header = ["record_set_num", "block_id", "record_id"] writer.writerow(header) for block in blocks: rec_1, rec_2 = block rec_1_id, _ = rec_1 block_entry = ["1", block_id, rec_1_id] writer.writerow(block_entry) rec_2_id, _ = rec_2 block_entry = ["2", block_id, rec_2_id] writer.writerow(block_entry) block_id += 1 def read_linker_blocks(unlabeled_data_1, unlabeled_data_2, blocks_filepath): # assumes that the records sorted by block number block_records = () block_set_1 = [] block_set_2 = [] current_block_id = None """ from dedupe source code: Each block must be a made up of two sequences, (base_sequence, target_sequence) """ with open(blocks_filepath, "r") as csv_file: reader = csv.DictReader(csv_file) for row in reader: record_set_num, block_id, record_id = row["record_set_num"], row["block_id"], row["record_id"] if current_block_id == block_id: if record_set_num == "1": block_set_1.append((record_id, unlabeled_data_1[record_id])) elif record_set_num == "2": block_set_2.append((record_id, unlabeled_data_2[record_id])) else: raise ValueError("record_set_num should only be 1 or 2, but got {}".format(record_set_num)) else: if current_block_id is not None: block_records = (block_set_1, block_set_2) yield block_records current_block_id = block_id if record_set_num == "1": block_set_1 = [(record_id, unlabeled_data_1[record_id])] block_set_2 = [] elif record_set_num == "2": block_set_1 = [] block_set_2 = [(record_id, unlabeled_data_2[record_id])] else: raise ValueError("record_set_num should only be 1 or 2, but got {}".format(record_set_num)) block_records = (block_set_1, block_set_2) yield block_records def get_blocked_pairs(deduper_or_linker, blocked_data): if isinstance(deduper_or_linker, dedupe.api.DedupeMatching): pairs = (combinations(sorted(block), 2) for block in blocked_data) elif isinstance(deduper_or_linker, dedupe.api.RecordLinkMatching): pairs = (product(base, target) for base, target in blocked_data) else: raise ValueError("Passed not of class DedupeMatching or of RecordLinkMatching!") return pairs def count_blocked_pairs(deduper_or_linker, blocked_data): candidate_records = itertools.chain.from_iterable(get_blocked_pairs(deduper_or_linker, blocked_data)) i = 0 for _ in candidate_records: i += 1 return i def write_training_set_from_pairs(labeled_pair_ids_df, labeled_data_filepath, unlabeled_data, unlabeled_data_2 = None): # create a labeled training set directly for dedupe's consumption labeled_data_train = {"distinct":[], "match":[]} for _, row in labeled_pair_ids_df.iterrows(): rec_id_1 = row["record id 1"] rec_id_2 = row["record id 2"] rec_data_1 = unlabeled_data[rec_id_1] if unlabeled_data_2 is None: rec_data_2 = unlabeled_data[rec_id_2] else: rec_data_2 = unlabeled_data_2[rec_id_2] label = row["label"] data_entry = { "__class__":"tuple", "__value__":[rec_data_1, rec_data_2] } labeled_data_train[label].append(data_entry) with open(labeled_data_filepath, "w") as json_file: simplejson.dump(labeled_data_train, json_file, default=dedupe.serializer._to_json, tuple_as_array=False, ensure_ascii=True) def get_deduped_data_for_rl(task_name, saved_files_path): # gets deduped dataset from respective deduping for rl dataset_name = task_name.split("-")[1] dataset_1_name, dataset_2_name = dataset_name.split("_") dedup_task_1 = "dedup-{}".format(dataset_1_name) dedup_task_2 = "dedup-{}".format(dataset_2_name) # get all filepaths unlabeled_data_1_filepath, unlabeled_data_2_filepath = dm_file_checker.get_proper_unlabeled_data_filepath(task_name, saved_files_path) numeric_fields_1, numeric_fields_2 = dm_file_checker.get_dataset_info(task_name, "numeric_fields", saved_files_path) print("Numeric fields 1 are {}".format(numeric_fields_1)) print("Numeric fields 2 are {}".format(numeric_fields_2)) canonicals_1_filepath = dm_file_checker.get_filepath(dedup_task_1, "cluster_canonical", saved_files_path) canonicals_2_filepath = dm_file_checker.get_filepath(dedup_task_2, "cluster_canonical", saved_files_path) mapped_records_1_filepath = dm_file_checker.get_filepath(dedup_task_1, "mapped_records", saved_files_path) mapped_records_2_filepath = dm_file_checker.get_filepath(dedup_task_2, "mapped_records", saved_files_path) # read in data from filepaths unlabeled_data_1 = read_unlabeled_data_json(unlabeled_data_1_filepath, empty_str_to_none = False, numeric_fields = numeric_fields_1) unlabeled_data_2 = read_unlabeled_data_json(unlabeled_data_2_filepath, empty_str_to_none = False, numeric_fields = numeric_fields_2) canonicals_1_df = pd.read_csv(canonicals_1_filepath, keep_default_na = False, low_memory = False) canonicals_2_df = pd.read_csv(canonicals_2_filepath, keep_default_na = False, low_memory = False) mapped_records_1_df = pd.read_csv(mapped_records_1_filepath, keep_default_na = False) mapped_records_2_df = pd.read_csv(mapped_records_2_filepath, keep_default_na = False) # get deduped data in dictionary form deduped_data_1 = get_deduped_data(mapped_records_1_df, canonicals_1_df, unlabeled_data_1, none_to_empty_str = False) deduped_data_2 = get_deduped_data(mapped_records_2_df, canonicals_2_df, unlabeled_data_2, none_to_empty_str = False) if numeric_fields_1 is not None: for col in numeric_fields_1: deduped_data_1[col] = deduped_data_1[col].apply(lambda x: x if x == "" else float(x)) if numeric_fields_2 is not None: for col in numeric_fields_2: deduped_data_2[col] = deduped_data_2[col].apply(lambda x: x if x == "" else float(x)) for col in deduped_data_1.columns: empty_str_bool = (deduped_data_1[col] == "") print("in deduped data 1, converting {} empty string values of column {} to None".format(empty_str_bool.sum(), col)) deduped_data_1.loc[empty_str_bool,col] = None for col in deduped_data_2.columns: empty_str_bool = (deduped_data_2[col] == "") print("in deduped data 2, converting {} empty string values of column {} to None".format(empty_str_bool.sum(), col)) deduped_data_2.loc[empty_str_bool,col] = None # converting NaNs of numeric columns (NaNs introduced because of the previous line) to None if numeric_fields_1 is not None: for col in numeric_fields_1: not_nan_bool = deduped_data_1[col].notnull() print("in deduped data 1, converting {} NaN values of {} to None".format((~not_nan_bool).sum(), col)) deduped_data_1[col] = deduped_data_1[col].where((not_nan_bool), None) if numeric_fields_2 is not None: for col in numeric_fields_2: not_nan_bool = deduped_data_2[col].notnull() print("in deduped data 2, converting {} NaN values of {} to None".format((~not_nan_bool).sum(), col)) deduped_data_2[col] = deduped_data_2[col].where((not_nan_bool), None) deduped_data_1 = deduped_data_1.to_dict(orient = "index") deduped_data_2 = deduped_data_2.to_dict(orient = "index") return deduped_data_1, deduped_data_2 # function to make sure the all record ids are prepended with the name of the dataset def verify_rec_id_format(record_id, data_name): if pd.isnull(record_id): is_ok = True else: is_ok = (record_id.split("-")[0] == data_name) return is_ok # function to return all results from all record linkage results def get_all_rl_results(rl_task_names, saved_files_path): dupe_records = pd.DataFrame(columns = ["record id 1", "record id 2", "confidence score"]) all_records = set() # iterate over each rl mapped file for rl_task in rl_task_names: data_name_1, data_name_2 = rl_task.split("-")[1].split("_") mapped_records_filepath = dm_file_checker.get_filepath(rl_task, "mapped_records", saved_files_path) print("Getting mapped record links from {}".format(rl_task)) mapped_records_df = pd.read_csv(mapped_records_filepath) # make sure all record ids are prepended with the name of the dataset ok_records_1 = mapped_records_df["record id 1"].apply(lambda x: verify_rec_id_format(x, data_name_1)).all() ok_records_2 = mapped_records_df["record id 2"].apply(lambda x: verify_rec_id_format(x, data_name_2)).all() assert (ok_records_1 and ok_records_2), "Record ids aren't prepended with the dataset name!" append_dupe_records = mapped_records_df.loc[mapped_records_df["link type"] == "dup",\ ["record id 1", "record id 2","confidence score"]] dupe_records = dupe_records.append(append_dupe_records, ignore_index = True) append_all_records = mapped_records_df.loc[:,["record id 1","record id 2"]] append_all_records = append_all_records["record id 1"].dropna().unique().tolist() \ + append_all_records["record id 2"].dropna().unique().tolist() append_all_records = set(append_all_records) all_records.update(append_all_records) all_records = list(all_records) pairs = dupe_records.loc[:,["record id 1", "record id 2"]]\ .apply(lambda row: (row["record id 1"], row["record id 2"]), axis = 1)\ .tolist() n_pairs = len(pairs) id_type = (str, 265) pairs = np.array(pairs, dtype = id_type) scores = dupe_records.loc[:,["confidence score"]].to_numpy(dtype = float).reshape(-1) dtype = np.dtype([("pairs", id_type, 2), ("score", "f4", 1)]) temp_file, file_path = tempfile.mkstemp() os.close(temp_file) scored_pairs = np.memmap(file_path, shape = n_pairs, dtype = dtype) scored_pairs["pairs"] = pairs scored_pairs["score"] = scores return scored_pairs, all_records def get_fusion_probs_and_threshold(scored_pairs, recall_weight = 1): probs = scored_pairs['score'] probs = probs.copy() probs.sort() probs = probs[::-1] expected_dupes = np.cumsum(probs) recall = expected_dupes / expected_dupes[-1] precision = expected_dupes / np.arange(1, len(expected_dupes) + 1) score = recall * precision / (recall + recall_weight ** 2 * precision) i = np.argmax(score) print('Maximum expected recall and precision') print('recall: {:.2f}%'.format(recall[i]*100)) print('precision: {:.2f}%'.format(precision[i]*100)) print('With threshold: {:.2f}%'.format(probs[i]*100)) return probs, probs[i] def map_cluster_fusion_ids(scored_pairs, all_records, threshold): clustered_dupes = dedupe_cluster(scored_pairs, threshold) mapped_records = [] record_ids_in_clusters = [] # assign cluster ids to record ids i = 0 print("Mapping cluster ids...") for cluster in tqdm(clustered_dupes): i += 1 cluster_id = "fs-{}".format(i) id_set, scores = cluster for record_id, score in zip(id_set, scores): record_dict = { "record id": record_id, "cluster id": cluster_id, "confidence score": score, "cluster type":'link' } mapped_records.append(record_dict) record_ids_in_clusters.append(record_id) record_ids_in_clusters = set(record_ids_in_clusters) solo_ids = [key for key in all_records if key not in record_ids_in_clusters] # assign solo ids to record ids print("Mapping solo record ids...") for record_id in tqdm(solo_ids): i += 1 cluster_id = "fs-{}".format(i) record_dict = { "record id":record_id, "cluster id":cluster_id, "confidence score":None, "cluster type":'solo' } mapped_records.append(record_dict) mapped_records = pd.DataFrame(mapped_records) return mapped_records def get_all_dedup_results(rl_task_names, saved_files_path, remove_data_name_prefix = True): all_dedup_mapped_records = pd.DataFrame() dedup_datasets = set() for rl_task in rl_task_names: data_name_1, data_name_2 = rl_task.split("-")[1].split("_") for data_name in [data_name_1, data_name_2]: dedup_task = "dedup-{}".format(data_name) mapped_records_filepath = dm_file_checker.get_filepath(dedup_task, "mapped_records", saved_files_path) # replace IDs only of datasets that have undergone deduplication if os.path.exists(mapped_records_filepath) & (data_name not in dedup_datasets): dedup_datasets.add(data_name) dedup_mapped_records = pd.read_csv(mapped_records_filepath) dedup_mapped_records = dedup_mapped_records.rename(columns = {"confidence score":"dedup confidence score", "cluster type":"dedup cluster type"}) if remove_data_name_prefix: dedup_mapped_records["record id"] = dedup_mapped_records["record id"]\ .apply(lambda x: x.replace("{}-".format(data_name), "")) all_dedup_mapped_records = all_dedup_mapped_records.append(dedup_mapped_records, ignore_index = True) return all_dedup_mapped_records def check_block_sizes(blocks): block_sizes = [] for block in blocks: block_size = len(block) block_sizes.append(block_size) block_sizes = sorted(block_sizes, reverse = True) print("Sizes of top 10 biggest blocks are: {}".format(block_sizes[:10])) record_pair_contributions = [int(size*(size-1)/2) for size in block_sizes[:10]] print("Record pair contributions from top 10 biggest blocks are : {}".format(record_pair_contributions))
StarcoderdataPython
1745746
<gh_stars>1-10 # ipop-project # Copyright 2016, University of Florida # # 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 datetime import hashlib import threading try: import simplejson as json except ImportError: import json import urllib.request as urllib2 from controller.framework.ControllerModule import ControllerModule class UsageReport(ControllerModule): def __init__(self, cfx_handle, module_config, module_name): super(UsageReport, self).__init__(cfx_handle, module_config, module_name) self._stat_data = {"ready": False, "pending_request": False} self.submit_time = datetime.datetime(2015, 1, 1, 0, 0) self.lck = threading.Lock() def initialize(self): self.register_cbt("Logger", "LOG_INFO", "{0} Loaded".format(self._module_name)) def process_cbt(self, cbt): if cbt.op_type == "Response": if cbt.request.action == "SIG_QUERY_REPORTING_DATA": if not cbt.response.status: self.register_cbt("Logger", "LOG_WARNING", "CBT failed {0}".format(cbt.response.data)) self.free_cbt(cbt) else: self.create_report(cbt) else: parent_cbt = cbt.parent cbt_data = cbt.response.data cbt_status = cbt.response.status self.free_cbt(cbt) if (parent_cbt is not None and parent_cbt.child_count == 1): parent_cbt.set_response(cbt_data, cbt_status) self.complete_cbt(parent_cbt) else: self.req_handler_default(cbt) def timer_method(self): cur_time = datetime.datetime.now() self.lck.acquire() if self._stat_data["ready"]: data = self._stat_data["data"] self._stat_data = {} self._stat_data["ready"] = False self._stat_data["pending_request"] = False self.lck.release() self.submit_report(data) self.submit_time = datetime.datetime.now() elif not self._stat_data["pending_request"] and cur_time > self.submit_time: self._stat_data["pending_request"] = True self.lck.release() self.request_report() def terminate(self): pass def request_report(self): self.register_cbt("Signal", "SIG_QUERY_REPORTING_DATA") def create_report(self, cbt): nid = self._cm_config["NodeId"] report_data = cbt.response.data for overlay_id in report_data: report_data[overlay_id] = { "xmpp_host": hashlib.sha1(report_data[overlay_id]["xmpp_host"].\ encode("utf-8")).hexdigest(), "xmpp_username": hashlib.sha1(report_data[overlay_id]["xmpp_username"].\ encode("utf-8")).hexdigest(), } stat = { "NodeId": hashlib.sha1(nid.encode("utf-8")).hexdigest(), "Time": str(datetime.datetime.now()), "Model": self._cfx_handle.query_param("Model"), "Version": self._cfx_handle.query_param("IpopVersion") } stat.update(report_data) self.lck.acquire() self._stat_data["data"] = stat self._stat_data["ready"] = True self._stat_data["pending_request"] = False self.lck.release() self.free_cbt(cbt) def submit_report(self, report_data): data = json.dumps(report_data).encode('utf8') self.register_cbt("Logger", "LOG_DEBUG", "Usage report data: {0}".format(data)) url = None try: url = "http://" + self._cm_config["ServerAddress"] + ":" + \ str(self._cm_config["ServerPort"]) + "/api/submit" req = urllib2.Request(url=url, data=data) req.add_header("Content-Type", "application/json") res = urllib2.urlopen(req) if res.getcode() == 200: log = "Usage report successfully submitted to server {0}\n" \ "HTTP response code:{1}, msg:{2}" \ .format(url, res.getcode(), res.read()) self.register_cbt("Logger", "LOG_INFO", log) else: self.register_cbt("Logger", "LOG_WARNING", "Usage report server indicated error " "code: {0}".format(res.getcode())) except (urllib2.HTTPError, urllib2.URLError) as error: log = "Usage report submission failed to server {0}. " \ "Error: {1}".format(url, error) self.register_cbt("Logger", "LOG_WARNING", log)
StarcoderdataPython
1694138
<filename>utility/nginx_current_port_by_domain.py import re import sys configLocation = sys.argv[1] domain = sys.argv[2] def currentPort(): with open(configLocation) as nginxConf: for line in nginxConf.readlines(): if ("proxy_pass" in line) and (domain in line): match = re.search(':(\d+);', line) return match.group(1) return "unknown" if __name__ == "__main__": print(currentPort())
StarcoderdataPython
73034
<filename>wiki/admin.py<gh_stars>1-10 from django.contrib import admin from .models import WikiPage admin.site.register(WikiPage)
StarcoderdataPython
1613258
import time from lib import tasks import tests.test_recommender as rec def test_add(): res = tasks.add.delay(1, 2) success = False val = res.get(timeout=5) rec.test_race_filter() assert val == 3 if __name__ == "__main__": test_add()
StarcoderdataPython
1627073
<filename>newscollector/real_time_manager.py<gh_stars>0 # coding=utf-8 from time import sleep from threading import Thread from .newscollector_worker import search_index from .db_functions import add_source_if_missed def read_configs(fname): configs = __import__(fname) return configs.sources def index_check_runner(config): """ Поток для периодической проверки главной страницы новостного сайта """ delay = config.get('refresh_delay') url = config.get('url') while True: # Запуска задачи просмотра главной страницы, и после ее завершения запуск задачи загрузки найденных ссылок print('Launch index task for {}'.format(url)) # следующую очередь запускать с высочайшим приоритетом search_index.apply_async(args=(config,), priority=255) sleep(delay) def real_time_manager(): configs = read_configs('sources_config') for config in configs: # todo сделать на каждый источник по очереди celery и по воркеру enabled = config.get('enabled') if not enabled: continue # проверка списка источников и добавление отсутствующих add_source_if_missed(config) # Запуск потока для постоянной проверки Thread(target=index_check_runner, args=(config, )).start() if __name__ == '__main__': real_time_manager()
StarcoderdataPython
3247140
<filename>LunchBot/message.py __author__ = 'Simon' import email class Attachment(object): def __init__(self,msg_part): open(msg_part.get_filename(), 'wb').write(msg_part.get_payload(decode=True)) self.data = open(msg_part.get_filename(),'r').read() self.data_type = msg_part.get_content_type() self.file_name = msg_part.get_filename() def __str__(self): return self.data class Body(object): def __init__(self,msg_part): self.body = msg_part.get_payload(decode=True) def __str__(self): return self.body def parse_attachment(msg_part): content_disposition = msg_part.get("Content-Disposition", None) if content_disposition: # dispositions = content_disposition.strip().split(";") if bool(content_disposition and dispositions[0].lower() == "attachment"): attachment = Attachment(msg_part) return attachment return None def parse_body(msg_part): body = msg_part.get_payload(decode=True) return body def parse_mail(mail): attachments = [] body = None for part in mail.walk(): attachment = parse_attachment(part) if attachment: attachments.append(attachment) elif part.get_content_type == 'text/plain': if not body: body = Body(part) if len(attachments) != 0: return attachments return body
StarcoderdataPython
3277532
from .request_method_routing import RequestMethodRouting from .create import Create from .update import Update from .delete import Delete from .read import Read class CRUDByMethod(RequestMethodRouting): def __init__(self, di): super().__init__(di) def method_handler_map(self): return { 'CREATE': Create, 'GET': Read, 'POST': Read, 'PATCH': Update, 'DELETE': Delete, }
StarcoderdataPython
1656672
<filename>tests/diffcalc/test_utils.py ### # Copyright 2008-2011 Diamond Light Source Ltd. # This file is part of Diffcalc. # # Diffcalc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Diffcalc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Diffcalc. If not, see <http://www.gnu.org/licenses/>. ### from diffcalc.hkl.geometry import Position from tests.tools import degrees_equivalent class TestUtils: def testDegreesEqual(self): tol = 0.001 assert degrees_equivalent(1, 1, tol) assert degrees_equivalent(1, -359, tol) assert degrees_equivalent(359, -1, tol) assert not degrees_equivalent(1.1, 1, tol) assert not degrees_equivalent(1.1, -359, tol) assert not degrees_equivalent(359.1, -1, tol) class TestPosition: def testCompare(self): # Test the compare method pos1 = Position(1, 2, 3, 4, 5, 6) pos2 = Position(1.1, 2.1, 3.1, 4.1, 5.1, 6.1) assert pos1 == pos1 assert pos1 != pos2
StarcoderdataPython
3347839
<filename>web/datasets/tests/management/commands/test_cityhall.py from datetime import datetime import pytest from django.utils.timezone import make_aware from web.datasets.management.commands._cityhall import save_bid @pytest.mark.django_db class TestSaveBid: def test_save_bid(self, mock_backup_file): item = { "crawled_at": make_aware(datetime(2020, 3, 21, 7, 15, 17, 908831)), "crawled_from": "http://www.feiradesantana.ba.gov.br/servicos.asp", "session_at": make_aware(datetime(2018, 4, 17, 8, 30, 0)), "public_agency": "PMFS", "month": 4, "year": 2018, "description": ( "Aquisi\u00e7\u00e3o de arma de fogo longa para a " "Guarda Municipal de Feira de Santana.OBS: EDITAL DISPON\u00cdVEL" "NO SITE: WWW.BLLCOMPRAS.ORG.BR" ), "history": [], "codes": ( "Licita\u00e7\u00e3o 133-2018 / " "Preg\u00e3o Eletr\u00f4nico 047-2018" ), "modality": "pregao_eletronico", "files": [ { "url": "http://www.feiradesantana.ba.gov.br/servicos.asp?id=2", "checksum": "checksum", "content": None, } ], } bid = save_bid(item) assert bid.session_at == item["session_at"] assert bid.description == item["description"] assert bid.public_agency == item["public_agency"] assert bid.modality == item["modality"] assert bid.files def test_save_history(self, mock_backup_file): item = { "public_agency": "PMFS", "crawled_at": make_aware(datetime(2020, 4, 4, 14, 29, 49, 261985)), "crawled_from": "http://www.feiradesantana.ba.gov.br/servicos.asp", "session_at": make_aware(datetime(2019, 4, 5, 8, 30)), "description": ( "Contratação de empresa para prestação de serviços " "profissionais de apoio administrativo em Unidades de Saúde da " "Secretaria Municipal de Saúde.Edital disponível no site do " "Banco do Brasil: www.licitacoes-e.com.br.Código " "Correspondente Banco do Brasil: nº 755980REMARCADA" ), "codes": ( "Licita\u00e7\u00e3o 133-2018 / " "Preg\u00e3o Eletr\u00f4nico 047-2018" ), "modality": "pregao_eletronico", "history": [ { "published_at": make_aware(datetime(2018, 4, 17, 8, 30, 0)), "event": "Resposta a pedido de esclarecimento", "url": "http://www.feiradesantana.ba.gov.br/SMS.pdf", } ], } bid = save_bid(item) assert bid.events.count() == 1 event = bid.events.first() assert event.published_at is not None assert event.summary == item["history"][0]["event"] assert event.files.count() == 1 def test_handle_with_existent_event(self, mock_backup_file): item = { "public_agency": "PMFS", "crawled_at": make_aware(datetime(2020, 4, 4, 14, 29, 49, 261985)), "crawled_from": "http://www.feiradesantana.ba.gov.br/servicos.asp", "session_at": make_aware(datetime(2019, 4, 5, 8, 30)), "description": ( "Contratação de empresa para prestação de serviços " "profissionais de apoio administrativo em Unidades de Saúde da " "Secretaria Municipal de Saúde.Edital disponível no site do " "Banco do Brasil: www.licitacoes-e.com.br.Código " "Correspondente Banco do Brasil: nº 755980REMARCADA" ), "codes": ( "Licita\u00e7\u00e3o 133-2018 / " "Preg\u00e3o Eletr\u00f4nico 047-2018" ), "modality": "pregao_eletronico", "history": [ { "published_at": make_aware(datetime(2019, 4, 4, 16, 20, 0)), "event": "Resposta a pedido de esclarecimento", "url": "http://www.feiradesantana.ba.gov.br/SMS.pdf", } ], } bid = save_bid(item) assert bid.events.count() == 1 item["history"] = [ { "published_at": make_aware(datetime(2019, 4, 4, 16, 20, 0)), "event": "Resposta a pedido de esclarecimento", "url": "http://www.feiradesantana.ba.gov.br/SMS.pdf", }, { "published_at": make_aware(datetime(2019, 4, 4, 18, 20, 0)), "event": "Resposta a pedido de esclarecimento", "url": "http://www.feiradesantana.ba.gov.br/SMS.pdf", }, { "published_at": make_aware(datetime(2019, 4, 4, 16, 20, 0)), "event": "CORREÇÃO DE EDITAL", "url": "http://www.feiradesantana.ba.gov.br/SMS.pdf", }, ] save_bid(item) assert bid.events.count() == 3 def test_handle_with_updated_bid(self, mock_backup_file): item = { "crawled_at": make_aware(datetime(2020, 3, 21, 7, 15, 17, 908831)), "crawled_from": "http://www.feiradesantana.ba.gov.br/servicos.asp", "session_at": make_aware(datetime(2018, 4, 17, 8, 30, 0)), "public_agency": "PMFS", "month": 4, "year": 2018, "description": ( "Aquisi\u00e7\u00e3o de arma de fogo longa para a " "Guarda Municipal de Feira de Santana.OBS: EDITAL DISPON\u00cdVEL" "NO SITE: WWW.BLLCOMPRAS.ORG.BR" ), "history": [], "codes": ( "Licita\u00e7\u00e3o 133-2018 / " "Preg\u00e3o Eletr\u00f4nico 047-2018" ), "modality": "pregao_eletronico", "files": [ { "url": "http://www.feiradesantana.ba.gov.br/servicos.asp?id=2", "checksum": "checksum", "content": None, } ], } bid = save_bid(item) item["description"] = "Aquisição de arma de flores." updated_bid = save_bid(item) assert bid.pk == updated_bid.pk assert bid.description != updated_bid.description def test_create_different_bids_for_different_agency_modality( self, mock_backup_file ): item = { "crawled_at": make_aware(datetime(2020, 3, 21, 7, 15, 17, 908831)), "crawled_from": "http://www.feiradesantana.ba.gov.br/servicos.asp", "session_at": make_aware(datetime(2018, 4, 17, 8, 30, 0)), "public_agency": "PMFS", "month": 4, "year": 2018, "description": ( "Aquisi\u00e7\u00e3o de arma de fogo longa para a " "Guarda Municipal de Feira de Santana.OBS: EDITAL DISPON\u00cdVEL" "NO SITE: WWW.BLLCOMPRAS.ORG.BR" ), "history": [], "codes": ( "Licita\u00e7\u00e3o 133-2018 / " "Preg\u00e3o Eletr\u00f4nico 047-2018" ), "modality": "pregao_eletronico", "files": [ { "url": "http://www.feiradesantana.ba.gov.br/servicos.asp?id=2", "checksum": "checksum", "content": None, } ], } bid = save_bid(item) item["public_agency"] = "FHFS" item["codes"] = "CHAMADA PÚBLICA 004-2019" another_bid = save_bid(item) assert bid.pk != another_bid.pk
StarcoderdataPython
1796748
import colt def test_version() -> None: assert colt.__version__ == "0.7.3"
StarcoderdataPython
1710056
<reponame>An00bRektn/CTF #!/usr/bin/python3 from pwn import * from hashlib import sha256 BLOCK_SIZE = 32 def decrypt_block(block, secret): dec_block = b'' for i in range(BLOCK_SIZE): val = (block[i]-secret[i]) % 256 dec_block += bytes([val]) return dec_block r = remote('172.16.17.32',30855) message = b'Command executed: cat secret.txt' r.sendlineafter('>', 'cat secret.txt') ct = r.recvlineS().strip() blocks = [ct[i:i+64] for i in range(0, len(ct), 64)] ref = bytes.fromhex(blocks[0]) init_key = b'' p = log.progress('brute forcing initial key...') for i in range(BLOCK_SIZE): for guess in range(256): val = (message[i]+guess) % 256 p.status(f'val: {val}\nref: {ref[i]}\nrec: {init_key}') if val == ref[i]: init_key += bytes([guess]) info(f'init_key: {init_key.hex()}') h = init_key plaintext = b'' for block in blocks: block = bytes.fromhex(block) dec_block = decrypt_block(block, h) h = sha256(block + dec_block).digest() plaintext += dec_block success(plaintext.decode('utf-8'))
StarcoderdataPython
8217
<filename>09_multiprocessing/prime_validation/primes_factor_test.py<gh_stars>0 import math import time def check_prime(n): if n % 2 == 0: return False, 2 for i in range(3, int(math.sqrt(n)) + 1): if n % i == 0: return False, i return True, None if __name__ == "__main__": primes = [] t1 = time.time() # 100109100129100151 big prime # http://primes.utm.edu/curios/page.php/100109100129100151.html # number_range = xrange(100109100129100153, 100109100129101238, 2) number_range = range(100109100129101237, 100109100129201238, 2) # new expensive near-primes # [(95362951, (100109100129100369, 7.254560947418213)) # (171656941, (100109100129101027, 13.052711009979248)) # (121344023, (100109100129101291, 8.994053840637207) # note these two lines of timings look really wrong, they're about 4sec # each really # [(265687139, (100109100129102047, 19.642582178115845)), (219609683, (100109100129102277, 16.178056001663208)), (121344023, (100109100129101291, 8.994053840637207))] # [(316096873, (100109100129126653, 23.480671882629395)), (313994287, (100109100129111617, 23.262380123138428)), (307151363, (100109100129140177, 22.80288815498352))] # primes # 100109100129162907 # 100109100129162947 highest_factors = {} for possible_prime in number_range: t2 = time.time() is_prime, factor = check_prime(possible_prime) if is_prime: primes.append(possible_prime) print("GOT NEW PRIME", possible_prime) else: highest_factors[factor] = (possible_prime, time.time() - t2) hf = highest_factors.items() hf = sorted(hf, reverse=True) print(hf[:3]) print("Took:", time.time() - t1) print(len(primes), primes[:10], primes[-10:])
StarcoderdataPython
1641186
"""Contains all schedules spreadsheet settings commands related to Tosurnament.""" from discord.ext import commands from bot.modules.tosurnament import module as tosurnament from common.api import spreadsheet class TosurnamentSchedulesSpreadsheetCog(tosurnament.TosurnamentBaseModule, name="schedules_spreadsheet"): """Tosurnament schedules spreadsheet settings commands.""" def __init__(self, bot): super().__init__(bot) self.bot = bot def cog_check(self, ctx): """Check function called before any command of the cog.""" return self.admin_cog_check(ctx) @commands.command(aliases=["sss"]) async def set_schedules_spreadsheet(self, ctx, spreadsheet_id: str, *, sheet_name: str = ""): """Sets the schedules spreadsheet.""" tournament = self.get_tournament(ctx.guild.id) bracket = tournament.current_bracket spreadsheet_id = bracket.update_spreadsheet_of_type(self.bot, "schedules", spreadsheet_id, sheet_name) await self.send_reply(ctx, "success", spreadsheet_id) async def set_schedules_spreadsheet_values(self, ctx, values): """Puts the input values into the corresponding bracket.""" tournament = self.get_tournament(ctx.guild.id) any_spreadsheet = tournament.current_bracket.get_spreadsheet_from_type("schedules") if not any_spreadsheet: raise tosurnament.NoSpreadsheet("schedules") await self.update_table(ctx, any_spreadsheet, values) async def set_schedules_spreadsheet_range_value(self, ctx, range_name, range_value): """Puts the input values into the corresponding bracket.""" if not spreadsheet.check_range(range_value): raise commands.UserInputError() await self.set_schedules_spreadsheet_values(ctx, {range_name: range_value}) @commands.command(aliases=["ssssn"]) async def set_schedules_spreadsheet_sheet_name(self, ctx, *, sheet_name: str = ""): """Sets the sheet name of the schedules spreadsheet.""" await self.set_schedules_spreadsheet_values(ctx, {"sheet_name": sheet_name}) @commands.command(aliases=["sssdf"]) async def set_schedules_spreadsheet_date_format(self, ctx, *, date_format: str = ""): """Sets the date format used in the date range of the schedules spreadsheet.""" await self.set_schedules_spreadsheet_values(ctx, {"date_format": date_format}) @commands.command(aliases=["ssssir"]) async def set_schedules_spreadsheet_staff_is_range(self, ctx, use_range: bool): """Sets the staff_is_range of the schedules spreadsheet.""" await self.set_schedules_spreadsheet_values(ctx, {"use_range": use_range}) @commands.command(aliases=["sssrmi"]) async def set_schedules_spreadsheet_range_match_id(self, ctx, *, cell_range: str): """Sets the schedules spreadsheet range match id.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_match_id", cell_range) @commands.command(aliases=["sssrt1"]) async def set_schedules_spreadsheet_range_team1(self, ctx, *, cell_range: str): """Sets the schedules spreadsheet range team1.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_team1", cell_range) @commands.command(aliases=["sssrt2"]) async def set_schedules_spreadsheet_range_team2(self, ctx, *, cell_range: str): """Sets the schedules spreadsheet range team2.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_team2", cell_range) @commands.command(aliases=["sssrst1"]) async def set_schedules_spreadsheet_range_score_team1(self, ctx, *, cell_range: str = ""): """Sets the schedules spreadsheet range score team1.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_score_team1", cell_range) @commands.command(aliases=["sssrst2"]) async def set_schedules_spreadsheet_range_score_team2(self, ctx, *, cell_range: str = ""): """Sets the schedules spreadsheet range score team2.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_score_team2", cell_range) @commands.command(aliases=["sssrd"]) async def set_schedules_spreadsheet_range_date(self, ctx, *, cell_range: str): """Sets the schedules spreadsheet range date.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_date", cell_range) @commands.command(aliases=["sssrt"]) async def set_schedules_spreadsheet_range_time(self, ctx, *, cell_range: str = ""): """Sets the schedules spreadsheet range time.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_time", cell_range) @commands.command(aliases=["sssrr"]) async def set_schedules_spreadsheet_range_referee(self, ctx, *, cell_range: str): """Sets the schedules spreadsheet range referee.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_referee", cell_range) @commands.command(aliases=["sssrs"]) async def set_schedules_spreadsheet_range_streamer(self, ctx, *, cell_range: str = ""): """Sets the schedules spreadsheet range streamer.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_streamer", cell_range) @commands.command(aliases=["sssrc"]) async def set_schedules_spreadsheet_range_commentator(self, ctx, *, cell_range: str = ""): """Sets the schedules spreadsheet range commentator.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_commentator", cell_range) @commands.command(aliases=["sssrml"]) async def set_schedules_spreadsheet_range_mp_links(self, ctx, *, cell_range: str = ""): """Sets the schedules spreadsheet range mp links.""" await self.set_schedules_spreadsheet_range_value(ctx, "range_mp_links", cell_range) def get_class(bot): """Returns the main class of the module""" return TosurnamentSchedulesSpreadsheetCog(bot) def setup(bot): """Setups the cog""" bot.add_cog(TosurnamentSchedulesSpreadsheetCog(bot))
StarcoderdataPython
1720006
<gh_stars>0 #<NAME>, <NAME>, <NAME> #Lab 6 import random # generates a list of random integers # int -> list def rand_num(size): alist = [] for i in range(size): #integer random numbers between 10 and 70 n = random.randint(10,70) alist.append(n) return alist # generates a list of numbers in ascending order # int -> list def ordered_num(size): alist = [] for i in range(size): alist.append(i) return alist # sorts a list using the insertion sort algorithm # list -> def insert_sort(alist): counter = 0 # loops from the first index in the list to the last for index in range(1,len(alist)): counter += 1 # saves the current value currentvalue = alist[index] # saves the position position = index # loops while the position is not zero and the list value is above current value while position > 0 and alist[position - 1] > currentvalue: counter += 1 # incriments the counter for every comparison made # changes the list value to the previous one alist[position] = alist[position - 1] # decrements the position position = position - 1 alist[position] = currentvalue print(counter) # sorts a list using the selection sort algorithm and prints the number of comparisons # list -> def select_sort(alist): # variable that keeps track of the number of comparisons compCount = 0 # goes through every index in the list for fillslot in range(len(alist)-1,0,-1): # sets first index as maximum positionOfMax=0 # goes through every value up to fillslot to find the maximum in that section of the list for location in range(1,fillslot+1): # counts the number of comparisons compCount += 1 # finds index of maximum if alist[location]>alist[positionOfMax]: positionOfMax = location # swaps the values in indexes fillslot and positionOfMax temp = alist[fillslot] alist[fillslot] = alist[positionOfMax] alist[positionOfMax] = temp print(compCount) ''' merge_sort: list -> list Takes a list and returns a sorted list Splits the list into a tree by cutting it in half and recursively applying merge_sort to the split lists Then sorts the lists as it moves back up the tree Sorts in O(nlog(n)) ''' def merge_sort(alist): count = 0 if len(alist)>1: count += 1 #splits list into sublists mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] #recursively calls merge_sort on the split lists count +=merge_sort(lefthalf) count +=merge_sort(righthalf) i=0 j=0 k=0 #compares items in lists to determine smaller item while i < len(lefthalf) and j < len(righthalf): count+=3 #places smaller item in correct spot if lefthalf[i] < righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 k=k+1 count+=1 while i < len(lefthalf): count+=1 alist[k]=lefthalf[i] i=i+1 k=k+1 count+=1 while j < len(righthalf): count+=1 alist[k]=righthalf[j] j=j+1 k=k+1 count+=1 return count # tests selectionSort, insertionSort, and mergeSort with lists of 100, 500, 1000, 5000, and 10000 random numbers # list -> def listUnordered(): size = 100 # variable used to determine whether to multiply size by 2 or 5 switch = 0 while size <= 50000: # generates the list of random numbers and creates two copies of it alist = rand_num(size) blist = list(alist) clist = list(alist) print("Size: " + str(size)) # sorts the list and prints the number of comparisons using selection sort, insertion sort, and merge sort print("Selection Sort:") select_sort(alist) print("Insertion Sort:") insert_sort(blist) print("Merge Sort:") print(merge_sort(clist)) print("") if switch == 0: size = size * 5 switch = 1 else: size = size * 2 switch = 0 # tests selectionSort, insertionSort, and mergeSort with lists of 100, 500, 1000, 5000, and 10000 numbers in ascending order # list -> def listOrdered(): size = 100 # variable used to determine whether to multiply size by 2 or 5 switch = 0 while size <= 50000: # generates the list of numbers and two copies of it alist = ordered_num(size) blist = list(alist) clist = list(alist) print("Size: " + str(size)) # sorts the list and prints the number of comparisons using selection sort, insertion sort, and merge sort print("Selection Sort:") select_sort(alist) print("Insertion Sort:") insert_sort(blist) print("Merge Sort:") print(merge_sort(clist)) print("") if switch == 0: size = size * 5 switch = 1 else: size = size * 2 switch = 0 print("Unordered Lists:") listUnordered() print("") print("Ordered Lists:") listOrdered()
StarcoderdataPython
1740427
import sdp.scripts.load_nstx_exp_ref as nstx_exp import sdp.scripts.FWR2D_NSTX_139047_Postprocess as fwrpp import sdp.plasma.analysis as ana import matplotlib.pyplot as plt import pickle import numpy as np with open('/p/gkp/lshi/XGC1_NSTX_Case/FullF_XGC_ti191_output/ref_pos.pck','r') as f: ref_pos = pickle.load(f) dne_ana = ana.XGC_Density_Loader('/p/gkp/lshi/XGC1_NSTX_Case/FullF_XGC_ti191_output/dne_file.sav.npz') n_channel = 16 #create the distance matrix, dx[i,j] is the absolute distance between the reflection points of i-th and j-th channel dx = np.absolute(np.zeros((n_channel,n_channel))+ref_pos[np.newaxis,:]-ref_pos[:,np.newaxis]) #calculate cross-correlation matrix from synthetic signals cc_fwr = fwrpp.pp.Cross_Correlation_by_fft(fwrpp.ref2d_out) cc_fwr2 = fwrpp.pp.Cross_Correlation_by_fft(fwrpp.ref2d_amp2_out) cc_fwr01 = fwrpp.pp.Cross_Correlation_by_fft(fwrpp.ref2d_amp01_out) cc_3d = fwrpp.pp.Cross_Correlation_by_fft(fwrpp.ref3d_out) cs_fwr = fwrpp.pp.Self_Correlation(fwrpp.ref2d_out) cs_fwr2 = fwrpp.pp.Self_Correlation(fwrpp.ref2d_amp2_out) cs_fwr01 = fwrpp.pp.Self_Correlation(fwrpp.ref2d_amp01_out) cs_3d = fwrpp.pp.Self_Correlation(fwrpp.ref3d_out) print('FWR data loaded') #calculate cross-correlation matrix from experimental signals, note that for our case, the simulated time slice is at t=0.632s, so we choose corresponding experimental data from 0.632-0.640, the total sample number is chosen to be 2000 because larger sample doesn't bring in any difference, since the increased samples are not statistical independent. cc_exp = nstx_exp.analyser.Cross_Correlation_by_fft(0.632,0.640,8000) #cc_exp_short = nstx_exp.analyser.Cross_Correlation_by_fft(0.634,0.6348,8000) #calculate coherent signal for all channels from NSTX. The result is an 2D array containing time series of coherent signal from all the channels. cs_exp = nstx_exp.analyser.Coherent_over_time(0.632,0.640,2e-5,1e-4) print('nstx data loaded') #choose the channel ranges representing top/bottom part of pedestal, and center channels for each region. top_center = 11 top_range = [8,12] bottom_center = 6 bottom_range = [2,7] #pick chosen data from whole correlation matrices fwr_top=[] fwr2_top = [] fwr01_top=[] fwr3d_top=[] exp_top = [] dx_top=[] def pick_top(): global fwr_top,fwr2_top,exp_top,dx_top,fwr01_top,fwr3d_top fwr_top = np.absolute(cc_fwr[top_center,top_range[0]:top_range[1]]) fwr2_top = np.absolute(cc_fwr2[top_center,top_range[0]:top_range[1]]) fwr01_top = np.absolute(cc_fwr01[top_center,top_range[0]:top_range[1]]) fwr3d_top = np.absolute(cc_3d[top_center,top_range[0]:top_range[1]]) exp_top = np.absolute(cc_exp[top_center,top_range[0]:top_range[1]]) dx_top = dx[top_center,top_range[0]:top_range[1]] pick_top() fwr_bot=[] fwr2_bot=[] fwr01_bot = [] fwr3d_bot = [] exp_bot=[] dx_bot=[] def pick_bottom(): global fwr_bot,fwr2_bot,fwr01_bot,exp_bot,dx_bot,fwr3d_bot fwr_bot = np.absolute(cc_fwr[bottom_center,bottom_range[0]:bottom_range[1]]) fwr2_bot = np.absolute(cc_fwr2[bottom_center,bottom_range[0]:bottom_range[1]]) fwr01_bot = np.absolute(cc_fwr01[bottom_center,bottom_range[0]:bottom_range[1]]) fwr3d_bot = np.absolute(cc_3d[bottom_center,bottom_range[0]:bottom_range[1]]) exp_bot = np.absolute(cc_exp[bottom_center,bottom_range[0]:bottom_range[1]]) dx_bot = dx[bottom_center,bottom_range[0]:bottom_range[1]] pick_bottom() #fitting with gaussian(for bottom) and exponential(for top) xmax_t = 0 xfit_t = 0 fwr_fit_t = 0 fwr2_fit_t = 0 fwr01_fit_t = 0 fwr3d_fit_t = 0 exp_fit_t = 0 fwr_t_a,fwr_t_sa = 0,0 fwr2_t_a,fwr2_t_sa = 0,0 fwr01_t_a,fwr01_t_sa = 0,0 fwr3d_t_a,fwr3d_t_sa = 0,0 exp_t_a,exp_t_sa = 0,0 xgc_fit_t = 0 xgc_t_a,xgc_t_sa = 0,0 x_t,dne_c_t = 0,0 def fit_top(): global fwr_t_a,fwr_t_sa,fwr2_t_a,fwr2_t_sa,fwr01_t_a,fwr01_t_sa,fwr3d_t_a,fwr3d_t_sa,exp_t_a,expt_sa,xmax_t,xfit_t,fwr_fit_t,fwr2_fit_t,exp_fit_t,fwr01_fit_t,fwr3d_fit_t,xgc_fit_t,xgc_t_a,xgc_t_sa,x_t,dne_c_t fwr_t_a,fwr_t_sa = fwrpp.pp.fitting_cross_correlation(fwr_top,dx_top,'exponential') fwr2_t_a,fwr2_t_sa = fwrpp.pp.fitting_cross_correlation(fwr2_top,dx_top,'exponential') fwr01_t_a,fwr01_t_sa = fwrpp.pp.fitting_cross_correlation(fwr01_top,dx_top,'exponential') fwr3d_t_a,fwr3d_t_sa = fwrpp.pp.fitting_cross_correlation(fwr3d_top,dx_top,'exponential') exp_t_a,exp_t_sa = fwrpp.pp.fitting_cross_correlation(exp_top,dx_top,'exponential') opt_t,x_t,dne_c_t = dne_ana.density_correlation(ref_pos[top_center],width = ref_pos[top_range[0]]-ref_pos[top_center]) xgc_t_a,xgc_t_sa = opt_t xmax_t = 2*np.max((np.abs(fwr_t_a),np.abs(fwr2_t_a),np.abs(exp_t_a))) xfit_t = np.linspace(0,xmax_t,500) fwr_fit_t = fwrpp.pp.exponential_fit(xfit_t,fwr_t_a) fwr2_fit_t = fwrpp.pp.exponential_fit(xfit_t,fwr2_t_a) fwr01_fit_t = fwrpp.pp.exponential_fit(xfit_t,fwr01_t_a) fwr3d_fit_t = fwrpp.pp.exponential_fit(xfit_t,fwr3d_t_a) exp_fit_t = fwrpp.pp.exponential_fit(xfit_t,exp_t_a) xgc_fit_t = ana.gaussian_correlation_func(xfit_t,xgc_t_a) fit_top() xmax_b = 0 xfit_b = 0 fwr_fit_b = 0 fwr2_fit_b = 0 fwr01_fit_b = 0 fwr3d_fit_b = 0 exp_fit_b = 0 fwr_b_a,fwr_b_sa = 0,0 fwr2_b_a,fwr2_b_sa = 0,0 fwr01_b_a,fwr01_b_sa = 0,0 fwr3d_b_a,fwr3d_b_sa = 0,0 exp_b_a,exp_b_sa = 0,0 xgc_fit_b = 0 xgc_b_a,xgc_b_sa = 0,0 x_b,dne_c_b = 0,0 def fit_bot(): global fwr_b_a,fwr_b_sa,fwr2_b_a,fwr2_b_sa,fwr01_b_a,fwr01_b_sa,fwr3d_b_a,fwr3d_b_sa,exp_b_a,expt_sa,xmax_b,xfit_b,fwr_fit_b,fwr2_fit_b,exp_fit_b,fwr01_fit_b,fwr3d_fit_b,xgc_fit_b,xgc_b_a,xgc_b_sa,x_b,dne_c_b fwr_b_a,fwr_b_sa = fwrpp.pp.fitting_cross_correlation(fwr_bot,dx_bot,'gaussian') fwr2_b_a,fwr2_b_sa = fwrpp.pp.fitting_cross_correlation(fwr2_bot,dx_bot,'gaussian') fwr01_b_a,fwr01_b_sa = fwrpp.pp.fitting_cross_correlation(fwr01_bot,dx_bot,'gaussian') fwr3d_b_a,fwr3d_b_sa = fwrpp.pp.fitting_cross_correlation(fwr3d_bot,dx_bot,'gaussian') exp_b_a,exp_b_sa = fwrpp.pp.fitting_cross_correlation(exp_bot,dx_bot,'gaussian') opt_b,x_b,dne_c_b = dne_ana.density_correlation(ref_pos[bottom_center],width = ref_pos[bottom_range[0]]-ref_pos[bottom_center]) xgc_b_a,xgc_b_sa = opt_b xmax_b = 2*np.sqrt(np.max((np.abs(fwr_b_a),np.abs(fwr2_b_a),np.abs(exp_b_a)))) xfit_b = np.linspace(0,xmax_b,500) fwr_fit_b = fwrpp.pp.gaussian_fit(xfit_b,fwr_b_a) fwr2_fit_b = fwrpp.pp.gaussian_fit(xfit_b,fwr2_b_a) fwr01_fit_b = fwrpp.pp.gaussian_fit(xfit_b,fwr01_b_a) fwr3d_fit_b = fwrpp.pp.gaussian_fit(xfit_b,fwr3d_b_a) exp_fit_b = fwrpp.pp.gaussian_fit(xfit_b,exp_b_a) xgc_fit_b = ana.gaussian_correlation_func(xfit_b,xgc_b_a) fit_bot() print('fitting complete') print('fitting curve ready. call plot() to plot. note that the default region is top, pass "bottom" as the argument to plot bottom region. ') #plot the data points and curves total_plot = 0 #top data def plot(region = 'top'): global total_plot #plt.figure() #total_plot += 1 if(region == 'top'): plt.title('Cross-Correlation at Upper Pedestal,center_channel at {0:.4}m'.format(ref_pos[top_center])) plt.plot(dx_top,exp_top,'bs',label = 'exp data') plt.plot(dx_top,fwr_top,'ro',label = 'FWR data amp=1') plt.plot(dx_top,fwr2_top,'r^',label = 'FWR data amp=2') plt.plot(dx_top,fwr01_top,'r+',label = 'FWR data amp=0.1') plt.plot(xfit_t,exp_fit_t,'b-',label = 'exp exponential fit') plt.plot(xfit_t,fwr_fit_t,'r--',label = 'FWR fit') plt.plot(xfit_t,fwr2_fit_t,'r-.',label = 'FWR amp2 fit') plt.plot(xfit_t,fwr01_fit_t,'r:',label = 'FWR amp0.1 fit') plt.xlabel('distance from center channel reflection($m$)') plt.ylabel('cross-correlation') plt.legend(labelspacing = 0.2,prop = {'size':12}) plt.tight_layout() elif(region == 'bottom'): plt.title('Cross-Correlation at Lower Pedestal,center_channel at {0:.4}m'.format(ref_pos[bottom_center])) plt.plot(dx_bot,exp_bot,'bs',label = 'exp data') plt.plot(dx_bot,fwr_bot,'ro',label = 'FWR data amp=1') plt.plot(dx_bot,fwr2_bot,'r^',label = 'FWR data amp=2') plt.plot(dx_bot,fwr01_bot,'r+',label = 'FWR data amp=0.1') plt.plot(xfit_b,exp_fit_b,'b-',label = 'exp gaussian fit') plt.plot(xfit_b,fwr_fit_b,'r--',label = 'FWR fit') plt.plot(xfit_b,fwr2_fit_b,'r-.',label = 'FWR amp2 fit') plt.plot(xfit_b,fwr01_fit_b,'r:',label = 'FWR amp0.1 fit') plt.xlabel('distance from center channel reflection($m$)') plt.ylabel('cross-correlation') plt.legend(labelspacing = 0.2,prop = {'size':12}) plt.tight_layout() elif(region == '2d/3d_top'): plt.title('Cross-Correlation at Upper Pedestal,center_channel at {0:.4}m'.format(ref_pos[top_center])) plt.plot(dx_top,exp_top,'bs',label = 'exp data') plt.plot(dx_top,fwr_top,'ro',label = 'FWR2D data') plt.plot(dx_top,fwr3d_top,'r^',label = 'FWR3D data') plt.plot(xfit_t,exp_fit_t,'b-',label = 'exp exponential fit') plt.plot(xfit_t,fwr_fit_t,'r--',label = 'FWR2D fit') plt.plot(xfit_t,fwr3d_fit_t,'r-.',label = 'FWR3D fit') plt.xlabel('distance from center channel reflection($m$)') plt.ylabel('cross-correlation') plt.legend(labelspacing = 0.2,prop = {'size':12}) plt.tight_layout() elif(region =='2d/3d_bot'): #plt.title('Cross-Correlation at Lower Pedestal,center_channel at {0:.4}m'.format(ref_pos[bottom_center])) plt.plot(dx_bot,exp_bot,'bs',label = 'exp data') plt.plot(dx_bot,fwr_bot,'go',label = 'FWR2D data') plt.plot(dx_bot,fwr3d_bot,'r^',label = 'FWR3D data') plt.plot(xfit_b,exp_fit_b,'b-') plt.plot(xfit_b,fwr_fit_b,'g--') plt.plot(xfit_b,fwr3d_fit_b,'r-.') plt.xlabel('$distance from center channel(mm)$') plt.ylabel('$\gamma$') plt.legend(labelspacing = 0.2,prop = {'size':15}) plt.tight_layout() elif(region == '3d_bot'): plt.title('2D/3D Cross-Correlation and XGC1 Density Correlation, Lower') plt.plot(dx_bot,fwr_bot,'ro',label = '2D') plt.plot(dx_bot,fwr3d_bot,'r^',label = '3D') plt.plot(x_b,dne_c_b,'bs',label = 'XGC') plt.plot(xfit_b,fwr_fit_b,'r-.',label = '2D fit') plt.plot(xfit_b,fwr3d_fit_b,'r--',label = '3D fit') plt.plot(xfit_b,xgc_fit_b,'b-',label = 'XGC fit') plt.xlabel('distance from center channel relfection($m$)') plt.ylabel('cross-corelation') plt.legend(labelspacing = 0.2,prop = {'size':12}) plt.tight_layout() elif(region == '3d_top'): plt.title('2D/3D Cross-Correlation and XGC1 Density Correlation, Upper') plt.plot(dx_top,fwr_top,'ro',label = '2D') plt.plot(dx_top,fwr3d_top,'r^',label = '3D') plt.plot(x_t,dne_c_t,'bs',label = 'XGC') plt.plot(xfit_t,fwr_fit_t,'r-.',label = '2D fit') plt.plot(xfit_t,fwr3d_fit_t,'r--',label = '3D fit') plt.plot(xfit_t,xgc_fit_t,'b-',label = 'XGC fit') plt.xlabel('distance from center channel relfection($m$)') plt.ylabel('cross-corelation') plt.legend(labelspacing = 0.2,prop = {'size':12}) plt.tight_layout() def clear_all(): global total_plot for i in range(total_plot): plt.close() # Coherent Signal comparison
StarcoderdataPython
146416
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * class PyPyspellchecker(PythonPackage): """Pure python spell checker based on work by <NAME>""" homepage = "https://github.com/barrust/pyspellchecker" pypi = "pyspellchecker/pyspellchecker-0.6.2.tar.gz" version('0.6.2', sha256='af6a1d0393a175499475a873f31e52135f1efd5fc912c979101b795b3c2ee77f') depends_on('[email protected]:', type=('build', 'run')) depends_on('py-setuptools', type='build')
StarcoderdataPython
3238521
from setuptools import setup, find_packages requirements:list = [] with open("requirements.txt", "r") as file: requirements = file.readlines() setup( name="cclr", version="0.0.1B", author="<NAME>", author_email="<EMAIL>", packages=find_packages(), install_requires=requirements, entry_points={ "console_scripts":[ "cclr = cclr_py_scripts.entry:main" ] } )
StarcoderdataPython
3383174
from django.contrib import admin from .models import Passport # Register your models here. admin.site.register(Passport)
StarcoderdataPython
180912
from nslocapysation.classes.localized_string import LocalizedString class DynamicLocalizedString(LocalizedString): """ A subclass of LocalizedString, whose instances represent localized strings that are used with a dynamic key (i.e. some variable as key). Those are special because you need to check that there is a localization for every possible value of the variable. """ def __eq__(self, other): if not isinstance(other, self.__class__): return False return (self.key == other.key and self.full_sourcefile_path == other.full_sourcefile_path and self.sourcefile_line_number == other.sourcefile_line_number and self.line_occurrence_number == other.line_occurrence_number) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return (hash(self.key) ^ hash(self.sourcefile_line_number) ^ hash(self.line_occurrence_number) ^ hash(self.full_sourcefile_path))
StarcoderdataPython
4811493
<filename>sla_app/migrations/0010_remove_keyperformanceindicator_for_period.py # Generated by Django 2.1.3 on 2018-12-04 21:10 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sla_app', '0009_merge_20181204_2108'), ] operations = [ migrations.RemoveField( model_name='keyperformanceindicator', name='for_period', ), ]
StarcoderdataPython
3270781
<reponame>OsmosizBiz/tphysics #Imports from tphysics.shapes import * #Create a class to hold a verlet version of the circle class VerletCircle(Circle): #Define init for the circle def __init__(self, x, y, radius, xspeed, yspeed): #Crete our derivative shape super(VerletCircle, self).__init__(x, y, radius) #Set the radious self.radius = radius #Store the previous position values self.prevx = self.x - xspeed self.prevy = self.y - yspeed #Create a function to set the speed def setspeed(self, xspeed, yspeed): #Update the previous position to match the speed self.prevx = self.x - xspeed self.prevy = self.y - yspeed #Create a function to set the speed def setxspeed(self, xspeed): #Update the previous position to match the speed self.prevx = self.x - xspeed #Create a function to set the speed def setyspeed(self, yspeed): #Update the previous position to match the speed self.prevy = self.y - yspeed #Create a function to get the x speed def getxspeed(self): #Return the x speed return self.x - self.prevx #Create a function to get the speed def getyspeed(self): #Return the y speed return self.y - self.prevy #Create a function to bounce on the x def bouncex(self, elasticity): #Bounce on the x axis tempx = self.prevx self.prevx = self.x self.x = self.x + ((tempx - self.prevx) * elasticity) #Create a function to bounce on the y def bouncey(self, elasticity, friction): #Bounce on the y axis tempy = self.prevy self.prevy = self.y self.y = self.y + ((tempy - self.y) / (1/ elasticity)) self.x = self.x + ((self.prevx - self.x) * friction) #Create a function to update the position def update(self): #Store the current position tempx = self.x tempy = self.y #Update the position self.x = self.x + (self.x - self.prevx) self.y = self.y + (self.y - self.prevy) #Store the previous position self.prevx = tempx self.prevy = tempy #Check whether the ball has come to an effective stop if abs(self.x - self.prevx) < 0.01: self.prevx = self.x if abs(self.y - self.prevy) < 0.01: self.prevy = self.y
StarcoderdataPython
1708716
# # Software distrubuted under MIT License (MIT) # # Copyright (c) 2020 Flexpool # # 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 requests import datetime from . import shared __WORKER_API_ENDPOINT__ = None def update_endpoint(endpoint): global __WORKER_API_ENDPOINT__ __WORKER_API_ENDPOINT__ = endpoint + "/worker" class Worker: def __init__(self, address: str, worker_name: str, online: bool, last_seen_timestamp: int): # Warning: this class is expected to be initialized only by this library itself. # There are no checks either the given address + worker_name exist or not. self.address = address self.worker_name = worker_name self.is_online = online self.last_seen_date = datetime.datetime.fromtimestamp( last_seen_timestamp) self.endpoint = __WORKER_API_ENDPOINT__ + \ f"/{self.address}/{self.worker_name}" def current_hashrate(self): api_request = requests.get(self.endpoint + "/current/") shared.check_response(api_request) api_request = api_request.json()["result"] return api_request["effective_hashrate"], api_request["reported_hashrate"] def stats(self): api_request = requests.get(self.endpoint + "/stats/") shared.check_response(api_request) api_request = api_request.json()["result"] class_ = shared.Stats( api_request["current"]["effective_hashrate"], api_request["daily"]["effective_hashrate"], api_request["current"]["reported_hashrate"], api_request["daily"]["reported_hashrate"], api_request["daily"]["valid_shares"], api_request["daily"]["stale_shares"], api_request["daily"]["invalid_shares"]) return class_ def daily_average_stats(self): api_request = requests.get(self.endpoint + "/daily/") shared.check_response(api_request) api_request = api_request.json()["result"] class_ = shared.DailyAverageStats( api_request["effective_hashrate"], api_request["reported_hashrate"], api_request["valid_shares"], api_request["stale_shares"], api_request["invalid_shares"]) return class_ def chart(self): api_request = requests.get(self.endpoint + "/chart/") shared.check_response(api_request) items = [] for item in api_request.json()["result"]: items.append(shared.StatChartItem( item["effective_hashrate"], item["reported_hashrate"], item["valid_shares"], item["stale_shares"], item["invalid_shares"], item["timestamp"] )) return items def __repr__(self): return "<flexpoolapi.worker.Worker object "\ f"{self.worker_name} ({self.address})>"
StarcoderdataPython
3253444
#!/usr/bin/env python __title__ = 'dockerlief' __version__ = '0.1.0' __author__ = '<NAME>' __author_email__ = '<EMAIL>' __license__ = 'Apache 2.0'
StarcoderdataPython
1654899
from helpers.base_viewset import BaseViewSet from .models import BaseAccount from .serializers import WholeAccountSerializer class AccountViewSet(BaseViewSet): queryset = BaseAccount.objects.all() serializer_class = WholeAccountSerializer
StarcoderdataPython
3224329
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.auth.models import User from powerpages.models import Page from powerpages.sync import PageFileDumper from powerpages.admin import website_link, sync_status, save_page from powerpages.signals import page_edited from .test_sync import BaseSyncTestCase class WebsiteLinkTestCase(TestCase): maxDiff = None def test_no_object(self): self.assertIsNone(website_link(None)) def test_empty_url(self): self.assertEqual( website_link(Page(url='')), '<a href="" style="font-weight: normal;"> &raquo;</a>' ) def test_root_url(self): self.assertEqual( website_link(Page(url='/')), '<a href="/" style="font-weight: normal;">/ &raquo;</a>' ) def test_first_level_url(self): self.assertEqual( website_link(Page(url='/test/')), '<a href="/test/" style="font-weight: normal;">' '/<span style="font-weight: bold">test</span>/' ' &raquo;</a>' ) def test_second_level_url(self): self.assertEqual( website_link(Page(url='/nested/test/')), '<a href="/nested/test/" style="font-weight: normal;">' '/nested/<span style="font-weight: bold">test</span>/' ' &raquo;</a>' ) def test_file(self): self.assertEqual( website_link(Page(url='/robots.txt')), '<a href="/robots.txt" style="font-weight: normal;">' '/<span style="font-weight: bold">robots.txt</span>' ' &raquo;</a>' ) def test_nested_file(self): self.assertEqual( website_link(Page(url='/nested/robots.txt')), '<a href="/nested/robots.txt" style="font-weight: normal;">' '/nested/<span style="font-weight: bold">robots.txt</span>' ' &raquo;</a>' ) class SyncStatusTestCase(BaseSyncTestCase): maxDiff = None def test_no_object(self): self.assertIsNone(sync_status(None)) def test_file_synced(self): page = Page.objects.create( url='/test-page/', template='<h1>Test Page</h1>' ) PageFileDumper(page).save() self.assertEqual( sync_status(page), '<span style="color: green">File is synced</span>' ) def test_file_content_differs(self): page = Page.objects.create( url='/test-page/', template='<h1>Test Page</h1>' ) PageFileDumper(page).save() page.title = '<NAME>' page.save() self.assertEqual( sync_status(page), '<span style="color: orange">File content differs</span>' ) def test_file_is_missing(self): page = Page.objects.create( url='/test-page/', template='<h1>Test Page</h1>' ) self.assertEqual( sync_status(page), '<span style="color: red">File is missing</span>' ) def test_file_content_differs_modified_in_admin(self): page = Page.objects.create( url='/test-page/', template='<h1>Test Page</h1>' ) PageFileDumper(page).save() page.title = '<NAME>' page.is_dirty = True # modified in Admin page.save() self.assertEqual( sync_status(page), '<span style="color:black; font-weight:bold">' 'Changed in Admin!</span><br>' '<span style="color: orange">File content differs</span>' ) class SavePageTestCase(TestCase): maxDiff = None def setUp(self): def page_edited_test_handler(sender, **kwargs): self.page_edited_kwargs = kwargs self.page_edited_kwargs = None page_edited.connect( page_edited_test_handler, dispatch_uid='test_page_edited', weak=False ) def tearDown(self): page_edited.disconnect(dispatch_uid='test_page_edited') self.page_edited_kwargs = None def test_create_page(self): page = Page(url='/test-page/') user = User.objects.create_user('admin-user') save_page(page=page, user=user, created=True) self.assertIsNotNone(page.pk) self.assertTrue(page.is_dirty) self.assertDictContainsSubset( {'page': page, 'user': user, 'created': True}, self.page_edited_kwargs ) def test_modify_page(self): page = Page.objects.create(url='/test-page/', title='Lorem') page.title = 'Ipsum' user = User.objects.create_user('admin-user') save_page(page=page, user=user, created=False) self.assertEqual(Page.objects.get(pk=page.pk).title, 'Ipsum') self.assertTrue(page.is_dirty) self.assertDictContainsSubset( {'page': page, 'user': user, 'created': False}, self.page_edited_kwargs ) class SwitchEditModeViewTestCase(TestCase): maxDiff = None def setUp(self): self.url = reverse('switch_edit_mode') self.staff_member = User.objects.create_user( 'staff_member', password='<PASSWORD>', is_staff=True ) self.super_user = User.objects.create_user( 'super_user', password='<PASSWORD>', is_superuser=True ) self.regular_user = User.objects.create_user( 'regular_user', password='<PASSWORD>' ) Page.objects.create(url='/') Page.objects.create(url='/test-page/') def test_enable_edit_mode_staff_member_referrer(self): self.client.login(username='staff_member', password='<PASSWORD>') response = self.client.get(self.url, HTTP_REFERER='/test-page/') self.assertTrue(self.client.session.get('WEBSITE_EDIT_MODE')) self.assertRedirects(response, '/test-page/') def test_disable_edit_mode_staff_member_no_referrer(self): self.client.login(username='staff_member', password='<PASSWORD>') session = self.client.session session['WEBSITE_EDIT_MODE'] = True session.save() response = self.client.get(self.url) self.assertNotIn('WEBSITE_EDIT_MODE', self.client.session) self.assertRedirects(response, '/') def test_enable_edit_mode_super_user_no_referrer(self): self.client.login(username='super_user', password='<PASSWORD>') response = self.client.get(self.url) self.assertTrue(self.client.session.get('WEBSITE_EDIT_MODE')) self.assertRedirects(response, '/') def test_disable_edit_mode_super_user_referrer(self): self.client.login(username='super_user', password='<PASSWORD>') session = self.client.session session['WEBSITE_EDIT_MODE'] = True session.save() response = self.client.get(self.url, HTTP_REFERER='/test-page/') self.assertNotIn('WEBSITE_EDIT_MODE', self.client.session) self.assertRedirects(response, '/test-page/') def test_access_forbidden_regular_user(self): self.client.login(username='regular_user', password='<PASSWORD>') response = self.client.get(self.url) self.assertRedirects( response, '{0}?next={1}'.format(settings.LOGIN_URL, self.url), fetch_redirect_response=False ) def test_access_forbidden_anonmous(self): response = self.client.get(self.url) self.assertRedirects( response, '{0}?next={1}'.format(settings.LOGIN_URL, self.url), fetch_redirect_response=False )
StarcoderdataPython
3218126
<reponame>Strata-ai/Social-Distancing-Detector import numpy as np from PyQt5.QtCore import Qt, QThread, QTimer from PyQt5.QtGui import QPixmap, QFont, QImage, QCursor, QIntValidator from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton, QHBoxLayout, QApplication, QLabel, \ QDialog, QDialogButtonBox, QVBoxLayout, QLineEdit from pyqtgraph import ImageView, PlotWidget, GraphicsView, ImageItem import cv2 class PictureView(GraphicsView): def __init__(self, *args, **kwargs): super(PictureView, self).__init__(*args, **kwargs) def mousePressEvent(self, event): print(event.pos()) def mouseReleaseEvent(self, event): cursor = QCursor() print(cursor.pos()) class ConfigDialog(QDialog): def __init__(self, *args, **kwargs): super(ConfigDialog, self).__init__(*args, **kwargs) self.setWindowTitle("Region of Interest Configuration") QBtn = QDialogButtonBox.Save | QDialogButtonBox.Cancel self.buttonBox = QDialogButtonBox(QBtn) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) validator = QIntValidator(0, 1500) self.layout = QVBoxLayout() h_layout_1 = QHBoxLayout() h_layout_2 = QHBoxLayout() h_layout_1.addWidget(QLabel("Video Source:")) self.video_source = QLineEdit() h_layout_1.addWidget(self.video_source) v_layout_1 = QVBoxLayout() v_layout_1.addWidget(QLabel("Bottom Left - pixel (x, y):")) v_layout_1.addWidget(QLabel("Bottom Right - pixel (x, y):")) v_layout_1.addWidget(QLabel("Top Right - pixel (x, y):")) v_layout_1.addWidget(QLabel("Top Left - pixel (x, y):")) v_layout_1.addWidget(QLabel("Dimension - cm (width, depth):")) h_layout_2.addLayout(v_layout_1) v_layout_2 = QVBoxLayout() self.bl_x = QLineEdit() self.bl_x.setValidator(validator) v_layout_2.addWidget(self.bl_x) self.br_x = QLineEdit() self.br_x.setValidator(validator) v_layout_2.addWidget(self.br_x) self.tr_x = QLineEdit() self.tr_x.setValidator(validator) v_layout_2.addWidget(self.tr_x) self.tl_x = QLineEdit() self.tl_x.setValidator(validator) v_layout_2.addWidget(self.tl_x) self.width = QLineEdit() self.width.setValidator(validator) v_layout_2.addWidget(self.width) h_layout_2.addLayout(v_layout_2) v_layout_3 = QVBoxLayout() self.bl_y = QLineEdit() self.bl_y.setValidator(validator) v_layout_3.addWidget(self.bl_y) self.br_y = QLineEdit() self.br_y.setValidator(validator) v_layout_3.addWidget(self.br_y) self.tr_y = QLineEdit() self.tr_y.setValidator(validator) v_layout_3.addWidget(self.tr_y) self.tl_y = QLineEdit() self.tl_y.setValidator(validator) v_layout_3.addWidget(self.tl_y) self.depth = QLineEdit() self.depth.setValidator(validator) v_layout_3.addWidget(self.depth) h_layout_2.addLayout(v_layout_3) self.layout.addLayout(h_layout_1) self.layout.addLayout(h_layout_2) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) class StartWindow(QMainWindow): def __init__(self, camera = None, net = None, config = None, image_width = 950): super().__init__() self.camera = camera self.net = net self.config = config self.image_width = image_width self.setFixedWidth(image_width + 78) self.setFixedHeight(780) self.central_widget = QWidget(self) self.label_logo = QLabel(self.central_widget) logo = QPixmap("logo.png") self.label_logo.setPixmap(logo) self.label_logo.setGeometry(20,20,181,81) self.label_logo.setScaledContents(True) self.label_logo_2 = QLabel(self.central_widget) logo_2 = QPixmap("logo_2.png") self.label_logo_2.setPixmap(logo_2) self.label_logo_2.setGeometry(670,30,206,61) self.label_logo_2.setScaledContents(True) self.button_config = QPushButton('Configuration', self.central_widget) self.button_config.setGeometry(240,30,191,61) font = QFont() font.setPointSize(24) self.button_config.setFont(font) self.button_config.clicked.connect(self.start_config) self.button_detection = QPushButton('Start Detection', self.central_widget) self.button_detection.setGeometry(450,30,191,61) font = QFont() font.setPointSize(24) self.button_detection.setFont(font) self.button_detection.clicked.connect(self.start_movie) #self.label_image = QLabel(self.central_widget) self.image_view = PictureView(self.central_widget) self.image_view.setGeometry(39,110,image_width,630) #self.image_view.hideAxis('left') #self.image_view.hideAxis('bottom') self.image_view.setStyleSheet("border :1px solid black;") #self.label_image.setGeometry(40,110,1067,600) #self.label_image.setScaledContents(True) #self.label_image.setStyleSheet("border :1px solid black;") self.setCentralWidget(self.central_widget) self.update_timer = QTimer() self.update_timer.timeout.connect(self.update_movie) def start_config(self): dlg = ConfigDialog(self) dlg.bl_x.setText(str(self.config.bl_x)) dlg.bl_y.setText(str(self.config.bl_y)) dlg.br_x.setText(str(self.config.br_x)) dlg.br_y.setText(str(self.config.br_y)) dlg.tl_x.setText(str(self.config.tl_x)) dlg.tl_y.setText(str(self.config.tl_y)) dlg.tr_x.setText(str(self.config.tr_x)) dlg.tr_y.setText(str(self.config.tr_y)) dlg.width.setText(str(self.config.width)) dlg.depth.setText(str(self.config.depth)) dlg.video_source.setText(self.config.video_source) if dlg.exec_(): self.config.bl_x = int(dlg.bl_x.text()) self.config.bl_y = int(dlg.bl_y.text()) self.config.br_x = int(dlg.br_x.text()) self.config.br_y = int(dlg.br_y.text()) self.config.tl_x = int(dlg.tl_x.text()) self.config.tl_y = int(dlg.tl_y.text()) self.config.tr_x = int(dlg.tr_x.text()) self.config.tr_y = int(dlg.tr_y.text()) self.config.width = int(dlg.width.text()) self.config.depth = int(dlg.depth.text()) self.config.video_source = dlg.video_source.text() self.config.save() def update_image(self): frame = self.camera.get_frame() frame = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE) #self.image_view.setImage(frame.T) image_item = ImageItem(frame) self.image_view.addItem(image_item) #height, width, channel = frame.shape #bytesPerLine = 3 * width #qimg = QImage(frame.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped() #self.label_image.setPixmap(QPixmap(qimg)) #self.update() #print(height, width) def update_movie(self): #print(self.camera.last_frame.shape) image_item = ImageItem(self.camera.last_frame) self.image_view.addItem(image_item) #self.image_view.setImage(self.camera.last_frame.T) def update_brightness(self, value): value /= 10 self.camera.set_brightness(value) def start_movie(self): self.movie_thread = MovieThread(self.camera, self.net, self.config) self.movie_thread.start() self.update_timer.start(30) class MovieThread(QThread): def __init__(self, camera, net, config): super().__init__() self.camera = camera self.net = net self.config = config def run(self): #self.camera.acquire_movie(500) self.camera.detect_in_movie(500, self.net, self.config) if __name__ == '__main__': app = QApplication([]) window = StartWindow() window.show() app.exit(app.exec_())
StarcoderdataPython
78670
from kivy.uix.screenmanager import Screen class HomeScreen(Screen): """ The Welcome Screen """ def __init__(self, BippyApp, **kwargs): super(HomeScreen, self).__init__(**kwargs) self.BippyApp = BippyApp return
StarcoderdataPython
3312718
<filename>turbo_stream/utils/request_handlers.py """ Request Handler Methods & Wrappers """ import logging import time from functools import wraps from random import random logging.basicConfig( format="%(asctime)s %(name)-12s %(levelname)-8s %(message)s", level=logging.INFO ) def request_handler(wait: float = 1, backoff_factor: float = 0.5): """ Wrapper to handle the request process. :param wait: Initial wait time. :param backoff_factor: Increase wait time by given factor. :return: None """ def retry_decorator(function): @wraps(function) def func_with_retries(*args, **kwargs): _delay = round(wait * (1 + backoff_factor * random()), 2) logging.info(f"Waiting {_delay} seconds before the next attempt...") time.sleep(_delay) return function(*args, **kwargs) return func_with_retries return retry_decorator def retry_handler( exceptions, total_tries: int = 4, initial_wait: float = 0.5, backoff_factor: int = 2, should_raise: bool = False, ): """ Wrapper to handle the request process. :param exceptions: Exceptions to handle. :param total_tries: Total tries before raising an exception. :param initial_wait: Initial wait after first exception handled. :param backoff_factor: Increase wait period by given factor. :param should_raise: Bool raise exception after all tries. :return: None """ def retry_decorator(function): @wraps(function) def func_with_retries(*args, **kwargs): tries = 1 delay = initial_wait while True: try: logging.info(f"Attempt {tries} of {total_tries}.") return function(*args, **kwargs) except exceptions as exception: if tries <= total_tries and should_raise: raise Exception( f"Function: {function.__name__}\n" f"Failed despite best efforts after {total_tries} tries\n" f"Exception {exception}." ) logging.info( f"Function: {function.__name__}\n" f"Failed at {tries} tries, trying again in {delay} seconds...\n" f"Exception {exception}." ) tries += 1 time.sleep(delay) delay = delay * backoff_factor return func_with_retries return retry_decorator
StarcoderdataPython
1737711
# Copyright 2022 The OFA-Sys Team. # All rights reserved. # This source code is licensed under the Apache 2.0 license # found in the LICENSE file in the root directory. import json import logging import math from dataclasses import dataclass, field from typing import Optional import torch from fairseq import metrics from fairseq.dataclass import ChoiceEnum from fairseq.tasks import register_task from tasks.ofa_task import OFATask, OFAConfig from data.nlu_data.qqp_dataset import QQPDataset from data.file_dataset import FileDataset from utils.trie import Trie logger = logging.getLogger(__name__) @dataclass class QQPConfig(OFAConfig): ans2label_dict: Optional[str] = field( default='{"no": 0, "yes": 1}', metadata={"help": 'answer to label dict'}, ) prompt_type: ChoiceEnum(["none", "src", "prev_output"]) = field( default="none", metadata={"help": "decoder prompt"}, ) @register_task("qqp", dataclass=QQPConfig) class QQPTask(OFATask): def __init__(self, cfg: QQPConfig, src_dict, tgt_dict): super().__init__(cfg, src_dict, tgt_dict) self.ans2label_dict = json.loads(self.cfg.ans2label_dict) def load_dataset(self, split, epoch=1, combine=False, **kwargs): paths = self.cfg.data.split(',') assert len(paths) > 0 if split == 'train': file_path = paths[(epoch - 1) % (len(paths) - 1)] else: file_path = paths[-1] dataset = FileDataset(file_path, self.cfg.selected_cols) self.datasets[split] = QQPDataset( split, dataset, self.bpe, self.src_dict, self.tgt_dict, max_src_length=self.cfg.max_src_length, max_tgt_length=self.cfg.max_tgt_length, constraint_trie=self.constraint_trie, prompt_type=self.cfg.prompt_type ) def build_model(self, cfg): model = super().build_model(cfg) self.constraint_trie = Trie(self.tgt_dict.eos()) for i, answer in enumerate(self.ans2label_dict.keys()): answer_item = self.tgt_dict.encode_line( line=self.bpe.encode(' ' + answer), add_if_not_exist=False, append_eos=False ).long() self.constraint_trie.insert([self.tgt_dict.bos()] + answer_item.tolist() + [self.tgt_dict.eos()]) return model def build_generator( self, models, args, seq_gen_cls=None, extra_gen_cls_kwargs=None, prefix_allowed_tokens_fn=None, ): seq_generator = super().build_generator(models, args, seq_gen_cls, extra_gen_cls_kwargs, prefix_allowed_tokens_fn) seq_generator.constraint_trie = self.constraint_trie return seq_generator def valid_step(self, sample, model, criterion): loss, sample_size, logging_output = super().valid_step(sample, model, criterion) model.eval() with torch.no_grad(): net_output = model(**sample["net_input"]) net_output[0].masked_fill_(~sample["constraint_masks"], -math.inf) last_token_ids = sample["net_input"]["prev_output_tokens"].ne(self.src_dict.pad()).sum(1, keepdim=True) - 1 logits = net_output[0].gather(1, last_token_ids.unsqueeze(2).expand(-1, -1, net_output[0].size(2))) logits = logits.squeeze(1) predicts = logits.argmax(1).tolist() hyps = [self.bpe.decode(self.src_dict[predict]).strip() for predict in predicts] scores = [ref_dict.get(hyp, 0) for ref_dict, hyp in zip(sample['ref_dict'], hyps)] TP = sum([ref_dict.get(hyp, 0) if hyp == 'yes' else 0 for ref_dict, hyp in zip(sample['ref_dict'], hyps)]) FP = sum([1 - ref_dict.get(hyp, 0) if hyp == 'yes' else 0 for ref_dict, hyp in zip(sample['ref_dict'], hyps)]) FN = sum([1 - ref_dict.get(hyp, 0) if hyp == 'no' else 0 for ref_dict, hyp in zip(sample['ref_dict'], hyps)]) logging_output["_score_sum"] = sum(scores) logging_output["_score_cnt"] = len(scores) logging_output["_TP"] = TP logging_output["_FP"] = FP logging_output["_FN"] = FN return loss, sample_size, logging_output def reduce_metrics(self, logging_outputs, criterion): super().reduce_metrics(logging_outputs, criterion) def sum_logs(key): import torch result = sum(log.get(key, 0) for log in logging_outputs) if torch.is_tensor(result): result = result.cpu() return result def compute_acc(meters): score = meters["_score_sum"].sum / meters["_score_cnt"].sum score = score if isinstance(score, float) else score.item() return round(score, 4) def compute_f1(meters): score = 2*meters["_TP"].sum / (2*meters["_TP"].sum + meters["_FP"].sum + meters["_FN"].sum) score = score if isinstance(score, float) else score.item() return round(score, 3) if sum_logs("_score_cnt") > 0: metrics.log_scalar("_score_sum", sum_logs("_score_sum")) metrics.log_scalar("_score_cnt", sum_logs("_score_cnt")) metrics.log_scalar("_TP", sum_logs("_TP")) metrics.log_scalar("_FP", sum_logs("_FP")) metrics.log_scalar("_FN", sum_logs("_FN")) metrics.log_derived("acc", compute_acc) metrics.log_derived("F1", compute_f1)
StarcoderdataPython
1723076
<filename>PopUp.py from PyQt5.QtWidgets import QWidget, QMessageBox from PyQt5 import QtCore class PopUpWrapper(QWidget): def __init__(self, title, msg, more=None, yesMes=None, noMes=None, actionWhenYes=None, actionWhenNo=None, parent=None): super().__init__() self.width = 320 self.height = 200 if parent is None: self.parentless = True app = QtCore.QCoreApplication.instance() screen_resolution = app.desktop().screenGeometry() self.scr_width, self.scr_height = screen_resolution.width(), screen_resolution.height() self.setGeometry((self.scr_width - self.width) / 2, (self.scr_height - self.height) / 2, 300, 400) else: self.parentless = False self.left = parent.width()/2 - self.width/2 self.top = parent.height()/2 - self.height/2 self.title = title self.msg = msg self.actionWhenYes = actionWhenYes self.actionWhenNo = actionWhenNo self.yesMes = yesMes self.noMes = noMes self.more = more self.loaded = False if self.more is not None and self.yesMes is None: self.infoWindow() else: self.questionWindow() def questionWindow(self): self.setWindowTitle(self.title) if self.parentless: self.setGeometry((self.scr_width - self.width) / 2, (self.scr_height - self.height) / 2, 300, 400) else: self.setGeometry(self.left, self.top, self.width, self.height) buttonReply = QMessageBox.question(self, self.title, self.msg, self.yesMes | self.noMes, self.yesMes) if buttonReply == self.yesMes: if self.actionWhenYes is not None: self.actionWhenYes() else: if self.actionWhenNo is not None: self.actionWhenNo() self.show() def infoWindow(self): self.setWindowTitle(self.title) if self.parentless: self.setGeometry((self.scr_width - self.width) / 2, (self.scr_height - self.height) / 2, 300, 400) else: self.setGeometry(self.left, self.top, self.width, self.height) infotext = QMessageBox.information(self, self.title, self.msg, QMessageBox.Ok) if infotext == QMessageBox.Ok: if self.loaded: self.close() else: self.infoWindow() self.show()
StarcoderdataPython
61768
<filename>django/docs/ref/models/instances.txt.py XXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXX XXXXXXXX XXXXXXXXX XXX XXXXXXX XX XXX XXXXXXXXX XXXX XX XXXXXX XX XXX XXXXXXXX XXXXXXXXX XX XXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXX XX XXXXXX XXXXXXXX XXXX XX XXXX XXX XXXXXXXXXX XXXXX XXXXXXXXX XXXXXX XXXXXXX XXXX XXXX XXXXXXXXXX XXXX XXXXXXXXX XXXXX XXX XXX XXXXXXXXXXXXX XXXXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XX XXX XXXXXXXXXXXXXX XXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXXX XXXXXXXXXXXXXXXX XX XXXXXX X XXX XXXXXXXX XX X XXXXXX XXXXXXXXXXX XX XXXX XXX XXXXX XXXXXX XXXXXX XX XXXXXXX XXXXXXXXXXXXXXX XXX XXXXXXX XXXXXXXXX XXX XXX XXXXX XX XXX XXXXXX XXXXXX XXXXXXX XX XXXX XXXXXX XXXX XXXX XXXXXXXXXXXXX X XXXXX XX XX XXX XXXXXXX XXXX XXXXXXXXX XXX XXXXX XXX XXXX XX XXXXXXXXXXXXXXXXXXXXXX XX XXXXXX XXX XXX XX XXXXXXX XX XXXXXXXXX XXX XXXXX XX XXXXXXXXXX XXX XXXXXXXXXXXX XXXXXXX XX XXX XX XXX XXXXXXXX XXXX XXXX XXX XX XXXXXX XXX XXXXXXX XXXXXXXXX XX XXX XXXXXX XXX XXXXXXX XXX XXXXX XXXXXXXX XXXX XXXXX XXXXXX XXXXXX XXXX XXXXXXXXXX XXXXXXXXXXXXX XXX XXXXX XXX XX XXXXX XXXXXXXXXXX XX XXX X XXXXXXXXXXX XX XXX XXXXX XXXXXXX XXXX XXXXXXXXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXXXXX XXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXX XXX XXXXXXXXXXX XXXXXXX XXXX X XXXXXXXXXXXXXXXX X XX XXXXXXXXX XXXX XXX XXXX XXXXXX XXXX XXXX X XXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXX XX XXX X XXXXXX XX X XXXXXX XXXXXXX XXXXXXXX XXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXX XXXXXXX XXXX X XXXXXXXXXXXXXXXXXXXXXXXX X XX XXXXXXXXX XXXX XXX XXXX XXXXXX XXXX XXXXX XXXXXXXXXXXXXXXXXXX XXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX X XXXXXXXXXXXXX XXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXX XXXXXXXXXXX XXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXX XXXXXXX XXX XXXXXXXXXXXXX XXXXXX XXX XX XXXX XX XXXXXXXXX XXXXX XXXXXXXX XXXXXXXX XXXX XXXXXXX XXXX XXX XXXXXXXXX XXX XXXXXX XXXXXXXX XXXXXXXX XXX XXXXXXXX XXXXX XXX XXX XXXXXXXX XXX XXXXX XX XXXXXX XXXXX XXXXXXXXXXXXXXX XXXXXXXX XXX XXXXX XX XXX XXXXXX XXXXXXX XXX XXXXXXXXXX XXXXXXXX XXX XXXXXX XXXXXX XXX XXXX XXXXX XX XXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXX XXX XX XXX XXXX XXXXX XX XXX XXXXXXXXXXX XX XXX XX XXX XXXXXXX XXXXXX XXX XXXXXXXX XXXX XXXXXXXXXX XXX XXXXXXXXXX XX XX XX XXX XXXXX XXXXXXXXXXXXXX XXXXXXX XXXXX XXXX XXX XXX XXXXXXXX XXX XX XXXXXXX XX XXXXXXXXXXXXXXXXX XX XXX XXXXXX XXX XXXXXXXXX XXXX XXXXX XXXXXX XX XXXXXXXXXXXXXXXX XX XXXX XXXXX XXXXXX X XXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXX XX XXX XXXXXXX XXXXXXX XX XXXXXXXX XX XXXXXXXX XXX XXX XXXXXX XXX XXXXXXXXXXXXX XXXXXX XXXX XXX XXX XXXXXXXXXX XXX XXXXXX XXXXX XX XXX XXX XXXXXXXXXX XXXXXXXXXX XXXXXXXXXX XXXXX XX XX XXXXXXX XXXXXXX XXX XX XXXXXX XXX XXXXXXX XXXXXX XX XXXXXX XXXX XXX XXXXXX XXXX XXX XXXXXXXXXX XXXX XXXXXXXXXXXXXXXX XXXXXX XXXXXXXX XXXXXXXXXXXX XXX XXXXXXXXXXXX XXX XXXXXXXXXXXX XXXXXXXX X XXXXXXX XXXXXXXXXXXXXX XX XXXXXXXXX XXXXXXXX XX XXXXXX XXX XXXXX X XX XXXXXXXX XXXX XXXXXXXXX XX XXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX X XXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXX X X XXXXXXXXXXXX XX XXXXXXXXX XX XXXXXXXXXXX XXXX XXXXXXXX XXX X XX XXXXXXXXXXXXXXXXXXXXXXXXX X XXXXXXXX X XXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX X XXXXX XXXXXXXXXXXXXXXXXX X XX X XXXXXXXXXXXXX XX XXXXX XXX XXXXXXXX XXXXX XXXXXX XX XXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX X XXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXX XXXXXXXX XXX XXXXXXXXXX XXXXXX XXXXXXXXXX X XXXXX XXX XXX XXXXXXX XXXXXX XXXXXX XXXX XXXXXXXXXXXXXXXX XXX XXXXXXXX X XXXXXXX XXXXXXXX XXX XXXXXXXXXX XX XXX XXXXXX XXXXX XXXXXXX XXXXXXX X XXXXXXX XXXXX XXXXX XXXXXXXXXXXX XX XXXXXXXXXX XX XXX XXXXXXXXXXXXXXXXXX XXX X XXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXX XXX XXXXX XX XXXXXXX XXXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXX XXX XXXXXXX XXXXX XXXXX X XXXX XXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXXXX XXX XXXX XX XXXXX XX XXXX XXXX XX XXXXX XX XXXXXXXX XX XXX X XXXXXXXXXXX XXXX XX XXX XXXXXXXXXXXXX XXXXXXX XXXXXXXXXX XXXXXXX XXXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXX XXXXXX X XXXXX XXXX X XXXXX XXXXXXXXX XXXXXXXXX XX XXXXX XXXXXXX XXX XXXXX XXXX XXX XXXXXXXXXX XXX XXX X XXXXXXXXXXXXXXXXXXXXXXX XXX XXX XXXXXXXXX XXX XXXXXXXXX X XXXXX XXX XXXXX XXXX XXX XXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXX XX XXX XXXX XX XXXXXX X XXXXXXX XXXXXX XXXX XXX XXXXXXXXX XXX XXX XXX XXX XXXXXXXXXXXXXXXXXXXXX XXXXXXX XXXX XXXX XXXXXX XX XXXXXX XXXXXXX XXXXXXXXX XXX XXXXXXXXX XX XXXXX XX XXX XXXXXXXXXXXX XXXXXX XX XXX XXXXX XXX XXXXXXX XX XXX XXXXXX XXXXXXXXX XXXXXXX XX XXX XXXXXXXXX XX XXX XXXXXX XXXXXXXXX XXX XXXXXXX XXXX XXX XXXXXXXX XXXXXXXXX XXXX XXXXXX XX XXX XXXXX XXX XXXXXXXX XXXX XXX XXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXX XXXXXX XXXX XX XXXXXXXXXXX XXXXXX XXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XXXXXX XXXXXXX XXXXXXX XXX XXXXXXXXX XXXXXXX XXXX XXX XXXXXXXX XXX XXXXXXXX XXX XXXXXX XXXXX XX XXXX XXX XXXXXXX XXXXXXXX XX XXX XXXXXXXX XXXXXX XXXXXX XXXX XXX XXXXXXXXX XXX XXXXXXXXX XXXXXXXX XXX XX XXXX XX XXXXX XXX XXXXXXXX XXXX XXX XXXXXXXXXX XX XX XXXXXXXX XX XXXXX XXX XXX XX XXXXXX XX XX XXXXXX XX XXXXX XXX XXXXXXXXXX XXXXXXXXX XXX XXXXXXXX XX XXXX XXXX XX XXXXXXXXXXXX XXXX XXXXXXXX XX XXX XXXXXXXX XXXXXXX XXX XXXXX XXXXX X XXXX XXXXXXX XX XXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXX XXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X XX X XX XXXX XXXXX XXXXXXX XX XXXXX XX XXX XXX XXXXX XX XXX XXXXXXXX X XXX XXXXXXX XX XX XXX XXXXXXXX XXXXXXX XXXXX XXXXX XX XX XXXXXXXX X XXXX XXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XX XXXX XXXX XXXX XXXXXXXX XXXXXX XXX XXXXXXXXX XXX XXXXXXX XX XXX XXXXXXXX XXXXXXX XXXXX XXXXXXX XXXXXXX XXXX XXXXXXX XXXX XX XX XXXXXXXX XX XXXXXXXXX XXX XXX XXXXXXXX XXXXXXX XXXXXXXX XXX XXXXXXX XXXXX XXXXX XXX XXX XXX XXXXXX XXX XX XXX XXXXXXXXXX XXXXXX XXXX X XXXXXXXX XXXXX XX XXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXX X XXXXXX XXXXXXXX XXX XXXX XX XXX XXXXXXXX XXXXX XX XX X XXXXXXX XX XXXXXX XX XXX XXXXX XXXXXX X XXXXXXXXXXX XXXXXXXXXXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXX X XX XXX XXXXXXXX XXXXX XX XXXXX XX XX XXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X XXXX XXXX XXX XX XXXX XXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX XXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX X XXXXXX XXXXXX XXXX XXXXXXX X XXX XXXXXXXXXX XXX XXXXXXXXX XXXXX XX XXX XXXXX XXXXXX XXXX XXX XXXXXXXXX XXXXXXXX XXX XXXX XXXXXX XX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXX XXXXX XXX XXXXX XXXXX XXXXXXXX XX XXXXXXXXXX X XXXXXX XX XXXXXXXX XXX XXXXX XXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXX XXX XXXXX XX X XXXXX X XXXXXXXXXXXXXXXXXXXXX XX XXXXXXXX XXX XXXXX XXXXXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXX XXXXX XXX XXXXXXXXX XXXX XXX XXXX X XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX XXXX XXX XXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXXX XXXXX XXXXXXXXXX XXXXX XXX XXX XXX XXXXXX XXXX XXX XXXXXXXX XX XXX XXXXX XXX XXX XXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXX XXXXXXXXXXXX XXX XXXXXX XXXX XXXX XX XXXX X XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XX XXX XXXX XX XXXXXX XXXXXXXXXX XXXXXX XXXXXXXXX XX XX XXX XXXX XXXXXXXX XXXXXX XXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXXX XXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXX XXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXX XX XXXXXXXXXX XX XXXX XXXXX XXX XXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXX X XXXXXXXXXXXXXXXX XXXXXXXXX XXXXXXXXXX XXXXXX XXXX XXX XXXXX XXXXXXX XXX XXXXXXXX XXXXXXXXXXX XXXXXXXX XXX XX XXXX XX XXXXXXX X XXXX XX XXXXX XXXXX XXXX XXX XX XXXXXXXX XXXX XXXXXXXXXX XXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXXXXXX XX XXXXXXX XXXXXX XXXX XXXXXX XXXXXXX XX XXXX XXXX XXXX XXXXX XXXXXXXXX XXXXX XXX XXXXXX XXXXXX XXXXX XXX XX XXXXXXXXX XX XXX XXXXX XXXX XXXX XXXXXXXXXXXXXXXX XXXX XXXXX XX XXXXXX XXXXXXXXXXXXX XXXX XXX XXXX XXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXX XXXXXX XXXX XX XXXX XX XXXXXXXX XXXX XXX XXXX XX XXX XXXXXXXX XXXXX XXXXXXXXXX XXX XXXX XXX XXXXXXXX XXXXXXX XXXXXXX XXX XXXXXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXX XXXX XXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXX XX XX X XX XXXXXXXXX XXXXX XX XXX XXXXXX XXXXXXXXX XX XXXXXXXXXXXXXXX X XXXXXXX XXXX XX X XXXXX XX XXXXXX XXXX XXXXXXXXXXXXXXXXX XXXX XXX XXXXX XXXX XXXXXXXXXXXXXXXX XXXXXXXX XX XX XXXXX XXXX XXXXXXXXXX XXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXX XXXX XXXXXXXX XXX XXXXXX XX XXXX XXXXXX XXX XXXXXXXX XXXXXXXXXXX XXXXXXXX XXXX XXX XXXXXXX X XXXX XX XXXXX XXXXX XX XXXXXXX XXXX XXXXXXXXXXX XX XXXX XXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXX XXXXXX XXXX XXXXXXXXXXX XXX XXXXXX XXXX XXXXXXXXXXXXXXXX XXXXXXXX XX XX XXXX XXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXX XXXXXX XX XXXXXXXXXX XX XXXXXXX XXXXXX XXXXXXXXXX XX XXXX XXXXXX XX XXXXXXXX XXXXXXXXXXXXX XXXX XXXXXX XXXXXX XX XXXX XX XXXXXXX XXXXXX XXXXX XXXXXXXXXXX XXX XX XXXXXX XXXXXXXXXX XX XXXX XXXXX XX XXXXXXXX XXX XXXXXXXXX XXX XXXXX XXX XX XX XXXXXXXXXXXXX XXXXXXX X XXXXX XXX X XXXXXX XX XX XX XXXXXXXXXX XXXX XXXXXXXX XXXXXX XX XXXX XXXX X XXXXXX XXXXXXX XXXXXX XXXXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXX XXXX XXXXXXXXX XXXXXX XXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXX XX X XXXXX XXXXXXXXXXXXXXXXXXXXXX XXX XXX XXXXXXXXXXXX X XXXXX XXXXX XXXXX XXXXXXX XX XXXX X XXXXXXXXX XX XXXXXXXXXXX XX XXXXXXX XXX XXXXXXXXXXXXX XX XXX XXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX XXX XXX XXXX X XXXXXXXXXXX XXXXXXXX X XXX XXX XXXXXXXX XXX XXXXXXXXX XXXXX XX XX XXXXXX XXXX XXX XXXXXXXX XX XXXXXXXXXXX XX XXXXXXXXXXX XXX XXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXX X XXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXX XXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX X XXXXXXX XXXXXXXXXXX XXXXXX XX XXX XXXXXXX XXXX XXX XXXX XXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXX XX XXX XXXXX XXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XXXXXX XX XXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXX XXXX X XXXXXXX XX XX XXXX XX XXXXXX XX X XXXXXXX XXXXX XXXXXXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXX XX XXXX XXX XXXXXX XXXX XXX XXXX XX XXX XXXXXX XXXXX XXXXXXX XX XX X XXXXXXXX XXXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXX XXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXX XX XX XXXXXXXXXXXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXX XXXXXXXXXX XX X XXXXXXXX XXXXXX XXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX X XXXXXXXXXXX XXXXX XXX XXXX XXX XXX XXXXX XXXXXX XX XXXXX XXXXXX XXX XXXXXXXX XXXXXXX XX XXXXXX XXX XXXXX XX XXX XXXXXXXXXXXX XXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXX XXX XXX XXXXXXXXXXXX X XXXXX XXXXX XXXXX XXXXXXX XX XXXX X XXXXXXXXX XX XXXXXXXXXXX XX XXXXXXX XXX XXXXXXXXXXXXX XX XXX XXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXXX XXX XXX XXXX X XXXXXXXXXXX XXXXXXXXX XXX XX XXX XXXXXX XXXXXX XX XXXXXXXX XXXXXX XXXXXX XXXXXXXXXXXXXXXXXX XXX XXX XXXX XXXX X XXXXXXXXXX XXXXXXX XXXXX XXXXX XX XXXXXXXX XXXXX XXXXXXXXXXXXXXXXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXXXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXX XXXX XXXXX XXX XXXXXX XXXXXXXXXXX XX XXXX XXXXXX XX XXXXXXXXXXXX XXX XX XXXXX XXXXXXXXXXXXXX XXXXXXXXXX XXXXXX XX XXXXX XXXXXX XXXXX XXXXXX XX X XXXXXXXXXXXXX XXX XXXXX XXXXX XXXXXXXXXX XXXXXX XX XXXXXXXXXXXXXXXXX XXX XXXXXX XXXX XXXXX XXXXXX XX X XXXXX XXXX XX XXXX XXX XXXXX XXX XXXXXX XXXXX XXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXX XXXXX XX XXXX XXXXX X XXXXXXXXXXXXXX XXXXXXX XXX XXXXXXXXXX XXXXX XXXXX XX XXXX XX XX XXXXXXXXXX XXXX XXX XXXXXXXX XXXXXX XX XXXX XXXXXX XXXX XXXXXXXX XXXXXXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XXXXXXXX XXX XXXX XX XXXXXX XXXX XXX XXXXXXXX XXXX XXXXXXXXXXX XXX XXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXX XXX XXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXX XX XXXXXXX XXX XXXXXXXXXXXXX XX XXX XXXXX XX XXXXXXX XXX XXXXXXXX XX XXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXX XXXXXXX XXX XXX XXXX X XXXXXXXXXXX XXXXXXX X XXXXX XXXXX XXXXXXXXXXXXXXXXX XXXXXXXXX XX XXXX XXXXXX XX XXXXX XX XXXXX XX XXX X X XXXXXXXXXXXX XXXXXX XX XX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXX XX XXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXX XXX XXXXXXXXXX XXXXXXXXXXX XX XXXX XXXXX XXXXXXX XX XXXXXXXXXX XXXXX XXXXXXX XXX XXXXXXXX XXXXXXXXXXX XXXXXXXX XXXXXX XXX XX XXXXXXX X XXXX XX XXXXX XXXXX XX XXXXXXX XXXX XXXXXXXXXXX XX XXXX XXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXX XXXXXX XXXX XXXXXXXXXXX XXXX XXXX XX XXX XXXXXXX XX XXXXXXXXXXX XXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XXXXXXXXX XXX XX XXX XXXXXX XXX XXXXXXXX XXXX XXX XX XXXXXXXX XXXXXX XXXXXXX XXXXXXXXXXXXXX XX XXXX XX XXXXXX XXXX XX XXX XXXXXXXXX XXXX XXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XX XXX XXXX XXXXXXXXXX XXXXXX XXXXXXXXX XXX XXX XXXXXXXX XXXX XXXXXXXXXX XXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXX XXXXXXXX XXX XXXXX XXXX XXXXXXX XXXX XXX XXXX XXXXXXXXXXX XXX XXX XXXXXXXX XXXXXX XXXXXXXXXXXXXXXXX XXXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX X XXXXX XXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X XX XXXXXXXXXXXXXXXXX XXXXXXX XXX X XXXX XXXX XXXXXXXXXXXXXXXX XXXXX XXXX XX XXXXXXXXXX XXX XXXXX XX XX XXXXXXXXX XX XXXX XXXXXX XXX XXXXX XXXX XXX XXXX XXXXXXXXXXXX XXX XX X XXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXXXX XX XXXXXXXXX XXX XXXXX X XXXXXXX XXXXX XXXXXXX XX XXXXXXX XXXX XX XX XXXX XXX XXXXXXXXX XXX XXXXX X XXXXXXX XXX XX XX XXXX XXX XXXXXXX XXXXXXX XX XXX XX XXXX XXXX XXX XXXXX XX XX XX XXXX XX XXXXXX XXX XXXX XXXXXXXXXXX XXXXXXX XXXX XXXXX XX XXXXXXXXXX XX XXXX XXXXXXXXX XXX XX XXXXXXX XXX XXXXXXXXXXXX XXXX XXXXX XXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXX XX XXXXXXX XXXXXX XXX XXXXXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXX XX X XXXXX XX XXXX XXXXXX XXX XXX XXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXX XXXXXXXX XXX XXXXXX XXXXXXXX XXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXX XXXXXXXX XXXXXXXXXX XX XXXXXXX XXX XXXXXX X XXXXXXX XXX XXXXX XXXXXXXXX XX XXX XXXXXX XXXXXX XXX XXX XXXX XXXX XXXXX XXXX XXXX X XXXXXXXX XXXXXX XXXXXXX XX XXXXXXX XXXX X XXXXXX XXXXXXXXX XX XXX XXXXXX XXX XX XXXXXXXX XX XXXXX XXX XXXXXXXXX XXXXXXXXX XX XXX XXXXXXX XXX XXXXX XXX XXX XXXXXX XXX XXX XXXX XXX XXX XXXX XXXXXX XXXX XX XXX XXXXX XXX XXX XXXXX XXXXXXXXXX XXX XX XXXX XXXXXX XXX XXXXXXX XXXXX XX XXX XXXXXX XXXXXXXXXX XXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX X XXXXX XXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXX XXXX XX XXXXXX X XXX XXXXXXXX XX XXXXXXXXXX XXXX XXXXXXX XXXXXX XX XXXXXXXXXX XXXXXX XXXXXXX XXXXXX XXXX XXXXXXX XX XXX XXXXXXXXXXXXXXX XX XXX XXXX XXX XX X XXXXXXXXXX XXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXXXX XX XXXXXXXXX XXX XXXXX X XXXXXXX XX XXX XXXXXXXXX XXX XXXXX X XXXXXXX XX XX XXX XXXXXX XXXXXXXXXXXXXXXX XXXXXX XXXXXXXXX XXXX XXXX XXX XX XXX XX XXXXXXXXXXXXXXXX XXXXXXXXXXX XXXXXX XX XXX XXXXXX X XXX XXXXXX XXXX XX XXXXXXXX XXXXXXXXXXX XXXXX XXXX XXXXXXX XXXXXX XX XXX XXXXXXXXX XXXXXX XXXX XXXXXX XXXXXX XXXXXXXX XXX XXXXXXXX XXXXXX XXXXXX XXXX XXXXXXXX X XXX XXXX XXXXX XXX XXXXX XXXXXXXXXX XXXXXXX XXXX XXXXXXXX XXXX XXXXXXX XXXXX XXXXXXXX XXX XXXXXXXX XXXXXX XX XXX XXXXXXXXXX XX X XXXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXXXX XXX XXXXXXXXX XXXXXXXXX X XXXXXXXXX XXX XXXXXXXX XXXX XXXX XXXXX XXX XXXX XXXXXX XXXXX XX XXXXXX XXX XXXXXXXXX XXXXXX XXX XXX XXXXXX XXXX XXXXXXXX XXXXXXXXXX XXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXX XX XXXXXX XXXXXX XXX XXXXXXXXXXX XXXXXXXX XXXX XXXXXX XXXXXXXXX XXX XXXXX XXXX XXXXXXXXXXX XXXXXXXXXX XX XXXXXX XXXXX XXXXXXXXXXX XXX XXXXXXXX XXXXXXXXXX XXXX XXX XXXXXXX XXX XXXXX XXXX XX XX XXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXXX XXXX XXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXX XXXX XX XXXXXXX XXXXXX XXXXXXXX XXX XXXXXXXXX XXXXXX XX XXXXXX X XXXXXXXX XXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XX XXXXX XXXXXXXX XXX XXXXXXXXX XXXXXXXXX XXX XXXX XXXXXX XX XX XXXXXXXXXX XX XXXXXXXXXXXX XXX XXXXXXX XXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XX XXXXXX XX XXXXXXX XXX XXXXXXXXX XXXX XXXXXXXXXXXX XXXXXX XXXXXXX XXX XXXXXXXX XXX XXXXXXXXX XXXXXX XXXXXXXX XXXXXXXXXXXXXX XX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXX XXX XXXX XXX XXX XXXXXXXXXXX XXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XX XXXXX XX XXXXXXX XXX XXXXXXX XXXXX XX X XXXX XXXX XXXX XXX XX XXXXXXX XX XXX XXXXXXXXX XXXX XXXXXX XXXXX XXXXXXX XXXX XXXXXXXXXXXX XXXXXX XXXX XXXXXX XXXX XX XXXXXXXX XXX XXXXXXXX XXX XXXXXX XX XXXXXX XX X XXXXXX XXXXXXX XXXXXXXX XXXX XXXXXXX XXXX XXXXX XXXXX XXXXXXX XXXX XXXXXXXXXXXXX XXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXX X XXXXXX XXXXXXXXXXXX XXXXXX XX XXXXX XXXXX XXXXXXXXX XXXXX XXXXX XXXXXXXXXXXX XXXXXXXX XX XXX XXXXX XXXXX XXXX XX XXXXXXXXX XXXX XX XXXXXXXXXXXXX XXXX XXXXXX XXX XXXXXXXXX XXXX XXX XXXXXXXXX XX XXXXXXXX XXX XXXX XXXX XXX XXXXXXXXXXX XXX XXXXXXXXXXXXX XXXXXXXX XXXX XX XXXXXXXX XXXX XX XXX XXXXXXXXX XXX XXXXXXXXX XXXX XXX XXXXXXXXX XX XXXXXX X XXXXXXXXX XXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XX XXXXX XXXXXXXX XXX XXXXXXXXX XXXXXXXXX XXX XXXX XXXXXX XX XX XXXXXXXXXX XXX XXXXXX XXXXX XX XXXXXX XXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXX XXXX XXXXXXX XXXXXX XXXXXXXX XXXXXXX XXX XXX XXXX XXXXXXXXXX XXXXXX XXX XXXXXXXX XXX XXXXXXXX XXXXXXXX XXXXXX XXXXXXXXX XXX XXXX XX XXX XXXXXXXXXX XX XXXXXXXXXX XXX XXXXXXXXXXX XXXXXXXXXXXXX XXXX XXX XXXX XXXXXXXXXX XXX XXX XXXXXXXX XXXXXXX XXX XXXXXXXXX XXXX XXXXXXX XXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXX XXXX XXXXXXXXXX X XX XXX XXXXXXXX XXXXXXX XXX XXXXXXXXX XX XXX XX X XXXXX XXXX XXXXXXXXX XX XXXXXXXX XXXXXX X XXXXX XXXXX XXXX XXXXXXXX XX XXX XXXXX XXXXXXXX XXXXXX XXXXXXXX XX XXXXXXXXXXX X XX XXX XXXXXXXX XXXXXXX XXX XXXXXXXXX XX XXXXX XXX XX XX XXX XXXXXXXXXX XXXXXX XXXXXX XXXXXXXX XXXXX XX XXXXXXX XXX XX XXX XX X XXXXX XXXX XXXXXXX XXXXX XX XXX XXXXXXXXXX XXXXXX XXXXXXXX XX XXXXXXXXXXX XX XXX XXXXXXXX XXXXXXX XXX XXXXXXXXX XXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXX XXXXXXXX XX XXXXXXXXXX XX XX XX XX XXXXXXXX XXXXX XXXXXXXX XXX XXXXXXX XXX XX XXX XX X XXXXX XXXX XXXXXX XX XXX XXXXXXXXX XXXXXXXXXX XXXXXX XXXXXXXX XX XXXXXXXXXXX XXX XXX XXXXXX XXXX XX XXXX XXX XXXXXX XX XXXXXXX XXX XX XXXXXXX X XXXXXXXXXXX XXXXX XXXXXXXXXX XXXX XXXXXX XXX XXXXXXXX XX XXX XXXXXX XXXXXXXXX XXX XXXXXXXXXXX XXXXX XX XXXXXXX XXX XXXX XX XXXX XXXXXXX XXX XXXXXXXXXXX XXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXX XXXXX XXX XXXXXXXX XX XXXXXX XX XXXXXXXX XXXXXX XX XXXXXX XXX XXX XXXXXXXX XXXXXX XXX X XXXXXXXXXX XXXX XXX XXXXXXX XXX XXXXXXXXX XXX XXXX XX XXX XXXXXXXXXX XXXXX X XXXX XXXX XXXXXX XXX XX XXXXXXXXXXX XXXXXXXXX XX XXX XX XXXXXXXXXXX XXX XXX XXXXXXXXX XXXXXXX XX XXX XXXX XXXXX XX XXX XXXXXXXXXX XXXXX XXXXX XXX XXXX XXXX XXXXX XXXXX XXX XXXXXXXX XXXXXXX XXXXXX XXXX X XXX XXX XXXXXXX XXXX XX XXX XXXXXXXX XXXXXXXX X XXX XXX XXX XXXXXXXX XXXXXXX XXX XXXXXX XX XXXXXXX XX XXX XXXXXXXXXX XXXX XXXXXXXX XXXXXXX XXXXX XXXXXXX XXXXXXXXX XX XXXX XXXXX XX XX XXXXXXXX XX XXXXXX XX XXX XXX XXXXXXXXX XX XXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XX XXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX XX XXXXXX XX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXX XXXX XXXXXXXXXXXXXX XXXX XXXXXXXXX XX XX XXXX XX XXXXX XXX XXXXXXXXXXXXXXXXXXXXX XXXXXX XX XXXXXXX XX XXX XXXXXXXXXX XXX XXX XXXX XXXX XX XXXXX XX XXXXXXXXXXX XX XXXXXXXXXXX XXXXXXX XX XXXXXXXXX XXX XXX XXXXXX X XXX XXXX XX XXXXX XXXXX XXX XXX XXXX XXX XXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XX XXX XXXXXXXXXXXXXXXXXXXXX XXXXXXX XXXXXXX XXXX XXXXXXXXXX XX XX XXXXXX XXX XXXXXX XXXX XXXXXX XXXXX XXXXXX XX XXX XXXX XXXXX XX XXXXXX XX XXXX XXXX XXXX XXXXXX XXXX XX XXX XXXXX XXXXXXXXXXX XXXXXX XXXX XXXXXX XXXXXX XX XXX XXXXX XXXXX XXX XXXXXX XX XXXXXXXX XXXX XXXX XXXX XX XXXXXX XXXX XXX XXXXXXXXX XX XXXXX XXXXX XXXX XXXXXXX XX XXX XXXXXXXX XXX XXXXX XXXXX XXXXXXXXXXXXXXXXX XXXX XXXXX XX XXXXXX XXXXXXXXX XX XXXXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXXXXXX XXXXX XX XXXXXXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XXXXXX XXXX XX XXXXXXX X XXXXXX XXXXXXXXXX XXXX XX X XXXXXX XXXX XX XXXXXXXXXXXX XX XXXXXXXXXXXX XXX XXXXXXX XXXXXX XXX XXX XX XXXXXXXXX XXXX XX XXXXX XXX XXXXXXXXXX XX XXXXXX XXXXXX XXX XXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXX XXX XXXXXXXXXXXXXXXXXXX XX X XXX XXXXXXXXXXXXXX XX XXX XXX XXXXXXXXXXXXXXX XXXXX XXXXXXXXX XXXX XXX XXXXXXXX XXX XXX XXXX XXX XXXXX XX XX XXXX XX XXXXXXX XXXX XX XXX XXXXXXXXX XXX XXXXXXX XXX XX XXXX XXXXXXX XXXXXXXXXXXXXX X XXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXX XX XXXXXXXX XXXXXX XX XXXXXXXXXX XXX XXXXXX XXXXXXXX XX XXX XXXXXXXX XXXXX XXXXXX XXXXXX XXXX XX XX XXXXXXXX XXXXXXXXXX XX X XXX XXXXXX XXXXXX XXXXXXXX XXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXX XXXX XXXX XX XXXXXXXX XXXXXXX XXXXX XXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXX XXXXXXX XX XXXXXXXXX XXXX XXX XXXX XXXXXXXXXXXXXXXX XXXXXX X XXX XXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXX XXX XXXXXXXXXXXXXXXXXXX X XXXXXXXXXXXXXXXX X X XXX XXXXXXXXXXXXXX XXX XXXX XXXXXXXX XXX XXX XXXXXXXXXXXXX XX XXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXX XXXXX XXXXXXXXX XX XXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XXXXX XXXXXX XX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXX XX XXXXXX X XXXX XX XXXXX XXXXX XX XXXXXXX XXXXXXXX XXXXXXXXXXXXXXXXXX XXXX XXX XXXXXX XXXXX XX XXXX XXXX XXXX XX XXXXXXXX XXXX XXX XX XXXXXXXXX XX XXX XXXX XX XXXXXX XXXX XXX XX X XXX XXXXXX XX XX XXXXXXX XXXXX XXXX XX X XXXXXX XXXXXXXXXXX XXXXXXX XXXX XXXXXXXXXX XXX XX XXX XXXXX XXXXXX XXXX XXXXX XXXXXXX XX XXX XXXXXXXXX XXX XXXXXXXXX XXXXXXXXXXXX X XXXXX XXXXXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXX XXXXXXXX XXX XX XXX XXXXXXXX XXXXXXXXXX XXXXXXXX XX XXXXX XXXXXXXXXXXXXXXXX XXXXXXXX XXXX XXXX XXX XXXXX X XXXXX XX XXXX XXXX XXXXXXX XX XXXXXX XX XXX XXXXXXX XXXXXXXXXX XXXXXXXXXXXXXXXXX XXXX XXXXX XX XXXXXXX XXXX XXXXXX X XXXXX XXXXXXX XXXXXXX XXXXXXXX XXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXX XXXXXX XXXXXX XXXX XXX XX XXXX XXX XXXXXXXX XX XXXXXX XXXXX XX XX XXXXXXXXX XXXXXXXXXXXXXXXXX XX XXXX XXXXX XX XXX XXXXXX XX XXXXXX XXX XXXXXXXX XXXXX XXXXXX XXX XXXXX XXXX XX XXXXX XX XXX XXXXXXX XXXXXXX XXXXXXXX XXXXXXX XXXXXXXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXX XX XXX XXXXXXXXXX XXX XXX XXXXXXX XXXX XXXX XXXXXXX XXX XXXXXX XX XXX XXXXXXXXX XXX XXXXXX XXXXXXXX XXXX XXXXX XXXXX XXX XXXX XXXXX XXXX XXXX XX XXX XXXXXXX XXXX XXXXXX XXXXXXX XXX XXXXXX XX XXXXXXX XXXXXXX XXX X XXXXXXXXXX XXXX XXX XXXXXX XX XXXXXXXXX XXX XXXXXX XXXXX XXX XXXX XXXXXXXX XXXXXXXXX XXX XX XXXXXX XXXXXXX XX XXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXX XXXX XXXXXXXXXX XXXXXXXX XXXXXXXXX XXX XXX XXXXXXXX XXX XXXXXXXXXXXX XXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXX XXXXXXXX XXXXXXXXX XXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXX XXXX XX XXXXXX XXXX X XXXXX XXXXXXX XXXXX XXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXX XXXX XXX XXXXXX XXXXXXX XXXXX XXXXXXXX XXXXXXX XXXXXXXXXXXXXXXX XXXX XXX XXXXXXXXXXXXX X XXXXXX XXX XXXXXXX XXXXX XX XXXXXXXX XXXX XXX XXXXXXXX XXX XXXXX XXXXXXX XXX XXXXX XXXXXXXX XX XXX XXXXXX XX XXX XXXXXXXX XXXXXX XXXX XXX XXXX XXXXXX XXXXXXXXX XX XXX XXXXXXXXX XX XXXXXXXXXXXX XXX XXXXX XXXXX XXXXXXX XXXXXXX XXXXXXXX XXXXXXX XX XXXXXX XXX XXXX XXXXX XXX XXX XXXXXXX XX XXXXXX XXXX XXX XXXX XX XXXXXXXX XXXXX XX XXX XXXXXXXX X XXXXXX XXXXX XXXXXX XXXXXXX XX XXXXX XX XX XXXXXXXXX XXXX XXXXXX XXXX XX XXXXXXXX XXXX XXXXXX XXXXXXX XXXX XXXXXXX XXXXXX XXX XX XXXX XX XXXX XX X XXXXXXXXX XXXXXXXX XXXXXXXXX XXXXX XXXXXX XXXXXXXXXXXXX XXXXXX XXX XX XXXXXXXXX XX XXXXXXXXX XXXX XX XXXXXXXX XXXXXXXXX XXXXXXXX X XXXXXXXXXXXXXXXXXX XX XXXXXX XXXX XXX XXX XX XXXXXXXX X XXXXX XX X XXXXXX XXXXXXX XXXX XX XXXXXXXXX XXXX XXX XXX XX XXXXX XX XXX XXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXX XXXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX X XXX XXXXXX XXXXXXX XXXX XXXXXXX XXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXX XXX XXXXXXXXXXXXX XXXXXX XX XXXXXX XXXXXXXX XXX XXXX XXXXXXXXX XX XX XXXXXXX XXXXXX XXXX XXXXXXXXXXXX XX X XXXXXX XX XXXXXXX XXXX XXXXXXXX XX XXXXXXX XX XXXXXX XX XXX XXXXXX XXXXX XXXX XXX XX XXX XXXXX XXXXXXXX XXXX X XXXXXXXX XXXX XX XXXXXXXX XX XXXXXXX XXXXX XXX XXXXXX XXXXXX XXXXXX X XXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXX XXXXX XXXX XXX XXXXXXXXXXXXX XXXXXXX XXX XXXXXXXXX XXXX XXXXXXXXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXX XXXXXX XXX XXX X XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXX XXX XXXXXXXX XXXXXX XX XXXXXXX XXXX XXXX XXXXXXXXX XXXX XXX XXXX XXXXXXX XXX XXXXX XXX XXX XXXX XXXXXXXX XXXXX XXX XXXXXXXXXX XXXXXX XXXXXX XXXX XXXXXXXXX XXXX X XXXXXXX XXX XXXXX XX XXXXXXXX XXXXXX XXXXX XX XXXXXXXX XXXXXX XXXXXXXXXXX XXX XXXXX XXXXXXX XXXXXXXX XXXXX XX XXXXXXX XX XXX XXXXXXX XXXXX XXXXXXXXX XXXXXXX XXX XXX XXXXX XXXXXX XXXX XXXXXX XXX XXXXXXX XXXXXX XXX XXXXXXXXX XXXX XXXXXXXXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXX XX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXX XXXXX X XXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX X XXXXXXX XXXX XXXXXXXX XXXXXXXXXXXXX XX XXXXXXXXXXXXX XXXXXXXXXXXXX XX XXXXXXXXXXXXX X XXXXXXX XXXX XXX XXXX XXXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXX X XXXX XXXXXXXX XXXXXXXX X XXXXXXXXXXXXXXXX XXXXXXXX XX XXXXXXXX X XXXXX XXXXX XXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXX X XXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXX XXXXXX XX XXXXX XX XXX XXXXXXXXXX XXXXXXX XXX XXXXXX XX XX XXXXXXXXXXX XXXXXXXXXXXXXXXXX XX XXX XXXXXXXX XXXXXXX XXXX X XXXXXXX XXX XXXXX XXXX X XXXXXXXXXXXXX XXXX XX XXXXXX XXXXXXXXXX XXX XXXXXXXXXXXXXX XXXXXX XXXXX XXXXXX XXXXXXXXX XXXXXX XXXXXX XXX XXXXX XXX XXXXXXXX XX XXXXXX XXX XXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXX XX XX XXXXXXXX XX XXXXXXXXX XX XXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXX X XXXXXXXXXXXXXXXXXXXXXX XXXXXX XX XXXX XXXXXX XXX XX XXXXXXXXX XXX XXXXXXXXX XXX XXX XX XXXXXXX XX XXXXXXXX XXXX XXXXXX XXXXXX XXXXXX XX XXXXXX X XXXXXX XXXX XXX XX XXXX XX XXXXX XX XXX XXXXXX XXXX XXXXX XXX XXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXX X XXXXXXX XXXXX XXXX XXXX XX XXXXXXX XXX XXXXXXX XX XXX XXX XX XXX XXXX XXXXXXXX XXX XX XX XXXXX XXXX XXXX XX XXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XX XXXXXXX XXX XXXX XXXXXXXXX XXX XXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXXXXXXX XXXXXX XXXXXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXX XXXXX XXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXX XX XX XXX XXXXX XXXX XX XX XXXXXX XXXXXXX XXXX XXXXXXX XXX XXXXXXXXXXXXXX XXXX XXXX XXXX X XXXXX XX XXXXX XXXX XXXX XXXX XXXX XXX XXXXXXXX XX XXX XXXXXXXX XXXXXX XXXXX XX XXXXX XX XXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX X XXXXXX XX XXXXX XXXX XX XXXXXXX XXXX XX XXX XXXXXXXXXXXXXXXXX XXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXX XXXX XX XX XXXXXXXX XX XX XXXXX XXXXX XXX XXXX XXXXXXX XXXXXXXXX XX XXXX XXXX X XXXXXX XXXX XXX XXXXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXX XXX XXXXXX XXXXX XXXXXXXX XXX XXX XXXX XXXXXXXXXXX XXXX XXXXXX XX XXXXX XX XXXXXX XXXXXXXXXXXXX XX XXXX XX XXXXXXXX XXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXX X XXXXXXXXX XX XXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXX XXXX XXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXX XX XXXXX XX X XXXXX XXXXXX XXXXXXXX XXX XXX XXX XXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXXXXXX XX XXX XXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXX XXXXXXX XX XXXXXXXXXXX XXXX XXXXXXXX XXXXX XXX XXXXXXXX XXXX XXXXXXXX XXXX XX XXXX XX XXXXXXXXXXXX XXXXXXXXXXX XXXX XXX XXXXXXXX XXXXX XXXXXX XXX XX XXXXXXXXXXXXXXXXXXXXX XXXX XXXXXXXX XXXX XX XXXX XXXXXXX XX XXXXXXXXXXXX XXXXXXXXXXX XX XXXXXXXXXXXX XXX XXXXX XXXX XX XXXX XX XXX XXXXXX XXX XXX XXXXXXXXX XX XXXX XXXXXXXX XXXX XXX XXXXXXXXX XXXXX XXXX XXXXXXXXXX X XXXXXXXX XXXXXX XXX XXXXX XXXX XX XXXX XX XXXXX XXXX XXXXX XXXXX XXXX XXX XXX XXXXX XX XXXXXXXX XXXXXXX XX XXXXX XX XXXXXXXXXXXXXXXXXXXXXX XXX XXXX XXX XXXX XXXXX XXXX XXXX XXXX XXX XXXXXX XX XXXXXX XXX XXXXXX XXX XXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXXX XXXX XXXXX XXXXXXXXXX XXXXXXXXX XX XXX XXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXX XX XXXXXXXXXXXX XX XXXXXXXXXX XXXX XXX XXXXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXX XX XXXX XX XXX XXX XXXXXX XXXXXXXX XXXXXXX XXX XXXXXXX XXXXXXXXXXX XXX XXX XXXX XX XXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XX XXXX XXXX XXXX XX XXX XXX XXXXX XXXXXXX XXXXXXXXXX XXXXXXXXXX XXXXXXX XXX XXXXX XXXXXX XXXXX XXXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX X XXXXX XXXXXX XXXXX XXXX XXXX XX XXX XXXXXXXXX XXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XXX XXXXX XXXXX XXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXX XXXXXX XXXX XXXX X XXXXXXXXXXXXXXXXXXXXX XXXXXXX XXXXX XXXXXXX XX XXX XXXX XX XXX XXXXXX XXXX XXXXXX XXXXXXX XXX XXXXXXXXXXXXXXXX XXXXX XX XXX XXXXXX XXX XXXXXXXXX XXXX XXXXXXXXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXX X X XXXXX XXXXXXXXX XXXXX XXXXXXXXXX XXXXX XXXXXXXXX X XXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XX XXX X X XXXXXXXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXXXXX XXX XXXXXXXX XXX XXXXXXXXXXXX XXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX XX XXXXXXXXXXXXXXXX XXX XXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXX XXX XXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXX XXXX XXXX XXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXX XXXXXXX XX XXX XXXX XX XXX XXXXXX XXXX XXXXXXX XXX XXXX XXX XXXXXXXX XXXXXX XXXX XXXXXXX XX XXX XXXX XXXXXX XXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XXXX XXXXXXXXXXXX XXXX XX XXXXX XXXXXXX XXXX XXXXXXX XXXXX XXXXXXX XXXXX XXX XXXXXXX XXXXXXX XXX XXX XXXXXX XX XXX XXXX XX XXXXXXX XXXXXXXXX XXXX XX X XXXXXX XXXXXXXX XX XXXX XX XXXXXXX XXXXXXX XXXXXX XXXXXXXXXX XXXX XXXXXXX XXXX XXXXXX XXXXXXXX XXXXXXX XXXXXXXXXX XXXXX XXXXXX XX XX XXX XXXXXX XXXXXXXXX XX XXXXXXXXXXX XXXXXXX XXXXXXXXXXXXXXXXX XXXX XXXX XX XXX XXXX XX XXXXXXXXX XXXX XXXXXXX XXXXX XXXXXXX XXXX XXX XXX XXXXXXX XXX XX X XXXXXXXXXXXX XXXX XXXXXXXXXX XXXX XX XXXXXXX XXX XXXXXXX XX XXXXXXXXXXX XXXX XXXX XXXXX XXX XXXXXX XXX XXXXX XXXXXXX XX XXXXXXX XXXXXXXX XX XXXXXXXXXXXX XXXXXXXXXX XXXXX XXXXXXXX XXXXXXX XX XXXX XXXXX XXXXXXXXXX XX XXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXX XX XXXXXXXXX XXXXX XXXX XXX XXXXX XX XXX XXXXXXXXX XXXXXXXX XX XX XXX XXXXXXXXX XX XXXXXXX XXX XXX XXXXXXXX XXXXXXXXXXX XXXXXXXXXXX XX XXXX XXXXXXX XXXXX XXX XXXXXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXX XXX XXXXXXX XXX XXXXX XXXXX XXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XX XXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXX XXXXXXXXX XX XXXXXX XX XXX XXX XX X XXXXXX XXXXXXX XXX XXXXXXX XX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XX XXXXXX XX XXX XXXXX XXX XXX XXXXX XXXXX XXXXXXXXXXX XXXXXX XXXXXXXX X XXXXXXXXXXXXXXXX XXXXXXXXX XX XX XXXXXXXXX XX XXXX XXXXX XXXXX XX XXXXXXXX XXX XXXXX XX XXXXXX XXXX XXXXX XXX XX XXXXX XXX XX XXXXX XXX XX XXXXX X XXXXXXXXXX XXXXX XXXXX XXXX XXXXXXXXXXXXXXX XXX XXXXXXXXX XX X XXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
StarcoderdataPython
63876
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path import warnings import covsirphy as cs def main(): warnings.simplefilter("error") # Create output directory in example directory code_path = Path(__file__) input_dir = code_path.parent.with_name("input") output_dir = code_path.with_name("output").joinpath(code_path.stem) output_dir.mkdir(exist_ok=True, parents=True) # Create data loader instance data_loader = cs.DataLoader(input_dir) # Load JHU dataset print("<The number of cases>") jhu_data = data_loader.jhu() print(jhu_data.citation) ncov_df = jhu_data.cleaned() ncov_df.to_csv(output_dir.joinpath("covid19_cleaned_jhu.csv"), index=False) # Subset for Japan japan_df, _ = jhu_data.records("Japan") japan_df.to_csv( output_dir.joinpath("jhu_cleaned_japan.csv"), index=False) # Load Population dataset print("<Population values>") population_data = data_loader.population() print(population_data.citation) population_df = population_data.cleaned() population_df.to_csv( output_dir.joinpath("population_cleaned.csv"), index=False ) # Load OxCGRT dataset print("<Government response tracker>") oxcgrt_data = data_loader.oxcgrt() print(oxcgrt_data.citation) oxcgrt_df = oxcgrt_data.cleaned() oxcgrt_df.to_csv( output_dir.joinpath("oxcgrt_cleaned.csv"), index=False ) # Load PCR test dataset print("<The number of PCR tests>") pcr_data = data_loader.pcr() print(pcr_data.citation) pcr_df = pcr_data.cleaned() pcr_df.to_csv( output_dir.joinpath("pcr_cleaned.csv"), index=False) pcr_data.positive_rate( country="Greece", filename=output_dir.joinpath("pcr_positive_rate_Greece.jpg")) # Load vaccine dataset print("<The number of vaccinations>") vaccine_data = data_loader.vaccine() print(vaccine_data.citation) vaccine_df = vaccine_data.cleaned() vaccine_df.to_csv( output_dir.joinpath("vaccine_cleaned.csv"), index=False) subset_df = vaccine_data.subset(country="Canada") subset_df.to_csv( output_dir.joinpath("vaccine_subset_canada.csv"), index=False) # Load population pyramid dataset print("<Population pyramid>") pyramid_data = data_loader.pyramid() print(pyramid_data.citation) subset_df = pyramid_data.subset(country="Japan") subset_df.to_csv( output_dir.joinpath("pyramid_subset_japan.csv"), index=False) if __name__ == "__main__": main()
StarcoderdataPython
1750219
<reponame>harmsm/uhbd<gh_stars>0 """ UhbdErrorCheck.py A set of functions to check for errors in uhbd output. """ def checkOut(out,filename): """ Check for errors in uhbdaa and uhbdpr.out. """ lines = out.split("\n") # Check for fatal errors hash = [l[1:6] for l in lines] try: err_index = hash.index("FATAL") err = ["%s\n" % (80*"-")] err.append("Fatal Error in %s:\n" % filename) err.extend(["%s\n" % (80*"-")]) err.append("tail -5 %s\n\n" % filename) err.extend(["%s\n" % l for l in lines[-5:]]) return 1, "".join(err) except ValueError: return 0, ""
StarcoderdataPython
3260736
<gh_stars>10-100 import re import shutil import tempfile from copy import deepcopy from itertools import permutations from pathlib import Path import wordninja from app.attack.hashcat_cmd import HashcatCmdStdout from app.domain import Rule, WordListDefault from app.logger import logger from app.utils import subprocess_call from app.word_magic.hamming import hamming_ball MAX_COMPOUNDS = 5 # max compounds for rule best64 attack def _split_uppercase(word: str) -> set: """ EverGreen -> Ever, Green """ pos_upper = [pos for pos, letter in enumerate(word) if letter.isupper()] pos_upper.append(len(word)) simple_words = set([]) for left, right in zip(pos_upper[:-1], pos_upper[1:]): simple_words.add(word[left: right]) return simple_words def _word_compounds(word: str, min_length=2): return [compound for compound in wordninja.split(word) if len(compound) >= min_length] def _word_compounds_permutation(word: str, max_compounds=MAX_COMPOUNDS, min_length=2, alpha_only=False): """ catonsofa -> cat, on, sofa """ compounds = _word_compounds(word, min_length=min_length) if alpha_only: compounds = filter(re.compile("[a-z]", flags=re.IGNORECASE).match, compounds) compounds = sorted(compounds, key=len, reverse=True)[:max_compounds] compounds_perm = list(compounds) for r in range(2, len(compounds) + 1): compounds_perm.extend(map(''.join, permutations(compounds, r))) return compounds_perm def _collect_essid_parts(essid_origin: str, max_compounds=MAX_COMPOUNDS): def modify_case(word: str): return {word, word.lower(), word.upper(), word.capitalize(), word.lower().capitalize()} regex_non_char = re.compile('[^a-zA-Z]') essid_parts = {essid_origin} essid_parts.add(re.sub(r'\W+', '', essid_origin)) essid_parts.add(re.sub('[^a-z]+', '', essid_origin, flags=re.IGNORECASE)) essid_parts.update(_word_compounds_permutation(essid_origin, max_compounds=max_compounds)) regex_split_parts = regex_non_char.split(essid_origin) regex_split_parts = list(filter(len, regex_split_parts)) for word in regex_split_parts: essid_parts.update(_word_compounds_permutation(word, max_compounds=max_compounds)) essid_parts.update(_word_compounds_permutation(word.lower(), max_compounds=max_compounds)) essid_parts.update(regex_split_parts) essid_parts.update(_split_uppercase(essid_origin)) for essid in list(essid_parts): essid = regex_non_char.sub('', essid) essid_parts.update(modify_case(essid)) essid_parts.update(modify_case(essid_origin)) essid_parts = set(word for word in essid_parts if len(word) > 1) essid_parts.update(modify_case(essid_origin)) # special case when ESSID is a single letter return essid_parts def _collect_essid_hamming(essid: str, hamming_dist_max=1): essid_hamming = set() essid_hamming.update(hamming_ball(s=essid, n=hamming_dist_max)) essid_hamming.update(hamming_ball(s=essid.lower(), n=hamming_dist_max)) logger.debug(f"Essid {essid} -> {len(essid_hamming)} hamming cousins with dist={hamming_dist_max}") return essid_hamming def _collect_essid_rule(essid_wordlist_path: Path): """ Run ESSID + best64.rule attack. """ with tempfile.NamedTemporaryFile(mode='w+', errors='ignore') as f: # Ignore UnicodeDecodeError: 'utf-8' codec can't decode byte ... hashcat_stdout = HashcatCmdStdout(outfile=f.name) hashcat_stdout.add_wordlists(essid_wordlist_path) hashcat_stdout.add_rule(Rule.ESSID) subprocess_call(hashcat_stdout.build()) candidates = f.read().splitlines() return candidates def _run_essid_digits(compounds_fpath: Path, hashcat_cmd=None, fast=True): if not fast: assert hashcat_cmd is not None, \ "Non-fast mode requires running a hashcat command." candidates = set() wordlist_order = [compounds_fpath] if fast: wordlist_order.append(WordListDefault.DIGITS_APPEND_SHORT) else: wordlist_order.append(WordListDefault.DIGITS_APPEND) with open(compounds_fpath) as f: compounds_count = len(f.readlines()) if compounds_count > 1000 and hashcat_cmd is not None: # reduce IO operations, run the hashcat attack directly fast = False for reverse in range(2): with tempfile.NamedTemporaryFile(mode='w+', errors='ignore') as f: hashcat_stdout = HashcatCmdStdout(outfile=f.name) hashcat_stdout.add_wordlists(*wordlist_order, options=['-a1']) subprocess_call(hashcat_stdout.build()) if fast: candidates.update(f.read().splitlines()) else: _hashcat_cmd_tmp = deepcopy(hashcat_cmd) _hashcat_cmd_tmp.add_wordlists(f.name) subprocess_call(_hashcat_cmd_tmp.build()) wordlist_order = wordlist_order[::-1] return candidates def run_essid_attack(essid, hashcat_cmd=None, fast=True): # hashcat_cmd could be None for debug mode to check the no. of candidates password_candidates = set() essid_as_wordlist_dir = Path(tempfile.mkdtemp()) # (1) Hamming ball attack essid_compounds = _collect_essid_parts(essid) # Limit the number of word compounds to an arbitrary number. if len(essid_compounds) < 100: for compound in essid_compounds: password_candidates.update(_collect_essid_hamming(essid=compound)) else: password_candidates.update(_collect_essid_hamming(essid=essid)) # (2) best64 rule attack # strip all except digits, letters and '_' compounds_fpath = essid_as_wordlist_dir / re.sub(r'\W+', '', essid) compounds_fpath.write_text('\n'.join(essid_compounds)) password_candidates.update(_collect_essid_rule(compounds_fpath)) # (3) digits_append attack password_candidates.update(_run_essid_digits(compounds_fpath, hashcat_cmd=hashcat_cmd, fast=fast)) if hashcat_cmd is not None: with tempfile.NamedTemporaryFile(mode='w') as f: f.write('\n'.join(password_candidates)) hashcat_cmd = deepcopy(hashcat_cmd) hashcat_cmd.add_wordlists(f.name) subprocess_call(hashcat_cmd.build()) shutil.rmtree(essid_as_wordlist_dir) return password_candidates if __name__ == '__main__': # run_essid_attack("lrtgn5s19b41e21f1202unc77i8093") run_essid_attack("MaloinvazivTrile_2.4GHz") run_essid_attack("PetitCafe") for essid in ["Tanya007", "My_rabbit", "Myrabbit", "MyRabbit", "PetitCafe2017"]: compounds = sorted(_word_compounds_permutation(essid)) candidates = sorted(_collect_essid_parts(essid)) print(f"'{essid}'\n\t{len(compounds)} compounds: {compounds}") print(f"\t{len(candidates)} candidates: {candidates}")
StarcoderdataPython
3217643
# -*- coding: utf-8 -*- """ infermedica_api.webservice ~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains classes and function responsible for making API requests. """ import json import platform import warnings import requests from . import __version__, exceptions, models, API_CONFIG, DEFAULT_API_VERSION, DEFAULT_API_ENDPOINT class SearchFilters: """Simple class to hold search filter constants.""" SYMPTOMS = "symptom" RISK_FACTORS = "risk_factor" LAB_TESTS = "lab_test" ALL = [SYMPTOMS, RISK_FACTORS, LAB_TESTS] SEARCH_FILTERS = SearchFilters() class API: """Class which handles requests to the Infermedica API.""" # User-Agent for HTTP request library_details = f"requests {requests.__version__}; python {platform.python_version()}" user_agent = f"Infermedica-API-Python {__version__} ({library_details})" def __init__(self, **kwargs): """ Initialize API object. Usage:: >>> import infermedica_api >>> api = infermedica_api.API(app_id='YOUR_APP_ID', app_key='YOUR_APP_KEY') """ self.endpoint = kwargs.get("endpoint", DEFAULT_API_ENDPOINT) self.api_version = kwargs.get("api_version", DEFAULT_API_VERSION) self.app_id = kwargs["app_id"] # Mandatory parameter, so not using `dict.get` self.app_key = kwargs["app_key"] # Mandatory parameter, so not using `dict.get` self.default_headers = self.__calculate_headers(kwargs) if self.api_version in kwargs.get("api_definitions", {}) or {}: self.api_methods = kwargs["api_definitions"][self.api_version]['methods'] elif self.api_version in API_CONFIG: self.api_methods = API_CONFIG[self.api_version]['methods'] else: self.api_methods = API_CONFIG[DEFAULT_API_VERSION]['methods'] def __calculate_headers(self, parameters): headers = parameters.get("default_headers", {}) if parameters.get("model", None): headers.update({ "Model": parameters["model"] }) if parameters.get("dev_mode", None) and parameters["dev_mode"] == True: headers.update({ "Dev-Mode": "true" }) return headers def __get_url(self, method): return self.endpoint + self.api_version + method def __get_headers(self, override): """Returns default HTTP headers.""" headers = { "Content-Type": "application/json", "Accept": "application/json", "User-Agent": self.user_agent, "App-Id": self.app_id, "App-Key": self.app_key } headers.update(self.default_headers) headers.update(override) return headers def __api_call(self, url, method, **kwargs): kwargs['headers'] = self.__get_headers(kwargs['headers'] or {}) response = requests.request(method, url, **kwargs) return self.__handle_response(response) def __handle_response(self, response): """ Validates HTTP response, if response is correct decode json data and returns dict object. If response is not correct raise appropriate exception. :returns: dict or list with response data :rtype: dict or list :raises: infermedica_api.exceptions.BadRequest, infermedica_api.exceptions.UnauthorizedAccess, infermedica_api.exceptions.ForbiddenAccess, infermedica_api.exceptions.ResourceNotFound, infermedica_api.exceptions.MethodNotAllowed, infermedica_api.exceptions.ServerError, infermedica_api.exceptions.ConnectionError """ status = response.status_code content = response.content.decode('utf-8') if 200 <= status <= 299: return json.loads(content) if content else {} elif status == 400: raise exceptions.BadRequest(response, content) elif status == 401: raise exceptions.UnauthorizedAccess(response, content) elif status == 403: raise exceptions.ForbiddenAccess(response, content) elif status == 404: raise exceptions.ResourceNotFound(response, content) elif status == 405: raise exceptions.MethodNotAllowed(response, content) elif 500 <= status <= 599: raise exceptions.ServerError(response, content) else: raise exceptions.ConnectionError(response, content) def __get(self, method, params=None, headers=None): """Wrapper for a GET API call.""" return self.__api_call(self.__get_url(method), "GET", headers=headers, params=params) def __post(self, method, data, params=None, headers=None): """Wrapper for a GET API call.""" return self.__api_call(self.__get_url(method), "POST", headers=headers, data=data, params=params) def __get_method(self, name): try: return self.api_methods[name] except KeyError as e: raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, name) def __get_interview_id_headers(self, diagnosis_request=None, interview_id=None): headers = {} if interview_id: headers['Interview-Id'] = interview_id elif isinstance(diagnosis_request, models.Diagnosis) and diagnosis_request.interview_id: headers['Interview-Id'] = diagnosis_request.interview_id return headers def info(self): """Makes an API request and returns basic API model information.""" return self.__get(self.__get_method('info')) def search(self, phrase, sex=None, max_results=8, filters=None, **kwargs): """ Makes an API search request and returns list of dicts containing keys: 'id', 'label' and 'type'. Each dict represent an evidence (symptom, lab test or risk factor). By default only symptoms are returned, to include other evidence types use filters. :param phrase: Phrase to look for. :type phrase: str :param sex: Sex of the patient 'female' or 'male'. :type sex: str :param max_results: Maximum number of result to return, default is 8. :type max_results: int :param filters: List of search filters, taken from SEARCH_FILTERS variable. :type filters: list :returns: A List of dicts with 'id' and 'label' keys. :rtype: list """ method = self.__get_method('search') params = kwargs.pop('params', {}) params.update({ 'phrase': phrase, 'max_results': max_results }) if sex: params['sex'] = sex if filters: if isinstance(filters, (list, tuple)): params['type'] = filters elif isinstance(filters, str): params['type'] = [filters] for filter in params['type']: if filter not in SEARCH_FILTERS.ALL: raise exceptions.InvalidSearchFilter(filter) return self.__get(method, params=params) def lookup(self, phrase, sex=None): """ Makes an API lookup request and returns evidence details object. :param phrase: Phrase to look for. :type phrase: str :param sex: Sex of the patient 'female' or 'male'. :type sex: str :returns: Dictionary with details. :rtype: dict """ method = self.__get_method('lookup') params = { 'phrase': phrase } if sex: params['sex'] = sex return self.__get(method, params=params) def suggest(self, diagnosis_request, max_results=8, interview_id=None, **kwargs): """ Makes an API suggest request and returns a list of suggested evidence. :param diagnosis_request: Diagnosis request object or json request for diagnosis method. :type diagnosis_request: :class:`infermedica_api.models.Diagnosis` or dict :returns: A list of suggestions, dicts with 'id', 'name' and 'common_name' keys. :rtype: list """ method = self.__get_method('suggest') headers = self.__get_interview_id_headers(interview_id=interview_id) params = kwargs.pop('params', {}) params.update({'max_results': max_results}) request = diagnosis_request if isinstance(diagnosis_request, models.Diagnosis): request = diagnosis_request.get_api_request() return self.__post( method, params=params, headers=headers, data=json.dumps(request) ) def parse(self, text, include_tokens=False, interview_id=None, **kwargs): """ Makes an parse API request with provided text and include_tokens parameter. Returns parse results with detailed list of mentions found in the text. :param phrase: Text to parse. :type phrase: str :param include_tokens: Switch to manipulate the include_tokens parameter. :type include_tokens: bool :returns: A ParseResults object :rtype: :class:`infermedica_api.models.ParseResults` """ method = self.__get_method('parse') headers = self.__get_interview_id_headers(interview_id=interview_id) params = kwargs.pop('params', {}) request = { 'text': text, 'include_tokens': include_tokens } response = self.__post( method, json.dumps(request), params=params, headers=headers ) return models.ParseResults.from_json(response) def diagnosis(self, diagnosis_request, interview_id=None, **kwargs): """ Makes a diagnosis API request with provided diagnosis data and returns diagnosis question with possible conditions. :param diagnosis_request: Diagnosis request object or json request for diagnosis method. :type diagnosis_request: :class:`infermedica_api.models.Diagnosis` or dict :param interview_id: Unique interview id for diagnosis :type interview_id: str :returns: A Diagnosis object with api response :rtype: :class:`infermedica_api.models.Diagnosis` """ method = self.__get_method('diagnosis') headers = self.__get_interview_id_headers( diagnosis_request=diagnosis_request, interview_id=interview_id ) params = kwargs.pop('params', {}) if isinstance(diagnosis_request, models.Diagnosis): response = self.__post( method, json.dumps(diagnosis_request.get_api_request()), params=params, headers=headers ) diagnosis_request.update_from_api(response) return diagnosis_request return self.__post( method, json.dumps(diagnosis_request), params=params, headers=headers ) def explain(self, diagnosis_request, target_id, interview_id=None, **kwargs): """ Makes an explain API request with provided diagnosis data and target condition. Returns explain results with supporting and conflicting evidences. :param diagnosis_request: Diagnosis request object or json request for diagnosis method. :type diagnosis_request: :class:`infermedica_api.models.Diagnosis` or dict :param target_id: Condition id for which explain shall be calculated. :type target_id: str :returns: A Diagnosis object with api response :rtype: :class:`infermedica_api.models.Diagnosis` """ method = self.__get_method('explain') headers = self.__get_interview_id_headers(diagnosis_request=diagnosis_request, interview_id=interview_id) params = kwargs.pop('params', {}) if isinstance(diagnosis_request, models.Diagnosis): request = diagnosis_request.get_explain_request(target_id) else: request = dict(diagnosis_request, **{'target': target_id}) response = self.__post( method, json.dumps(request), params=params, headers=headers ) return models.ExplainResults.from_json(response) def triage(self, diagnosis_request, interview_id=None, **kwargs): """ Makes a triage API request with provided diagnosis data. Returns triage results dict. See the docs: https://developer.infermedica.com/docs/triage. :param diagnosis_request: Diagnosis request object or json request for diagnosis method. :type diagnosis_request: :class:`infermedica_api.models.Diagnosis` or dict :returns: A dict object with api response :rtype: dict """ method = self.__get_method('triage') headers = self.__get_interview_id_headers(diagnosis_request=diagnosis_request, interview_id=interview_id) params = kwargs.pop('params', {}) request = diagnosis_request if isinstance(diagnosis_request, models.Diagnosis): request = diagnosis_request.get_api_request() return self.__post( method, json.dumps(request), params=params, headers=headers ) def condition_details(self, _id): """ Makes an API request and returns condition details object. :param _id: Condition id :type _id: str :returns:A Condition object :rtype: :class:`infermedica_api.models.Condition` """ method = self.__get_method('condition_details') response = self.__get(method.format(**{'id': _id})) return models.Condition.from_json(response) def conditions_list(self): """ Makes an API request and returns list of condition details objects. :returns: A ConditionList list object with Condition objects :rtype: :class:`infermedica_api.models.ConditionList` """ response = self.__get(self.__get_method('conditions')) return models.ConditionList.from_json(response) def symptom_details(self, _id): """ Makes an API request and returns symptom details object. :param _id: Symptom id :type _id: str :returns: A Symptom object :rtype: :class:`infermedica_api.models.Symptom` """ method = self.__get_method('symptom_details') response = self.__get(method.format(**{'id': _id})) return models.Symptom.from_json(response) def symptoms_list(self): """ Makes an API request and returns list of symptom details objects. :returns: A SymptomList list object with Symptom objects :rtype: :class:`infermedica_api.models.SymptomList` """ response = self.__get(self.__get_method('symptoms')) return models.SymptomList.from_json(response) def lab_test_details(self, _id): """ Makes an API request and returns lab_test details object. :param _id: LabTest id :type _id: str :returns: A LabTest object :rtype: :class:`infermedica_api.models.LabTest` """ method = self.__get_method('lab_test_details') response = self.__get(method.format(**{'id': _id})) return models.LabTest.from_json(response) def lab_tests_list(self): """ Makes an API request and returns list of lab_test details objects. :returns: A LabTestList list object with LabTest objects :rtype: :class:`infermedica_api.models.LabTestList` """ response = self.__get(self.__get_method('lab_tests')) return models.LabTestList.from_json(response) def risk_factor_details(self, _id): """ Makes an API request and returns risk factor details object. :param _id: risk factor id :type _id: str :returns: A RiskFactor object :rtype: :class:`infermedica_api.models.RiskFactor` """ method = self.__get_method('risk_factor_details') response = self.__get(method.format(**{'id': _id})) return models.RiskFactor.from_json(response) def risk_factors_list(self): """ Makes an API request and returns list of risk factors details objects. :returns: A RiskFactorList list object with RiskFactor objects :rtype: :class:`infermedica_api.models.RiskFactorList` """ response = self.__get(self.__get_method('risk_factors')) return models.RiskFactorList.from_json(response) def red_flags(self, diagnosis_request, max_results=8, interview_id=None, **kwargs): """ Makes an API request with provided diagnosis data and returns a list of evidence that may be related to potentially life-threatening conditions. :param diagnosis_request: Diagnosis request object or diagnosis json. :type diagnosis_request: :class:`infermedica_api.models.Diagnosis` or dict :param interview_id: Unique interview id for diagnosis :type interview_id: str :returns: A list of RedFlag objects :rtype: :class:`infermedica_api.models.RedFlagList` """ method = self.__get_method('red_flags') headers = self.__get_interview_id_headers( diagnosis_request=diagnosis_request, interview_id=interview_id, ) params = kwargs.pop('params', {}) params.update({'max_results': max_results}) request = diagnosis_request if isinstance(diagnosis_request, models.Diagnosis): request = diagnosis_request.get_api_request() response = self.__post( method, json.dumps(request), params=params, headers=headers ) return models.RedFlagList.from_json(response) def rationale(self, diagnosis_request, interview_id=None, **kwargs): """ Makes an API request with provided diagnosis data and returns an explenation of why the given question has been selected by the reasoning engine. :param diagnosis_request: Diagnosis request object or diagnosis json. :type diagnosis_request: :class:`infermedica_api.models.Diagnosis` or dict :param interview_id: Unique interview id for diagnosis :type interview_id: str :returns: An instance of the RationaleResult :rtype: :class:`infermedica_api.models.RationaleResult` """ method = self.__get_method('rationale') headers = self.__get_interview_id_headers( diagnosis_request=diagnosis_request, interview_id=interview_id, ) params = kwargs.pop('params', {}) request = diagnosis_request if isinstance(diagnosis_request, models.Diagnosis): request = diagnosis_request.get_api_request() response = self.__post( method, json.dumps(request), params=params, headers=headers ) return models.RationaleResult.from_json(response) __api__ = None __api_aliased__ = {} def get_api(alias=None): """ Returns global API object and if present, otherwise raise MissingConfiguration exception. :param alias: Alias of the API to retrieve :type alias: str :returns: An API object :rtype: :class:`infermedica_api.webservice.API` :raises: :class:`infermedica_api.exceptions.MissingConfiguration` """ global __api__ global __api_aliased__ if isinstance(alias, str): try: return __api_aliased__[alias] except KeyError: raise exceptions.MissingConfiguration(alias) if __api__ is None: raise exceptions.MissingConfiguration() return __api__ def configure(options=None, **config): """ Configure and create new global API object with given configuration. Configuration can be passed as a dict or separate arguments. Returns newly created object. Usage: >>> import infermedica_api >>> infermedica_api.configure({'app_id': 'YOUR_APP_ID', 'app_key': 'YOUR_APP_KEY'}) ... or: >>> import infermedica_api >>> infermedica_api.configure(app_id='YOUR_APP_ID', app_key='YOUR_APP_KEY') :param options: Dict with configuration data :type options: dict :returns: An API object :rtype: :class:`infermedica_api.webservice.API` """ global __api__ global __api_aliased__ configuration = dict(options or {}, **config) if 'alias' in configuration and isinstance(configuration['alias'], str): __api_aliased__[configuration['alias']] = API(**configuration) if configuration.get('default', False): __api__ = __api_aliased__[configuration['alias']] return __api_aliased__[configuration['alias']] __api__ = API(**configuration) return __api__
StarcoderdataPython
3236571
<reponame>ennsk/fort-pymdwizard #!/usr/bin/env python # -*- coding: utf8 -*- """ The MetadataWizard(pymdwizard) software was developed by the U.S. Geological Survey Fort Collins Science Center. See: https://github.com/usgs/fort-pymdwizard for current project source code See: https://usgs.github.io/fort-pymdwizard/ for current user documentation See: https://github.com/usgs/fort-pymdwizard/tree/master/examples for examples of use in other scripts License: Creative Commons Attribution 4.0 International (CC BY 4.0) http://creativecommons.org/licenses/by/4.0/ PURPOSE ------------------------------------------------------------------------------ Provide a pyqt widget for the FGDC component with a shortname matching this file's name. SCRIPT DEPENDENCIES ------------------------------------------------------------------------------ This script is part of the pymdwizard package and is not intented to be used independently. All pymdwizard package requirements are needed. See imports section for external packages used in this script as well as inter-package dependencies U.S. GEOLOGICAL SURVEY DISCLAIMER ------------------------------------------------------------------------------ This software has been approved for release by the U.S. Geological Survey (USGS). Although the software has been subjected to rigorous review, the USGS reserves the right to update the software as needed pursuant to further analysis and review. No warranty, expressed or implied, is made by the USGS or the U.S. Government as to the functionality of the software and related material nor shall the fact of release constitute any such warranty. Furthermore, the software is released on condition that neither the USGS nor the U.S. Government shall be held liable for any damages resulting from its authorized or unauthorized use. Any use of trade, product or firm names is for descriptive purposes only and does not imply endorsement by the U.S. Geological Survey. Although this information product, for the most part, is in the public domain, it also contains copyrighted material as noted in the text. Permission to reproduce copyrighted items for other than personal use must be secured from the copyright owner. ------------------------------------------------------------------------------ """ from copy import deepcopy from pymdwizard.core import utils from pymdwizard.core import xml_utils from pymdwizard.gui.wiz_widget import WizardWidget from pymdwizard.gui.ui_files import UI_DataQuality from pymdwizard.gui.AttributeAccuracy import AttributeAccuracy from pymdwizard.gui.LogicalAccuracy import LogicalAccuracy from pymdwizard.gui.Completeness import Completeness from pymdwizard.gui.PositionalAccuracy import PositionalAccuracy from pymdwizard.gui.sourceinput import SourceInput from pymdwizard.gui.procstep import ProcStep class DataQuality(WizardWidget): drag_label = "Data Quality <dataqual>" acceptable_tags = ['dataqual'] ui_class = UI_DataQuality.Ui_fgdc_dataqual def build_ui(self): self.ui = self.ui_class() self.ui.setupUi(self) self.setup_dragdrop(self) self.attraccr = AttributeAccuracy(parent=self) self.logic = LogicalAccuracy(parent=self) # self.complete = Completeness(parent=self) self.complete = Completeness(parent=self) self.posacc = PositionalAccuracy(parent=self) self.sourceinput = SourceInput(parent=self) self.procstep = ProcStep(parent=self) self.ui.two_column_left.layout().addWidget(self.attraccr) self.ui.two_column_left.layout().addWidget(self.logic) self.ui.two_column_left.layout().addWidget(self.complete) self.ui.two_column_left.layout().addWidget(self.posacc) self.ui.bottom_layout.layout().addWidget(self.sourceinput) self.ui.fgdc_lineage.layout().addWidget(self.procstep) self.scroll_area = self.ui.idinfo_scroll_area def clear_widget(self): self.sourceinput.clear_widget() WizardWidget.clear_widget(self) self.complete.ui.fgdc_complete.sizeChange() def to_xml(self): # add code here to translate the form into xml representation dataqual_node = xml_utils.xml_node(tag='dataqual') attraccr_node = self.attraccr.to_xml() dataqual_node.append(attraccr_node) logic_node = self.logic.to_xml() dataqual_node.append(logic_node) complete_node = self.complete.to_xml() dataqual_node.append(complete_node) if self.posacc.has_content(): posacc_node = self.posacc.to_xml() dataqual_node.append(posacc_node) if self.sourceinput.has_content(): srcinfo_node = self.sourceinput.to_xml() procstep_node = self.procstep.to_xml() procstep_children = procstep_node.getchildren() for i in procstep_children: srcinfo_node.append(i) if self.original_xml is not None: methods = xml_utils.search_xpath(self.original_xml, 'lineage/method', only_first=False) for i, method in enumerate(methods): method.tail = None srcinfo_node.insert(i, deepcopy(method)) dataqual_node.append(srcinfo_node) if self.original_xml is not None: cloud = xml_utils.search_xpath(self.original_xml, 'cloud') if cloud is not None: cloud.tail = None dataqual_node.append(deepcopy(cloud)) return dataqual_node def from_xml(self, xml_dataqual): self.original_xml = xml_dataqual try: attraccr = xml_dataqual.xpath('attracc')[0] self.attraccr.from_xml(attraccr) except IndexError: pass try: logic = xml_dataqual.xpath('logic')[0] self.logic.from_xml(logic) except IndexError: pass try: complete = xml_dataqual.xpath('complete')[0] self.complete.from_xml(complete) except IndexError: pass try: posacc = xml_dataqual.xpath('posacc')[0] self.posacc.from_xml(posacc) except IndexError: pass try: sourceinput = xml_dataqual.xpath('lineage')[0] self.sourceinput.from_xml(sourceinput) except IndexError: pass try: procstep = xml_dataqual.xpath('lineage')[0] self.procstep.from_xml(procstep) except IndexError: pass if __name__ == "__main__": utils.launch_widget(DataQuality, "DataQual testing")
StarcoderdataPython
3295496
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author : pengj @ date : 2019/10/14 9:27 @ IDE : PyCharm @ GitHub : https://github.com/JackyPJB @ Contact : <EMAIL> ------------------------------------------------- Description : 5223. 可以攻击国王的皇后 显示英文描述 https://leetcode-cn.com/contest/weekly-contest-158/problems/queens-that-can-attack-the-king/ 用户通过次数708 用户尝试次数779 通过次数709 提交次数1178 题目难度Medium 在一个 8x8 的棋盘上,放置着若干「黑皇后」和一个「白国王」。 「黑皇后」在棋盘上的位置分布用整数坐标数组 queens 表示,「白国王」的坐标用数组 king 表示。 「黑皇后」的行棋规定是:横、直、斜都可以走,步数不受限制,但是,不能越子行棋。 请你返回可以直接攻击到「白国王」的所有「黑皇后」的坐标(任意顺序)。 示例 1: 输入:queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0] 输出:[[0,1],[1,0],[3,3]] 解释: [0,1] 的皇后可以攻击到国王,因为他们在同一行上。 [1,0] 的皇后可以攻击到国王,因为他们在同一列上。 [3,3] 的皇后可以攻击到国王,因为他们在同一条对角线上。 [0,4] 的皇后无法攻击到国王,因为她被位于 [0,1] 的皇后挡住了。 [4,0] 的皇后无法攻击到国王,因为她被位于 [1,0] 的皇后挡住了。 [2,4] 的皇后无法攻击到国王,因为她和国王不在同一行/列/对角线上。 示例 2: 输入:queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3] 输出:[[2,2],[3,4],[4,4]] 示例 3: 输入:queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4] 输出:[[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]] 提示: 1 <= queens.length <= 63 queens[0].length == 2 0 <= queens[i][j] < 8 king.length == 2 0 <= king[0], king[1] < 8 一个棋盘格上最多只能放置一枚棋子。 ------------------------------------------------- """ import time from typing import List import copy __author__ = 'Max_Pengjb' start_time = time.time() # 下面写上代码块 class Solution: def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]: directions = [(1, 0), (-1, 0), (0, 1), (0, -1), (-1, -1), (1, 1), (-1, 1), (1, -1)] res = [] for direction in directions: hit = copy.deepcopy(king) print(king) while hit not in queens: hit[0] = hit[0] + direction[0] hit[1] = hit[1] + direction[1] if hit[0] < 0 or hit[0] > 7 or hit[1] < 0 or hit[1] > 7: break if hit in queens: res.append(hit) return res # 上面中间写上代码块 end_time = time.time() print('Running time: %s Seconds' % (end_time - start_time)) queens = [[5, 6], [7, 7], [2, 1], [0, 7], [1, 6], [5, 1], [3, 7], [0, 3], [4, 0], [1, 2], [6, 3], [5, 0], [0, 4], [2, 2], [1, 1], [6, 4], [5, 4], [0, 0], [2, 6], [4, 5], [5, 2], [1, 4], [7, 5], [2, 3], [0, 5], [4, 2], [1, 0], [2, 7], [0, 1], [4, 6], [6, 1], [0, 6], [4, 3], [1, 7]] king = [3, 4] rr = Solution().queensAttacktheKing(queens, king) print(rr)
StarcoderdataPython
187592
<filename>redback/get_data/fermi.py<gh_stars>1-10 class FermiDataGetter(object): def __init__(self) -> None: raise NotImplementedError()
StarcoderdataPython
4801464
import datetime import re from dataclasses import dataclass from datetime import timezone import pytz from dateutil.parser import parse NanosecPattern = re.compile(r".+\.(\d+).*") RequiredTimePattern = re.compile(r".*\d\d?[/:-]\d\d?.*") @dataclass class DateTimeWithNS: datetime: datetime.datetime nanosec: int original_string: str def tupple(self) -> (datetime.datetime, int): return (self.datetime, self.nanosec) def __str__(self) -> str: return self.original_string @classmethod def parse(cls, datetime_like_string: str, tz_str=None): return elastic_time_parse(datetime_like_string, tz_str=tz_str) def elastic_time_parse(src, tz_str=None, logger=None) -> DateTimeWithNS: """Parse src string as datetime and nanosec part. Raise exception if src format is NOT valid. """ if src is None: raise ValueError if not re.match(RequiredTimePattern, src): raise ValueError nano = 0 ret = parse(src) if ret.tzinfo is None: try: tz_info = pytz.timezone(tz_str) offset = timezone(tz_info.utcoffset(ret)) ret = ret.replace(tzinfo=offset) except Exception: ret = ret.replace(tzinfo=timezone.utc) m = NanosecPattern.match(src) if(m is not None): nano = int(m.group(1)[0:9].ljust(9, '0')) return DateTimeWithNS(ret, nano, src)
StarcoderdataPython
1697514
import logging import os import typing from typing import Dict, Optional, Text, Union from rasa.core.domain import Domain if typing.TYPE_CHECKING: from rasa.core.interpreter import NaturalLanguageInterpreter logger = logging.getLogger(__name__) async def train( domain_file: Union[Domain, Text], stories_file: Text, output_path: Text, interpreter: Optional["NaturalLanguageInterpreter"] = None, endpoints: "AvailableEndpoints" = None, dump_stories: bool = False, policy_config: Text = None, exclusion_percentage: int = None, kwargs: Optional[Dict] = None, ): from rasa.core.agent import Agent from rasa.core import config, utils from rasa.core.utils import AvailableEndpoints if not endpoints: endpoints = AvailableEndpoints() if not kwargs: kwargs = {} policies = config.load(policy_config) agent = Agent( domain_file, generator=endpoints.nlg, action_endpoint=endpoints.action, interpreter=interpreter, policies=policies, ) data_load_args, kwargs = utils.extract_args( kwargs, { "use_story_concatenation", "unique_last_num_states", "augmentation_factor", "remove_duplicates", "debug_plots", }, ) training_data = await agent.load_data( stories_file, exclusion_percentage=exclusion_percentage, **data_load_args ) agent.train(training_data, **kwargs) agent.persist(output_path, dump_stories) return agent async def train_comparison_models( stories, domain, output_path="", exclusion_percentages=None, policy_configs=None, runs=1, dump_stories=False, kwargs=None, ): """Train multiple models for comparison of policies""" from rasa.core import config exclusion_percentages = exclusion_percentages or [] policy_configs = policy_configs or [] for r in range(runs): logging.info("Starting run {}/{}".format(r + 1, runs)) for i in exclusion_percentages: current_round = exclusion_percentages.index(i) + 1 for policy_config in policy_configs: policies = config.load(policy_config) if len(policies) > 1: raise ValueError( "You can only specify one policy per model for comparison" ) policy_name = type(policies[0]).__name__ output = os.path.join( output_path, "run_" + str(r + 1), policy_name + str(current_round) ) logging.info( "Starting to train {} round {}/{}" " with {}% exclusion" "".format(policy_name, current_round, len(exclusion_percentages), i) ) await train( domain, stories, output, policy_config=policy_config, exclusion_percentage=i, kwargs=kwargs, dump_stories=dump_stories, ) async def get_no_of_stories(story_file, domain): """Get number of stories in a file.""" from rasa.core.domain import TemplateDomain from rasa.core.training.dsl import StoryFileReader stories = await StoryFileReader.read_from_folder( story_file, TemplateDomain.load(domain) ) return len(stories) async def do_compare_training(cmdline_args, stories, additional_arguments): from rasa.core import utils await train_comparison_models( stories, cmdline_args.domain, cmdline_args.out, cmdline_args.percentages, cmdline_args.config, cmdline_args.runs, cmdline_args.dump_stories, additional_arguments, ) no_stories = await get_no_of_stories(cmdline_args.stories, cmdline_args.domain) # store the list of the number of stories present at each exclusion # percentage story_range = [ no_stories - round((x / 100.0) * no_stories) for x in cmdline_args.percentages ] story_n_path = os.path.join(cmdline_args.out, "num_stories.json") utils.dump_obj_as_json_to_file(story_n_path, story_range) def do_interactive_learning(cmdline_args, stories, additional_arguments=None): from rasa.core.training import interactive interactive.run_interactive_learning( stories, skip_visualization=cmdline_args.skip_visualization, server_args=cmdline_args.__dict__, additional_arguments=additional_arguments, ) if __name__ == "__main__": raise RuntimeError( "Calling `rasa.core.train` directly is no longer supported. Please use " "`rasa train` to train a combined Core and NLU model or `rasa train core` " "to train a Core model." )
StarcoderdataPython
1647460
import os import time import random import numpy as np import datasets # CHANGE THESE PATHS TO PATHS OF THE .mat DATASETS DESCRIBED IN THE PAPER mat_path_coil20 = os.path.expanduser("~/Documents/datasets/elm/coil20.mat") mat_path_g50c = os.path.expanduser("~/Documents/datasets/elm/g50c.mat") mat_path_uspst = os.path.expanduser("~/Documents/datasets/elm/uspst.mat") # SET UNDESIRED DATASETS TO FALSE # e.g to not generate a json file for them do_coil20 = True do_coil20b = True do_g50c = True do_uspst = True do_uspstb = True # place to store generated indices (folds) # support for changing this might be flaky, so it is best to leave it as is. json_output_directory = os.path.expanduser("./idx_datasets/") def gen(): seed = 32 random.seed(seed) np.random.seed(seed) print("Generating k-fold partitions") t = str(time.time()).split('.')[0] unique_subdir = os.path.join(json_output_directory, t) os.mkdir(unique_subdir) print("Storing json files in directory {}".format(unique_subdir)) # coil20 if do_coil20: d = datasets.gen_partitions(mat_path_coil20, size=1440, L=40, U=1000, V=40, T=360) finalpath = os.path.join(unique_subdir, "coil20.json") datasets.dump_json(d, finalpath) # coil20b, strictly speaking generated the same way as coil20 # (the binarization is done when the coil20 set is loaded for use with # the model, as the indices are the same with just the classes changed # to [1,2] -- but using a different shuffle seemed appropriate) if do_coil20b: d = datasets.gen_partitions(mat_path_coil20, size=1440, L=40, U=1000, V=40, T=360) finalpath = os.path.join(unique_subdir, "coil20b.json") datasets.dump_json(d, finalpath) # G50C if do_g50c: d = datasets.gen_partitions(mat_path_g50c, size=550, L=50, U=314, V=50, T=136) finalpath = os.path.join(unique_subdir, "g50c.json") datasets.dump_json(d, finalpath) # USPST if do_uspst: d = datasets.gen_partitions(mat_path_uspst, size=2007, L=50, U=1409, V=50, T=498) finalpath = os.path.join(unique_subdir, "uspst.json") datasets.dump_json(d, finalpath) # USPST(B) if do_uspstb: d = datasets.gen_partitions(mat_path_uspst, size=2007, L=50, U=1409, V=50, T=498) finalpath = os.path.join(unique_subdir, "uspstb.json") datasets.dump_json(d, finalpath) if __name__ == '__main__': gen()
StarcoderdataPython
56812
from RestrictedPython import compile_restricted from RestrictedPython import Eval from RestrictedPython import Guards from RestrictedPython import safe_globals from RestrictedPython import utility_builtins from RestrictedPython.PrintCollector import PrintCollector from multiprocessing import Process from multiprocessing import Manager import local_libs.ProblemFileHandler as Handler import time class PyOJAgent: def __init__(self, memory_limit=1048576, time_limit=5): self.name = 'default_agent' self.memory_limit = memory_limit self.time_limit = time_limit self.submission_result = [] self.problem_dict = {} self.compile_error_flag = False self.compile_error_info = '' self.problem_file_handler = Handler.ProblemFileHandler() def load_problem_file(self, problem_file): self.problem_dict = self.problem_file_handler.load_problem_file(problem_file) if self.problem_dict: return True else: return False def test_submission(self, submission_code_str): self.submission_result = [] self.compile_error_flag = False if not self.problem_dict: return else: pass try: compile_restricted(submission_code_str, '<inline>', 'exec') except Exception as e: self.compile_error_flag = True self.compile_error_info = repr(e) return for test_case in self.problem_dict['test_cases']: print('testing test case:', test_case, sep='\n') suffix = '\noutput = main_function' + str(tuple(test_case[0])) try: manager = Manager() py_code = submission_code_str + suffix ret_dict = manager.dict() p = Process(target=target_function, args=(py_code, ret_dict)) p.start() time.sleep(self.time_limit) p.terminate() p.join() if not ret_dict: self.submission_result.append('服务器资源不足!') return else: print('submission result: ', ret_dict['output']) if ret_dict['RE_flag']: self.submission_result.append('Runtime Error! ' + ret_dict['RE_info']) elif ret_dict['TLE_flag']: self.submission_result.append('Time Limit Exceeded! ') elif ret_dict['output'] == test_case[1]: self.submission_result.append('Accepted! ') else: self.submission_result.append('Wrong Answer! ') # add error types here maybe except Exception as e: print(repr(e)) def report_submission_result(self): if self.compile_error_flag: return "Compile Error!\n" + self.compile_error_info elif not self.problem_dict: return '未加载题目!' elif not self.submission_result: return 'No Report Available!' else: ret = '' n = len(self.submission_result) ret += '{0}组数据已测试,结果如下:\n'.format(n) for i in range(n): ret += '测试点{0}/{1}:'.format(i + 1, n) ret += self.submission_result[i] ret += '\n' return ret def describe_problem(self): if not self.problem_dict: return '未加载题目!' else: ret = '题目描述:\n' ret += self.problem_dict['text'] ret += '\n========\n' ret += '附加信息:\n' ret += '本次测试时间限制:{0} s,内存限制:{1} KB\n'.format(self.time_limit, self.memory_limit) return ret def reset(self): self.submission_result = [] self.problem_dict = {} # this function has to be defined outside the PyOJAgent class for multiprocessing to pickle def target_function(py_code, ret_dict): policy_globals = generate_restricted_environment_policy() policy_globals['output'] = None ret_dict['RE_flag'] = False ret_dict['RE_info'] = '' ret_dict['TLE_flag'] = True ret_dict['output'] = None try: byte_code = compile_restricted(py_code, '<inline>', 'exec') exec(byte_code, policy_globals) ret_dict['TLE_flag'] = False ret_dict['output'] = policy_globals['output'] except Exception as e: print(repr(e)) ret_dict['RE_flag'] = True # if RE, TLE flag would also be True ret_dict['RE_info'] = repr(e) finally: pass # print('finally') def generate_restricted_environment_policy(): policy_globals = {**safe_globals, **utility_builtins} policy_globals['__builtins__']['__metaclass__'] = type policy_globals['__builtins__']['__name__'] = type policy_globals['_getattr_'] = Guards.safer_getattr policy_globals['_write_'] = Guards.full_write_guard policy_globals['_getiter_'] = Eval.default_guarded_getiter policy_globals['_getitem_'] = Eval.default_guarded_getitem policy_globals['_print_'] = PrintCollector policy_globals['_iter_unpack_sequence_'] = Guards.guarded_iter_unpack_sequence return policy_globals
StarcoderdataPython
112446
<reponame>minhpqn/pyvi<filename>pyvi/__init__.py __author__ = 'trungtv'
StarcoderdataPython
1764870
#! /usr/bin/env python from z_app import app if __name__ == "__main__": app.run(debug=True)
StarcoderdataPython
1640377
""" Cpp solution with explanation in details It's a very classical question. Ref: http://www.geeksforgeeks.org/partition-set-k-subsets-equal-sum/ class Solution { public: // Method returns true if nums can be partitioned into K subsets // with equal sum bool canPartitionKSubsets(vector<int>& nums, int K) { int N = nums.size(); // If K is 1, then complete array will be our answer if (K == 1) return true; // If total number of partitions are more than N, then // division is not possible if (N < K) return false; // if array sum is not divisible by K then we can't divide // array into K partitions int sum = 0; for (int i = 0; i < N; i++) sum += nums[i]; if (sum % K != 0) return false; // the sum of each subset should be subset (= sum / K) int subset = sum / K; int subsetSum[K]; bool taken[N]; // Initialize sum of each subset from 0 for (int i = 0; i < K; i++) subsetSum[i] = 0; // mark all elements as not taken for (int i = 0; i < N; i++) taken[i] = false; // initialize first subsubset sum as last element of // array and mark that as taken subsetSum[0] = nums[N - 1]; taken[N - 1] = true; // call recursive method to check K-substitution condition return canPartitionKSubsets(nums, subsetSum, taken, subset, K, N, 0, N - 1); } // Recursive Utility method to check K equal sum // subsetition of array /** array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken */ bool canPartitionKSubsets(vector<int>& nums, int subsetSum[], bool taken[], int subset, int K, int N, int curIdx, int limitIdx) { if (subsetSum[curIdx] == subset) { /* current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'*/ if (curIdx == K - 2) return true; // recursive call for next subsetition return canPartitionKSubsets(nums, subsetSum, taken, subset, K, N, curIdx + 1, N - 1); } // start from limitIdx and include elements into current partition for (int i = limitIdx; i >= 0; i--) { // if already taken, continue if (taken[i]) continue; int tmp = subsetSum[curIdx] + nums[i]; // if temp is less than subset then only include the element // and call recursively if (tmp <= subset) { // mark the element and include into current partition sum taken[i] = true; subsetSum[curIdx] += nums[i]; bool nxt = canPartitionKSubsets(nums, subsetSum, taken, subset, K, N, curIdx, i - 1); // after recursive call unmark the element and remove from // subsetition sum taken[i] = false; subsetSum[curIdx] -= nums[i]; if (nxt) return true; } } return false; } }; """ """ class Solution(object): def canPartitionKSubsets(self, nums, k): if len(nums) < k or sum(nums) % k != 0 : return False sub_sum = sum(nums) / k if any(num > sub_sum for num in nums): return False nums.sort() return self.dfs(sub_sum,nums[-1], nums[: -1]) def dfs(self, sub_sum, cur_sum, nums): if cur_sum == sub_sum: if not nums: return True return self.dfs(sub_sum, nums[-1], nums[: -1]) size = len(nums) for index in xrange(size): tmp = nums[index] if nums[index] + cur_sum <= sub_sum: nums[index], nums[-1] = nums[-1], nums[index] nums.pop() if self.dfs(sub_sum, cur_sum + tmp, nums): return True nums.append(tmp) nums[index], nums[-1] = nums[-1], nums[index] return False """ """ class Solution { public boolean canPartitionKSubsets(int[] nums, int k) { int sum=0,len=nums.length; for(int i:nums) sum+=i; if(sum%k!=0) return false; int[] sums= new int[k]; int target=sum/k; Arrays.sort(nums); return helper(nums,sums,target,len-1); } public boolean helper(int[]nums,int[] sums,int target,int curidx){ if(curidx==0){ for(int i=0;i<sums.length-1;i++){ if(sums[i]!=target) return false; } return true; } for(int i=0;i<sums.length;i++){ if(sums[i]+nums[curidx]<=target){ sums[i]+=nums[curidx]; if(helper(nums,sums,target,curidx-1)) return true; sums[i]-=nums[curidx]; } } return false; } } """ """ [Java/C++]Straightforward dfs solution Update: This question has been changed after the contest. It added the special restriction 0 < nums[i] < 10000. My solution here is without that consideration. Assume sum is the sum of nums[] . The dfs process is to find a subset of nums[] which sum equals to sum/k. We use an array visited[] to record which element in nums[] is used. Each time when we get a cur_sum = sum/k, we will start from position 0 in nums[] to look up the elements that are not used yet and find another cur_sum = sum/k. An corner case is when sum = 0, my method is to use cur_num to record the number of elements in the current subset. Only if cur_sum = sum/k && cur_num >0, we can start another look up process. Some test cases may need to be added in: nums = {-1,1,0,0}, k = 4 nums = {-1,1}, k = 1 nums = {-1,1}, k = 2 nums = {-1,1,0}, k = 2 ... Java version: public boolean canPartitionKSubsets(int[] nums, int k) { int sum = 0; for(int num:nums)sum += num; if(k <= 0 || sum%k != 0)return false; int[] visited = new int[nums.length]; return canPartition(nums, visited, 0, k, 0, 0, sum/k); } public boolean canPartition(int[] nums, int[] visited, int start_index, int k, int cur_sum, int cur_num, int target){ if(k==1)return true; if(cur_sum == target && cur_num>0)return canPartition(nums, visited, 0, k-1, 0, 0, target); for(int i = start_index; i<nums.length; i++){ if(visited[i] == 0){ visited[i] = 1; if(canPartition(nums, visited, i+1, k, cur_sum + nums[i], cur_num++, target))return true; visited[i] = 0; } } return false; } C++ version: bool canPartitionKSubsets(vector<int>& nums, int k) { int sum = 0; for(int num:nums)sum+=num; if(k <= 0 || sum%k != 0)return false; vector<int> visited(nums.size(), 0); return canPartition(nums, visited, 0, k, 0, 0, sum/k); } bool canPartition(vector<int>& nums, vector<int>& visited, int start_index, int k, int cur_sum, int cur_num, int target){ if(k==1) return true; if(cur_sum == target && cur_num >0 ) return canPartition(nums, visited, 0, k-1, 0, 0, target); for(int i = start_index; i<nums.size(); i++){ if(!visited[i]){ visited[i] = 1; if(canPartition(nums, visited, i+1, k, cur_sum + nums[i], cur_num++, target)) return true; visited[i] = 0; } } return false; } """ class Solution(object): def canPartitionKSubsets(self, nums, k): if k <= 0 or len(nums) < k or sum(nums) % k != 0: return False def canPartition(nums, start_index, k, cur_sum, cur_num, target): if cur_sum > target: return False if k == 1: return True if cur_sum == target and cur_num > 0: return canPartition(nums, 0, k-1, 0, 0, target) for i in range(start_index, len(nums)): if self.visited[i] is False: self.visited[i] = True if canPartition(nums, start_index + 1, k, cur_sum + nums[i], cur_num + 1, target): return True self.visited[i] = False return False self.visited = [False] * len(nums) return canPartition(nums, 0, k, 0, 0, sum(nums) // k) s = Solution() print(s.canPartitionKSubsets([4, 5, 3, 2, 5, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5], 14)) print(s.canPartitionKSubsets([780,935,2439,444,513,1603,504,2162,432,110,1856,575,172,367,288,316], 4)) class Solution(object): def canPartitionKSubsets(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ if k <= 0 or len(nums) < k or sum(nums) % k != 0: return False def dfs(target, cur_sum, nums): if target == cur_sum: if len(nums) == 0: return True return dfs(target, nums[-1], nums[:-1]) for i in range(len(nums)): tried_val = nums[i] if tried_val + cur_sum <= target: nums[i], nums[-1] = nums[-1], nums[i] if dfs(target, cur_sum + tried_val, nums[:-1]): return True nums[-1], nums[i] = nums[i], nums[-1] return False nums = sorted(nums) return dfs(sum(nums)//k, nums[-1], nums[:-1])
StarcoderdataPython
11140
<gh_stars>1-10 # Given an integer n, count the total number of digit 1 appearing # in all non-negative integers less than or equal to n. # # For example: # Given n = 13, # Return 6, because digit 1 occurred in the following numbers: # 1, 10, 11, 12, 13. # class Solution: def countDigitOne(self, n): """ :type n: int :rtype: int """ # sum all the '1's inside the n numbers count = 0 for i in range(1, n+1): # count including n count += self.numberOfDigitOne(i) return count def numberOfDigitOne(self, n): """ function to count number of digit ones in a number n. mod by 10 to test if 1st digit is 1; then divide by 10 to get next digit; next test if next digit is 1. """ result = 0 while n: if n % 10 == 1: result += 1 n = n / 10 return result if __name__ == "__main__": print Solution().countDigitOne(13)
StarcoderdataPython
73117
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding : utf-8 -*- # Author: <NAME> import json import argparse from humblecritic import goodreads as gr from humblecritic import __version__ def setup_parser(): parser = argparse.ArgumentParser( description='Get score for HumbleBundle bundles.') parser.add_argument('-v', '--version', help="print the script version", action='version', version=__version__) parser.add_argument('-l', '--link', help="URL [1 or more] to specific HumbleBundle book bundle.", dest='urls', nargs='*', action='store') parser.add_argument('-j', '--json', help="export results to json file.", dest='json_file', action='store') return parser.parse_args() def export_to_json(path, bundles): data = [] for bundle in bundles: tiers = [] for tier in bundle.tiers: items = [] for item in tier.items: entry = {} if isinstance(item.meta_item, gr.Book): entry = {"id": item.meta_item.id, "title": item.meta_item.title, "authors": item.meta_item.authors, "link": item.meta_item.link, "average_rating": item.meta_item.average_rating, "ratings_count": item.meta_item.ratings_count} else: entry = {"id": "", "title": item.title, "authors": "", "link": "", "average_rating": "", "ratings_count": ""} items.append(entry) tiers.append( {"title": tier.title, "price": tier.price, "items": items}) data.append({"title": bundle.title, "link": bundle.url, "type": bundle.type.value, "tiers": tiers}) with open(path, 'w') as outfile: json.dump(data, outfile) def item_description(item): lines = [] if isinstance(item.meta_item, gr.Book): description = item.meta_item.title + " by " for author in item.meta_item.authors: description += str(author) + ", " lines.append(description) description = "Average rating of " + \ str(item.meta_item.average_rating) description += " from " + \ str(item.meta_item.ratings_count) + " reviews." lines.append(description) else: lines = [ str(item) + " was not found (will not be counted in total score)."] return lines def print_summary(bundle): print("\n" + bundle.title) ratings = [] for tier_index, tier in enumerate(bundle.tiers): prefix = "│" if tier_index is (len(bundle.tiers) - 1): print("└── " + tier.title) prefix = " " else: print("├── " + tier.title) tier_ratings = [] for item_index, item in enumerate(tier.items): description = item_description(item) for index, line in enumerate(description): if index is 0: if item_index is (len(tier.items) - 1): print(prefix + "   └── " + line) else: print(prefix + "   ├── " + line) else: if item_index is (len(tier.items) - 1): print(prefix + "   " + line) else: print(prefix + "   │ " + line) if isinstance(item.meta_item, gr.Book): tier_ratings.append(float(item.meta_item.average_rating)) ratings += tier_ratings average = float(sum(ratings)) / max(len(ratings), 1) print("\nAverage rating in bundle: {0:.2f}".format(average))
StarcoderdataPython
199059
<reponame>kmr0877/pyq<filename>src/pyq/tests/test_numpy.py from __future__ import absolute_import try: import numpy from numpy import ma except ImportError: numpy = ma = None import pytest import pyq from pyq import * from pyq import _PY3K, Q_VERSION from .test_k import K_INT_CODE, K_LONG_CODE SYM_NA = int(K.int.na if Q_VERSION < 3.6 else K.long.na) pytestmark = pytest.mark.skipif(numpy is None, reason="numpy is not installed") SIZE_OF_PTR = pyq._k.SIZEOF_VOID_P SIMPLE_DTYPES = 'bool uint8 int16 int32 int64 float32 float64'.split() # TODO: Add support for the "Y" unit. What to do with ps and as? # TIME_UNITS = 'Y M W D h m s ms us ns ps as'.split() TIME_UNITS = 'M W D h m s ms us ns'.split() DATETIME_DTYPES = ['datetime64[%s]' % unit for unit in TIME_UNITS] TIMEDELTA_DTYPES = ['timedelta64[%s]' % unit for unit in TIME_UNITS if unit != 'M'] @pytest.mark.parametrize(('t', 'r'), [ ('?', 'b'), ('h', 'h'), ('i', 'i'), ('q', 'j'), ('f', 'e'), ('d', 'f'), ]) def test_ndarray(t, r): a = numpy.zeros(0, t) assert K(a) == k('"%c"$()' % r) a = numpy.zeros(1, t) assert K(a) == k(',0' + r) def test_ma(): x = ma.array([1.0, 2, 3]) assert K(x) == k('1.0 2 3') x = ma.masked_values([1.0, 0, 2], 0) assert K(x) == k('1 0n 2') s = ma.masked_values(0.0, 0) assert K(s) == k('0n') @pytest.mark.parametrize(('n', 'k'), [ ('int8', '0x01'), ('int16', '1h'), ('int32', '1i'), ('int64', '1j'), ('float32', '1e'), ('float64', '1f'), ]) def test_scalar_conversion(n, k): x = getattr(numpy, n)(1) assert K(x) == q(k) @pytest.mark.parametrize('a', [ '0n', '1i', '1j', '0.1f', '1e', '1h', '010101b', '0xdeadbeef', '0 0n 1 0n', '0 0N 1 0N', '1 2 3 0Nh', '0.0 0.1 0Nf', '"abracadabra"', '"s p a c e d"', '0.0 0.1 0Ne', '1 2 3 0Nj', '1 2 3 0Ni', ]) def test_ma_array_roundtrip(a): x = q(a) m = ma.array(x) assert K(m) == x def test_ma_conversion(): x = q('1 0N 2') m = ma.array(x) assert isinstance(m.mask, numpy.ndarray) @pytest.mark.parametrize( 't,char,size', [ (1, '?', 1), (4, 'B', 1), (5, 'h', 2), (6, K_INT_CODE, 4), (7, K_LONG_CODE, 8), (8, 'f', 4), (9, 'd', 8), (10, 'S', 1), # (11, 'O', SIZE_OF_PTR) # issue #589 (12, 'M', 8), (13, 'M', 8), (14, 'M', 8), # (15, 'M', 8), # datetime (16, 'm', 8), (17, 'm', 8), (18, 'm', 8), (19, 'm', 8), ]) def test_empty(t, char, size): x = q('$[;()]', K._kh(t)) a = numpy.array(x) assert a.dtype.char == char assert a.dtype.itemsize == size def test_chartype(): x = kp('abc') a = numpy.array(x) assert a.tolist() == [b'a', b'b', b'c'] assert K(a) == x def test_bytestype(): x = q('0xabab') a = numpy.array(x) assert a.tolist() == [0xAB] * 2 assert K(a) == x @pytest.mark.xfail # issue #591 def test_splayed_char(tmpdir): x = q('([]x:enlist"abc")') d = q('{sv[`;x,`x`]}', tmpdir) d.set(x) y = d.get.x a = numpy.array(y) assert y.inspect(b't') == 87 assert a.dtype.char == 'S' assert a.tolist() == [b'a', b'b', b'c'] @pytest.mark.skipif("pyq.Q_VERSION < 3") def test_symbol_list(): x = K(['a']) a = numpy.array(x) assert numpy.array_equiv(a, ['a']) x = K(['a'] * 3) a = numpy.array(x, 'O') assert a[0] is a[1] is a[2] == 'a' def test_settitem(): a = numpy.array([1]) a[0] = K(2) assert a[0] == 2 def test_issue652(): a = numpy.array([(q('1h'), q('1i'), q('1j'))], dtype='h,i,q') assert a.dtype == numpy.dtype('h,i,q') def test_datetime64_vector(): a = numpy.array(['2001-01-01'] * 3, dtype='M8') assert K(a) == q('3#2001.01.01') a = numpy.array(['2001-01-01T00Z'], dtype='M8[ns]') assert K(a) == q('enlist 2001.01.01D00') a = numpy.array(['2001-01-01T00Z'], dtype='M8[h]') assert K(a) == q('enlist 2001.01.01D00') a = numpy.array(['2001-01-01T00Z'], dtype='M8[m]') assert K(a) == q('enlist 2001.01.01D00') a = numpy.array(['2001-01-01T00Z'], dtype='M8[s]') assert K(a) == q('enlist 2001.01.01D00') a = numpy.array(['2001-01-01T00Z'], dtype='M8[ms]') assert K(a) == q('enlist 2001.01.01D00') a = numpy.array(['2001-01-01T00Z'], dtype='M8[us]') assert K(a) == q('enlist 2001.01.01D00') def test_datetime64_scalar(): a = numpy.array('2001-01-01', dtype='M8') assert K(a) == q('2001.01.01') a = numpy.datetime64(1, 'Y') assert K(a) == q('1971.01m') a = numpy.datetime64(1, 'M') assert K(a) == q('1970.02m') a = numpy.datetime64(1, 'W') assert K(a) == q('1970.01.08') a = numpy.array('2001-01-01T00Z', dtype='M8[ns]') assert K(a) == q('2001.01.01D00') a = numpy.array('2001-01-01T00Z', dtype='M8[h]') assert K(a) == q('2001.01.01D00') a = numpy.array('2001-01-01T00Z', dtype='M8[m]') assert K(a) == q('2001.01.01D00') a = numpy.array('2001-01-01T00Z', dtype='M8[s]') assert K(a) == q('2001.01.01D00') a = numpy.array('2001-01-01T00Z', dtype='M8[ms]') assert K(a) == q('2001.01.01D00') a = numpy.array('2001-01-01T00Z', dtype='M8[us]') assert K(a) == q('2001.01.01D00') def test_timedelta64_vector(): a = numpy.array([1, 2, 3], dtype='m8[s]') assert K(a) == q('"n"$ 1 2 3 * 1000000000j') a = numpy.array([1, 2, 3], dtype='m8[ms]') assert K(a) == q('"n"$ 1 2 3 * 1000000j') a = numpy.array([1, 2, 3], dtype='m8[us]') assert K(a) == q('"n"$ 1 2 3 * 1000j') a = numpy.array([1, 2, 3], dtype='m8[ns]') assert K(a) == q('"n"$ 1 2 3j') def test_timedelta64_scalar(): a = numpy.timedelta64(1, 'W') assert K(a) == q('7D00:00:00') a = numpy.timedelta64(1, 'D') assert K(a) == q('1D00:00:00') a = numpy.timedelta64(1, 'h') assert K(a) == q('0D01:00:00') a = numpy.timedelta64(1, 'm') assert K(a) == q('0D00:01:00') a = numpy.timedelta64(1, 's') assert K(a) == q('0D00:00:01') a = numpy.timedelta64(1, 'ms') assert K(a) == q('0D00:00:00.001') a = numpy.timedelta64(1, 'us') assert K(a) == q('0D00:00:00.000001') a = numpy.timedelta64(1, 'ns') assert K(a) == q('0D00:00:00.000000001') def test_record_arrays(): a = numpy.array([(date(2001, 1, 1), 1, 3.14), (date(2001, 1, 2), 2, 2.78), ], dtype=[('date', 'M8[D]'), ('num', 'i2'), ('val', 'f')]) t = K(a) assert t.date == q('2001.01.01 2001.01.02') assert t.num == q('1 2h') assert t.val == q('3.14 2.78e') r = K(a[0]) assert r == q("`date`num`val!(2001.01.01;1h;3.14e)") def test_unsupported_dtype_errors(): with pytest.raises(TypeError): a = numpy.array('abc', dtype='S3') K(a) @pytest.mark.parametrize('e', ['sym', 'other']) def test_enum_conversion(q, e): x = q('`%s?`a`b`c' % e) a = numpy.asarray(x.data) a.tolist() == [0, 1, 2] @pytest.mark.parametrize('data, dtype, kstr', [ ([1, 0, 1], bool, '101b'), ([1, 2, 3], 'h', '1 2 3h'), ([1, 2, 3], 'i', '1 2 3i'), ([1, 2, 3], 'q', '1 2 3j'), ([1, 2, 3], 'f', '1 2 3e'), ([1, 2, 3], 'd', '1 2 3f'), ]) def test_from_array_struct(data, dtype, kstr): a = numpy.array(data, dtype) x = K._from_array_struct(a.__array_struct__) assert x == q(kstr) def test_from_array_struct_errors(): with pytest.raises(TypeError): K._from_array_struct() # XXX: Shouldn't this be a TypeError? with pytest.raises(ValueError): K._from_array_struct(None) # XXX: Shouldn't this be a NotImplementedError? # a = numpy.zeros((1, 1)) # with pytest.raises(ValueError): # K._from_array_struct(a.__array_struct__) a = numpy.array(['', None], 'O') # XXX: Shouldn't this be a TypeError? with pytest.raises(ValueError): K._from_array_struct(a.__array_struct__) def test_numpy_in_versions(capsys): versions() out = capsys.readouterr()[not _PY3K] assert 'NumPy' in out def test_no_dtype(): class NoDtype(numpy.ndarray): """A helper class to test error branches""" @property def dtype(self): raise AttributeError('intentional error') x = NoDtype([0], dtype='M8[D]') with pytest.raises(AttributeError) as info: K(x) assert 'intentional error' in str(info.value) @pytest.mark.parametrize('kstr, typestr', zip( ('0b;0x00;0h;0i;0j;0e;0.0;" ";`;2000.01m;2000.01.01;' '2000.01.01T00:00:00.000;00:00;00:00:00;00:00:00.000').split(';'), ('<b1,<u1,<i2,<i4,<i8,<f4,<f8,<S1,' '|O%d,<i4,<i4,<f8,<i4,<i4,<i4' % SIZE_OF_PTR).split(','))) def test_array_typestr(kstr, typestr): x = q(kstr) assert x.__array_typestr__ == typestr def test_there_and_back_again(q): x = q.til(10) a = numpy.asarray(x) y = K(a) assert x is y def test_table_to_array(): t = q('([]a:1 2;b:"xy")') a = numpy.array(t) assert a.tolist() == [(1, b'x'), (2, b'y')] @pytest.mark.parametrize('dtype', SIMPLE_DTYPES + TIMEDELTA_DTYPES + DATETIME_DTYPES) def test_table_to_array_all_types(dtype): c = numpy.zeros(1, dtype) t = +q('!', ['c'], (c,)) a = numpy.asarray(t) assert a.dtype.names == ('c',) assert numpy.array_equiv(c, a['c']) @pytest.mark.skipif("q('.z.K') < 3") @pytest.mark.parametrize('dtype', SIMPLE_DTYPES) def test_2d(dtype): a = numpy.zeros((2, 3), dtype) x = K(a) y = K(a.flatten()) assert x.raze == y @pytest.mark.skipif("q('.z.K') < 3.4") @pytest.mark.parametrize('dtype', SIMPLE_DTYPES) def test_3d(dtype): a = numpy.zeros((2, 3, 2), dtype) x = K(a) y = K(a.flatten()) assert x.raze.raze == y @pytest.mark.parametrize('dtype', SIMPLE_DTYPES) def test_0d(dtype): a = numpy.ones((), dtype) x = K(a) assert x.enlist[0] == 1 def test_enum_to_array(q): x = q('`sym?`a`b') a = numpy.array(['a', 'b'], dtype=object) assert numpy.array_equiv(x, a) @pytest.mark.skipif("q('.z.K') < 3.4") @pytest.mark.parametrize('dtype', SIMPLE_DTYPES) def test_2d_roundtrip(dtype): a = numpy.zeros((3, 2), dtype) x = K(a) b = numpy.array(x) assert numpy.array_equiv(a, b) def test_priority(): a = numpy.arange(2) b = q.til(2) assert isinstance(a + b, K) assert isinstance(b + a, K) class A(object): @property def __array_struct__(self): raise TypeError def test_broken_array_struct(): with pytest.raises(TypeError): K(A()) def test_broken_mask(): class B(object): a = numpy.zeros(0) @property def __array_struct__(self): return self.a.__array_struct__ @property def mask(self): raise TypeError with pytest.raises(TypeError): K(B()) def test_strided_nd(): a = numpy.zeros((2, 2, 2)) with pytest.raises(ValueError): K(a.diagonal()) def test_0d_str(): a = numpy.array('x', 'O') assert K(a) == 'x' def test_call_python(q): def f(): return numpy.array([1.0, 2.0]) q.f = f assert q("f()") == [1.0, 2.0] def test_enum_to_numpy(q): x = q('`sym?`a`b`') assert numpy.asarray(x.data).tolist() == [0, 1, SYM_NA]
StarcoderdataPython
55077
from pathlib import Path from boucanpy.core import logger from boucanpy.cli.base import BaseCommand from boucanpy.db.models import models class DbTruncate(BaseCommand): name = "db-truncate" aliases = ["truncate"] description = "truncate db" add_log_level = True add_debug = True @classmethod def parser(cls, parser): parser.add_argument("-c", "--confirm", action="store_true", help="seed data") return parser async def run(self): self.db_register() failed = [] if self.option("confirm"): for class_name, model in models.items(): for item in self.session().query(model).all(): logger.warning(f"run@db_truncate.py - Deleting {item}") try: self.session().delete(item) self.session().commit() except Exception as e: failed.append((item, e)) else: logger.warning("run@db_truncate.py - You must confirm to drop data") if len(failed) > 0: logger.warning("run@db_truncate.py - Encountered errors") for f in failed: print("Failed:", item[0]) print("Error", item[1])
StarcoderdataPython