content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
from __future__ import annotations from spark_auto_mapper_fhir.fhir_types.uri import FhirUri from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType # This file is auto-generated by generate_classes so do not edit manually # noinspection PyPep8Naming class ActUncertainty(GenericTypeCode): """ v3.ActUncertainty From: http://terminology.hl7.org/ValueSet/v3-ActUncertainty in v3-codesystems.xml OpenIssue: Missing Description """ """ http://terminology.hl7.org/CodeSystem/v3-ActUncertainty """ codeset: FhirUri = "http://terminology.hl7.org/CodeSystem/v3-ActUncertainty" class ActUncertaintyValues: """ Specifies that the act statement is made without explicit tagging of uncertainty. This is the normal statement, meaning that it is not free of errors and uncertainty may still exist. From: http://terminology.hl7.org/CodeSystem/v3-ActUncertainty in v3-codesystems.xml """ StatedWithNoAssertionOfUncertainty = ActUncertainty("N") """ Specifies that the originator of the Act statement does not have full confidence in the applicability (i.e., in event mood: factual truth) of the statement. From: http://terminology.hl7.org/CodeSystem/v3-ActUncertainty in v3-codesystems.xml """ StatedWithUncertainty = ActUncertainty("U")
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 9009, 62, 23736, 62, 76, 11463, 62, 69, 71, 343, 13, 69, 71, 343, 62, 19199, 13, 9900, 1330, 376, 71, 343, 52, 380, 198, 198, 6738, 9009, 62, 23736, 62, 76, 11463, 62, 69, 71...
2.87976
499
"""Router for gathering the views together.""" from fastapi import APIRouter from guid import views api_router = APIRouter() api_router.include_router(views.router, prefix="/guid", tags=["guid"])
[ 37811, 49, 39605, 329, 11228, 262, 5009, 1978, 526, 15931, 198, 6738, 3049, 15042, 1330, 3486, 4663, 39605, 198, 6738, 10103, 1330, 5009, 628, 198, 15042, 62, 472, 353, 796, 3486, 4663, 39605, 3419, 198, 15042, 62, 472, 353, 13, 17256, ...
3.142857
63
import time real_time = time.strftime("00. %Y年%m月%d日%y点:%m分:%S秒", time.localtime()) print(real_time) giao=open("file.txt","w") print(giao.write(real_time))
[ 11748, 640, 198, 198, 5305, 62, 2435, 796, 640, 13, 2536, 31387, 7203, 405, 13, 4064, 56, 33176, 112, 4, 76, 17312, 230, 4, 67, 33768, 98, 4, 88, 163, 224, 117, 25, 4, 76, 26344, 228, 25, 4, 50, 163, 100, 240, 1600, 640, 13, ...
1.938272
81
import warnings from typing import Any import airtable from prefect import Task from prefect.client import Secret from prefect.utilities.tasks import defaults_from_attrs class WriteAirtableRow(Task): """ A task for writing a row to an Airtable table. Note that _all_ initialization settings can be provided / overwritten at runtime. Args: - base_key (str): the Airtable base key - table_name (str): the table name - credentials_secret (str, DEPRECATED): the name of a secret that contains an Airtable API key. - **kwargs (optional): additional kwargs to pass to the `Task` constructor """ @defaults_from_attrs("base_key", "table_name", "credentials_secret") def run( self, data: dict, base_key: str = None, table_name: str = None, api_key: str = None, credentials_secret: str = None, ) -> dict: """ Inserts data into an Airtable table Args: - data (dict): the data to insert. This should be formatted as a dictionary mapping each column name to a value. - base_key (str): the Airtable base key - table_name (str): the table name - api_key (str): an Airtable API key. This can be provided via a Prefect Secret - credentials_secret (str, DEPRECATED): the name of a secret that contains an Airtable API key. Returns: - a dictionary containing information about the successful insert """ if credentials_secret is not None: warnings.warn( "The `credentials_secret` argument is deprecated. Use a `Secret` task " "to pass the credentials value at runtime instead.", UserWarning, ) api_key = Secret(credentials_secret).get() table = airtable.Airtable(base_key, table_name, api_key) return table.insert(data)
[ 11748, 14601, 198, 6738, 19720, 1330, 4377, 198, 198, 11748, 1633, 11487, 198, 198, 6738, 662, 2309, 1330, 15941, 198, 6738, 662, 2309, 13, 16366, 1330, 3943, 198, 6738, 662, 2309, 13, 315, 2410, 13, 83, 6791, 1330, 26235, 62, 6738, 6...
2.489822
786
from fabric.api import * from ec2 import running_instances, instances_by_zones, instances_by_role DEFAULT_REGION = 'eu-west-1' # TODO: (NF 2013-01-03) Refactor this around a decent data model that is non-AWS specific. ROLE_TAG='aws:autoscaling:groupName' ROLE_TAG='category' @task def region(region=DEFAULT_REGION): """ Graph AWS region into an SVG diagram. """ instances = running_instances(region) with open('docs/ec2.diag', 'w') as fd: fd.write(nwdiag(instances_by_zones(instances), instances_by_role(instances))) try: local('nwdiag --ignore-pil -Tsvg docs/ec2.diag') except: print "Error running nwdiag"
[ 6738, 9664, 13, 15042, 1330, 1635, 198, 6738, 9940, 17, 1330, 2491, 62, 8625, 1817, 11, 10245, 62, 1525, 62, 89, 1952, 11, 10245, 62, 1525, 62, 18090, 198, 198, 7206, 38865, 62, 31553, 2849, 796, 705, 12496, 12, 7038, 12, 16, 6, 1...
2.486989
269
# # PySNMP MIB module RBTWS-REGISTRATION-CHASSIS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBTWS-REGISTRATION-CHASSIS-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:53:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint") rbtwsRegistration, = mibBuilder.importSymbols("RBTWS-ROOT-MIB", "rbtwsRegistration") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Integer32, ModuleIdentity, Counter64, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Counter32, TimeTicks, Unsigned32, Gauge32, MibIdentifier, iso, ObjectIdentity, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "ModuleIdentity", "Counter64", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Counter32", "TimeTicks", "Unsigned32", "Gauge32", "MibIdentifier", "iso", "ObjectIdentity", "Bits") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") rbtwsRegistrationChassisMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 3, 5)) rbtwsRegistrationChassisMib.setRevisions(('2007-08-22 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: rbtwsRegistrationChassisMib.setRevisionsDescriptions(('v1.0: initial version, published in 6.2 release',)) if mibBuilder.loadTexts: rbtwsRegistrationChassisMib.setLastUpdated('200708231753Z') if mibBuilder.loadTexts: rbtwsRegistrationChassisMib.setOrganization('Enterasys Networks') if mibBuilder.loadTexts: rbtwsRegistrationChassisMib.setContactInfo('www.enterasys.com') if mibBuilder.loadTexts: rbtwsRegistrationChassisMib.setDescription("The MIB module for Enterasys Networks wireless switch chassis component OID registrations. These are generic OIDs: they apply to any switch model, if the respective chassis component is present in the switch. Copyright 2007 Enterasys Networks, Inc. All rights reserved. This SNMP Management Information Base Specification (Specification) embodies confidential and proprietary intellectual property. This Specification is supplied 'AS IS' and Enterasys Networks makes no warranty, either express or implied, as to the use, operation, condition, or performance of the Specification.") rbtwsChassisComponents = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 3, 4)) rbtwsChasCompPowerSupplies = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 3, 4, 1)) rbtwsChasCompFans = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 3, 4, 2)) rbtwsChasCompPowerSupply1 = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 3, 4, 1, 1)) rbtwsChasCompPowerSupply2 = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 3, 4, 1, 2)) rbtwsChasCompFan1 = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 3, 4, 2, 1)) rbtwsChasCompFan2 = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 3, 4, 2, 2)) rbtwsChasCompFan3 = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 3, 4, 2, 3)) mibBuilder.exportSymbols("RBTWS-REGISTRATION-CHASSIS-MIB", rbtwsChasCompPowerSupplies=rbtwsChasCompPowerSupplies, rbtwsChasCompPowerSupply1=rbtwsChasCompPowerSupply1, rbtwsChasCompFan3=rbtwsChasCompFan3, rbtwsRegistrationChassisMib=rbtwsRegistrationChassisMib, rbtwsChassisComponents=rbtwsChassisComponents, rbtwsChasCompPowerSupply2=rbtwsChasCompPowerSupply2, rbtwsChasCompFan2=rbtwsChasCompFan2, rbtwsChasCompFans=rbtwsChasCompFans, rbtwsChasCompFan1=rbtwsChasCompFan1, PYSNMP_MODULE_ID=rbtwsRegistrationChassisMib)
[ 2, 198, 2, 9485, 15571, 7378, 337, 9865, 8265, 17986, 51, 19416, 12, 31553, 1797, 5446, 6234, 12, 3398, 10705, 1797, 12, 8895, 33, 357, 4023, 1378, 16184, 76, 489, 8937, 13, 785, 14, 79, 893, 11632, 8, 198, 2, 7054, 45, 13, 16, ...
2.695825
1,509
# coding=utf-8 from django.core.management import BaseCommand import datetime
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 1330, 7308, 21575, 198, 11748, 4818, 8079, 628 ]
3.590909
22
from vfmflathub.api import get_applications from vfmflathub.application import Application from vfmflathub.flatpak import add_flathub, get_installed_applications, install, uninstall, update_all
[ 6738, 410, 38353, 2704, 776, 549, 13, 15042, 1330, 651, 62, 1324, 677, 602, 198, 6738, 410, 38353, 2704, 776, 549, 13, 31438, 1330, 15678, 198, 6738, 410, 38353, 2704, 776, 549, 13, 38568, 41091, 1330, 751, 62, 2704, 776, 549, 11, 6...
3.344828
58
from defs import * __pragma__('noalias', 'name') __pragma__('noalias', 'undefined') __pragma__('noalias', 'Infinity') __pragma__('noalias', 'keys') __pragma__('noalias', 'get') __pragma__('noalias', 'set') __pragma__('noalias', 'type') __pragma__('noalias', 'update') class CreepSpawner: """Class definition for creep spawner containing functions used while spawning creeps. spawn: the current spawn from Game.spawns num_creeps: the number of <role> creeps present in the room. role: The current role. last_source_idx: The index of the last source a harvester was sent to.""" def get_source(self): """Method to find all sources in a room and assign the correct one to the currently spawning harvester.""" sources = self.spawn.room.find(FIND_SOURCES) if self.num_creeps == 0: source = sources[0] self.spawn.memory.last_idx = 0 return source.id, self.spawn.memory.last_idx elif self.num_creeps != 0 and self.spawn.memory.last_idx == 0: source = sources[1] self.spawn.memory.last_idx = 1 return source.id, self.spawn.memory.last_idx elif self.num_creeps != 0 and self.spawn.memory.last_idx == 1: source = sources[0] self.spawn.memory.last_idx = 0 return source.id, self.spawn.memory.last_idx @staticmethod def get_part_cost(parts): """Method to calculate the cost of bodies while building them.""" cost_dict = { MOVE: 50, WORK: 100, CARRY: 50, ATTACK: 80, RANGED_ATTACK: 150, HEAL: 250, TOUGH: 10, CLAIM: 600 } cost = 0 for part in parts: cost += cost_dict[part] return cost
[ 6738, 825, 82, 1330, 1635, 198, 198, 834, 1050, 363, 2611, 834, 10786, 3919, 26011, 3256, 705, 3672, 11537, 198, 834, 1050, 363, 2611, 834, 10786, 3919, 26011, 3256, 705, 917, 18156, 11537, 198, 834, 1050, 363, 2611, 834, 10786, 3919, ...
2.185185
837
#!/usr/bin/python3.4 # nginx_hit_counter.py v1.0 # Small tool for monitoring nginx log file and sending a hit to Graphite when a page is accessed # Usage: Feed in nginx access.log file, graphite endpoint, profit. # Original inspiration taken and expanded on from this post on Stack Overflow (by Jochen Ritzel): # http://stackoverflow.com/questions/1703640/how-to-implement-a-pythonic-equivalent-of-tail-f # Written by Pseudophed Trismegistus import socket, time, os, argparse, sys, datetime if __name__ == '__main__': parser = argparse.ArgumentParser(description='Hit Counter for Nginx Access Logs to Feed Metrics to Graphite', prog='nginx_hit_counter.py') parser.add_argument('-H', action='store', dest='hostname', help='Graphite Server Hostname', required=True) parser.add_argument('-p', action='store', dest='port', help='Graphite Server Port', type=int) #parser.add_argument('-u', action='store_true', dest='udp', help='Use UDP instead of TCP to send metrics.') parser.add_argument('-f', action='store', dest='filename', help='Nginx Access Log File (i.e. /var/log/nginx/access.log)', required=True) parser.add_argument('-v, --version', action='version', version='%(prog)s 1.0') args = parser.parse_args() #adding UDP vs TCP in the future... defauling to UDP for now #if args.udp: # proto = 'udp' #else: # proto = 'tcp' if args.port: port = args.port else: port = 2003 run(args.hostname, port, 'udp', args.filename)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 13, 19, 198, 2, 299, 42822, 62, 17945, 62, 24588, 13, 9078, 410, 16, 13, 15, 198, 2, 10452, 2891, 329, 9904, 299, 42822, 2604, 2393, 290, 7216, 257, 2277, 284, 29681, 578, 618, 257, 2443, ...
2.894212
501
""" add, update, clear, discard union | intersection & (todos os elementos presentes nos dois sets) difference - (elementos apenas no set da esquerda) symmetric_difference ^ (elementos que estao nos dois sets, mas nao em ambos) """ # sets so recebem valores, não possuem chave e valor igual os dicionarios(json) # sets nao respeitam ordem # sets nao repetem valores # s1 = {1,2,3,4,5,6} # s2 = set() # criar set vazio # s2.add(1) # s2.add(2) # s2.add(3) # s2.add(4) # s2.add(5) # s2.update('a') # s2.update('python') # # s2.discard(2) # # for v in s2: # print(v) # l1 = [1,2,1,1,3,4,5,5,6,6,6,6,6,7,8,9,'lincoln', 'lincoln'] # print(l1) # # l1 = set(l1) # print(l1) # # l1 = list(l1) # print(l1) # s1 = {1,2,3,4,5, 7} # s2 = {1,2,3,4,5,6} # s3 = s1 | s2 # s4 = s1 & s2 # # s5 = s1 - s2 # s5 = s2 - s1 # s6 = s1 ^ s2 # # print(s6) l1 = ['lincoln', 'joao', 'maria'] l2 = ['lincoln', 'joao', 'maria','lincoln','lincoln','lincoln','lincoln','lincoln', 'maria'] print(l1 != l2) l1 = set(l1) l2 = set(l2) print(l1 == l2)
[ 37811, 198, 2860, 11, 4296, 11, 1598, 11, 27537, 198, 24592, 930, 198, 3849, 5458, 1222, 357, 83, 375, 418, 28686, 5002, 418, 1944, 274, 43630, 466, 271, 5621, 8, 198, 26069, 1945, 532, 357, 30854, 418, 2471, 268, 292, 645, 900, 123...
1.926829
533
from .naive import load_model, get_scene_embeddings, get_timestamp_embeddings __version__ = "2021.1.0"
[ 6738, 764, 2616, 425, 1330, 3440, 62, 19849, 11, 651, 62, 29734, 62, 20521, 67, 654, 11, 651, 62, 16514, 27823, 62, 20521, 67, 654, 198, 198, 834, 9641, 834, 796, 366, 1238, 2481, 13, 16, 13, 15, 1, 198 ]
2.6
40
import os import pandas as pd import pytest from mighty_regression.log_init import initialize_logger initialize_logger() @pytest.fixture(scope="session") @pytest.fixture(scope="session")
[ 11748, 28686, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 12972, 9288, 198, 198, 6738, 18680, 62, 2301, 2234, 13, 6404, 62, 15003, 1330, 41216, 62, 6404, 1362, 198, 198, 36733, 1096, 62, 6404, 1362, 3419, 198, 198, 31, 9078...
3
64
# HelixStudios import re, os, platform, urllib from utils import Utils # import certifi, requests AGENT_NAME = 'Helix Studios' AGENT_VERSION = '2020.06.27.0' AGENT_LANGUAGES = [Locale.Language.NoLanguage, Locale.Language.English] AGENT_FALLBACK_AGENT = False AGENT_PRIMARY_PROVIDER = False AGENT_CONTRIBUTES_TO = ['com.plexapp.agents.cockporn'] AGENT_CACHE_TIME = CACHE_1HOUR * 24 # Delay used when requesting HTML, may be good to have to prevent being # banned from the site REQUEST_DELAY = 0 # URLS BASE_URL = 'https://www.helixstudios.net%s' # Example Video Details URL # https://www.helixstudios.net/video/3437/hosing-him-down.html BASE_VIDEO_DETAILS_URL = BASE_URL % '/video/%s/index.html' # Example Movie Details URL # https://www.helixstudios.net/movie/HXM118/index.html BASE_MOVIE_DETAILS_URL = BASE_URL % '/movie/%s/index.html' # Example Model Details URL # https://www.helixstudios.net/model/984/index.html BASE_MODEL_DETAILS_URL = BASE_URL % '/model/%s/index.html' # Example Search URL: # https://www.helixstudios.net/videos/?q=Hosing+Him+Down BASE_SEARCH_URL = BASE_URL % '/videos/?q=%s'
[ 2, 5053, 844, 13007, 4267, 201, 198, 11748, 302, 11, 28686, 11, 3859, 11, 2956, 297, 571, 201, 198, 6738, 3384, 4487, 1330, 7273, 4487, 201, 198, 201, 198, 2, 1330, 5051, 22238, 11, 7007, 201, 198, 201, 198, 4760, 3525, 62, 20608, ...
2.340594
505
from googletrans import Translator translator = Translator() print(translator.translate('안녕하세요.'))
[ 6738, 467, 519, 1616, 26084, 1330, 3602, 41880, 198, 7645, 41880, 796, 3602, 41880, 3419, 198, 4798, 7, 7645, 41880, 13, 7645, 17660, 10786, 168, 243, 230, 167, 227, 243, 47991, 246, 168, 226, 116, 168, 248, 242, 2637, 4008 ]
2.45
40
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-17 00:43 from __future__ import unicode_literals from django.db import migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 940, 319, 2864, 12, 3070, 12, 1558, 3571, 25, 3559, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.709091
55
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class UpdateTargetDetectorRuleDetails(object): """ Overriden settings of a Detector Rule applied on target """ def __init__(self, **kwargs): """ Initializes a new UpdateTargetDetectorRuleDetails object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param condition_groups: The value to assign to the condition_groups property of this UpdateTargetDetectorRuleDetails. :type condition_groups: list[oci.cloud_guard.models.ConditionGroup] """ self.swagger_types = { 'condition_groups': 'list[ConditionGroup]' } self.attribute_map = { 'condition_groups': 'conditionGroups' } self._condition_groups = None @property def condition_groups(self): """ Gets the condition_groups of this UpdateTargetDetectorRuleDetails. Condition group corresponding to each compartment :return: The condition_groups of this UpdateTargetDetectorRuleDetails. :rtype: list[oci.cloud_guard.models.ConditionGroup] """ return self._condition_groups @condition_groups.setter def condition_groups(self, condition_groups): """ Sets the condition_groups of this UpdateTargetDetectorRuleDetails. Condition group corresponding to each compartment :param condition_groups: The condition_groups of this UpdateTargetDetectorRuleDetails. :type: list[oci.cloud_guard.models.ConditionGroup] """ self._condition_groups = condition_groups
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 15069, 357, 66, 8, 1584, 11, 33448, 11, 18650, 290, 14, 273, 663, 29116, 13, 220, 1439, 2489, 10395, 13, 198, 2, 770, 3788, 318, 10668, 12, 36612, 284, 345, 739, 262, 14499, 2448, 33532, 1...
2.872063
766
import getopt import sys from runner import run_worker if __name__ == "__main__": print("Starting worker: %s" % sys.argv) start_worker(sys.argv[1:])
[ 11748, 651, 8738, 198, 11748, 25064, 198, 198, 6738, 17490, 1330, 1057, 62, 28816, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 3601, 7203, 22851, 8383, 25, 4064, 82, 1, 4064, 25064, 13, ...
2.596774
62
""" Gluon objects and sequential models used in the subpackage. """ import functools from typing import Callable, Dict, List, Optional, Union import mxnet as mx from mxnet import gluon from .._types import ActivationT, ContextT, InitializerT, StateInitializerT # Available RNNs. RNN_MAP: Dict[str, type] = { 'vanilla': gluon.rnn.RNN, 'lstm': gluon.rnn.LSTM, 'gru': gluon.rnn.GRU, } INIT_MAP: Dict[str, mx.init.Initializer] = { 'normal': mx.init.Normal(), 'uniform': mx.init.Uniform(), 'orthogonal_uniform': mx.init.Orthogonal(rand_type='uniform'), 'orthogonal_normal': mx.init.Orthogonal(rand_type='normal'), 'xavier_uniform': mx.init.Xavier(rnd_type='uniform'), 'xavier_normal': mx.init.Xavier(rnd_type='gaussian') } CTX_MAP: Dict[str, Callable[[int], mx.context.Context]] = { 'cpu': mx.context.cpu, 'gpu': mx.context.gpu, } STATE_INIT_MAP: Dict[str, Callable[..., mx.nd.NDArray]] = { 'zeros': mx.nd.zeros, 'ones': mx.nd.ones, 'uniform': functools.partial(mx.nd.uniform, low=-0.32, high=0.32), 'normal': functools.partial(mx.nd.normal, scale=0.07), } def mlp( *, n_layers: int, n_units: Union[int, List[int]], activation: Union[ActivationT, List[ActivationT]], output_dim: int, dtype: str, dropout: Union[float, List[float]], init: InitializerT, prefix: Optional[str] = 'decoder_', params: Optional[mx.gluon.ParameterDict] = None, ) -> Union[gluon.nn.Dense, gluon.nn.HybridSequential]: """A single dense layer or an MLP built with mxnet.gluon.nn.HybridSequential. """ n_hidden_layers = n_layers - 1 if isinstance(n_units, int): n_units = [n_units] * n_hidden_layers elif len(n_units) != n_hidden_layers: raise ValueError(f'`n_units` must contain exactly `n_layers-1` elements.') if not isinstance(activation, list): activation = [activation] * n_hidden_layers elif len(activation) != n_hidden_layers: raise ValueError(f'`activation` must contain exactly `n_layers-1` elements.') if isinstance(dropout, float): dropout = [dropout] * n_hidden_layers elif len(dropout) != n_hidden_layers: raise ValueError(f'`dropout` must contain exactly `n_layers-1` elements.') output_dense = gluon.nn.Dense( units=output_dim, dtype=dtype, flatten=False, weight_initializer=init, prefix=prefix if n_layers == 1 else f'{prefix}out_', params=params, ) if n_layers == 1: return output_dense net = gluon.nn.HybridSequential(prefix=f'{prefix.rstrip("_")}seq_') for i in range(n_hidden_layers): net.add(gluon.nn.Dense( units=n_units[i], activation=activation[i], dtype=dtype, flatten=False, weight_initializer=init, prefix=f'{prefix}l{i}_', )) if dropout != 0.: net.add(gluon.nn.Dropout(dropout[i])) net.add(output_dense) return net
[ 37811, 198, 38, 2290, 261, 5563, 290, 35582, 4981, 973, 287, 262, 850, 26495, 13, 198, 37811, 198, 198, 11748, 1257, 310, 10141, 198, 6738, 19720, 1330, 4889, 540, 11, 360, 713, 11, 7343, 11, 32233, 11, 4479, 198, 198, 11748, 285, 8...
2.149401
1,419
# Copyright (c) 2017 Qumulo, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import qumulo.lib.request as request import qumulo.lib.util as util # Deprecated, use v2 instead. @request.request # Deprecated, use v2 instead. @request.request # Deprecated, use v2 instead. @request.request @request.request @request.request @request.request @request.request @request.request @request.request @request.request
[ 2, 15069, 357, 66, 8, 2177, 1195, 388, 43348, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 407, 198, 2, 779, 428, 2393, 2845, 287, 11846, 351, 262, ...
3.503846
260
from AudioExtraction.Video import Video
[ 6738, 13491, 11627, 7861, 13, 10798, 1330, 7623, 628 ]
4.555556
9
# -*- coding: utf-8 -*- from dart_fss.corp.corp import Corp from dart_fss.corp.corp_list import CorpList, get_corp_list __all__ = ['Corp', 'CorpList', 'get_corp_list']
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 35970, 62, 69, 824, 13, 10215, 79, 13, 10215, 79, 1330, 11421, 198, 6738, 35970, 62, 69, 824, 13, 10215, 79, 13, 10215, 79, 62, 4868, 1330, 11421, 8053, 11, 65...
2.333333
72
#!/usr/bin/env python import os, sys from distutils.core import setup, Extension, Command import base32 setup_args = { 'name': 'base32', 'version': base32.base32_verstr, 'description': 'libbase32 is an implementation of base32 encoding for encoding arbitrary binary data so that humans can remember, copy, e-mail and cut-n-paste it.', 'author': 'zooko', 'author_email': 'zooko@zooko.com', 'license': 'BSD-Like', 'package_dir': {'base32': '.'}, 'packages': ['base32'], } if __name__ == '__main__': apply(setup, (), setup_args)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 11, 25064, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 11, 27995, 11, 9455, 198, 198, 11748, 2779, 2624, 198, 198, 40406, 62, 22046, 796, 1391, 198, 220, 220, 220,...
2.676056
213
import numpy as np import torch import random import pandas as pd import os import cv2 import argparse import math import matplotlib.pyplot as plt import pathlib def mask_step(x, step): """ Create a mask to only contain the step-th element starting from the first element. Used to downsample """ mask = np.zeros_like(x) mask[::step] = 1 return mask.astype(bool) def downsample(df, step): """ Downsample data by the given step. Example, SDD is recorded in 30 fps, with step=30, the fps of the resulting df will become 1 fps. With step=12 the result will be 2.5 fps. It will do so individually for each unique pedestrian (metaId) :param df: pandas DataFrame - necessary to have column 'metaId' :param step: int - step size, similar to slicing-step param as in array[start:end:step] :return: pd.df - downsampled """ mask = df.groupby(['metaId'])['metaId'].transform(mask_step, step=step) return df[mask] def filter_short_trajectories(df, threshold): """ Filter trajectories that are shorter in timesteps than the threshold :param df: pandas df with columns=['x', 'y', 'frame', 'trackId', 'sceneId', 'metaId'] :param threshold: int - number of timesteps as threshold, only trajectories over threshold are kept :return: pd.df with trajectory length over threshold """ len_per_id = df.groupby(by='metaId', as_index=False).count() # sequence-length for each unique pedestrian idx_over_thres = len_per_id[len_per_id['frame'] >= threshold] # rows which are above threshold idx_over_thres = idx_over_thres['metaId'].unique() # only get metaIdx with sequence-length longer than threshold df = df[df['metaId'].isin(idx_over_thres)] # filter df to only contain long trajectories return df def sliding_window(df, window_size, stride): """ Assumes downsampled df, chunks trajectories into chunks of length window_size. When stride < window_size then chunked trajectories are overlapping :param df: df :param window_size: sequence-length of one trajectory, mostly obs_len + pred_len :param stride: timesteps to move from one trajectory to the next one :return: df with chunked trajectories """ gb = df.groupby(['metaId'], as_index=False) df = gb.apply(groupby_sliding_window, window_size=window_size, stride=stride) df['metaId'] = pd.factorize(df['newMetaId'], sort=False)[0] df = df.drop(columns='newMetaId') df = df.reset_index(drop=True) return df def split_at_fragment_lambda(x, frag_idx, gb_frag): """ Used only for split_fragmented() """ metaId = x.metaId.iloc()[0] counter = 0 if metaId in frag_idx: split_idx = gb_frag.groups[metaId] for split_id in split_idx: x.loc[split_id:, 'newMetaId'] = '{}_{}'.format(metaId, counter) counter += 1 return x def split_fragmented(df): """ Split trajectories when fragmented (defined as frame_{t+1} - frame_{t} > 1) Formally, this is done by changing the metaId at the fragmented frame and below :param df: DataFrame containing trajectories :return: df: DataFrame containing trajectories without fragments """ gb = df.groupby('metaId', as_index=False) # calculate frame_{t+1} - frame_{t} and fill NaN which occurs for the first frame of each track df['frame_diff'] = gb['frame'].diff().fillna(value=1.0).to_numpy() fragmented = df[df['frame_diff'] != 1.0] # df containing all the first frames of fragmentation gb_frag = fragmented.groupby('metaId') # helper for gb.apply frag_idx = fragmented.metaId.unique() # helper for gb.apply df['newMetaId'] = df['metaId'] # temporary new metaId df = gb.apply(split_at_fragment_lambda, frag_idx, gb_frag) df['metaId'] = pd.factorize(df['newMetaId'], sort=False)[0] df = df.drop(columns='newMetaId') return df def rot(df, image, k=1): ''' Rotates image and coordinates counter-clockwise by k * 90° within image origin :param df: Pandas DataFrame with at least columns 'x' and 'y' :param image: PIL Image :param k: Number of times to rotate by 90° :return: Rotated Dataframe and image ''' xy = df.copy() if image.ndim == 3: y0, x0, channels = image.shape else: y0, x0= image.shape xy.loc()[:, 'x'] = xy['x'] - x0 / 2 xy.loc()[:, 'y'] = xy['y'] - y0 / 2 c, s = np.cos(-k * np.pi / 2), np.sin(-k * np.pi / 2) R = np.array([[c, s], [-s, c]]) xy.loc()[:, ['x', 'y']] = np.dot(xy[['x', 'y']], R) for i in range(k): image = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE) if image.ndim == 3: y0, x0, channels = image.shape else: y0, x0= image.shape xy.loc()[:, 'x'] = xy['x'] + x0 / 2 xy.loc()[:, 'y'] = xy['y'] + y0 / 2 return xy, image def fliplr(df, image): ''' Flip image and coordinates horizontally :param df: Pandas DataFrame with at least columns 'x' and 'y' :param image: PIL Image :return: Flipped Dataframe and image ''' xy = df.copy() if image.ndim == 3: y0, x0, channels = image.shape else: y0, x0= image.shape xy.loc()[:, 'x'] = xy['x'] - x0 / 2 xy.loc()[:, 'y'] = xy['y'] - y0 / 2 R = np.array([[-1, 0], [0, 1]]) xy.loc()[:, ['x', 'y']] = np.dot(xy[['x', 'y']], R) image = cv2.flip(image, 1) if image.ndim == 3: y0, x0, channels = image.shape else: y0, x0= image.shape xy.loc()[:, 'x'] = xy['x'] + x0 / 2 xy.loc()[:, 'y'] = xy['y'] + y0 / 2 return xy, image def augment_data(data, image_path='data/SDD/train', images={}, image_file='reference.jpg', seg_mask=False, use_raw_data=False): ''' Perform data augmentation :param data: Pandas df, needs x,y,metaId,sceneId columns :param image_path: example - 'data/SDD/val' :param images: dict with key being sceneId, value being PIL image :param image_file: str, image file name :param seg_mask: whether it's a segmentation mask or an image file :return: ''' ks = [1, 2, 3] for scene in data.sceneId.unique(): scene_name, scene_idx = scene.split("_") if use_raw_data: im_path = os.path.join(image_path, scene_name, f"video{scene_idx}", image_file) else: im_path = os.path.join(image_path, scene, image_file) if seg_mask: im = cv2.imread(im_path, 0) else: im = cv2.imread(im_path) images[scene] = im data_ = data.copy() # data without rotation, used so rotated data can be appended to original df k2rot = {1: '_rot90', 2: '_rot180', 3: '_rot270'} for k in ks: metaId_max = data['metaId'].max() for scene in data_.sceneId.unique(): if use_raw_data: im_path = os.path.join(image_path, scene_name, f"video{scene_idx}", image_file) else: im_path = os.path.join(image_path, scene, image_file) if seg_mask: im = cv2.imread(im_path, 0) else: im = cv2.imread(im_path) data_rot, im = rot(data_[data_.sceneId == scene], im, k) # image rot_angle = k2rot[k] images[scene + rot_angle] = im data_rot['sceneId'] = scene + rot_angle data_rot['metaId'] = data_rot['metaId'] + metaId_max + 1 data = data.append(data_rot) metaId_max = data['metaId'].max() for scene in data.sceneId.unique(): im = images[scene] data_flip, im_flip = fliplr(data[data.sceneId == scene], im) data_flip['sceneId'] = data_flip['sceneId'] + '_fliplr' data_flip['metaId'] = data_flip['metaId'] + metaId_max + 1 data = data.append(data_flip) images[scene + '_fliplr'] = im_flip return data, images def resize_and_pad_image(images, size, pad=2019): """ Resize image to desired size and pad image to make it square shaped and ratio of images still is the same, as images all have different sizes. """ for key, im in images.items(): H, W, C = im.shape im = cv2.copyMakeBorder(im, 0, pad - H, 0, pad - W, cv2.BORDER_CONSTANT) im = cv2.resize(im, (size, size), interpolation=cv2.INTER_AREA) images[key] = im if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data_raw", default='datset_raw', type=str) parser.add_argument("--step", default=12, type=int) parser.add_argument("--window_size", default=20, type=int) parser.add_argument("--stride", default=20, type=int) parser.add_argument("--data_filter", default='datset_filter', type=str) parser.add_argument("--labels", default=['Pedestrian', 'Biker'], help=['Biker', 'Bus', 'Car', 'Cart', 'Pedestrian', 'Skater'], type=str) args = parser.parse_args() # Create dataset df = load_raw_dataset(args.data_raw, args.step, args.window_size, args.stride) vel_ranges = [(0.25, 0.75), (1.25, 1.75), (2.25, 2.75), (3.25, 3.75)] create_vel_dataset(df, vel_ranges, args.labels, args.data_filter)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 4738, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686, 198, 11748, 269, 85, 17, 198, 11748, 1822, 29572, 198, 11748, 10688, 198, 11748, 2603, 29487, 8019, 13, 9078, 2...
2.556578
3,261
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import signal __author__ = 'Nick Dingwall and Christopher Potts' right_boundary_str = r""" (?: \s+(?:on|in|at|for|to|by|of)\s* )""" date_time_stamp_re = r"""\[?\(\d+/\d+\s+\d+\s+\w+\)\-?\]?\-?""" price_re = r"""[\$₤£¥€]\s*\d+[\d.,]+\d+""" # phrase_re = ur"""(?:[a-zA-Z'\s+&/]|(?:\d+\s)|(?:\d[a-z]))+""" phrase_re = r""" (?:\s* (?:[a-zA-Z](?:[a-z\-A-Z'\s+&]*/?[a-z\-A-Z'\s+&]+)*[a-zA-Z]) # Standard phrases, working hard to treat // as a boundary | (?:\d+[a-z]+) # Words like 2nd, 1st, 43rd | (?:%s) # price_re abvove with spacing allowed around it | (?:\d+[\d.,]+\d+) # Numbers that aren't prices (just like price_re but without currency mark) \s*)+""" % price_re apostrophes = r"'\u0027\u02BC\u2019" word_re = r""" (?:[a-z][a-z%s\-_]+[a-z]) # Words with apostrophes or dashes. | (?:[+\-]?\d+[,/.:-]\d+[+\-]?) # Numbers, including fractions, decimals. | (?:[\w_&]+) # Words without apostrophes or dashes. | (?:\.(?:\s*\.){1,}) # Ellipsis dots. | (?:\*{1,}) # Asterisk runs. | (?:\S) # Everything else that isn't whitespace. """ % apostrophes phone_number_re = r""" (?: (?: # (international) \+?[01] [\-\s.]* )? (?: # (area code) [\(]? \d{3} [\-\s.\)]* )? \d{3} # exchange [\-\s.]* \d{4} # base )""" long_date_re = r""" (?: (?:0?[1-9]|1[12]) # month [\-\s/.\\]+ (?:[012]?[0-9]|3[01]) # day (?:[\-\s/.\\]+ \d{2,4})? # year | (?:[012]?[0-9]|3[01]) # day [\-\s/.\\]+ (?:0?[1-9]|1[12]) # month (?:[\-\s/.\\]+ \d{2,4})? # year | \d{2,4} # year [\-\s/.\\]+ (?:0?[1-9]|1[12]) # month [\-\s/.\\]+ (?:[012]?[0-9]|3[01]) # day | (?:[012]?[0-9]|3[01]) \s+ (?: (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept?|Oct|Nov|Dec)\.? | (?:January|February|March|April|May|June|July|August|September|October|November|December) ) \s+ \d{2,4} | (?: (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept?|Oct|Nov|Dec)\.? | (?:January|February|March|April|May|June|July|August|September|October|November|December) ) [\s,]+ (?:[012]?[0-9]|3[01]) [\s,]+ \d{2,4} )""" short_date_re = r""" (?: (?: (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept?|Oct|Nov|Dec)\.? | (?:January|February|March|April|May|June|July|August|September|October|November|December) ) \s+ (?:[012]?[0-9]|3[01]) | (?:[012]?[0-9]|3[01]) \s+ (?: (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept?|Oct|Nov|Dec)\.? | (?:January|February|March|April|May|June|July|August|September|October|November|December) ) )""" urls = r""" (?: (?: [a-z][\w-]+: # URL protocol and colon (?: /{1,3} # 1-3 slashes | # or [a-z0-9%] # Single letter or digit or '%' (Trying not to match e.g. "URI::Escape") ) | # or www\d{0,3}[.] # "www.", "www1.", "www2." … "www999." | # or [a-z0-9.\-]+[.][a-z]{2,4}/ # looks like domain name followed by a slash ) (?: # One or more: [^\s()<>]+ # Run of non-space, non-()<> | # or \((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\) # balanced parens, up to 2 levels )+ (?: # End with: \((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\) # balanced parens, up to 2 levels | # or [^\s`!()\[\]{};:'".,<>?«»“”‘’] # not a space or one of these punct chars ) )""" emoticons = r""" (?: # non-capturing group [<>]? # optional hat/brow [:;=8] # eyes [\-o\*\']? # optional nose [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth | #### reverse orientation [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth [\-o\*\']? # optional nose [:;=8] # eyes [<>]? # optional hat/brow )""" tags = r"""<[^>]+>""" hat_tip = r"[Hh]/[Tt]" email = r"(?:[\w._%+-]+@[\w._%+-]+\.\w{2,})" twitter_username = r"""(?:@[\w_]+)""" twitter_hashtag = r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)" def timeout_handler(signum, frame): """Help us to control the tokenizer should it go out of control for some unknown reason related to the complexity of regex matching. """ raise TimeoutException() class WordOnlyTokenizer: """Seeks to identify only word-like things, including dates, numbers, and prices, but excluding URLs. Parameters ---------- lower : bool Whether downcase all tokens. preserve_acronyms : bool If `True`, then tokens that return true for `isupper` will not be downcases even if `lower=True`. offsets : bool If `True`, then `tokenize` returns a list of (str, offset) tuples. If `False`, it returns just a list of str. remove_whitespace_tokens : bool If `True`, then tokens consisting of whitespace are removed. This is usually the expected behavior. If `False`, then they are kept, and we guarantee that `"".join(tokenize(s)) == s` modulo the case parameters to the tokenizer instance. """ def tokenize(self, s): """The tokenizing method. Parameters ---------- s : str Returns ------- list of str if `self.offsets=False`, else list of (str, int) tuples. """ tokens = [] # The Python regex module sometimes really blows up, taking # ages to tokenize. This will prevent that by limiting the # permitted tokenizing time based on the length of the input. old_handler = signal.signal(signal.SIGALRM, timeout_handler) secs = int(round(1 + (len(s)/100000.0), 0)) signal.alarm(secs) try: tokens = self.regex.findall(s) except TimeoutException: return [] finally: signal.signal(signal.SIGALRM, old_handler) signal.alarm(0) # This cleanup is easier to do separately than to try to # get it just right with the core regex. tokens = [self._token_cleanup(s) for s in tokens] if self.offsets: total = 0 indices = [0] for tok in tokens[:-1]: total += len(tok) indices.append(total) results = list(zip(tokens, indices)) if self.remove_whitespace_tokens: results = [(w, i) for w, i in results if w.strip()] return results else: if self.remove_whitespace_tokens: tokens = [w for w in tokens if w.strip()] return tokens
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 302, 198, 11748, 6737, 198, 198, 834, 9800, 834, 796, 705, 23609, 46980, 11930, 290, 12803, 6902, 912, 6, 628, ...
1.77427
4,213
#!/usr/bin/env python2.6 #Copyright 2010 Gabriele Modena <gm@nowave.it>. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are # permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of # conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list # of conditions and the following disclaimer in the documentation and/or other materials # provided with the distribution. # #THIS SOFTWARE IS PROVIDED BY Gabriele Modena ``AS IS'' AND ANY EXPRESS OR IMPLIED #WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND #FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR #CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON #ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING #NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF #ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # #The views and conclusions contained in the software and documentation are those of the #authors and should not be interpreted as representing official policies, either expressed #or implied, of Gabriele Modena. __author__ = 'gm@nowave.it' __version__ = '0.1-devel' from ctypes import c_ubyte # chip type CT_PN531 = c_ubyte(0x10) CT_PN532 = c_ubyte(0x20) CT_PN533 = c_ubyte(0x30)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 13, 21, 198, 2, 15269, 3050, 220, 12300, 5034, 293, 3401, 8107, 1279, 39870, 31, 2197, 1015, 13, 270, 28401, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 290, 779, 287, 2...
2.991653
599
""" .. /------------------------------------------------------------------------------\ | -- FACADE TECHNOLOGIES INC. CONFIDENTIAL -- | |------------------------------------------------------------------------------| | | | Copyright [2019] Facade Technologies Inc. | | All Rights Reserved. | | | | NOTICE: All information contained herein is, and remains the property of | | Facade Technologies Inc. and its suppliers if any. The intellectual and | | and technical concepts contained herein are proprietary to Facade | | Technologies Inc. and its suppliers and may be covered by U.S. and Foreign | | Patents, patents in process, and are protected by trade secret or copyright | | law. Dissemination of this information or reproduction of this material is | | strictly forbidden unless prior written permission is obtained from Facade | | Technologies Inc. | | | \------------------------------------------------------------------------------/ This module contains the Observer class, which watches the target GUI for changes. """ from threading import Lock import psutil from PySide2.QtCore import QThread, Signal from time import time from tguiil.application import Application from tguiil.supertokens import SuperToken from tguiil.tokens import Token class Observer(QThread): """ The observer continually traverses the target GUI and notifies when new components are found. It maintains a tree of super tokens to determine whether a component has already been found or not. To use: process = psutil.Popen(["C:\\Program Files\\Notepad++\\notepad++.exe"]) observer = Observer(process.pid, 'uia') observer.newSuperToken.connect(targetGUIModel.addSuperToken) observer.start() """ # This signal is emitted when a new component is detected. newSuperToken = Signal(SuperToken, SuperToken) # (new SuperToken, new SuperToken's parent SuperToken) # This signal is emitted when the backend has been detected. backendDetected = Signal(str) ignoreTypes = set() ignoreTypes.add("SysShadow") ignoreTypes.add("ToolTips") ignoreTypes.add("MSCTFIME UI") ignoreTypes.add("IME") ignoreTypes.add("Pane") # ignoreTypes.add("wxWindowNR") # ignoreTypes.add("wxWindow") def __init__(self, processID: int, captureImages: bool, backend: str = "uia"): """ Constructs an Observer. The target application must already be started before constructing the Observer. :raises: NoSuchProcess :raises: AccessDenied :param processID: The ID of the process to watch. :type processID: int :param captureImages: If True, capture images of components. If false, don't. :type captureImages: bool :param backend: "win32", "uia", or "auto" :type backend: str :return: None :rtype: NoneType """ QThread.__init__(self) self._pid = processID self._process = psutil.Process(processID) self._backend = backend self._childMapping = {None: []} # maps each super token to its list of children. # maps each super token to the last iteration it was matched on. self._lastSuperTokenIterations = {} self._iteration = 0 self._playing = False self._playingLock = Lock() self.capturing = captureImages def loadSuperTokens(self, tguim: 'TargetGuiModel') -> None: """ Loads existing super tokens into the observer to avoid duplication of super tokens. This method will iterate over all components in the target GUI model and extract the SuperToken references. It will build the simple of super tokens internally using dictionaries. This method is vital because when a new observer is created, it needs to know about existing super tokens to avoid duplication. .. note:: This method should be run in Facile's main thread BEFORE the observer is played. :param tguim: The target GUI model to load the super tokens from. :type tguim: TargetGuiModel :return: None :rtype: NoneType """ componentWork = tguim.getRoot().getChildren()[:] # add all of the top level components to be children of None self._childMapping[None] = [] for component in componentWork: superT = component.getSuperToken() self._childMapping[None].append(superT) while componentWork: component = componentWork.pop() super = component.getSuperToken() self._lastSuperTokenIterations[super] = -1 self._childMapping[super] = [] for child in component.getChildren(): self._childMapping[super].append(child.getSuperToken()) componentWork.append(child) def detectBackend(self): """ This function automatically detects the backend of the target app using a time-based approach. Whichever backend detects the largest number of unique components in the same number of seconds is selected. """ # Let the user know we are detecting the backend self.backendDetected.emit('detecting') # Time to wait to collect components waitTime = 3 # ---- UIA ---- # app = Application(backend="uia") app.setProcess(self._process) appTimeStamp = app.getStartTime() self._iteration = 0 endTime = time() + waitTime # In waitTime seconds, stop the loop while self._process.is_running(): if time() > endTime: break self._iteration += 1 if not self.isPlaying(): return 0 componentCount = 0 # work acts as a stack. Each element is a 2-tuple where the first element # is a GUI component and the second element is the parent super token. work = [(win, None) for win in app.windows()] while len(work) > 0: if time() > endTime: break if not self.isPlaying(): return 0 curComponent, parentSuperToken = work.pop() if curComponent.friendly_class_name() not in Observer.ignoreTypes: try: token = Token.createToken(appTimeStamp, curComponent, captureImage=self.capturing) # List boxes have a ton of children that we probably don't care about. # There are probably other types like it where we just want to ignore the # children. We can make this type of # if token.type == "ListBox": # continue except Token.CreationException as e: continue nextParentSuperToken = self.matchToSuperToken(token, parentSuperToken, detecting=True) self._lastSuperTokenIterations[nextParentSuperToken] = self._iteration else: nextParentSuperToken = parentSuperToken children = curComponent.children() for child in children: work.append((child, nextParentSuperToken)) uiaComps = len(self._childMapping) # Number of unique components found self._childMapping = {None: []} self._lastSuperTokenIterations = {} # ---- WIN32 ---- # app = Application(backend="win32") app.setProcess(self._process) appTimeStamp = app.getStartTime() self._iteration = 0 endTime = time() + waitTime # In waitTime seconds, stop the loop while self._process.is_running(): if time() > endTime: break self._iteration += 1 if not self.isPlaying(): return 0 componentCount = 0 # work acts as a stack. Each element is a 2-tuple where the first element # is a GUI component and the second element is the parent super token. work = [(win, None) for win in app.windows()] while len(work) > 0: if time() > endTime: break if not self.isPlaying(): return 0 curComponent, parentSuperToken = work.pop() if curComponent.friendly_class_name() not in Observer.ignoreTypes: try: token = Token.createToken(appTimeStamp, curComponent, captureImage=self.capturing) # List boxes have a ton of children that we probably don't care about. # There are probably other types like it where we just want to ignore the # children. We can make this type of # if token.type == "ListBox": # continue except Token.CreationException as e: continue nextParentSuperToken = self.matchToSuperToken(token, parentSuperToken, detecting=True) self._lastSuperTokenIterations[nextParentSuperToken] = self._iteration else: nextParentSuperToken = parentSuperToken children = curComponent.children() for child in children: work.append((child, nextParentSuperToken)) w32Comps = len(self._childMapping) self._childMapping = {None: []} self._lastSuperTokenIterations = {} if uiaComps > w32Comps: self._backend = 'uia' self.backendDetected.emit('uia') elif uiaComps < w32Comps: self._backend = 'win32' self.backendDetected.emit('win32') else: # If they detect the same amount, should probably rerun the test longer, but I doubt this will ever happen. # Leaving to default as uia for now self._backend = 'uia' self.backendDetected.emit('uia') def run(self) -> int: """ DO NOT CALL THIS METHOD. This method is run in a new thread when the start() method is called. :return: the exit code of the thread which should be 0. :rtype: int """ if self._backend == "auto": self.detectBackend() self._iteration = 0 app = Application(backend=self._backend) app.setProcess(self._process) appTimeStamp = app.getStartTime() while self._process.is_running(): self._iteration += 1 if not self.isPlaying(): return 0 componentCount = 0 # work acts as a stack. Each element is a 2-tuple where the first element # is a GUI component and the second element is the parent super token. work = [(win, None) for win in app.windows()] while len(work) > 0: if not self.isPlaying(): return 0 curComponent, parentSuperToken = work.pop() if curComponent.friendly_class_name() not in Observer.ignoreTypes: try: token = Token.createToken(appTimeStamp, curComponent, captureImage=self.capturing) # List boxes have a ton of children that we probably don't care about. # There are probably other types like it where we just want to ignore the # children. We can make this type of # if token.type == "ListBox": # continue except Token.CreationException as e: continue nextParentSuperToken = self.matchToSuperToken(token, parentSuperToken) self._lastSuperTokenIterations[nextParentSuperToken] = self._iteration else: nextParentSuperToken = parentSuperToken children = curComponent.children() for child in children: work.append((child, nextParentSuperToken)) def matchToSuperToken(self, token: Token, parentSuperToken: SuperToken, detecting=False) -> SuperToken: """ Gets the SuperToken that best matches the given token. The parentSuperToken is necessary in the case that a new SuperToken is created. In this case, both the new SuperToken and its parent will be carried in the newSuperToken signal which will be emitted. Having the parent super token also allows us to reduce the search space when finding the matched SuperToken. :param token: The token to find a SuperToken match with. :type token: Token :param parentSuperToken: The parent of the SuperToken that will be matched with the token. :type parentSuperToken: SuperToken :param detecting: If the function is called while detecting the backend. Default is False. :type detecting: bool :return: The SuperToken that gets matched to the provided token. :rtype: SuperToken """ if token.isDialog: parentSuperToken = None # determine if the new token matches any super tokens and how well it matches if it does. bestMatch = 0 bestDecision = Token.Match.NO.value selectedSuperToken = None potentialMatches = self._childMapping[parentSuperToken] for superToken in potentialMatches: if self._lastSuperTokenIterations[superToken] == self._iteration: continue decision, matchVal = superToken.shouldContain(token) bestDecision = min(bestDecision, decision.value) if decision == Token.Match.NO: continue elif decision == Token.Match.EXACT: return superToken elif decision == Token.Match.CLOSE: # in the case that multiple SuperTokens closely match the token, # we'll use the SuperToken that has the higher match. if matchVal > bestMatch: bestMatch = matchVal selectedSuperToken = superToken # At this point, we know the token will be used in the TGUIM. token.registerAsAccepted() # No match was found if selectedSuperToken is None: newSuperToken = SuperToken(token, parentSuperToken) self._childMapping[parentSuperToken].append(newSuperToken) self._childMapping[newSuperToken] = [] if not detecting: # this statement is satisfyingly clean self.newSuperToken.emit(newSuperToken, parentSuperToken) return newSuperToken # a close match was found else: selectedSuperToken.addToken(token) return selectedSuperToken def setPlaying(self, status: bool) -> None: """ Sets the running flag. :param status: True if running, False if not. :type status: bool :return: None :rtype: NoneType """ self._playingLock.acquire() self._playing = status self._playingLock.release() def isPlaying(self) -> bool: """ Gets the running status. :return: True if running, False if not. :rtype: bool """ self._playingLock.acquire() running = self._playing self._playingLock.release() return running def play(self): """ Runs the Observer. :return: True if the observer is running, False otherwise. :rtype: bool """ if not self._process.is_running(): return False if self.isRunning(): return True self.setPlaying(True) self.start() return self.isRunning() def pause(self): """ Stops the Observer. :return: True if the observer is running, False otherwise. :rtype: bool """ self.setPlaying(False) if self.isRunning(): self.quit() return True return False def getPID(self) -> int: """ Gets the Process ID of the process that is being watched by the observer :return: The process ID of the process that the observer is watching. :rtype: int """ return self._pid
[ 37811, 198, 492, 198, 220, 220, 220, 1220, 10097, 26171, 59, 198, 220, 220, 220, 930, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1377, 44216, 19266, 44999, 45, 33462, 11015, 19387, 13, 220, 7102,...
2.842001
5,057
""" Calls the NWChem executable. """ from decimal import Decimal from typing import Any, Dict, Optional, Tuple import numpy as np import qcelemental as qcel from qcelemental.models import Provenance, Result from qcelemental.util import safe_version, which from ..model import ProgramHarness from ...util import execute from .harvester import harvest
[ 37811, 198, 34, 5691, 262, 21966, 41829, 28883, 13, 198, 37811, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 32233, 11, 309, 29291, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 10662, ...
3.575758
99
import optuna from torch import nn as nn from typing import Any, Dict, Union, Callable, Optional from stable_baselines3.common.callbacks import EvalCallback from stable_baselines3.common.vec_env import VecEnv def sample_ppo(trial: optuna.Trial): """ Basic sampler for PPO hyperparameters """ return { 'batch_size' : trial.suggest_categorical("batch_size", [8, 16, 32, 64, 128, 256, 512]), 'n_steps': int(trial.suggest_loguniform('n_steps', 16, 2048)), 'learning_rate': trial.suggest_loguniform('learning_rate', 1e-5, 1.), 'gae_lambda' : trial.suggest_categorical("gae_lambda", [0.8, 0.9, 0.92, 0.95, 0.98, 0.99, 1.0]), 'ent_coef': trial.suggest_loguniform('ent_coef', 1e-8, 1e-1), 'clip_range': trial.suggest_uniform('cliprange', 0.1, 0.4) } def sample_ppo_params(trial: optuna.Trial) -> Dict[str, Any]: """ Sampler for PPO hyperparams. """ lr_schedule = trial.suggest_categorical("lr_schedule", ["linear", "constant"]) learning_rate = trial.suggest_loguniform("learning_rate", 1e-5, 1) batch_size = trial.suggest_categorical("batch_size", [8, 16, 32, 64, 128, 256]) n_steps = trial.suggest_categorical("n_steps", [8, 16, 32, 64, 128, 256, 512, 1024, 2048]) ent_coef = trial.suggest_loguniform("ent_coef", 0.00000001, 0.1) clip_range = trial.suggest_categorical("clip_range", [0.1, 0.2, 0.3, 0.4]) n_epochs = trial.suggest_categorical("n_epochs", [1, 5, 10, 20, 30]) gae_lambda = trial.suggest_categorical("gae_lambda", [0.8, 0.9, 0.92, 0.95, 0.98, 0.99, 1.0]) max_grad_norm = trial.suggest_categorical("max_grad_norm", [0.3, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 5]) vf_coef = trial.suggest_uniform("vf_coef", 0, 1) # Uncomment for network architecture setting #net_arch = trial.suggest_categorical("net_arch", ["small", "medium"]) # Uncomment for gSDE (continuous actions) #log_std_init = trial.suggest_uniform("log_std_init", -4, 1) # Uncomment for gSDE (continuous action) # sde_sample_freq = trial.suggest_categorical("sde_sample_freq", [-1, 8, 16, 32, 64, 128, 256]) # Orthogonal initialization #ortho_init = False # ortho_init = trial.suggest_categorical('ortho_init', [False, True]) # activation_fn = trial.suggest_categorical('activation_fn', ['tanh', 'relu', 'elu', 'leaky_relu']) activation_fn = trial.suggest_categorical("activation_fn", ["tanh", "relu"]) # TODO: account when using multiple envs if batch_size > n_steps: batch_size = n_steps if lr_schedule == "linear": learning_rate = linear_schedule(learning_rate) # Independent networks usually work best # when not working with images # net_arch = { # "small": [dict(pi=[64, 64], vf=[64, 64])], # "medium": [dict(pi=[256, 256], vf=[256, 256])], # }[net_arch] activation_fn = {"tanh": nn.Tanh, "relu": nn.ReLU, "elu": nn.ELU, "leaky_relu": nn.LeakyReLU}[activation_fn] return { "n_steps": n_steps, "batch_size": batch_size, "learning_rate": learning_rate, "ent_coef": ent_coef, "clip_range": clip_range, "n_epochs": n_epochs, "gae_lambda": gae_lambda, "max_grad_norm": max_grad_norm, "vf_coef": vf_coef, # "sde_sample_freq": sde_sample_freq, "policy_kwargs": dict( #log_std_init=log_std_init, #net_arch=net_arch, activation_fn=activation_fn #ortho_init=ortho_init, ), } def sample_a2c_params(trial: optuna.Trial) -> Dict[str, Any]: """ Sampler for A2C hyperparams. """ lr_schedule = trial.suggest_categorical("lr_schedule", ["linear", "constant"]) learning_rate = trial.suggest_loguniform("learning_rate", 1e-5, 1) n_steps = trial.suggest_categorical("n_steps", [4, 8, 16, 32, 64, 128]) gae_lambda = trial.suggest_categorical("gae_lambda", [0.8, 0.9, 0.92, 0.95, 0.98, 0.99, 1.0]) ent_coef = trial.suggest_loguniform("ent_coef", 0.0000001, 0.1) vf_coef = trial.suggest_uniform("vf_coef", 0, 1) normalize_advantage = trial.suggest_categorical("normalize_advantage", [False, True]) max_grad_norm = trial.suggest_categorical("max_grad_norm", [0.3, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 5]) # Toggle PyTorch RMS Prop (different from TF one, cf doc) use_rms_prop = trial.suggest_categorical("use_rms_prop", [False, True]) # Uncomment for gSDE (continuous actions) #log_std_init = trial.suggest_uniform("log_std_init", -4, 1) #ortho_init = trial.suggest_categorical("ortho_init", [False, True]) # Uncomment for network architecture setting #net_arch = trial.suggest_categorical("net_arch", ["small", "medium"]) # sde_net_arch = trial.suggest_categorical("sde_net_arch", [None, "tiny", "small"]) # full_std = trial.suggest_categorical("full_std", [False, True]) # activation_fn = trial.suggest_categorical('activation_fn', ['tanh', 'relu', 'elu', 'leaky_relu']) activation_fn = trial.suggest_categorical("activation_fn", ["tanh", "relu"]) if lr_schedule == "linear": learning_rate = linear_schedule(learning_rate) # net_arch = { # "small": [dict(pi=[64, 64], vf=[64, 64])], # "medium": [dict(pi=[256, 256], vf=[256, 256])], # }[net_arch] activation_fn = {"tanh": nn.Tanh, "relu": nn.ReLU, "elu": nn.ELU, "leaky_relu": nn.LeakyReLU}[activation_fn] return { "learning_rate": learning_rate, "n_steps": n_steps, "gae_lambda": gae_lambda, "ent_coef": ent_coef, "vf_coef": vf_coef, "max_grad_norm": max_grad_norm, "use_rms_prop": use_rms_prop, "normalize_advantage": normalize_advantage, "policy_kwargs": dict( #log_std_init=log_std_init, #net_arch=net_arch, activation_fn=activation_fn #ortho_init=ortho_init, ), } def linear_schedule(initial_value: Union[float, str]) -> Callable[[float], float]: """ Linear learning rate schedule. :param initial_value: (float or str) :return: (function) """ if isinstance(initial_value, str): initial_value = float(initial_value) def func(progress_remaining: float) -> float: """ Progress will decrease from 1 (beginning) to 0 :param progress_remaining: (float) :return: (float) """ return progress_remaining * initial_value return func class TrialEvalCallback(EvalCallback): """ Callback used for evaluating and reporting a trial. """
[ 11748, 2172, 9613, 198, 6738, 28034, 1330, 299, 77, 355, 299, 77, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 4479, 11, 4889, 540, 11, 32233, 198, 6738, 8245, 62, 12093, 20655, 18, 13, 11321, 13, 13345, 10146, 1330, 26439, 47258, ...
2.2743
2,891
from django.test import TestCase from django.db import IntegrityError from dbaccounting.models import AccountType,Account,Transaction # Create your tests here.
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 13, 9945, 1330, 39348, 12331, 198, 198, 6738, 20613, 23317, 278, 13, 27530, 1330, 10781, 6030, 11, 30116, 11, 48720, 198, 2, 13610, 534, 5254, 994, 13, 198, 220, ...
3.688889
45
import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm from os import path import os import autoarray as aa import autogalaxy.plot as aplt from autogalaxy.analysis.visualizer import plot_setting from autogalaxy.analysis.visualizer import Visualizer as AgVisualizer from autolens.lens.ray_tracing import Tracer from autolens.lens.plot.ray_tracing_plotters import TracerPlotter class Visualizer(AgVisualizer): """ Visualizes the maximum log likelihood model of a model-fit, including components of the model and fit objects. The methods of the `Visualizer` are called throughout a non-linear search using the `Analysis` classes `visualize` method. The images output by the `Visualizer` are customized using the file `config/visualize/plots.ini`. Parameters ---------- visualize_path The path on the hard-disk to the `image` folder of the non-linear searches results. """ def visualize_tracer( self, tracer: Tracer, grid: aa.type.Grid2DLike, during_analysis: bool ): """ Visualizes a `Tracer` object. Images are output to the `image` folder of the `visualize_path` in a subfolder called `ray_tracing`. When used with a non-linear search the `visualize_path` points to the search's results folder and this function visualizes the maximum log likelihood `Tracer` inferred by the search so far. Visualization includes individual images of attributes of the tracer (e.g. its image, convergence, deflection angles) and a subplot of all these attributes on the same figure. The images output by the `Visualizer` are customized using the file `config/visualize/plots.ini` under the [ray_tracing] header. Parameters ---------- tracer The maximum log likelihood `Tracer` of the non-linear search. grid A 2D grid of (y,x) arc-second coordinates used to perform ray-tracing, which is the masked grid tied to the dataset. during_analysis Whether visualization is performed during a non-linear search or once it is completed. """ mat_plot_2d = self.mat_plot_2d_from(subfolders="ray_tracing") tracer_plotter = TracerPlotter( tracer=tracer, grid=grid, mat_plot_2d=mat_plot_2d, include_2d=self.include_2d, ) if should_plot("subplot_ray_tracing"): tracer_plotter.subplot_tracer() if should_plot("subplot_plane_images"): tracer_plotter.subplot_plane_images() tracer_plotter.figures_2d( image=should_plot("image"), source_plane=should_plot("source_plane_image"), convergence=should_plot("convergence"), potential=should_plot("potential"), deflections_y=should_plot("deflections"), deflections_x=should_plot("deflections"), magnification=should_plot("magnification"), ) if not during_analysis: if should_plot("all_at_end_png"): tracer_plotter.figures_2d( image=True, source_plane=True, convergence=True, potential=True, deflections_y=True, deflections_x=True, magnification=True, ) if should_plot("all_at_end_fits"): fits_mat_plot_2d = self.mat_plot_2d_from( subfolders=path.join("ray_tracing", "fits"), format="fits" ) tracer_plotter = TracerPlotter( tracer=tracer, grid=grid, mat_plot_2d=fits_mat_plot_2d, include_2d=self.include_2d, ) tracer_plotter.figures_2d( image=True, source_plane=True, convergence=True, potential=True, deflections_y=True, deflections_x=True, magnification=True, ) def visualize_image_with_positions( self, image: aa.Array2D, positions: aa.Grid2DIrregular ): """ Visualizes the positions of a model-fit, where these positions are used to resample lens models where the positions to do trace within an input threshold of one another in the source-plane. Images are output to the `image` folder of the `visualize_path` in a subfolder called `positions`. When used with a non-linear search the `visualize_path` points to the search's results folder. The visualization is an image of the strong lens with the positions overlaid. The images output by the `Visualizer` are customized using the file `config/visualize/plots.ini` under the [ray_tracing] header. Parameters ---------- imaging The imaging dataset whose image the positions are overlaid. position The 2D (y,x) arc-second positions used to resample inaccurate mass models. """ mat_plot_2d = self.mat_plot_2d_from(subfolders="positions") if positions is not None: visuals_2d = aplt.Visuals2D(positions=positions) image_plotter = aplt.Array2DPlotter( array=image, mat_plot_2d=mat_plot_2d, include_2d=self.include_2d, visuals_2d=visuals_2d, ) image_plotter.set_filename("image_with_positions") if should_plot("image_with_positions"): image_plotter.figure_2d() def visualize_hyper_images( self, hyper_galaxy_image_path_dict: {str, aa.Array2D}, hyper_model_image: aa.Array2D, ): """ Visualizes the hyper-images and hyper dataset inferred by a model-fit. Images are output to the `image` folder of the `visualize_path` in a subfolder called `hyper`. When used with a non-linear search the `visualize_path` points to the search's results folder. Visualization includes individual images of attributes of the hyper dataset (e.g. the hyper model image) and a subplot of all hyper galaxy images on the same figure. The images output by the `Visualizer` are customized using the file `config/visualize/plots.ini` under the [hyper] header. Parameters ---------- hyper_galaxy_image_path_dict A dictionary mapping the path to each galaxy (e.g. its name) to its corresponding hyper galaxy image. hyper_model_image The hyper model image which corresponds to the sum of hyper galaxy images. """ mat_plot_2d = self.mat_plot_2d_from(subfolders="hyper") hyper_plotter = aplt.HyperPlotter( mat_plot_2d=mat_plot_2d, include_2d=self.include_2d ) if should_plot("model_image"): hyper_plotter.figure_hyper_model_image(hyper_model_image=hyper_model_image) if should_plot("images_of_galaxies"): hyper_plotter.subplot_hyper_images_of_galaxies( hyper_galaxy_image_path_dict=hyper_galaxy_image_path_dict ) def visualize_contribution_maps(self, tracer: Tracer): """ Visualizes the contribution maps that are used for hyper features which adapt a model to the dataset it is fitting. Images are output to the `image` folder of the `visualize_path` in a subfolder called `hyper`. When used with a non-linear search the `visualize_path` points to the search's results folder and this function visualizes the maximum log likelihood contribution maps inferred by the search so far. Visualization includes individual images of attributes of the hyper dataset (e.g. the contribution map of each galaxy) and a subplot of all contribution maps on the same figure. The images output by the `Visualizer` are customized using the file `config/visualize/plots.ini` under the [hyper] header. Parameters ---------- tracer The maximum log likelihood `Tracer` of the non-linear search which is used to plot the contribution maps. """ mat_plot_2d = self.mat_plot_2d_from(subfolders="hyper") hyper_plotter = aplt.HyperPlotter( mat_plot_2d=mat_plot_2d, include_2d=self.include_2d ) if hasattr(tracer, "contribution_map_list"): if should_plot("contribution_map_list"): hyper_plotter.subplot_contribution_map_list( contribution_map_list_list=tracer.contribution_map_list ) def visualize_stochastic_histogram( self, stochastic_log_likelihoods: np.ndarray, max_log_evidence: float, histogram_bins: int = 10, ): """ Certain `Inversion`'s have stochasticity in their log likelihood estimate. For example, the `VoronoiBrightnessImage` pixelization, which changes the likelihood depending on how different KMeans seeds change the pixel-grid. A log likelihood cap can be applied to model-fits performed using these `Inversion`'s to improve error and posterior estimates. This log likelihood cap is estimated from a list of stochastic log likelihoods, where these log likelihoods are computed using the same model but with different KMeans seeds. This function plots a histogram representing the distribution of these stochastic log likelihoods with a 1D Gaussian fit to the likelihoods overlaid. This figure can be used to determine how subject the fit to this dataset is to the stochastic likelihood effect. Parameters ---------- stochastic_log_likelihoods The stochastic log likelihood which are used to plot the histogram and Gaussian. max_log_evidence The maximum log likelihood value of the non-linear search, which will likely be much larger than any of the stochastic log likelihoods as it will be boosted high relative to most samples. histogram_bins The number of bins in the histogram used to visualize the distribution of stochastic log likelihoods. Returns ------- float A log likelihood cap which is applied in a stochastic model-fit to give improved error and posterior estimates. """ if stochastic_log_likelihoods is None: return if plot_setting("other", "stochastic_histogram"): file_path = path.join(self.visualize_path, "other") try: os.makedirs(file_path) except FileExistsError or IsADirectoryError: pass filename = path.join(file_path, "stochastic_histogram.png") if path.exists(filename): try: os.rmdir(filename) except Exception: pass (mu, sigma) = norm.fit(stochastic_log_likelihoods) n, bins, patches = plt.hist( x=stochastic_log_likelihoods, bins=histogram_bins, density=1 ) y = norm.pdf(bins, mu, sigma) plt.plot(bins, y, "--") plt.xlabel("log evidence") plt.title("Stochastic Log Evidence Histogram") plt.axvline(max_log_evidence, color="r") plt.savefig(filename, bbox_inches="tight") plt.close()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 6738, 629, 541, 88, 13, 34242, 1330, 2593, 201, 198, 6738, 28686, 1330, 3108, 201, 198, 11748, 28686, 201, 198, 201, 198, 1174...
2.246439
5,336
myList = LinkedList() print (myList.getSize()) print ("______*Inserting*_______") myList.addNode(5) myList.addNode(10) myList.addNode(15) myList.addNode(20) myList.addNode(25) print ("printing") myList.printNode() print ("Deleting") myList.deleteNode(10) myList.deleteNode(20) myList.deleteNode(5) myList.addNode(90) myList.addNode(2000) print (myList.getSize()) myList.printNode()
[ 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 1820, 8053, 796, 7502, 276, 8053, 3419, 198, 4798, 357, 1820, 8053, 13, 1136, 10699, 28955, 198, 4798, 5855, 25947, 9, 4...
2.286517
178
import os from mtcnn import MTCNN from image import draw_boxes, show_image, image_load def detection(image_name): """ Run detector on single image """ detector = MTCNN() try: return detector.detect(image_name) except ValueError: print("No sign detected") return [] def run_demo(): """ Run demo on images in folder "images" """ path = os.path.abspath("../images") image_list = os.listdir(path) for image_name in image_list: image_path = os.path.join(path, image_name) print("-----------------------------------------------") print("Path:", image_path) image = image_load(image_path) detect_data = detection(image_path) if len(detect_data) > 0: draw_boxes(image, detect_data[:,0:4], detect_data[:,4], detect_data[:,5], red=255) show_image(image, False) print(detect_data) if "__main__" == __name__: run_demo()
[ 11748, 28686, 198, 6738, 285, 23047, 20471, 1330, 337, 4825, 6144, 198, 6738, 2939, 1330, 3197, 62, 29305, 11, 905, 62, 9060, 11, 2939, 62, 2220, 198, 198, 4299, 13326, 7, 9060, 62, 3672, 2599, 198, 220, 220, 220, 37227, 198, 220, 2...
2.37561
410
''' ## Problem 🤔 You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. **Example 1** `Input: lists = [[1,4,5],[1,3,4],[2,6]]` `Output: [1,1,2,3,4,4,5,6]` _Explanation_ The linked-lists are: ``` [ 1->4->5, 1->3->4, 2->6 ] ``` merging them into one sorted list: ``` 1->1->2->3->4->4->5->6 ``` **Example 2** `Input: lists = []` `Output: []` **Example 3** `Input: lists = [[]]` `Output: []` **Note** - k == lists.length - 0 <= k <= 10^4 - 0 <= lists[i].length <= 500 - -10^4 <= lists[i][j] <= 10^4 - lists[i] is sorted in ascending order. - The sum of lists[i].length won't exceed 10^4 '''
[ 7061, 6, 198, 2235, 20647, 12520, 97, 242, 198, 198, 1639, 389, 1813, 281, 7177, 286, 479, 6692, 12, 20713, 8341, 11, 1123, 6692, 12, 4868, 318, 23243, 287, 41988, 1502, 13, 198, 198, 13102, 469, 477, 262, 6692, 12, 20713, 656, 530,...
2.342105
304
from project.family_car import FamilyCar from project.vehicle import Vehicle vehicle = Vehicle(50, 150) print(Vehicle.DEFAULT_FUEL_CONSUMPTION) print(FamilyCar.DEFAULT_FUEL_CONSUMPTION) print(vehicle.fuel) print(vehicle.horse_power) print(vehicle.fuel_consumption) vehicle.drive(100) print(vehicle.fuel) family_car = FamilyCar(150, 150) family_car.drive(50) print(family_car.fuel) family_car.drive(50) print(family_car.fuel) print(family_car.__class__.__bases__[0].__name__)
[ 6738, 1628, 13, 17989, 62, 7718, 1330, 7884, 9914, 198, 6738, 1628, 13, 33892, 1548, 1330, 21501, 198, 198, 33892, 1548, 796, 21501, 7, 1120, 11, 6640, 8, 198, 4798, 7, 37870, 1548, 13, 7206, 38865, 62, 38989, 3698, 62, 10943, 50, 5...
2.653631
179
# This directory is a Python package from .client import GithubClient
[ 2, 770, 8619, 318, 257, 11361, 5301, 198, 6738, 764, 16366, 1330, 38994, 11792, 198 ]
4.666667
15
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2012 Hewlett-Packard Development Company, L.P. # # 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. """Matcher classes to be used inside of the testtools assertThat framework.""" import pprint from testtools import content from lxml import etree class XMLMismatch(object): """Superclass for XML mismatch.""" class XMLTagMismatch(XMLMismatch): """XML tags don't match.""" class XMLAttrKeysMismatch(XMLMismatch): """XML attribute keys don't match.""" class XMLAttrValueMismatch(XMLMismatch): """XML attribute values don't match.""" class XMLTextValueMismatch(XMLMismatch): """XML text values don't match.""" class XMLUnexpectedChild(XMLMismatch): """Unexpected child present in XML.""" class XMLExpectedChild(XMLMismatch): """Expected child not present in XML.""" class XMLMatchState(object): """Maintain some state for matching. Tracks the XML node path and saves the expected and actual full XML text, for use by the XMLMismatch subclasses. """ def node(self, tag, idx): """Adds tag and index to the path; they will be popped off when the corresponding 'with' statement exits. :param tag: The element tag :param idx: If not None, the integer index of the element within its parent. Not included in the path element if None. """ if idx is not None: self.path.append("%s[%d]" % (tag, idx)) else: self.path.append(tag) return self class XMLMatches(object): """Compare XML strings. More complete than string comparison.""" def _compare_node(self, expected, actual, state, idx): """Recursively compares nodes within the XML tree.""" # Start by comparing the tags if expected.tag != actual.tag: return XMLTagMismatch(state, idx, expected.tag, actual.tag) with state.node(expected.tag, idx): # Compare the attribute keys expected_attrs = set(expected.attrib.keys()) actual_attrs = set(actual.attrib.keys()) if expected_attrs != actual_attrs: expected_only = expected_attrs - actual_attrs actual_only = actual_attrs - expected_attrs return XMLAttrKeysMismatch(state, expected_only, actual_only) # Compare the attribute values for key in expected_attrs: expected_value = expected.attrib[key] actual_value = actual.attrib[key] if 'DONTCARE' in (expected_value, actual_value): continue elif expected_value != actual_value: return XMLAttrValueMismatch(state, key, expected_value, actual_value) # Compare the contents of the node if len(expected) == 0 and len(actual) == 0: # No children, compare text values if ('DONTCARE' not in (expected.text, actual.text) and expected.text != actual.text): return XMLTextValueMismatch(state, expected.text, actual.text) else: expected_idx = 0 actual_idx = 0 while (expected_idx < len(expected) and actual_idx < len(actual)): # Ignore comments and processing instructions # TODO(Vek): may interpret PIs in the future, to # allow for, say, arbitrary ordering of some # elements if (expected[expected_idx].tag in (etree.Comment, etree.ProcessingInstruction)): expected_idx += 1 continue # Compare the nodes result = self._compare_node(expected[expected_idx], actual[actual_idx], state, actual_idx) if result is not True: return result # Step on to comparing the next nodes... expected_idx += 1 actual_idx += 1 # Make sure we consumed all nodes in actual if actual_idx < len(actual): return XMLUnexpectedChild(state, actual[actual_idx].tag, actual_idx) # Make sure we consumed all nodes in expected if expected_idx < len(expected): for node in expected[expected_idx:]: if (node.tag in (etree.Comment, etree.ProcessingInstruction)): continue return XMLExpectedChild(state, node.tag, actual_idx) # The nodes match return True
[ 2, 15069, 3050, 1578, 1829, 5070, 355, 7997, 416, 262, 198, 2, 22998, 286, 262, 2351, 15781, 261, 2306, 873, 290, 4687, 8694, 13, 198, 2, 15069, 2321, 30446, 15503, 12, 11869, 446, 7712, 5834, 11, 406, 13, 47, 13, 198, 2, 198, 2, ...
2.175452
2,599
# Flask interface setup from flask import Flask, render_template app = Flask(__name__) @app.route('/') @app.route('/index.htm') @app.route('/individual.htm') @app.route('/group.htm') @app.route('/blaster.htm') @app.route('/pattern.htm')
[ 2, 46947, 7071, 9058, 198, 198, 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 628, 198, 31, 1324, 13, 38629, 10786, 14, 11537, 198, 31, 1324, 13, 38629, 10786, 14, 9630, 13, 19211, ...
2.6
95
from contextlib import contextmanager import os import shutil import warnings try: from warnings import catch_warnings except ImportError: from django.conf import settings from django.core.files.base import ContentFile from django.test import TestCase from django.utils.functional import LazyObject from django_hashedfilenamestorage.storage import ( HashedFilenameMetaStorage, HashedFilenameFileSystemStorage, ) @contextmanager def patch(namespace, **values): """Patches `namespace`.`name` with `value` for (name, value) in values""" originals = {} if isinstance(namespace, LazyObject): if namespace._wrapped is None: namespace._setup() namespace = namespace._wrapped for (name, value) in values.items(): try: originals[name] = getattr(namespace, name) except AttributeError: originals[name] = NotImplemented if value is NotImplemented: if originals[name] is not NotImplemented: delattr(namespace, name) else: setattr(namespace, name, value) try: yield finally: for (name, original_value) in originals.items(): if original_value is NotImplemented: if values[name] is not NotImplemented: delattr(namespace, name) else: setattr(namespace, name, original_value) @contextmanager
[ 6738, 4732, 8019, 1330, 4732, 37153, 198, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 14601, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 14601, 1330, 4929, 62, 40539, 654, 198, 16341, 17267, 12331, 25, 198, 198, 6738, 42625,...
2.491319
576
# Copyright (c) 2019, CMCC Technologies Co., Ltd. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from rest_framework import serializers from lcm.nf_pm.counst import CrossingDirectionType from lcm.nf_pm.serializers.Link import LinkSerializer
[ 2, 15069, 357, 66, 8, 13130, 11, 16477, 4093, 21852, 1766, 1539, 12052, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 4943, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 1184...
3.629268
205
from __future__ import division from object import Segment as sg import math
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 2134, 1330, 1001, 5154, 355, 264, 70, 198, 11748, 10688, 628, 628, 628, 628 ]
3.818182
22
__author__ = 'stephenlenzi' import os import h5py import numpy as np import tempfile import subprocess """These are for running ilastik in headless mode within Python""" def ilastik_segment(data, ilastik_path, ilastik_project_path): """ Convert image data into a segmentation using ilastik. It requires that you have created a project file specifically for the type of images you want to classify. If this function fails, you should first verify that ilastik is able to form a segmentation when you add the image to the project file as you may need to train the algorithm more. :param data: NxM array, NxM is image shape. :param ilastik_path: path to ilastik installation (should be named something like run_ilastik.sh) :param ilastik_project_path: path to ilastik project file (user must create this in ilastik) example usage: ..code block:: python >>> ilastik_path = './ilastik-release/run_ilastik.sh' >>> ilastik_project_path = './data/GCaMP.ilp' >>> simple_segmentation = ilastik_segment(data, ilastik_path, ilastik_project_path) >>> """ tmp_data = tempfile.NamedTemporaryFile() # temporary file is created np.save(tmp_data.name, data) # input data is saved because ilastik works with files tmp_img = tempfile.NamedTemporaryFile() # temporary file created for ilastik output file # set filepaths for ilastik input_image_path = tmp_data.name + '.npy' output_image_path = tmp_img.name if not os.path.isfile(input_image_path): raise IOError('failed to create input image file') if not _check_tmp_file_equals_data(input_image_path, data): raise IOError('input image not the same as data') # call ilastik in headless mode (i.e. without opening the user interface) subprocess.call([ilastik_path, "--headless", # headless ilastik classification saves segmentation "--project=" + ilastik_project_path, "--output_filename_format=" + output_image_path, input_image_path, "--export_source=Simple Segmentation"]) if not os.path.isfile(output_image_path): raise IOError('output image not found') # load the newly generated image simple_segmentation = h5py.File(tmp_img.name + '.h5', 'r')["exported_data"].value[:, :, 0] # close the temporary files (resulting in their deletion) tmp_img.close() tmp_data.close() return simple_segmentation
[ 834, 9800, 834, 796, 705, 9662, 831, 11925, 17027, 6, 198, 198, 11748, 28686, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 20218, 7753, 198, 11748, 850, 14681, 628, 198, 37811, 4711, 389, 329, 2491, 4229, ...
2.746711
912
import dataclasses import functools import json import os import pkgutil import sys import typing import urllib.parse import dacite import deprecated import yaml from model.base import ( ConfigElementNotFoundError, ModelValidationError, NamedModelElement, ) from ci.util import ( existing_dir, not_empty, not_none, parse_yaml_file, warning, ) dc = dataclasses.dataclass empty_list = dataclasses.field(default_factory=list) ''' Configuration model and retrieval handling. Users of this module will most likely want to create an instance of `ConfigFactory` and use it to create `ConfigurationSet` instances. Configuration sets are factories themselves, that are backed with a configuration source. They create concrete configuration instances. While technically modifiable, all configuration instances should not be altered by users. Configuration objects should usually not be instantiated by users of this module. ''' @dc(frozen=True) @dc(frozen=True) @dc(frozen=True) @dc(frozen=True) @dc(frozen=True) class ConfigType: ''' represents a configuration type (used for serialisation and deserialisation) ''' model: ConfigTypeModel src: typing.Tuple[typing.Union[LocalFileCfgSrc, GithubRepoFileSrc]] = () class ConfigFactory: '''Creates configuration model element instances from the underlying configuration source Configuration elements are organised in a two-level hierarchy: Configuration type (named cfg_type by convention) which specifies a configuration schema (and semantics) and Configuration element name (named cfg_name or element_name by convention). Configuration model elements may be retrieved through one of two methods: - via the generic `_cfg_element(cfg_type_name, cfg_name)` - via a "factory method" (if defined in cfg_type) - example: `github(cfg_name)` There is a special configuration type named `ConfigurationSet`, which is used to group sets of configuration elements. Configuration sets expose an API equivalent to ConfigFactory. ''' CFG_TYPES = 'cfg_types' _cfg_type_cache = {} # <name>:<type> @staticmethod @staticmethod @staticmethod @staticmethod @staticmethod @deprecated.deprecated def _configs(self, cfg_name: str): ''' returns all known cfg-element-names ''' self._retrieve_cfg_elements(cfg_type_name=cfg_name) return self.raw[cfg_name] @functools.lru_cache def cfg_set(self, cfg_name: str) -> 'ConfigurationSet': ''' returns a new `ConfigurationSet` instance for the specified config name backed by the configured configuration source. ''' configs_dict = self._configs('cfg_set') if cfg_name not in configs_dict: raise ValueError('no cfg named {c} in {cs}'.format( c=cfg_name, cs=', '.join(configs_dict.keys()) ) ) return ConfigurationSet( cfg_factory=self, cfg_name=cfg_name, raw_dict=configs_dict[cfg_name] ) def _cfg_elements(self, cfg_type_name: str): '''Returns all cfg_elements for the given cfg_type. Parameters ---------- cfg_type_name: str The name of the cfg_type whose instances should be retrieved. Yields ------- NamedModelElement Instance of the given cfg_type. Raises ------ ValueError If the specified cfg_type is unknown. ''' not_empty(cfg_type_name) self._retrieve_cfg_elements(cfg_type_name=cfg_type_name) for element_name in self._cfg_element_names(cfg_type_name): yield self._cfg_element(cfg_type_name, element_name) def _cfg_element_names(self, cfg_type_name: str): '''Returns cfg-elements of the given cfg_type Parameters ---------- cfg_type_name: str The cfg type name Returns ------- Iterable[str] Contains the names of all cfg-elements of the given cfg_type known to this ConfigFactory. Raises ------ ValueError If the specified cfg_type is unknown. ''' not_empty(cfg_type_name) self._retrieve_cfg_elements(cfg_type_name=cfg_type_name) known_types = self._cfg_types() if cfg_type_name not in known_types: raise ValueError("Unknown config type '{c}'. Known types: {k}".format( c=cfg_type_name, k=', '.join(known_types.keys()), )) if cfg_type_name in self.raw: return set(self.raw[cfg_type_name].keys()) else: return set() class ConfigurationSet(NamedModelElement): ''' Represents a set of corresponding configuration. Instances are created by `ConfigFactory`. `ConfigurationSet` is itself a factory, offering a set of factory methods which create concrete configuration objects based on the backing configuration source. Not intended to be instantiated by users of this module ''' def _cfg_elements(self, cfg_type_name: str): '''Returns all container cfg elements of the given cfg_type Raises ------ ValueError If the specified cfg_type is unknown. ''' not_empty(cfg_type_name) for element_name in self._cfg_element_names(cfg_type_name): yield self._cfg_element(cfg_type_name, element_name) def _cfg_element_names(self, cfg_type_name: str): '''Returns all container cfg element names Raises ------ ValueError If the specified cfg_type is unknown. ''' not_empty(cfg_type_name) # ask factory for all known names. This ensures that the existance of the type is checked. all_cfg_element_names = self.cfg_factory._cfg_element_names(cfg_type_name=cfg_type_name) if cfg_type_name in self.raw.keys(): return all_cfg_element_names & set(self.raw[cfg_type_name]['config_names']) else: return set()
[ 11748, 4818, 330, 28958, 198, 11748, 1257, 310, 10141, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 279, 10025, 22602, 198, 11748, 25064, 198, 11748, 19720, 198, 11748, 2956, 297, 571, 13, 29572, 198, 198, 11748, 288, 330, 578, 198, ...
2.51175
2,468
from ._base import ServicePageHandler, ServiceFormHandler from anthill.framework.handlers.edit import FormMixin, ProcessFormMixin from admin.forms import ( EventForm, EventParticipantForm, EventCategoryForm, EventGeneratorForm, EventGeneratorPoolForm )
[ 6738, 47540, 8692, 1330, 4809, 9876, 25060, 11, 4809, 8479, 25060, 198, 6738, 26794, 359, 13, 30604, 13, 4993, 8116, 13, 19312, 1330, 5178, 35608, 259, 11, 10854, 8479, 35608, 259, 198, 6738, 13169, 13, 23914, 1330, 357, 198, 220, 220, ...
3.545455
77
import heterocl as hcl import heterocl.tvm as tvm import numpy as np
[ 11748, 14445, 38679, 355, 289, 565, 198, 11748, 14445, 38679, 13, 83, 14761, 355, 256, 14761, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.043478
23
# standard libraries import logging # rubiks cube libraries from rubikscubelookuptables.buildercore import BFS log = logging.getLogger(__name__)
[ 2, 3210, 12782, 198, 11748, 18931, 198, 198, 2, 6437, 72, 591, 23441, 12782, 198, 6738, 6437, 72, 591, 66, 549, 417, 566, 37623, 2977, 13, 11249, 2798, 382, 1330, 347, 10652, 198, 198, 6404, 796, 18931, 13, 1136, 11187, 1362, 7, 834...
3.104167
48
from urllib.request import urlopen, Request from bs4 import BeautifulSoup
[ 6738, 2956, 297, 571, 13, 25927, 1330, 19016, 9654, 11, 19390, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 628 ]
3.571429
21
import healpy as hp import numpy as np import schnell as snl import matplotlib.pyplot as plt from matplotlib import rc rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']}) rc('text', usetex=True) t_obs = 1 f_ref = 63 nside = 64 obs_time = t_obs*365*24*3600. freqs = np.linspace(10., 1010., 101) dets = [snl.GroundDetector('Hanford', 46.4, -119.4, 171.8, 'data/aLIGO.txt'), snl.GroundDetector('Livingstone', 30.7, -90.8, 243.0, 'data/aLIGO.txt'), snl.GroundDetector('Virgo', 43.6, 10.5, 116.5, 'data/Virgo.txt'), snl.GroundDetector('KAGRA', 36.3, 137.2, 225.0, 'data/KAGRA.txt')] print("HL") mc = snl.MapCalculator(dets[:2], f_pivot=f_ref) theta, phi = hp.pix2ang(nside, np.arange(hp.nside2npix(nside))) a_HL = mc.get_antenna(0, 1, 0., 10., theta, phi) hp.mollview(np.abs(a_HL), notext=True, cbar=True, title=r'$|{\cal A}_{\rm LIGO}(f=10\,{\rm Hz},\theta,\varphi)|$', min=0, max=0.2) plt.savefig("antenna.png", bbox_inches='tight') plt.show() nl_HL = mc.get_N_ell(obs_time, freqs, nside, no_autos=True) print("HLVK") mc = snl.MapCalculator(dets[:4], f_pivot=f_ref) nl_HLVK = mc.get_N_ell(obs_time, freqs, nside, no_autos=True) print("HLVKa") nl_HLVKa = mc.get_N_ell(obs_time, freqs, nside, no_autos=False) ls = np.arange(3*nside) plt.figure() plt.plot(ls, (ls+0.5)*nl_HL, label='LIGO') plt.plot(ls, (ls+0.5)*nl_HLVK, label=' + Virgo + KAGRA') plt.plot(ls, (ls+0.5)*nl_HLVKa, label=' + auto correlations') plt.loglog() plt.xlabel(r'$\ell$', fontsize=16) plt.ylabel(r'$(\ell+1/2)\,N_\ell$', fontsize=16) plt.ylim([3E-20, 1E-10]) plt.xlim([1, 100]) plt.legend(loc='upper left', fontsize='x-large', frameon=False) plt.gca().tick_params(labelsize="large") plt.savefig("Nell.png", bbox_inches='tight') plt.show()
[ 11748, 12035, 9078, 355, 27673, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 264, 1349, 695, 355, 3013, 75, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 1330, 48321, 198, 6015, 10786, 10...
1.854668
1,039
import logging import os logger = _get_logger()
[ 11748, 18931, 198, 11748, 28686, 628, 628, 198, 6404, 1362, 796, 4808, 1136, 62, 6404, 1362, 3419, 198 ]
2.888889
18
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.tests.unit import test_proxy_base from otcextensions.sdk.kms.v1 import _proxy from otcextensions.sdk.kms.v1 import data_key as _data_key from otcextensions.sdk.kms.v1 import key as _key from otcextensions.sdk.kms.v1 import misc as _misc # def test_encrypt(self): # self._verify2( # 'otcextensions.sdk.kms.v1.data_key.DataKey.encrypt', # self.proxy.encrypt_datakey, # method_args=['INSTANCE'], # expected_args=[self.proxy], # ) # # def test_decrypt(self): # self._verify2( # 'otcextensions.sdk.kms.v1.data_key.DataKey.decrypt', # self.proxy.decrypt_datakey, # method_args=['INSTANCE'], # expected_args=[self.proxy], # )
[ 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 257, 4866, 286, 262, 13789, 379, 198, 2,...
2.494361
532
# Copyright 2021 dimfred.1337@web.de # # 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 sys from pathlib import Path # https://imgflip.com/i/5xlpwv imxpy_path = str(Path(__file__).parent.parent) if imxpy_path not in sys.path: sys.path.insert(0, imxpy_path) from imxpy.imx_client import IMXClient from imxpy.imx_objects import * from imxpy.utils import paginate, all_pages, linear_retry, SafeNumber, IMXTime
[ 2, 15069, 33448, 5391, 39193, 13, 1485, 2718, 31, 12384, 13, 2934, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 428, 198, 2, 3788, 290, 3917, 10314, 3696, 357, 1169, ...
3.450363
413
#!/usr/bin/env python3 from .base_test import BaseTest from fbc.symphony.cli.graphql_compiler.gql.utils_codegen import CodeChunk
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 764, 8692, 62, 9288, 1330, 7308, 14402, 198, 6738, 277, 15630, 13, 37047, 23021, 13, 44506, 13, 34960, 13976, 62, 5589, 5329, 13, 70, 13976, 13, 26791, 62, 8189, 5235, ...
2.787234
47
import os import subprocess import sys from setuptools import Extension, setup from setuptools.command.build_ext import build_ext from setuptools.command.build_py import build_py setup( cmdclass={"build_ext": BuildExtCmd, "build_py": BuildPyCmd}, ext_modules=[LibGraphQLParserExtension()], )
[ 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 198, 6738, 900, 37623, 10141, 1330, 27995, 11, 9058, 198, 6738, 900, 37623, 10141, 13, 21812, 13, 11249, 62, 2302, 1330, 1382, 62, 2302, 198, 6738, 900, 37623, 10141, 13, 218...
3.08
100
""" @brief test log(time=3s) """ import unittest from pyquickhelper.pycode import ExtTestCase from wrapclib import re2 if __name__ == "__main__": unittest.main()
[ 37811, 198, 31, 65, 3796, 220, 220, 220, 220, 220, 1332, 2604, 7, 2435, 28, 18, 82, 8, 198, 37811, 198, 11748, 555, 715, 395, 198, 6738, 12972, 24209, 2978, 525, 13, 9078, 8189, 1330, 5683, 14402, 20448, 198, 6738, 14441, 565, 571, ...
2.485714
70
from typing import Text import pandas as pd import os #stabilisce il path locale in cui sit rova il file os.chdir(os.path.dirname(os.path.abspath(__file__))) ##DOPO SCRIPT ROBERTO e prima ahah #print(sentences("de_cv_dev.txt")) rows = sentences('de_cv_dev.txt') mega_list = [] frasi = list_sentences(sentences) for el in frasi: for el1 in el: word = el1.split(' ') mega_list.append(word) #print(mega_list) lista_1 = [] for l in mega_list: for i in range(len(mega_list)-1): lista_1.append([[mega_list[i]], [mega_list[i+1]]]) print(lista_1[1:3])
[ 6738, 19720, 1330, 8255, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686, 198, 198, 2, 301, 14991, 271, 344, 4229, 3108, 36693, 287, 269, 9019, 1650, 686, 6862, 4229, 2393, 198, 418, 13, 354, 15908, 7, 418, 13, 6978, 13, 159...
2.140845
284
import unittest from algorithms.rna_transcription import to_rna if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 16113, 13, 81, 2616, 62, 7645, 6820, 1330, 284, 62, 81, 2616, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.674419
43
"""Method decorators for Schevo.""" # Copyright (c) 2001-2009 ElevenCraft Inc. # See LICENSE for details. import sys from schevo.lib import optimize class extentmethod(_labelable_classmethod): """Mark a method of an `Entity` class as an extent method. When a function `fn` is decorated as an `extentmethod`, `isextentmethod(fn) -> True`, and when the method is called as `method(*args, **kw)`, the function is called as `fn(extent, *args, **kw)`. """ marker = '_extentmethod' class extentclassmethod(extentmethod): """Mark a method of an `Entity` class as an extent method that is called as an entity classmethod. When a function `fn` is decorated as an `extentclassmethod`, `isextentmethod(fn) -> True`, and when the method is called as `method(*args, **kw)`, the function is called as `fn(entity_class, *args, **kw)`. """ def with_label(label, plural=None): """Return a decorator that assigns a label and an optional plural label to a function.""" return label_decorator optimize.bind_all(sys.modules[__name__]) # Last line of module.
[ 37811, 17410, 11705, 2024, 329, 10011, 13038, 526, 15931, 198, 198, 2, 15069, 357, 66, 8, 5878, 12, 10531, 37339, 14467, 3457, 13, 198, 2, 4091, 38559, 24290, 329, 3307, 13, 198, 198, 11748, 25064, 198, 6738, 3897, 13038, 13, 8019, 13...
3.03794
369
from sqlalchemy.orm import relationship import zeeguu_core from sqlalchemy import Column, Integer, String, ForeignKey, and_ db = zeeguu_core.db class LocalizedTopic(db.Model): """ A localized topic is a localized version of a topic, it is the same topic but translated and with the added language_id and localized keywords. """ __table_args__ = {'mysql_collate': 'utf8_bin'} id = Column(Integer, primary_key=True) from zeeguu_core.model.topic import Topic topic_id = Column(Integer, ForeignKey(Topic.id)) topic = relationship(Topic) from zeeguu_core.model.language import Language language_id = Column(Integer, ForeignKey(Language.id)) language = relationship(Language) topic_translated = Column(String(30)) keywords = Column(String(1024)) @classmethod
[ 6738, 44161, 282, 26599, 13, 579, 1330, 2776, 198, 198, 11748, 1976, 1453, 5162, 84, 62, 7295, 198, 198, 6738, 44161, 282, 26599, 1330, 29201, 11, 34142, 11, 10903, 11, 8708, 9218, 11, 290, 62, 198, 198, 9945, 796, 1976, 1453, 5162, ...
2.920415
289
# 抛出自定义异常 if __name__ == '__main__': main()
[ 2, 10545, 232, 249, 49035, 118, 164, 229, 103, 22522, 248, 20046, 231, 28156, 224, 30585, 116, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419 ]
1.416667
36
"""Сервисный модуль для базы данных.""" from app.core import Base, SessionLocal, engine class DatabaseException(Exception): """Класс исключений.""" def with_traceback(self, tb) -> str: """Возврат трейсбека. Args: tb: трейсбек Returns: str: форматированная строка """ return f'{self.__class__.__name__}: {self.__traceback__}' async def create_database() -> Base: """Создание базы данных. Returns: Base.metadata.create_all(bind=engine): создание базы """ return Base.metadata.create_all(bind=engine) async def get_db() -> SessionLocal: """Получение экземпляра базы данных. Yields: db: SessionLocal экземпляр """ db = SessionLocal() try: yield db except DatabaseException as err: err.with_traceback(tb=err) finally: db.close()
[ 37811, 140, 94, 16843, 21169, 38857, 18849, 21727, 22177, 45035, 140, 117, 12466, 120, 25443, 112, 35072, 30143, 45367, 12466, 112, 30143, 40623, 12466, 109, 16142, 140, 115, 45035, 12466, 112, 16142, 22177, 22177, 45035, 141, 227, 526, 159...
1.67167
533
__________________________________________________________________________________________________ sample 32 ms submission # # @lc app=leetcode id=402 lang=python3 # # [402] Remove K Digits # __________________________________________________________________________________________________ sample 13060 kb submission __________________________________________________________________________________________________
[ 27193, 10221, 834, 198, 39873, 3933, 13845, 14498, 198, 2, 198, 2, 2488, 44601, 598, 28, 293, 316, 8189, 4686, 28, 32531, 42392, 28, 29412, 18, 198, 2, 198, 2, 685, 32531, 60, 17220, 509, 7367, 896, 198, 2, 198, 27193, 10221, 834, ...
7.722222
54
#!/usr/bin/env python # SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # Author: # Alberto Solino (@agsolino) # # Description: # This script will gather data about the domain's users and their corresponding email addresses. It will also # include some extra information about last logon and last password set attributes. # You can enable or disable the the attributes shown in the final table by changing the values in line 184 and # headers in line 190. # If no entries are returned that means users don't have email addresses specified. If so, you can use the # -all-users parameter. # # Reference for: # LDAP # from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import logging import sys from datetime import datetime, timedelta from calendar import timegm from impacket import version from impacket.dcerpc.v5.samr import UF_ACCOUNTDISABLE from impacket.examples import logger from impacket.ldap import ldap, ldapasn1 from impacket.smbconnection import SMBConnection
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 10729, 11335, 32, 24318, 9131, 4462, 13, 15069, 2864, 26707, 30515, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 3788, 318, 2810, 739, 739, 257, 4622, 9518, 2196, 198, 2...
3.649425
348
""" Init file for news module. """ __all__ = ['snapshot', 'stream', 'bulknews', 'taxonomy', 'Snapshot', 'SnapshotQuery', 'SnapshotFiles', 'Stream', 'Listener', 'Subscription', 'Taxonomy', 'SnapshotFiles'] from .__version__ import __version__ from .snapshot import (Snapshot, SnapshotQuery, SnapshotFiles) from .stream import (Stream, Listener, Subscription) from .taxonomy.taxonomy import Taxonomy from factiva.core import SnapshotFiles version = __version__
[ 198, 37811, 198, 220, 220, 220, 44707, 2393, 329, 1705, 8265, 13, 198, 37811, 198, 834, 439, 834, 796, 37250, 45380, 9442, 3256, 705, 5532, 3256, 705, 65, 12171, 10827, 3256, 705, 19290, 30565, 3256, 198, 220, 220, 220, 705, 43826, 94...
3.202703
148
# License info goes here. """ Test cases for Model Test cases can be run with: nosetests coverage report -m While debugging just these tests it's convinient to use this: nosetests --stop tests/test_models.py:TestPatModel """ import os import logging import unittest from datetime import datetime import json from werkzeug.exceptions import NotFound from service.models import Pat, Gender, DataValidationError, db from service import app #from .factories import PatFactory #read the sample jason to dictionary list and provide for test with open('tests/records.json') as jsonfile: sample_data = json.load(jsonfile) #Q: print(sample_data[0]["lname"]) DATABASE_URI = os.getenv( "DATABASE_URI", "postgres://postgres:postgres@localhost:5432/postgres" ) ###################################################################### # MODEL TEST CASES ###################################################################### class TestPatModel(unittest.TestCase): """ Test Cases for Model """ @classmethod def setUpClass(cls): """ These run once per Test suite """ app.config['TESTING'] = True app.config['DEBUG'] = False app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URI app.logger.setLevel(logging.CRITICAL) Pat.init_db(app) @classmethod def test_create_a_pat(self): """ Create a patient and assert that it exists """ pat = Pat(title="Ms.", fname="Daisy", lname="Dog", street="2000 Highland", postal_code="98765", city="Hayward", state="CA", phone_home="(510) 793-9896", email="dog@us.ibm.com", DOB=datetime.strptime('2010-10-09', "%Y-%m-%d"), gender=Gender.Female) self.assertTrue(pat != None) self.assertEqual(pat.id, None) self.assertEqual(pat.fname, "Daisy") self.assertEqual(pat.postal_code, "98765") self.assertEqual(pat.city, "Hayward") self.assertEqual(pat.gender, Gender.Female) self.assertEqual(pat.DOB, datetime.strptime('2010-10-09', "%Y-%m-%d")) def test_add_a_pat(self): """ Create a patient and add it to the database """ pats = Pat.all() self.assertEqual(pats, []) pat = Pat(title="Mr.", fname="Sweetheart", lname="Cat", street="2001 Highland", postal_code="98764", city="Los Angeles", state="CA", phone_home="(310) 893-9845", email="cat@us.ibm.com", DOB=datetime.strptime('2019-12-31', "%Y-%m-%d"), gender=Gender.Male) self.assertTrue(pat != None) self.assertEqual(pat.id, None) pat.create() # Asert that it was assigned an id and shows up in the database self.assertEqual(pat.id, 1) pats = Pat.all() self.assertEqual(len(pats), 1) def test_update_a_pat(self): """ Update a patient """ pat = Pat() pat = pat.deserialize(sample_data[0]) logging.debug(pat) pat.create() logging.debug(pat) self.assertEqual(pat.id, 1) # Change it an save it pat.postal_code = "97600" original_id = pat.id pat.save() self.assertEqual(pat.id, original_id) self.assertEqual(pat.postal_code, "97600") # Fetch it back and make sure the id hasn't changed # but the data did change pats = Pat.all() self.assertEqual(len(pats), 1) self.assertEqual(pats[0].id, 1) self.assertEqual(pats[0].postal_code, "97600") def test_delete_a_pat(self): """ Delete a patient """ #pat = PatFactory() pat = Pat() pat = pat.deserialize(sample_data[1]) pat.create() self.assertEqual(len(Pat.all()), 1) # delete the patient and make sure doesn't exist in the database pat.delete() self.assertEqual(len(Pat.all()), 0) def test_serialize_a_pat(self): """ Test serialization of a patient """ #pat = PatFactory() pat = Pat() pat = pat.deserialize(sample_data[2]) data = pat.serialize() self.assertNotEqual(data, None) self.assertIn("id", data) self.assertEqual(data["id"], pat.id) self.assertIn("fname", data) self.assertEqual(data["fname"], pat.fname) self.assertIn("lname", data) self.assertEqual(data["lname"], pat.lname) self.assertIn("postal_code", data) self.assertEqual(data["postal_code"], pat.postal_code) self.assertIn("phone_home", data) self.assertEqual(data["phone_home"], pat.phone_home) self.assertIn("DOB", data) self.assertEqual(data["DOB"], pat.DOB.strftime("%Y-%m-%d")) self.assertIn("sex", data) self.assertEqual(data["sex"], pat.gender.name) def test_deserialize_a_pat(self): """ Test deserialization of a patient """ #sample_data[3] = {'title': 'Mr.', 'fname': 'Richard', 'mname': 'Cortez', 'lname': 'Jones', 'street': '400 West Broadway', 'postal_code': '92101', 'city': 'San Diego', 'state': 'CA', 'phone_home': '(619) 555-5555', 'email': 'richard@pennfirm.com', 'DOB': '1940-12-16', 'sex': 'Male'} pat = Pat() pat.deserialize(sample_data[3]) self.assertNotEqual(pat, None) self.assertEqual(pat.id, None) self.assertEqual(pat.fname, "Richard") self.assertEqual(pat.street, "400 West Broadway") self.assertEqual(pat.state, "CA") self.assertEqual(pat.email, "richard@pennfirm.com") self.assertEqual(pat.gender, Gender.Male) def test_deserialize_missing_data(self): """ Test deserialization of a patient with missing required value """ #miss the required first name data = {'title': 'Mr.', 'mname': 'Alexis', 'lname': 'Jenane', 'street': '145 N. East Street', 'postal_code': '92111', 'city': 'La Mesa', 'state': 'CA', 'phone_home': '(619) 555-2222', 'email': 'i.jenane@email.com', 'DOB': '1933-03-22', 'sex': 'Female'} pat = Pat() self.assertRaises(DataValidationError, pat.deserialize, data) def test_deserialize_bad_data(self): """ Test deserialization of a patient with bad data """ #assign a wrong zip code data = {'title': 'Mr.', 'mname': 'Alexis', 'lname': 'Jenane', 'street': '145 N. East Street', 'postal_code': '921155', 'city': 'La Mesa', 'state': 'CA', 'phone_home': '(619) 555-2222', 'email': 'i.jenane@email.com', 'DOB': '1933-03-22', 'sex': 'Female'} pat = Pat() self.assertRaises(DataValidationError, pat.deserialize, data) def test_find_pat(self): """ Find a patient by ID """ #pats = PatFactory.create_batch(3) pats = [Pat() for i in range(3)] for idx, pat in enumerate(pats): pat = pat.deserialize(sample_data[idx]) pat.create() logging.debug(pats) # make sure they got saved self.assertEqual(len(Pat.all()), 3) # find the 2nd patient in the list pat = Pat.find(pats[1].id) self.assertIsNot(pat, None) self.assertEqual(pat.id, pats[1].id) self.assertEqual(pat.fname, pats[1].fname) self.assertEqual(pat.city, pats[1].city) def test_find_by_lname(self): """ Find patients by last name """ for i in range(4): pat = Pat() pat = pat.deserialize(sample_data[i]) pat.create() pats = Pat.find_by_lname("Moses") self.assertEqual(pats[0].lname, "Moses") self.assertEqual(pats[0].fname, "Jim") self.assertEqual(pats[0].phone_home, "(323) 555-4444") def test_find_by_fname(self): """ Find patients by first name """ for i in range(4): pat = Pat() pat = pat.deserialize(sample_data[i]) pat.create() pats = Pat.find_by_fname("Nora") self.assertEqual(pats[0].fname, "Nora") self.assertEqual(pats[0].lname, "Cohen") self.assertEqual(pats[0].phone_home, "(213) 555-5555") def test_find_by_phone(self): """ Find patients by home phone number """ for i in range(4): pat = Pat() pat = pat.deserialize(sample_data[i]) pat.create() pats = Pat.find_by_phone("(213) 555-5555") self.assertEqual(pats[0].fname, "Nora") self.assertEqual(pats[0].lname, "Cohen") self.assertEqual(pats[0].phone_home, "(213) 555-5555") def test_find_by_zip(self): """ Find patients by zip code """ for i in range(4): pat = Pat() pat = pat.deserialize(sample_data[i]) pat.create() pats = Pat.find_by_zip("92101") self.assertEqual(pats[0].fname, "Nora") self.assertEqual(pats[0].lname, "Cohen") self.assertEqual(pats[0].postal_code, "92101") def test_find_by_gender(self): """ Find patients by gender """ for i in range(7): pat = Pat() pat = pat.deserialize(sample_data[i]) pat.create() pats = Pat.find_by_gender(Gender.Female) pat_list = [pat for pat in pats] self.assertEqual(len(pat_list), 2) self.assertEqual(pats[1].fname, "Ilias") self.assertEqual(pats[1].lname, "Jenane") pats = Pat.find_by_gender(Gender.Male) pat_list = [pat for pat in pats] self.assertEqual(len(pat_list), 5) def test_find_or_404_found(self): """ Find or return 404 found """ #pats = PatFactory.create_batch(3) pats = [] for i in range(4): pat = Pat() pat = pat.deserialize(sample_data[i]) pat.create() pats.append(pat) pat = Pat.find_or_404(pats[1].id) self.assertIsNot(pat, None) self.assertEqual(pat.id, pats[1].id) self.assertEqual(pat.lname, pats[1].lname) self.assertEqual(pat.fname, pats[1].fname) self.assertEqual(pat.DOB, pats[1].DOB) def test_find_or_404_not_found(self): """ Find or return 404 NOT found """ self.assertRaises(NotFound, Pat.find_or_404, 0)
[ 2, 13789, 7508, 2925, 994, 13, 198, 198, 37811, 198, 14402, 2663, 329, 9104, 198, 198, 14402, 2663, 460, 307, 1057, 351, 25, 198, 220, 220, 220, 43630, 316, 3558, 198, 220, 220, 220, 5197, 989, 532, 76, 198, 198, 3633, 28769, 655, ...
2.192602
4,569
''' Created on 29 Mar 2019 @author: ssg37927 ''' from numpy import meshgrid, linspace, concatenate, zeros_like, sqrt
[ 7061, 6, 198, 41972, 319, 2808, 1526, 13130, 198, 198, 31, 9800, 25, 37786, 70, 29088, 1983, 198, 7061, 6, 198, 198, 6738, 299, 32152, 1330, 19609, 25928, 11, 300, 1040, 10223, 11, 1673, 36686, 378, 11, 1976, 27498, 62, 2339, 11, 19...
2.644444
45
# Grace Foster # ITP 100-01 # Program 03 - GUI # GUI.py # ------------------------------------------------- from tkinter import * from tkinter import ttk class GUI: '''def bye(self): if self.buttonsEnabled.get() >= 1: self.label.config(text="Goodbye World!")''' '''def hello(self): if self.buttonsEnabled.get() >= 1: self.label.config(text="Hello World!")''' main()
[ 2, 16156, 18489, 198, 2, 314, 7250, 1802, 12, 486, 198, 2, 6118, 7643, 532, 25757, 198, 2, 25757, 13, 9078, 198, 2, 20368, 1783, 12, 198, 198, 6738, 256, 74, 3849, 1330, 1635, 198, 6738, 256, 74, 3849, 1330, 256, 30488, 628, 198, ...
2.511905
168
from crownstone_core.util.BufferReader import BufferReader class UartCrownstoneStatusPacket: """ UART crownstone status packet: 1B flags """
[ 6738, 12389, 6440, 62, 7295, 13, 22602, 13, 28632, 33634, 1330, 47017, 33634, 628, 198, 4871, 471, 433, 34, 2053, 6440, 19580, 47, 8317, 25, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 471, 7227, 12389, 6440, 3722, 19638, 25, 198, ...
2.944444
54
# Copyright 2015 OpenStack Foundation. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import sys from mox3 import mox from neutronclient.common import exceptions from neutronclient.neutron.v2_0 import subnetpool from neutronclient.tests.unit import test_cli20
[ 2, 15069, 1853, 4946, 25896, 5693, 13, 198, 2, 1439, 6923, 33876, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, ...
3.438819
237
"""Method for grid plotting""" from matplotlib import patches, pyplot as plt def plot_grid(grid, width=1, height=1, primitive=True): """ Method for plotting grids. Simple numpy arrays can also be plotted of primitive is True """ nb_rows = len(grid) nb_cols = len(grid[0]) __, axs = plt.subplots(1, figsize=(40, 40)) for row in range(nb_rows): for col in range(nb_cols): facecolor = 'none' if not primitive: facecolor = grid[row, col].color r_x = col * width r_y = row * height axs.add_artist( patches.Rectangle( (r_x, r_y), width, height, facecolor=facecolor, edgecolor='black' ) ) axs.annotate( str(grid[row, col]), (r_x + width / 2.0, r_y + height / 2.0), ha='center', va='center' ) # Debug axs.annotate( str(len(grid[row, col].rect_list)), (r_x + width / 2.0, r_y) ) axs.set_xlim((0, nb_cols * width)) axs.set_ylim((0, nb_rows * height)) plt.tick_params( axis='both', which='both', bottom=False, top=False, left=False, labelbottom=False, labelleft=False ) plt.tight_layout(pad=0) plt.savefig("grid_full_python.png", dpi=600)
[ 37811, 17410, 329, 10706, 29353, 37811, 198, 198, 6738, 2603, 29487, 8019, 1330, 16082, 11, 12972, 29487, 355, 458, 83, 628, 198, 4299, 7110, 62, 25928, 7, 25928, 11, 9647, 28, 16, 11, 6001, 28, 16, 11, 20049, 28, 17821, 2599, 198, ...
1.74714
874
from functools import reduce from operator import mul from ..aoc_util import get_data import itertools import os if __name__ == '__main__': num_list = get_data(1) nums = sum_finder(num_list) print(f'Part 1: {reduce(mul, nums)}') nums = sum_finder(num_list, num_factors=3) print(f'Part 2: {reduce(mul, nums)}')
[ 6738, 1257, 310, 10141, 1330, 4646, 198, 6738, 10088, 1330, 35971, 198, 6738, 11485, 64, 420, 62, 22602, 1330, 651, 62, 7890, 198, 198, 11748, 340, 861, 10141, 198, 11748, 28686, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 1...
2.4
140
# coding: utf-8 """ Ed-Fi Operational Data Store API The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface. *** > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reasonable safeguards against cross-site scripting attacks and other malicious content, but the platform does not and cannot guarantee that the data it contains is free of all potentially harmful content.* *** # noqa: E501 OpenAPI spec version: 3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from swagger_client.configuration import Configuration class TpdmStaffExtension(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'gender_descriptor': 'str', 'probation_complete_date': 'date', 'tenured': 'bool', 'tenure_track': 'bool', 'background_checks': 'list[TpdmStaffBackgroundCheck]', 'highly_qualified_academic_subjects': 'list[TpdmStaffHighlyQualifiedAcademicSubject]', 'seniorities': 'list[TpdmStaffSeniority]', 'teacher_preparation_programs': 'list[TpdmStaffTeacherPreparationProgram]', 'salary': 'TpdmStaffSalary', 'teacher_educator_research': 'TpdmStaffTeacherEducatorResearch' } attribute_map = { 'gender_descriptor': 'genderDescriptor', 'probation_complete_date': 'probationCompleteDate', 'tenured': 'tenured', 'tenure_track': 'tenureTrack', 'background_checks': 'backgroundChecks', 'highly_qualified_academic_subjects': 'highlyQualifiedAcademicSubjects', 'seniorities': 'seniorities', 'teacher_preparation_programs': 'teacherPreparationPrograms', 'salary': 'salary', 'teacher_educator_research': 'teacherEducatorResearch' } def __init__(self, gender_descriptor=None, probation_complete_date=None, tenured=None, tenure_track=None, background_checks=None, highly_qualified_academic_subjects=None, seniorities=None, teacher_preparation_programs=None, salary=None, teacher_educator_research=None, _configuration=None): # noqa: E501 """TpdmStaffExtension - a model defined in Swagger""" # noqa: E501 if _configuration is None: _configuration = Configuration() self._configuration = _configuration self._gender_descriptor = None self._probation_complete_date = None self._tenured = None self._tenure_track = None self._background_checks = None self._highly_qualified_academic_subjects = None self._seniorities = None self._teacher_preparation_programs = None self._salary = None self._teacher_educator_research = None self.discriminator = None if gender_descriptor is not None: self.gender_descriptor = gender_descriptor if probation_complete_date is not None: self.probation_complete_date = probation_complete_date if tenured is not None: self.tenured = tenured if tenure_track is not None: self.tenure_track = tenure_track if background_checks is not None: self.background_checks = background_checks if highly_qualified_academic_subjects is not None: self.highly_qualified_academic_subjects = highly_qualified_academic_subjects if seniorities is not None: self.seniorities = seniorities if teacher_preparation_programs is not None: self.teacher_preparation_programs = teacher_preparation_programs if salary is not None: self.salary = salary if teacher_educator_research is not None: self.teacher_educator_research = teacher_educator_research @property def gender_descriptor(self): """Gets the gender_descriptor of this TpdmStaffExtension. # noqa: E501 The gender with which a person associates. # noqa: E501 :return: The gender_descriptor of this TpdmStaffExtension. # noqa: E501 :rtype: str """ return self._gender_descriptor @gender_descriptor.setter def gender_descriptor(self, gender_descriptor): """Sets the gender_descriptor of this TpdmStaffExtension. The gender with which a person associates. # noqa: E501 :param gender_descriptor: The gender_descriptor of this TpdmStaffExtension. # noqa: E501 :type: str """ if (self._configuration.client_side_validation and gender_descriptor is not None and len(gender_descriptor) > 306): raise ValueError("Invalid value for `gender_descriptor`, length must be less than or equal to `306`") # noqa: E501 self._gender_descriptor = gender_descriptor @property def probation_complete_date(self): """Gets the probation_complete_date of this TpdmStaffExtension. # noqa: E501 The date the probation period ended or is scheduled to end. # noqa: E501 :return: The probation_complete_date of this TpdmStaffExtension. # noqa: E501 :rtype: date """ return self._probation_complete_date @probation_complete_date.setter def probation_complete_date(self, probation_complete_date): """Sets the probation_complete_date of this TpdmStaffExtension. The date the probation period ended or is scheduled to end. # noqa: E501 :param probation_complete_date: The probation_complete_date of this TpdmStaffExtension. # noqa: E501 :type: date """ self._probation_complete_date = probation_complete_date @property def tenured(self): """Gets the tenured of this TpdmStaffExtension. # noqa: E501 Indicator of whether the staff member is tenured. # noqa: E501 :return: The tenured of this TpdmStaffExtension. # noqa: E501 :rtype: bool """ return self._tenured @tenured.setter def tenured(self, tenured): """Sets the tenured of this TpdmStaffExtension. Indicator of whether the staff member is tenured. # noqa: E501 :param tenured: The tenured of this TpdmStaffExtension. # noqa: E501 :type: bool """ self._tenured = tenured @property def tenure_track(self): """Gets the tenure_track of this TpdmStaffExtension. # noqa: E501 An indication that the staff is on track for tenure. # noqa: E501 :return: The tenure_track of this TpdmStaffExtension. # noqa: E501 :rtype: bool """ return self._tenure_track @tenure_track.setter def tenure_track(self, tenure_track): """Sets the tenure_track of this TpdmStaffExtension. An indication that the staff is on track for tenure. # noqa: E501 :param tenure_track: The tenure_track of this TpdmStaffExtension. # noqa: E501 :type: bool """ self._tenure_track = tenure_track @property def background_checks(self): """Gets the background_checks of this TpdmStaffExtension. # noqa: E501 An unordered collection of staffBackgroundChecks. Staff background check history and disposition. # noqa: E501 :return: The background_checks of this TpdmStaffExtension. # noqa: E501 :rtype: list[TpdmStaffBackgroundCheck] """ return self._background_checks @background_checks.setter def background_checks(self, background_checks): """Sets the background_checks of this TpdmStaffExtension. An unordered collection of staffBackgroundChecks. Staff background check history and disposition. # noqa: E501 :param background_checks: The background_checks of this TpdmStaffExtension. # noqa: E501 :type: list[TpdmStaffBackgroundCheck] """ self._background_checks = background_checks @property def highly_qualified_academic_subjects(self): """Gets the highly_qualified_academic_subjects of this TpdmStaffExtension. # noqa: E501 An unordered collection of staffHighlyQualifiedAcademicSubjects. The academic subject(s) in which the staff is deemed to be \"highly qualified\". # noqa: E501 :return: The highly_qualified_academic_subjects of this TpdmStaffExtension. # noqa: E501 :rtype: list[TpdmStaffHighlyQualifiedAcademicSubject] """ return self._highly_qualified_academic_subjects @highly_qualified_academic_subjects.setter def highly_qualified_academic_subjects(self, highly_qualified_academic_subjects): """Sets the highly_qualified_academic_subjects of this TpdmStaffExtension. An unordered collection of staffHighlyQualifiedAcademicSubjects. The academic subject(s) in which the staff is deemed to be \"highly qualified\". # noqa: E501 :param highly_qualified_academic_subjects: The highly_qualified_academic_subjects of this TpdmStaffExtension. # noqa: E501 :type: list[TpdmStaffHighlyQualifiedAcademicSubject] """ self._highly_qualified_academic_subjects = highly_qualified_academic_subjects @property def seniorities(self): """Gets the seniorities of this TpdmStaffExtension. # noqa: E501 An unordered collection of staffSeniorities. Entries of job experience contributing to computations of seniority. # noqa: E501 :return: The seniorities of this TpdmStaffExtension. # noqa: E501 :rtype: list[TpdmStaffSeniority] """ return self._seniorities @seniorities.setter def seniorities(self, seniorities): """Sets the seniorities of this TpdmStaffExtension. An unordered collection of staffSeniorities. Entries of job experience contributing to computations of seniority. # noqa: E501 :param seniorities: The seniorities of this TpdmStaffExtension. # noqa: E501 :type: list[TpdmStaffSeniority] """ self._seniorities = seniorities @property def teacher_preparation_programs(self): """Gets the teacher_preparation_programs of this TpdmStaffExtension. # noqa: E501 An unordered collection of staffTeacherPreparationPrograms. The Teacher Preparation Program(s) completed by the teacher. # noqa: E501 :return: The teacher_preparation_programs of this TpdmStaffExtension. # noqa: E501 :rtype: list[TpdmStaffTeacherPreparationProgram] """ return self._teacher_preparation_programs @teacher_preparation_programs.setter def teacher_preparation_programs(self, teacher_preparation_programs): """Sets the teacher_preparation_programs of this TpdmStaffExtension. An unordered collection of staffTeacherPreparationPrograms. The Teacher Preparation Program(s) completed by the teacher. # noqa: E501 :param teacher_preparation_programs: The teacher_preparation_programs of this TpdmStaffExtension. # noqa: E501 :type: list[TpdmStaffTeacherPreparationProgram] """ self._teacher_preparation_programs = teacher_preparation_programs @property def salary(self): """Gets the salary of this TpdmStaffExtension. # noqa: E501 :return: The salary of this TpdmStaffExtension. # noqa: E501 :rtype: TpdmStaffSalary """ return self._salary @salary.setter def salary(self, salary): """Sets the salary of this TpdmStaffExtension. :param salary: The salary of this TpdmStaffExtension. # noqa: E501 :type: TpdmStaffSalary """ self._salary = salary @property def teacher_educator_research(self): """Gets the teacher_educator_research of this TpdmStaffExtension. # noqa: E501 :return: The teacher_educator_research of this TpdmStaffExtension. # noqa: E501 :rtype: TpdmStaffTeacherEducatorResearch """ return self._teacher_educator_research @teacher_educator_research.setter def teacher_educator_research(self, teacher_educator_research): """Sets the teacher_educator_research of this TpdmStaffExtension. :param teacher_educator_research: The teacher_educator_research of this TpdmStaffExtension. # noqa: E501 :type: TpdmStaffTeacherEducatorResearch """ self._teacher_educator_research = teacher_educator_research def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(TpdmStaffExtension, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, TpdmStaffExtension): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, TpdmStaffExtension): return True return self.to_dict() != other.to_dict()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 1717, 12, 10547, 6564, 864, 6060, 9363, 7824, 628, 220, 220, 220, 383, 1717, 12, 10547, 440, 5258, 1220, 7824, 13536, 5479, 284, 1100, 290, 3551, 3707, 1366, 8574,...
2.517073
5,740
from mss.utils.dataloader import natural_keys, atof from mss.postprocessing.generator_c import * from mss.preprocessing.preprocesssing_main import * from tqdm import tqdm import glob import os import pickle ''' For each track in track_input 1) Load track - load IRMAS DATABASE - load MUSDB DATABASE 2) preprocess the track - preprocess IRMAS DATABASE - (MUSDB already preprocessed) 3) Model the track - convert preprocessed data into waveforms (track wise) - name the generated tracks according to original track_names 4) Evaluate tracks ''' TEST_DATA_DIR = "G:/Thesis/test/mixture/" class EncodedSpectrograms(): '''returns directory of encoded spectrograms in a list''' class Separator(): ''' separator is able to convert input songs to predicted waveforms takes as input x_mixture , y_other''' def evaluate_musdb_test(self): ''' inp: converts npy spectrograms (encoded test data) to evaluation metrics ''' self.filelist_X,self.filelist_Y = self.encoded_spectrograms.load_musdb(save=False) self.file_length = len(self.filelist_X) self.song_iterator = -1 # song is 1 lower than when you start songs counting from 1 ! for i in tqdm(range(self.file_length)): x_mixture_file_chunks,y_target_file_chunks = next(self._gen_eval()) self.gen.generate_waveform(x_mixture_file_chunks,y_target_file_chunks,self.song_iterator,inference=False,save_mixture=False) print("done") if __name__=="__main__": main()
[ 6738, 285, 824, 13, 26791, 13, 67, 10254, 1170, 263, 1330, 3288, 62, 13083, 11, 379, 1659, 198, 6738, 285, 824, 13, 7353, 36948, 13, 8612, 1352, 62, 66, 1330, 1635, 198, 6738, 285, 824, 13, 3866, 36948, 13, 3866, 14681, 12215, 62, ...
2.54295
617
# python3 weather_mood.py import leds import requests import time # OpenWeatherMap API key API_KEY = '6fdf8b1f9b3c4b3916e57166631c363d' # Current latitude LATITUDE = 51.577392 # Current longitude LONGITUDE = 0.179766 # Update interval INTERVAL = 1000 * 60 * 15 # Get a color suited to the current conditions string # # conditions - Weather conditions string from the API # Fetch current weather conditions # The main function if '__main__' in __name__: main()
[ 2, 21015, 18, 6193, 62, 76, 702, 13, 9078, 198, 198, 11748, 2957, 82, 198, 11748, 7007, 198, 11748, 640, 198, 198, 2, 4946, 41865, 13912, 7824, 1994, 198, 17614, 62, 20373, 796, 705, 21, 69, 7568, 23, 65, 16, 69, 24, 65, 18, 66,...
2.943396
159
import random import math if __name__ == '__main__': red = RNA(entradas=2, alpha=0.5, arquitectura=[2, 1], permitir_logs=True) red.generar() XOR_in_samples = [ [0, 0], [0, 1], [1, 0], [1, 1] ] XOR_out_samples = [ [0], [1], [1], [0] ] red.entrenar(XOR_in_samples, XOR_out_samples, 100000) for e in XOR_in_samples: print('Input: {}'.format(e)) res = red.fw_prop(e) # propagar hacia delante la entrada print('Output: {}'.format(res)) print('\n') input('Press Enter to continue') # Ejemplo usando clases de salida red = RNA(entradas=2, alpha=0.7, arquitectura=[2, 2], # 2 neuronas en la capa de salida permitir_logs=True) red.generar() XOR_in_samples = [ [0, 0], [0, 1], [1, 0], [1, 1] ] # La primera neurona representa la clase (1) y la segunda a (0) XOR_out_class_samples = [ # [(1), (0)] [0, 1], [1, 0], [1, 0], [0, 1] ] red.entrenar(XOR_in_samples, XOR_out_class_samples, 100000) for e in XOR_in_samples: print('Entrada: {}'.format(e)) true_val, false_val = red.fw_prop(e) if true_val < 0.01 and false_val > 0.99: res = 0 else: res = 1 print('Salida: {}'.format(res)) print('\n')
[ 11748, 4738, 201, 198, 11748, 10688, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 201, 198, 220, 220, 220, 2266, 796, 25897, 7, 298, 6335, 292, 28, 17, 11, 201, 198, 2...
1.653766
956
import os import time from flask import Flask, render_template, jsonify app = Flask(__name__) # What are we running on? isRPi = False if os.uname()[4][:3] == 'arm': import automationhat # pylint: disable=all isRPi = True # Our default homepage @app.route('/') # Grab a still from the camera @app.route('/photo') # Stream video from the camera @app.route('/video') # Door activity log @app.route('/door') # Letterbox activity log @app.route('/letterbox') # Show previous video @app.route('/history') # Unlock the door @app.route('/unlock') # Start the web server on port 5000 if __name__ == '__main__': app.run(host='0.0.0.0')
[ 11748, 28686, 198, 11748, 640, 198, 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 33918, 1958, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 198, 2, 1867, 389, 356, 2491, 319, 30, 198, 271, 20031, 72, 796, 10352, 198, ...
2.775424
236
# ------------------------------------------------------------------------------ # CodeHawk Binary Analyzer # Author: Henny Sipma # ------------------------------------------------------------------------------ # The MIT License (MIT) # # Copyright (c) 2016-2020 Kestrel Technology LLC # Copyright (c) 2020 Henny Sipma # Copyright (c) 2021 Aarno Labs LLC # # 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. # ------------------------------------------------------------------------------ from typing import Callable, Dict, List, Set import chb.util.graphutil as UG from chb.app.Callgraph import Callgraph from chb.util.DotGraph import DotGraph
[ 2, 16529, 26171, 198, 2, 6127, 39, 19301, 45755, 16213, 9107, 198, 2, 6434, 25, 367, 11870, 311, 541, 2611, 198, 2, 16529, 26171, 198, 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 198, 2, 15069, 357, 66, 8, 1584, 12, 42334, 509, ...
4.036408
412
from stix_shifter_utils.stix_translation.src.patterns.pattern_objects import StartStopQualifier, ObservationExpression, \ ComparisonExpression, Pattern, CombinedComparisonExpression, CombinedObservationExpression
[ 6738, 336, 844, 62, 1477, 18171, 62, 26791, 13, 301, 844, 62, 41519, 13, 10677, 13, 33279, 82, 13, 33279, 62, 48205, 1330, 7253, 19485, 46181, 7483, 11, 11086, 13208, 16870, 2234, 11, 3467, 198, 220, 220, 220, 34420, 16870, 2234, 11, ...
3.875
56
import socket import time # def main(): # stream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # stream.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # stream.bind("/etc/orion/container.sock") # stream.listen(1) # connection, client_address = stream.accept() # stream.send('{"sender": 23,"receiver": 23,"service": "test.net",}\n'.encode()) # stream.close() if __name__ == '__main__': main()
[ 11748, 17802, 198, 11748, 640, 198, 198, 2, 825, 1388, 33529, 198, 2, 220, 220, 220, 220, 4269, 796, 17802, 13, 44971, 7, 44971, 13, 8579, 62, 4944, 10426, 11, 17802, 13, 50, 11290, 62, 2257, 32235, 8, 198, 198, 2, 220, 220, 220, ...
2.359788
189
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ from flink_jira_rule import FlinkJiraRule class StaleMajorOrAboveRule(FlinkJiraRule): """ Tickets major and above need an assignee, or an update within {stale_<blocker|critical|major>.stale_days}, otherwise the priority will be reduced after a warning period of {stale_<blocker|critical|major>.warning_days} days. An update of on of the Sub-Tasks counts as an update to the ticket. Before this happens the assignee/reporter/watchers are notified that the ticket is about to become stale and will be deprioritized. The time periods before warning differ based on the priority: """
[ 29113, 29113, 14468, 198, 2, 220, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 220, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 220, 9387, 351, 428, 670, 329, 3224, 1321, 198, ...
3.992386
394
# -*- coding: utf-8 -*- # Authors: Kruthika Rathinavel # Version: 1.2.1 # Email: kruthika@vt.edu # Created: "2014-10-13 18:45:40" # Updated: "2015-02-13 15:06:41" # Copyright © 2014 by Virginia Polytechnic Institute and State University # All rights reserved # # Virginia Polytechnic Institute and State University (Virginia Tech) owns the copyright for the BEMOSS software and its # associated documentation ("Software") and retains rights to grant research rights under patents related to # the BEMOSS software to other academic institutions or non-profit research institutions. # You should carefully read the following terms and conditions before using this software. # Your use of this Software indicates your acceptance of this license agreement and all terms and conditions. # # You are hereby licensed to use the Software for Non-Commercial Purpose only. Non-Commercial Purpose means the # use of the Software solely for research. Non-Commercial Purpose excludes, without limitation, any use of # the Software, as part of, or in any way in connection with a product or service which is sold, offered for sale, # licensed, leased, loaned, or rented. Permission to use, copy, modify, and distribute this compilation # for Non-Commercial Purpose to other academic institutions or non-profit research institutions is hereby granted # without fee, subject to the following terms of this license. # # Commercial Use: If you desire to use the software for profit-making or commercial purposes, # you agree to negotiate in good faith a license with Virginia Tech prior to such profit-making or commercial use. # Virginia Tech shall have no obligation to grant such license to you, and may grant exclusive or non-exclusive # licenses to others. You may contact the following by email to discuss commercial use:: vtippatents@vtip.org # # Limitation of Liability: IN NO EVENT WILL VIRGINIA TECH, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE # THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR # CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO # LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE # OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF VIRGINIA TECH OR OTHER PARTY HAS BEEN ADVISED # OF THE POSSIBILITY OF SUCH DAMAGES. # # For full terms and conditions, please visit https://bitbucket.org/bemoss/bemoss_os. # # Address all correspondence regarding this license to Virginia Tech's electronic mail address: vtippatents@vtip.org from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.template import RequestContext from django.shortcuts import render_to_response import json import ast import re import time from alerts.views import get_notifications from ZMQHelper.zmq_pub import ZMQ_PUB from helper import config_helper from ZMQHelper import zmq_topics from .models import DeviceMetadata, Building_Zone, GlobalSetting from thermostat.models import Thermostat from smartplug.models import Plugload from lighting.models import Lighting from admin.models import NetworkStatus kwargs = {'subscribe_address': 'ipc:///tmp/volttron-lite-agent-subscribe', 'publish_address': 'ipc:///tmp/volttron-lite-agent-publish'} zmq_pub = ZMQ_PUB(**kwargs) @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/') @login_required(login_url='/login/')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 46665, 25, 13685, 1071, 9232, 26494, 1437, 626, 198, 2, 10628, 25, 352, 13, 17, 13, 16, 198, 2, 9570, 25, 479, 81, 1071, 9232, 31, 36540, 13, 15532, 198, 2, 156...
3.415435
1,218
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Flask-MailGun Flask extension to use the Mailgun email parsing service for sending and receving emails """ from io import open try: from setuptools import setup except ImportError: from distutils.core import setup with open('Version', encoding='utf-8') as f: version = next(f).strip() with open('README.rst', encoding='utf-8') as f: readme = f.read() __NAME__ = 'Flask-MailGun3' __doc__ = readme __author__ = 'Amey-SAM' __license__ = 'MIT' __copyright__ = '2016' setup( name=__NAME__, version=version, license=__license__, description='Flask extension to use the Mailgun email parsing service', long_description=__doc__, author=__author__, author_email='richard.mathie@amey.co.uk', url='https://github.com/amey-sam/Flask-MailGun', download_url='https://github.com/amey-sam/Flask-MailGun/tarball/master', # py_modules=['flask_mailgun'], packages=['flask_mailgun'], install_requires=[ 'Flask', 'requests', 'decorator', ], keywords=['flask', 'mailgun'], zip_safe=False, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 7414, 2093, 12, 25804, 22993, 198, 7414, 2093, 7552, 284, 779, 262, 11099, 7145, 3053, 32096, 2139, 198, 16...
2.600313
638
import tensorflow as tf import os from tensorflow.python.framework import ops import warnings warnings.filterwarnings("ignore") os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' ops.reset_default_graph() #value = tf.Variable(0, name="value") value = tf.get_variable("value", shape=[], dtype=tf.int32, initializer=None, regularizer=None, trainable=True, collections=None) one = tf.constant(1) update_value = tf.assign_add(value, one) initialize_var = tf.global_variables_initializer() with tf.Session() as sess: sess.run(initialize_var) print(sess.run(value)) for _ in range(5): sess.run(update_value) print(sess.run(value))
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 28686, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 30604, 1330, 39628, 198, 11748, 14601, 198, 198, 40539, 654, 13, 24455, 40539, 654, 7203, 46430, 4943, 198, 418, 13, 268, 2268, 17816, ...
2.60241
249
#This file, originally from the TensorFlow speech recognition tutorial, #has been heavily modified for use by SongExplorer. # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Model definitions for simple speech recognition. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import hashlib import math import os.path import random import re import sys import tarfile import csv import scipy.io.wavfile as spiowav import numpy as np from six.moves import urllib from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from tensorflow.python.ops import gen_audio_ops as audio_ops from tensorflow.python.ops import io_ops from tensorflow.python.platform import gfile from tensorflow.python.util import compat MAX_NUM_WAVS_PER_CLASS = 2**27 - 1 # ~134M def which_set(filename, validation_percentage, validation_offset_percentage, testing_percentage): """Determines which data partition the file should belong to. We want to keep files in the same training, validation, or testing sets even if new ones are added over time. This makes it less likely that testing samples will accidentally be reused in training when long runs are restarted for example. To keep this stability, a hash of the filename is taken and used to determine which set it should belong to. This determination only depends on the name and the set proportions, so it won't change as other files are added. It's also useful to associate particular files as related (for example words spoken by the same person), so anything after '_nohash_' in a filename is ignored for set determination. This ensures that 'bobby_nohash_0.wav' and 'bobby_nohash_1.wav' are always in the same set, for example. Args: filename: File path of the data sample. validation_percentage: How much of the data set to use for validation. validation_offset_percentage: Which part of the data set to use for validation. testing_percentage: How much of the data set to use for testing. Returns: String, one of 'training', 'validation', or 'testing'. """ base_name = os.path.basename(filename) # We want to ignore anything after '_nohash_' in the file name when # deciding which set to put a wav in, so the data set creator has a way of # grouping wavs that are close variations of each other. hash_name = re.sub(r'_nohash_.*$', '', base_name) # This looks a bit magical, but we need to decide whether this file should # go into the training, testing, or validation sets, and we want to keep # existing files in the same set even if more files are subsequently # added. # To do that, we need a stable way of deciding based on just the file name # itself, so we do a hash of that and then use that to generate a # probability value that we use to assign it. hash_name_hashed = hashlib.sha1(compat.as_bytes(hash_name)).hexdigest() percentage_hash = ((int(hash_name_hashed, 16) % (MAX_NUM_WAVS_PER_CLASS + 1)) * (100.0 / MAX_NUM_WAVS_PER_CLASS)) if percentage_hash < testing_percentage: result = 'testing' elif percentage_hash > (testing_percentage + validation_offset_percentage) and \ percentage_hash < (testing_percentage + validation_offset_percentage + validation_percentage): result = 'validation' else: result = 'training' return result class AudioProcessor(object): """Handles loading, partitioning, and preparing audio training data.""" def prepare_data_index(self, time_shift_ms, time_shift_random, wanted_words, labels_touse, validation_percentage, validation_offset_percentage, validation_files, testing_percentage, testing_files, subsample_skip, subsample_word, partition_word, partition_n, partition_training_files, partition_validation_files, testing_equalize_ratio, testing_max_samples, model_settings): """Prepares a list of the samples organized by set and label. The training loop needs a list of all the available data, organized by which partition it should belong to, and with ground truth labels attached. This function analyzes the folders below the `data_dir`, figures out the right labels for each file based on the name of the subdirectory it belongs to, and uses a stable hash to assign it to a data set partition. Args: wanted_words: Labels of the classes we want to be able to recognize. validation_percentage: How much of the data set to use for validation. validation_offset_percentage: Which part of the data set to use for validation. testing_percentage: How much of the data set to use for testing. Returns: Dictionary containing a list of file information for each set partition, and a lookup map for each class to determine its numeric index. Raises: Exception: If expected files are not found. """ time_shift_samples = int((time_shift_ms * model_settings["sample_rate"]) / 1000) # Make sure the shuffling is deterministic. wanted_words_index = {} for index, wanted_word in enumerate(wanted_words): wanted_words_index[wanted_word] = index self.data_index = {'validation': [], 'testing': [], 'training': []} all_words = {} # Look through all the subfolders to find audio samples desired_samples = model_settings['desired_samples'] search_path = os.path.join(self.data_dir, '*', '*.csv') wav_nsamples = {} subsample = {x:int(y) for x,y in zip(subsample_word.split(','),subsample_skip.split(',')) if x != ''} partition_words = partition_word.split(',') if '' in partition_words: partition_words.remove('') for csv_path in gfile.Glob(search_path): annotation_reader = csv.reader(open(csv_path)) annotation_list = list(annotation_reader) if len(partition_words)>0: random.shuffle(annotation_list) for (iannotation, annotation) in enumerate(annotation_list): wavfile=annotation[0] ticks=[int(annotation[1]),int(annotation[2])] kind=annotation[3] word=annotation[4] if kind not in labels_touse: continue wav_path=os.path.join(os.path.dirname(csv_path),wavfile) if word in subsample and iannotation % subsample[word] != 0: continue if word in partition_words: if wavfile not in partition_training_files and \ wavfile not in partition_validation_files: continue if wavfile in partition_training_files and \ sum([x['label']==word and x['file']==wav_path \ for x in self.data_index['training']]) >= partition_n: continue if wav_path not in wav_nsamples: _, data = spiowav.read(wav_path, mmap=True) wav_nsamples[wav_path] = len(data) nsamples = wav_nsamples[wav_path] if time_shift_random: if ticks[0]<desired_samples+time_shift_samples or \ ticks[1]>(nsamples-desired_samples-time_shift_samples): continue else: if ticks[0]<desired_samples+time_shift_samples or \ ticks[1]>(nsamples-desired_samples+time_shift_samples): continue all_words[word] = True if wavfile in validation_files: set_index = 'validation' elif wavfile in testing_files: set_index = 'testing' elif word in partition_words: if wavfile in partition_validation_files: set_index = 'validation' elif wavfile in partition_training_files: set_index = 'training' else: continue else: set_index = which_set(annotation[0]+annotation[1]+annotation[2], validation_percentage, validation_offset_percentage, \ testing_percentage) # If it's a known class, store its detail if word in wanted_words_index: self.data_index[set_index].append({'label': word, 'file': wav_path, \ 'ticks': ticks, 'kind': kind}) if not all_words: print('WARNING: No wanted words found in labels') if validation_percentage+testing_percentage<100: for index, wanted_word in enumerate(wanted_words): if wanted_word not in all_words: print('WARNING: '+wanted_word+' not in labels') # equalize for set_index in ['validation', 'testing', 'training']: tf.logging.info('num %s labels', set_index) words = [sample['label'] for sample in self.data_index[set_index]] if set_index != 'testing': for uniqword in sorted(set(words)): tf.logging.info('%8d %s', sum([word==uniqword for word in words]), uniqword) if set_index == 'validation' or len(self.data_index[set_index])==0: continue word_indices = {} for isample in range(len(self.data_index[set_index])): sample = self.data_index[set_index][isample] if sample['label'] in word_indices: word_indices[sample['label']].append(isample) else: word_indices[sample['label']]=[isample] if set_index == 'training': samples_largest = max([len(word_indices[x]) for x in word_indices.keys()]) for word in sorted(list(word_indices.keys())): samples_have = len(word_indices[word]) samples_needed = samples_largest - samples_have for _ in range(samples_needed): add_this = word_indices[word][random.randrange(samples_have)] self.data_index[set_index].append(self.data_index[set_index][add_this]) elif set_index == 'testing': if testing_equalize_ratio>0: samples_smallest = min([len(word_indices[x]) for x in word_indices.keys()]) del_these = [] for word in sorted(list(word_indices.keys())): samples_have = len(word_indices[word]) samples_needed = min(samples_have, testing_equalize_ratio * samples_smallest) if samples_needed<samples_have: del_these.extend(random.sample(word_indices[word], \ samples_have-samples_needed)) for i in sorted(del_these, reverse=True): del self.data_index[set_index][i] if testing_max_samples>0 and testing_max_samples<len(self.data_index[set_index]): self.data_index[set_index] = random.sample(self.data_index[set_index], \ testing_max_samples) if set_index == 'testing': words = [sample['label'] for sample in self.data_index[set_index]] for uniqword in sorted(set(words)): tf.logging.info('%7d %s', sum([word==uniqword for word in words]), uniqword) # Make sure the ordering is random. for set_index in ['validation', 'testing', 'training']: random.shuffle(self.data_index[set_index]) # Prepare the rest of the result data structure. self.words_list = wanted_words self.word_to_index = {} for word in all_words: if word in wanted_words_index: self.word_to_index[word] = wanted_words_index[word] def prepare_processing_graph(self, model_settings): """Builds a TensorFlow graph to apply the input distortions. Creates a graph that loads a WAVE file, decodes it, scales the volume, shifts it in time, calculates a spectrogram, and then builds an MFCC fingerprint from that. This must be called with an active TensorFlow session running, and it creates multiple placeholder inputs, and one output: - wav_filename_placeholder_: Filename of the WAV to load. - foreground_volume_placeholder_: How loud the main clip should be. - time_shift_offset_placeholder_: How much to move the clip in time. - mfcc_: Output 2D fingerprint of processed audio. Args: model_settings: Information about the current model being trained. """ desired_samples = model_settings['desired_samples'] channel_count = model_settings['channel_count'] sample_rate = model_settings['sample_rate'] self.foreground_data_placeholder_ = tf.placeholder(tf.float32, [desired_samples, channel_count]) # Allow the audio sample's volume to be adjusted. self.foreground_volume_placeholder_ = tf.placeholder(tf.float32, []) scaled_foreground = tf.multiply(self.foreground_data_placeholder_, self.foreground_volume_placeholder_) # Run the spectrogram and MFCC ops to get a 2D 'fingerprint' of the audio. self.waveform_ = scaled_foreground spectrograms = [] for ichannel in range(channel_count): spectrograms.append(audio_ops.audio_spectrogram( tf.slice(scaled_foreground, [0, ichannel], [-1, 1]), window_size=model_settings['window_size_samples'], stride=model_settings['window_stride_samples'], magnitude_squared=True)) self.spectrogram_ = tf.stack(spectrograms, -1) mfccs = [] for ichannel in range(channel_count): mfccs.append(audio_ops.mfcc( spectrograms[ichannel], sample_rate, upper_frequency_limit=model_settings['sample_rate']//2, filterbank_channel_count=model_settings['filterbank_channel_count'], dct_coefficient_count=model_settings['dct_coefficient_count'])) self.mfcc_ = tf.stack(mfccs, -1) def set_size(self, mode): """Calculates the number of samples in the dataset partition. Args: mode: Which partition, must be 'training', 'validation', or 'testing'. Returns: Number of samples in the partition. """ return len(self.data_index[mode]) def get_data(self, how_many, offset, model_settings, time_shift_ms, time_shift_random, mode, sess): """Gather samples from the data set, applying transformations as needed. When the mode is 'training', a random selection of samples will be returned, otherwise the first N clips in the partition will be used. This ensures that validation always uses the same samples, reducing noise in the metrics. Args: how_many: Desired number of samples to return. -1 means the entire contents of this partition. offset: Where to start when fetching deterministically. model_settings: Information about the current model being trained. time_shift: How much to randomly shift the clips by in time. time_shift_random: True means to pick a random shift; False means shift by exactly this value mode: Which partition to use, must be 'training', 'validation', or 'testing'. sess: TensorFlow session that was active when processor was created. Returns: List of sample data for the transformed samples, and list of label indexes """ time_shift_samples = int((time_shift_ms * model_settings["sample_rate"]) / 1000) # Pick one of the partitions to choose samples from. candidates = self.data_index[mode] ncandidates = len(self.data_index[mode]) if how_many == -1: sample_count = ncandidates else: sample_count = max(0, min(how_many, ncandidates - offset)) # Data and labels will be populated and returned. data = np.zeros((sample_count, model_settings['fingerprint_size'])) labels = np.zeros(sample_count) samples = [] desired_samples = model_settings['desired_samples'] pick_deterministically = (mode != 'training') if model_settings['representation']=='waveform': input_to_use = self.waveform_ elif model_settings['representation']=='spectrogram': input_to_use = self.spectrogram_ elif model_settings['representation']=='mel-cepstrum': input_to_use = self.mfcc_ # Use the processing graph we created earlier to repeatedly to generate the # final output sample data we'll use in training. for i in xrange(offset, offset + sample_count): # Pick which audio sample to use. if how_many == -1 or pick_deterministically: sample_index = i sample = candidates[sample_index] else: sample_index = np.random.randint(len(candidates)) sample = candidates[sample_index] foreground_offset = (np.random.randint(sample['ticks'][0], 1+sample['ticks'][1]) if sample['ticks'][0] < sample['ticks'][1] else sample['ticks'][0]) sample_rate, song = spiowav.read(sample['file'], mmap=True) if np.ndim(song)==1: song = np.expand_dims(song, axis=1) nchannels = np.shape(song)[1] assert sample_rate == model_settings['sample_rate'] assert nchannels == model_settings['channel_count'] if time_shift_samples > 0: if time_shift_random: time_shift_amount = np.random.randint(-time_shift_samples, time_shift_samples) else: time_shift_amount = time_shift_samples else: time_shift_amount = 0 foreground_clipped = song[foreground_offset-desired_samples//2 - time_shift_amount : foreground_offset+desired_samples//2 - time_shift_amount, :] foreground_float32 = foreground_clipped.astype(np.float32) foreground_scaled = foreground_float32 / abs(np.iinfo(np.int16).min) #extreme foreground_reshaped = foreground_scaled.reshape([nchannels, desired_samples], order='F') foreground_indexed = foreground_reshaped.reshape([desired_samples,nchannels]) input_dict = { self.foreground_data_placeholder_: foreground_indexed } input_dict[self.foreground_volume_placeholder_] = 1 # Run the graph to produce the output audio. data[i - offset, :] = sess.run(input_to_use, feed_dict=input_dict).flatten() label_index = self.word_to_index[sample['label']] labels[i - offset] = label_index samples.append(sample) return data, labels, samples
[ 2, 1212, 2393, 11, 6198, 422, 262, 309, 22854, 37535, 4046, 9465, 11808, 11, 198, 2, 10134, 587, 7272, 9518, 329, 779, 416, 10940, 18438, 11934, 13, 628, 198, 2, 15069, 2177, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, ...
2.619605
7,182
# Copyright 2013 GridCentric Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import time import random import tempfile import re from . logger import log from . util import Notifier from . shell import SecureShell from . shell import RootShell from . shell import WinShell from . host import Host from . vmsctl import Vmsctl from . breadcrumbs import SSHBreadcrumbs from . breadcrumbs import LinkBreadcrumbs from . util import fix_url_for_yum from . util import wait_for from . util import wait_for_ping from . util import wait_while_status from . util import wait_for_status from . util import wait_while_exists from . util import NestedExceptionWrapper from . shell import wait_for_shell from . requirements import AVAILABILITY_ZONE, SCHEDULER_HINTS
[ 2, 15069, 2211, 24846, 19085, 1173, 3457, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407,...
3.473684
380
#!/usr/bin/env python3 # coding: utf-8 """ Program reads input file line by line, matching PoS tags. Each is replaced by an LT tag. LT tags are provided by function srptagging.get_tag - """ import argparse import logging import os import sys import srptagging _args_ = None _logger_ = None _out_file_ = None LOG_FORMAT = '%(asctime)-15s %(levelname)s %(message)s' DIST_TAGS = [] # Checks for specially defined word types - i.e. reflexive verbs # Parse input file if __name__ == "__main__": init() parse_args() open_out_file() parse_file() close_out_file()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 15167, 9743, 5128, 2393, 1627, 416, 1627, 11, 12336, 7695, 50, 15940, 13, 5501, 318, 6928, 416, 281, 34146, 7621, 13, 198, ...
2.709677
217
from examples.a1_code_blocks import line #looping over sequences, 'for' statement is more like 'forEach' # 'in' acts more like an assignment operator in this context li = range(0, 10) print(line(), len(li), list(li)) def is_even(num): """ is an int is even or not """ if num % 2 == 0: return True else: return False for item in li: if is_even(item): # ** is a power operator print(line(), item ** 2) # enumerate loop with a counter for count, item in enumerate('Friday'): print(line(), count, item) # list comprehension # [output expression for item in iterable if condition] pow = [i**2 for i in li if is_even(i)] print(line(), pow) # nested list comprehension # 'for's are listed in order matrix = [[item for item in range(5)] for row in range(3)] print(line(), matrix) #flatten nested list flatten = [r for row in matrix for r in row] print(line(), flatten) # one line list comprehensions are not always a good idea numbers = [1, 2, 3, 4, 5, 6, 18, 20] squares = ["small" if number < 10 else "big" for number in numbers if number % 2 == 0 if number % 3 == 0] print(line(), squares) # more readable maintainable - be kind to your future self! numbers = [1, 2, 3, 4, 5, 6, 18, 20] squares = [ "small" if number < 10 else "big" for number in numbers if number % 2 == 0 if number % 3 == 0] print(line(), squares) # some times a plain for loop is better...
[ 6738, 6096, 13, 64, 16, 62, 8189, 62, 27372, 1330, 1627, 198, 198, 2, 5439, 15816, 625, 16311, 11, 705, 1640, 6, 2643, 318, 517, 588, 705, 1640, 10871, 6, 198, 2, 705, 259, 6, 6529, 517, 588, 281, 16237, 10088, 287, 428, 4732, 1...
2.810445
517
from datetime import datetime import telebot from modules.schedule import controller, permanent from modules.core.source import bot, log, main_markup from modules.electives_schedule.permanent import MESSAGE_FREE_DAY_ELECTIVE from modules.electives_schedule.controller import get_day_elective_lessons """ Module allows to set user's groups and get information about current and next lesson, lessons at some day of week or get link to official google doc Also may provide information about friend's current and next lessons by his alias Authors: @Nmikriukov @thedownhill """
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 5735, 13645, 198, 198, 6738, 13103, 13, 15952, 5950, 1330, 10444, 11, 7748, 198, 6738, 13103, 13, 7295, 13, 10459, 1330, 10214, 11, 2604, 11, 1388, 62, 4102, 929, 198, 6738, 13103, ...
3.753247
154
import twint from os import path from threading import Thread from re import compile from telebot import TeleBot from requests import head find_urls = compile(r"\b((?:https?://)?(?:(?:www\.)?(?:[\da-z\.-]+)\.(?:[a-z]{2,6})|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|(?:(?:[0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(?::[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(?:ffff(?::0{1,4}){0,1}:){0,1}(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])))(?::[0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])?(?:/[\w\.-]*)*/?)\b").findall if __name__ == "__main__": if not path.isfile("telegram.txt"): access_token = input("Введите токен от телеграм бота(Напишите @botfather /newbot) -> ") user_id = int(input("Введите айди пользователя, кому нужно отправлять сообщение -> ")) open("telegram.txt", "w+").write(f"{access_token};{str(user_id)}") else: access_token, user_id = open("telegram.txt", "r+").read().split(";") user_id = int(user_id) targets = open("twitters.txt", "r").read().strip().split("\n") for target in targets: task = Thread(target=main_worker, args=(target, access_token, user_id)) task.start() task.join()
[ 11748, 665, 600, 198, 6738, 28686, 1330, 3108, 198, 6738, 4704, 278, 1330, 14122, 198, 6738, 302, 1330, 17632, 198, 198, 6738, 5735, 13645, 1330, 14318, 20630, 198, 198, 6738, 7007, 1330, 1182, 198, 198, 19796, 62, 6371, 82, 796, 17632,...
1.457735
1,254
import inspect from slackbot.bot import Bot
[ 11748, 10104, 198, 198, 6738, 30740, 13645, 13, 13645, 1330, 18579 ]
4
11
# -*- coding: utf-8 -*- """Console script for pyboggler.""" import sys import click from bogglesolver import BoggleSolver @click.option('--grid', prompt='grid', help='.') @click.command() def main(grid): """Console script for pyboggler.""" bs = BoggleSolver(grid) for w in bs.solve():print w return 0 if __name__ == "__main__": sys.exit(main()) # pragma: no cover
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 47581, 4226, 329, 12972, 65, 10332, 1754, 526, 15931, 198, 11748, 25064, 198, 11748, 3904, 198, 198, 6738, 275, 48549, 14375, 1330, 347, 20258, 50, 14375, 198,...
2.457317
164
from unittesting import DeferrableTestCase import sublime from SublimeLinter.lint import ( Linter, linter as linter_module, backend, )
[ 6738, 555, 715, 37761, 1330, 2896, 8056, 540, 14402, 20448, 198, 198, 11748, 41674, 198, 6738, 3834, 27299, 43, 3849, 13, 75, 600, 1330, 357, 198, 220, 220, 220, 406, 3849, 11, 198, 220, 220, 220, 300, 3849, 355, 300, 3849, 62, 2141...
2.811321
53
""" References ---------- .. [1] Vinh, Nguyen X., Adolf Busemann, and Robert D. Culp. "Hypersonic and planetary entry flight mechanics." NASA STI/Recon Technical Report A 81 (1980). """ from math import * import beluga import logging import matplotlib.pyplot as plt ''' Begin the planar portion of the solution process. ''' ocp = beluga.Problem('planarHypersonic') # Define independent variables ocp.independent('t', 's') # Define equations of motion ocp.state('h', 'v*sin(gam)', 'm') \ .state('theta', 'v*cos(gam)/r', 'rad') \ .state('v', '-D/mass - mu*sin(gam)/r**2', 'm/s') \ .state('gam', 'L/(mass*v) + (v/r - mu/(v*r**2))*cos(gam)', 'rad') # Define quantities used in the problem ocp.quantity('rho', 'rho0*exp(-h/H)') ocp.quantity('Cl', '(1.5658*alfa + -0.0000)') ocp.quantity('Cd', '(1.6537*alfa**2 + 0.0612)') ocp.quantity('D', '0.5*rho*v**2*Cd*Aref') ocp.quantity('L', '0.5*rho*v**2*Cl*Aref') ocp.quantity('r', 're+h') # Define controls ocp.control('alfa', 'rad') # Define constants ocp.constant('mu', 3.986e5*1e9, 'm**3/s**2') # Gravitational parameter, m**3/s**2 ocp.constant('rho0', 0.0001*1.2, 'kg/m**3') # Sea-level atmospheric density, kg/m**3 ocp.constant('H', 7500, 'm') # Scale height for atmosphere of Earth, m ocp.constant('mass', 750/2.2046226, 'kg') # Mass of vehicle, kg ocp.constant('re', 6378000, 'm') # Radius of planet, m ocp.constant('Aref', pi*(24*.0254/2)**2, 'm**2') # Reference area of vehicle, m**2 ocp.constant('h_0', 80000, 'm') ocp.constant('v_0', 4000, 'm/s') ocp.constant('gam_0', (-90)*pi/180, 'rad') ocp.constant('h_f', 0, 'm') ocp.constant('theta_f', 0, 'rad') # Define costs ocp.terminal_cost('-v**2', 'm**2/s**2') # Define constraints ocp.initial_constraint('h-h_0', 'm') ocp.initial_constraint('theta', 'rad') ocp.initial_constraint('v-v_0', 'm/s') ocp.initial_constraint('gam-gam_0', 'rad') ocp.initial_constraint('t', 's') ocp.terminal_constraint('h-h_f', 'm') ocp.terminal_constraint('theta-theta_f', 'rad') ocp.scale(m='h', s='h/v', kg='mass', rad=1) bvp_solver = beluga.bvp_algorithm('spbvp') guess_maker = beluga.guess_generator( 'auto', start=[40000, 0, 2000, (-90)*pi/180], direction='forward', costate_guess=-0.1, control_guess=[0], use_control_guess=True) continuation_steps = beluga.init_continuation() # Start by flying straight towards the ground continuation_steps.add_step('bisection') \ .num_cases(5) \ .const('h_f', 0) # Slowly turn up the density continuation_steps.add_step('bisection') \ .num_cases(3) \ .const('rho0', 1.2) # Move downrange out a tad continuation_steps.add_step('bisection') \ .num_cases(3) \ .const('theta_f', 0.01*pi/180) # Bring flight-path angle up slightly to activate the control continuation_steps.add_step('bisection') \ .num_cases(11) \ .const('gam_0', -80*pi/180) \ .const('theta_f', 0.5*pi/180) continuation_steps.add_step('bisection') \ .num_cases(31) \ .const('gam_0', -0*pi/180) \ .const('theta_f', 3*pi/180) beluga.add_logger(file_level=logging.DEBUG, display_level=logging.INFO) cont_planar = beluga.solve(ocp=ocp, method='indirect', optim_options={'control_method': 'differential'}, bvp_algorithm=bvp_solver, steps=continuation_steps, guess_generator=guess_maker, initial_helper=True) sol = cont_planar[-1][-1] ''' Begin the 3 dof portion of the solution process. ''' ocp_2 = beluga.Problem('hypersonic3DOF') # Define independent variables ocp_2.independent('t', 's') rho = 'rho0*exp(-h/H)' Cl = '(1.5658*alpha + -0.0000)' Cd = '(1.6537*alpha**2 + 0.0612)' D = '(0.5*{}*v**2*{}*Aref)'.format(rho, Cd) L = '(0.5*{}*v**2*{}*Aref)'.format(rho, Cl) r = '(re+h)' # Define equations of motion ocp_2 \ .state('h', 'v*sin(gam)', 'm') \ .state('theta', 'v*cos(gam)*cos(psi)/({}*cos(phi))'.format(r), 'rad') \ .state('phi', 'v*cos(gam)*sin(psi)/{}'.format(r), 'rad') \ .state('v', '-{}/mass - mu*sin(gam)/{}**2'.format(D, r), 'm/s') \ .state('gam', '{}*cos(bank)/(mass*v) - mu/(v*{}**2)*cos(gam) + v/{}*cos(gam)'.format(L, r, r), 'rad') \ .state('psi', '{}*sin(bank)/(mass*cos(gam)*v) - v/{}*cos(gam)*cos(psi)*tan(phi)'.format(L, r), 'rad') # Define controls ocp_2.control('alpha', 'rad') \ .control('bank', 'rad') # Define costs ocp_2.terminal_cost('-v**2', 'm**2/s**2') # Define constraints ocp_2.initial_constraint('h-h_0', 'm') ocp_2.initial_constraint('theta-theta_0', 'rad') ocp_2.initial_constraint('phi-phi_0', 'rad') ocp_2.initial_constraint('v-v_0', 'm/s') ocp_2.initial_constraint('gam-gam_0', 'rad') ocp_2.initial_constraint('psi-psi_0', 'rad') ocp_2.initial_constraint('t', 's') ocp_2.terminal_constraint('h-h_f', 'm') ocp_2.terminal_constraint('theta-theta_f', 'rad') ocp_2.terminal_constraint('phi-phi_f', 'rad') # Define constants ocp_2.constant('mu', 3.986e5*1e9, 'm**3/s**2') # Gravitational parameter, m**3/s**2 ocp_2.constant('rho0', 1.2, 'kg/m**3') # Sea-level atmospheric density, kg/m**3 ocp_2.constant('H', 7500, 'm') # Scale height for atmosphere of Earth, m ocp_2.constant('mass', 750/2.2046226, 'kg') # Mass of vehicle, kg ocp_2.constant('re', 6378000, 'm') # Radius of planet, m ocp_2.constant('Aref', pi*(24*.0254/2)**2, 'm**2') # Reference area of vehicle, m**2 ocp_2.constant('rn', 1/12*0.3048, 'm') # Nose radius, m ocp_2.constant('h_0', sol.y[0, 0], 'm') ocp_2.constant('theta_0', sol.y[0, 1], 'rad') ocp_2.constant('phi_0', 0, 'rad') ocp_2.constant('v_0', sol.y[0, 2], 'm/s') ocp_2.constant('gam_0', sol.y[0, 3], 'rad') ocp_2.constant('psi_0', 0, 'rad') ocp_2.constant('h_f', sol.y[-1, 0], 'm') ocp_2.constant('theta_f', sol.y[-1, 1], 'rad') ocp_2.constant('phi_f', 0, 'rad') ocp_2.scale(m='h', s='h/v', kg='mass', rad=1) bvp_solver_2 = beluga.bvp_algorithm('Shooting', num_arcs=8) # bvp_solver_2 = beluga.bvp_algorithm('spbvp') guess_maker_2 = beluga.guess_generator( 'auto', start=[sol.y[0, 0], sol.y[0, 1], 0, sol.y[0, 2], sol.y[0, 3], 0], direction='forward', costate_guess=[sol.dual[0, 0], sol.dual[0, 1], -0.01, sol.dual[0, 2], sol.dual[0, 3], -0.01], control_guess=[sol.u[0, 0], 0.0], use_control_guess=True, time_integrate=sol.t[-1], ) continuation_steps_2 = beluga.init_continuation() continuation_steps_2.add_step('bisection').num_cases(3) \ .const('h_f', sol.y[-1, 0]) \ .const('theta_f', sol.y[-1, 1]) \ .const('phi_f', 0) continuation_steps_2.add_step('bisection').num_cases(41) \ .const('phi_f', 2*pi/180) cont_3dof = beluga.solve( ocp=ocp_2, method='indirect', optim_options={'control_method': 'algebraic', 'analytical_jacobian': False}, bvp_algorithm=bvp_solver_2, steps=continuation_steps_2, guess_generator=guess_maker_2) final_continuation = cont_3dof[-1] plt.figure() for trajectory in final_continuation: # Plot altitude vs velocity for the swept crossrange cases plt.plot(trajectory.y[:, 3], trajectory.y[:, 0]) plt.xlabel('Velocity [m/s]') plt.ylabel('Altitude [m]') plt.grid(True) plt.show()
[ 37811, 198, 19927, 198, 35937, 198, 492, 685, 16, 60, 11820, 71, 11, 42379, 1395, 1539, 35333, 347, 1904, 9038, 11, 290, 5199, 360, 13, 327, 29528, 13, 366, 49926, 882, 291, 290, 27047, 5726, 5474, 12933, 526, 198, 220, 220, 220, 88...
2.063667
3,534
#!/usr/bin/env python3 # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import tensorflow as tf from tensorflow.contrib import antares if tf.version.VERSION.startswith('2.'): tf = tf.compat.v1 tf.disable_eager_execution() from _common import * x = create_variable([1024, 64], dtype=tf.float32) compare_ops( tf.broadcast_to(tf.reshape(x, [1024, 64, 1]), shape=[1024, 64, 16]), antares.make_op('output0[N, M, K] = input0[N, M] where K in 16', [x]), )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 198, 2, 49962, 739, 262, 17168, 5964, 13, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 13, 3642, 822,...
2.609626
187
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on March 2020 @author: Quentin Lutz <qlutz@enst.fr> @author: Thomas Bonald <tbonald@enst.fr> """ import unittest from sknetwork.data.test_graphs import * from sknetwork.embedding import Spectral from sknetwork.hierarchy import LouvainHierarchy, Paris
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2805, 12131, 198, 31, 9800, 25, 42447, 406, 27839, 1279, 13976, 27839, 31, 268, 301, 13, ...
2.769912
113
import httplib2 import os import collections from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage from sheets import * # If modifying these scopes, delete your previously saved credentials # at ~/.credentials/sheets.googleapis.com-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/drive' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Google Sheets API Python Quickstart' def get_credentials(args): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 's3-acl-viewer.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME credentials = tools.run_flow(flow, store, args) print('Storing credentials to ' + credential_path) return credentials COLOR_GREEN_BG = { 'red': 0xCC/float(0xFF), 'green': 0xFF/float(0xFF), 'blue': 0xCC/float(0xFF) } COLOR_RED_BG = { 'red': 0xFF/float(0xFF), 'green': 0xCC/float(0xFF), 'blue': 0xCC/float(0xFF) }
[ 11748, 1841, 489, 571, 17, 198, 11748, 28686, 198, 11748, 17268, 198, 198, 6738, 2471, 291, 75, 1153, 1330, 9412, 198, 6738, 267, 18439, 17, 16366, 1330, 5456, 198, 6738, 267, 18439, 17, 16366, 1330, 4899, 198, 6738, 267, 18439, 17, 1...
2.77836
573
#Copyright (c) 2020 Ocado. All Rights Reserved. import sys, os import numpy as np sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))) from amrrt.metrics import GeodesicMetric
[ 2, 15269, 357, 66, 8, 12131, 440, 66, 4533, 13, 1439, 6923, 33876, 13, 198, 198, 11748, 25064, 11, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, ...
2.643678
87
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Setup script for MSG Data Processing and Operations. Additional file-based inclusions can be found in MANIFEST.in. The distribution archive is created as a source distribution, http://docs.python.org/2/distutils/sourcedist.html, using python setup.py sdist Installation is performed using python setup.py install [--prefix=${LIBRARY_PATH} --exec-prefix=${BIN_PATH] where the path arguments within the square brackets are optional. """ __author__ = 'Daniel Zhang (張道博)' __copyright__ = 'Copyright (c) 2014, University of Hawaii Smart Energy Project' __license__ = 'https://raw.github' \ '.com/Hawaii-Smart-Energy-Project/Maui-Smart-Grid/master/BSD' \ '-LICENSE.txt' from distutils.core import setup setup(name = 'Maui-Smart-Grid', version = '1.0.0', description = 'Data Processing and Data Operations for the Maui Smart ' 'Grid Project.', long_description = 'The University of Hawaii at Manoa was tasked with ' 'maintaining a data repository for use by analysts ' 'for the Maui Smart Grid (http://www.mauismartgrid' '.com) energy sustainability project through the ' 'Hawaii Natural Energy Institute (http://www.hnei' '.hawaii.edu). This software provides the data ' 'processing and operational resources necessary to ' 'accomplish this task. Source data arrives in ' 'multiple formats including XML, tab-separated ' 'values, and comma-separated values. Issues for this' ' project are tracked at the Hawaii Smart Energy ' 'Project YouTRACK instance (' 'http://smart-energy-project.myjetbrains' '.com/youtrack/rest/agile).', author = 'Daniel Zhang (張道博)', author_email = 'See https://github.com/dz1111', url = 'https://github.com/Hawaii-Smart-Energy-Project/Maui-Smart-Grid', license = 'https://raw.github' '.com/Hawaii-Smart-Energy-Project/Maui-Smart-Grid/master/BSD' '-LICENSE.txt', platforms = 'OS X, Linux', package_dir = {'': 'src'}, py_modules = [ 'filelock', 'meco_data_autoloader', 'meco_db_delete', 'meco_db_insert', 'meco_db_read', 'meco_dupe_check', 'meco_fk', 'meco_mapper', 'meco_plotting', 'meco_pv_readings_in_nonpv_mlh_notifier', 'meco_xml_parser', 'msg_aggregated_data', 'msg_configer', 'msg_data_aggregator', 'msg_data_verifier', 'msg_db_connector', 'msg_db_exporter', 'msg_db_util', 'msg_file_util', 'msg_logger', 'msg_math_util', 'msg_noaa_weather_data_dupe_checker', 'msg_noaa_weather_data_inserter', 'msg_noaa_weather_data_parser', 'msg_noaa_weather_data_util', 'msg_notifier', 'msg_python_util', 'msg_time_util', 'msg_types' ], scripts = [ 'src/automated-scripts/aggregateNewData.py', 'src/automated-scripts/autoloadNewMECOData.py', 'src/automated-scripts/exportDBsToCloud.py', 'src/automated-scripts/insertCompressedNOAAWeatherData.py', 'src/automated-scripts/insertMECOEnergyData.py', 'src/automated-scripts/insertSingleMECOEnergyDataFile.py', 'src/automated-scripts/reportExportSummary.py', 'src/automated-scripts/retrieveNOAAWeatherData.py', 'src/static-data-insert/insertCleanSCADAVoltageAndTapData.py', 'src/static-data-insert/insertLocationRecords.py', 'src/static-data-insert/insertMECOMeterLocationHistoryData.py', 'src/static-data-insert/insertMeterRecords.py', 'src/static-data-insert/insertNRELIrradianceData.py', 'src/static-data-insert/insertPowerMeterEvents.py', 'src/static-data-insert/insertSCADAWeatherData.py' ])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 40786, 4226, 329, 49064, 6060, 28403, 290, 16205, 13, 198, 198, 17699, 2393, 12, 3106, 287, 11539, 460...
1.921162
2,410
#!/usr/bin/python2 import psycopg2 as ps import psycopg2.extras as pse import random import time import collections import sys visited = {} start = time.time() d_cur = ps.connect("host='localhost' dbname='rs_ref'").cursor( cursor_factory=pse.RealDictCursor ) t_cur = ps.connect("host='localhost' dbname='rs_ref'").cursor() query = "SELECT * FROM data_50006 WHERE name ILIKE '%{0}%'".format( sys.argv[1] ) d_cur.execute( query ) final_data = d_cur.fetchall() for e in final_data: visited[e['id']] = True hit = len( final_data ) ids = str( [ e['id'] for e in final_data ] ).strip('[]') query = "SELECT DISTINCT parents FROM p_tree WHERE id IN ({0})".format( ids ) t_cur.execute(query) results = list( flatten( t_cur.fetchall() ) ) results = str( [ e for e in results if not visited.get( e, False ) ] ).strip('[]') query = '''SELECT * FROM data_50006 WHERE id IN ({0})'''.format( results ) d_cur.execute( query ) final_data += d_cur.fetchall() final_data.sort( key=lambda e: e['id'] ) end = time.time() - start #for d in final_data: # print '{0} :: {1:30s} // {2}'.format( d['id'], d['type'], d['name'] ) print '--------------------' print '{0} :: {1}'.format( hit, len( final_data ) ) print end
[ 2, 48443, 14629, 14, 8800, 14, 29412, 17, 198, 11748, 17331, 22163, 70, 17, 355, 26692, 198, 11748, 17331, 22163, 70, 17, 13, 2302, 8847, 355, 15838, 198, 11748, 4738, 198, 11748, 640, 198, 11748, 17268, 198, 11748, 25064, 628, 198, 4...
2.629067
461
# This code is generated automatically by ClointFusion BOT Builder Tool. import ClointFusion as cf import time cf.window_show_desktop() cf.mouse_click(int(cf.pg.size()[0]/2),int(cf.pg.size()[1]/2)) cf.key_write_enter('ote',key='') time.sleep(0) cf.key_press('enter') time.sleep(1) cf.key_write_enter('hi',key='') time.sleep(0) cf.key_press('space') time.sleep(0) cf.key_write_enter('sushil',key='') time.sleep(0) cf.key_press('space') time.sleep(0) cf.key_write_enter('how',key='') time.sleep(0) cf.key_press('space') time.sleep(0) cf.key_write_enter('ru',key='') time.sleep(1) cf.key_press('space') time.sleep(1) cf.key_press('alt+tab') time.sleep(1) cf.key_press('alt+tab') time.sleep(1) cf.key_press('alt+tab') time.sleep(0) time.sleep(1) cf.key_press('tab') time.sleep(0) cf.key_press('alt+tab') time.sleep(0) cf.key_press('alt+alt') time.sleep(2) cf.key_press('alt+tab') time.sleep(0) time.sleep(1) cf.key_press('alt+tab') time.sleep(0) cf.key_press('alt+tab') time.sleep(2) time.sleep(1) cf.key_press('alt+right') time.sleep(0) time.sleep(1) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\1-UntitledNotepad-595_441.png',conf=0.7, wait=11),left_or_right='left', single_double_triple = 'single') except: cf.mouse_click(595,441,left_or_right='left', single_double_triple = 'single') time.sleep(1) cf.key_press('alt+tab') time.sleep(0) time.sleep(2) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\2-ClointFusionBOTBuilderpyVisualStudioCode-694_379.png',conf=0.7, wait=12),left_or_right='left', single_double_triple = 'single') except: cf.mouse_click(694,379,left_or_right='left', single_double_triple = 'single') time.sleep(2) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\3-ClointFusionBOTBuilderpyVisualStudioCode-702_407.png',conf=0.7, wait=14),left_or_right='left', single_double_triple = 'single') except: cf.mouse_click(702,407,left_or_right='left', single_double_triple = 'single') time.sleep(4) cf.key_press('alt+tab') time.sleep(0) cf.key_press('alt+tab') time.sleep(1) cf.key_press('alt+tab') time.sleep(0) cf.key_press('alt+tab') time.sleep(1) cf.key_press('alt+tab') time.sleep(0) cf.key_press('alt+tab') time.sleep(1) cf.key_press('alt+tab') time.sleep(0) cf.key_press('alt+tab') time.sleep(0) cf.key_press('alt+tab') time.sleep(0) time.sleep(2) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\4-UntitledNotepad-1151_114.png',conf=0.7, wait=10),left_or_right='left', single_double_triple = 'double') except: cf.mouse_click(1151,114,left_or_right='left', single_double_triple = 'double') time.sleep(0) cf.key_press('alt+tab') time.sleep(0) cf.key_press('alt+tab') time.sleep(2) cf.key_press('alt+tab') time.sleep(0) time.sleep(1) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\5-UntitledNotepad-1365_0.png',conf=0.7, wait=11),left_or_right='left', single_double_triple = 'double') except: cf.mouse_click(1365,0,left_or_right='left', single_double_triple = 'double') time.sleep(1) cf.key_press('right') time.sleep(0) cf.key_press('enter') time.sleep(3) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\6-ClointFusionBOTBuilderpyVisualStudioCode-831_284.png',conf=0.7, wait=12),left_or_right='left', single_double_triple = 'single') except: cf.mouse_click(831,284,left_or_right='left', single_double_triple = 'single') time.sleep(2) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\7-ClointFusionBOTBuilderpyVisualStudioCode-828_345.png',conf=0.7, wait=11),left_or_right='left', single_double_triple = 'single') except: cf.mouse_click(828,345,left_or_right='left', single_double_triple = 'single') time.sleep(1) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\8-ClointFusionBOTBuilderpyVisualStudioCode-804_410.png',conf=0.7, wait=11),left_or_right='left', single_double_triple = 'double') except: cf.mouse_click(804,410,left_or_right='left', single_double_triple = 'double') time.sleep(1) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\9-ClointFusionBOTBuilderpyVisualStudioCode-810_366.png',conf=0.7, wait=11),left_or_right='left', single_double_triple = 'double') except: cf.mouse_click(810,366,left_or_right='left', single_double_triple = 'double') time.sleep(1) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\10-ClointFusionBOTBuilderpyVisualStudioCode-825_344.png',conf=0.7, wait=15),left_or_right='left', single_double_triple = 'single') except: cf.mouse_click(825,344,left_or_right='left', single_double_triple = 'single') time.sleep(5) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\11-ClointFusionBOTBuilderpyVisualStudioCode-841_350.png',conf=0.7, wait=12),left_or_right='left', single_double_triple = 'single') except: cf.mouse_click(841,350,left_or_right='left', single_double_triple = 'single') time.sleep(2) cf.key_press('alt+tab') time.sleep(0) time.sleep(1) try: cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\Sushil\AppData\Local\Temp\cf_log_c6_0kd3c_generator\Images\Snips\12-sbtestLoginRequestjava-844_333.png',conf=0.7, wait=10),left_or_right='left', single_double_triple = 'single') except: cf.mouse_click(844,333,left_or_right='left', single_double_triple = 'single') time.sleep(0) cf.key_press('alt') time.sleep(0) cf.key_press('tab') time.sleep(0)
[ 2, 770, 2438, 318, 7560, 6338, 416, 1012, 1563, 37, 4241, 347, 2394, 35869, 16984, 13, 198, 11748, 1012, 1563, 37, 4241, 355, 30218, 220, 198, 11748, 640, 220, 198, 198, 12993, 13, 17497, 62, 12860, 62, 41375, 3419, 220, 198, 12993, ...
2.300843
2,729
# -*- coding: utf-8 -*- # Copyright Noronha Development Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import click import os from noronha.api.movers import ModelVersionAPI as API from noronha.cli.callback import ListingCallback from noronha.cli.handler import CMD from noronha.common.parser import assert_dict @click.group() def movers(): """Model version management""" @click.command() @click.option('--model', '-m', required=True, help="Name of the model to which this version belongs") @click.option('--name', '-n', help="Name of the version") def info(**kwargs): """Information about a model version""" CMD.run(API, 'info', **kwargs) @click.command() @click.option('--model', '-m', required=True, help="Name of the model to which this version belongs") @click.option('--name', '-n', help="Name of the version") def rm(**kwargs): """Remove a model version and all of its files""" CMD.run(API, 'rm', **kwargs) @click.command('list') @click.option('--filter', '-f', '_filter', help="Query in MongoDB's JSON syntax") @click.option('--expand', '-e', default=False, is_flag=True, help="Flag: expand each record's fields") @click.option('--model', help="Only versions of this model will be listed") @click.option('--dataset', 'ds', help="Only versions trained with this dataset will be listed") @click.option('--train', help="Only model versions produced by this training will be listed") @click.option('--proj', help="To be used along with 'train': name of the project to which this training belongs") def _list(_filter, expand, **kwargs): """List model versions""" CMD.run( API, 'lyst', **kwargs, _filter=assert_dict(_filter, allow_none=True), _response_callback=ListingCallback(obj_title='Model Version', expand=expand) ) @click.command() @click.option('--name', '-n', help="Name of the version (defaults to a random name)") @click.option('--model', '-m', help="The model to which this version belongs (further info: nha model --help)") @click.option('--details', '-d', help="JSON with details related to the model version") @click.option( '--path', '-p', help="Path to the directory that contains the model files (default: current working directory)" ) @click.option('--dataset', 'ds', help="Name of the dataset that trained this model version") @click.option('--train', help="Name of the training that produced this model version") @click.option('--proj', help="To be used along with 'train': name of the project to which this training belongs") @click.option( '--pretrained', help= """Reference to another model version that was used as a pre-trained model for training this one. """ """Syntax: <model_name>:<model_version>. Example: word2vec:en-us-v1""" ) @click.option( '--compress', '-c', 'compressed', default=False, is_flag=True, help="Flag: compress all model files to a single tar.gz archive" ) @click.option('--skip-upload', default=False, is_flag=True, help="Flag: don't upload any files, just record metadata") @click.option('--lightweight', '--lw', 'lightweight', default=False, is_flag=True, help="Flag: use lightweight storage") def new(details, path=None, **kwargs): """Record a new model version in the framework""" CMD.run( API, 'new', **kwargs, path=path or os.getcwd(), details=assert_dict(details, allow_none=True) ) @click.command() @click.option('--name', '-n', required=True, help="Name of the model version you want to update") @click.option( '--model', '-m', required=True, help="The model to which this version belongs (further info: nha model --help)" ) @click.option('--details', '-d', help="JSON with details related to the version") @click.option( '--path', '-p', help="Path to the directory that contains the model files (default: current working directory)" ) @click.option('--dataset', 'ds', help="Name of the dataset that trained this model version") @click.option('--train', help="Name of the training that produced this model version") @click.option('--proj', help="To be used along with 'train': name of the project to which this training belongs") @click.option( '--pretrained', help= """Reference to another model version that was used as a pre-trained model for training this one. """ """Syntax: <model_name>:<model_version>. Example: word2vec:en-us-v1""" ) @click.option( '--compress', '-c', 'compressed', default=False, is_flag=True, help="Flag: compress all model files to a single tar.gz archive" ) def update(details, path=None, **kwargs): """Update a model version's details or files""" CMD.run( API, 'update', **kwargs, path=path, details=assert_dict(details, allow_none=True) ) commands = [new, _list, rm, update, info] for cmd in commands: movers.add_command(cmd)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 5414, 261, 3099, 7712, 4816, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 40...
3.051529
1,766