content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from multiprocessing import Queue, Value from time import sleep from access_face_vision.source.camera import Camera from access_face_vision.utils import create_parser from access_face_vision import access_logger LOG_LEVEL = 'debug' logger, log_que, que_listener = access_logger.set_main_process_logger(LOG_LEVEL) if __name__ == '__main__': test_camera()
[ 6738, 18540, 305, 919, 278, 1330, 4670, 518, 11, 11052, 198, 6738, 640, 1330, 3993, 198, 198, 6738, 1895, 62, 2550, 62, 10178, 13, 10459, 13, 25695, 1330, 20432, 198, 6738, 1895, 62, 2550, 62, 10178, 13, 26791, 1330, 2251, 62, 48610, ...
3.076271
118
from utils.deserializer.protobuf_deserializer import ProtoLoader from pathlib import Path import pandas as pd import pytest PROTOFILES_DIR_PATH = Path(__file__).parent.joinpath("protofilesdir").absolute().__str__() INVALID_PATH = "some/wrong/path"
[ 6738, 3384, 4487, 13, 8906, 48499, 7509, 13, 11235, 672, 3046, 62, 8906, 48499, 7509, 1330, 45783, 17401, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 12972, 9288, 198, 198, 4805, 2394, 19238, 41...
2.931034
87
#!/usr/bin/env python # encoding: utf-8 """ turbine.py Created by Andrew Ning and Katherine Dykes on 2014-01-13. Copyright (c) NREL. All rights reserved. """ from openmdao.main.api import Assembly, Component from openmdao.main.datatypes.api import Float, Array, Enum, Bool, Int from openmdao.lib.drivers.api import FixedPointIterator import numpy as np #from rotorse.rotor import RotorSE #from towerse.tower import TowerSE #from commonse.rna import RNAMass, RotorLoads from drivewpact.drive import DriveWPACT from drivewpact.hub import HubWPACT from commonse.csystem import DirectionVector from commonse.utilities import interp_with_deriv, hstack, vstack from drivese.drive import Drive4pt, Drive3pt from drivese.drivese_utils import blade_moment_transform, blade_force_transform from drivese.hub import HubSE, Hub_System_Adder_drive from SEAMLoads.SEAMLoads import SEAMLoads from SEAMTower.SEAMTower import SEAMTower from SEAMAero.SEAM_AEP import SEAM_PowerCurve from SEAMRotor.SEAMRotor import SEAMBladeStructure # from SEAMGeometry.SEAMGeometry import SEAMGeometry def configure_turbine(assembly, with_new_nacelle=True, flexible_blade=False, with_3pt_drive=False): """a stand-alone configure method to allow for flatter assemblies Parameters ---------- assembly : Assembly an openmdao assembly to be configured with_new_nacelle : bool False uses the default implementation, True uses an experimental implementation designed to smooth out discontinities making in amenable for gradient-based optimization flexible_blade : bool if True, internally solves the coupled aero/structural deflection using fixed point iteration. Note that the coupling is currently only in the flapwise deflection, and is primarily only important for highly flexible blades. If False, the aero loads are passed to the structure but there is no further iteration. """ #SEAM variables ---------------------------------- #d2e = Float(0.73, iotype='in', desc='Dollars to Euro ratio' assembly.add('rated_power',Float(3000., iotype='in', units='kW', desc='Turbine rated power', group='Global')) assembly.add('hub_height', Float(100., iotype='in', units='m', desc='Hub height', group='Global')) assembly.add('rotor_diameter', Float(110., iotype='in', units='m', desc='Rotor diameter', group='Global')) # assembly.add('site_type',Enum('onshore', values=('onshore', 'offshore'), iotype='in', desc='Site type', group='Global')) assembly.add('tower_bottom_diameter', Float(4., iotype='in', desc='Tower bottom diameter', group='Global')) assembly.add('tower_top_diameter', Float(2., iotype='in', desc='Tower top diameter', group='Global')) assembly.add('project_lifetime', Float(iotype = 'in', desc='Operating years', group='Global')) assembly.add('rho_steel', Float(7.8e3, iotype='in', desc='density of steel', group='Tower')) assembly.add('lifetime_cycles', Float(1.e7, iotype='in', desc='Equivalent lifetime cycles', group='Rotor')) assembly.add('stress_limit_extreme_tower', Float(iotype='in', units='MPa', desc='Tower ultimate strength', group='Tower')) assembly.add('stress_limit_fatigue_tower', Float(iotype='in', units='MPa', desc='Tower fatigue strength', group='Tower')) assembly.add('safety_factor_tower', Float(iotype='in', desc='Tower loads safety factor', group='Tower')) assembly.add('PMtarget_tower', Float(1., iotype='in', desc='', group='Tower')) assembly.add('wohler_exponent_tower', Float(4., iotype='in', desc='Tower fatigue Wohler exponent', group='Tower')) assembly.add('tower_z', Array(iotype='out', desc='Tower discretization')) assembly.add('tower_wall_thickness', Array(iotype='out', units='m', desc='Tower wall thickness')) assembly.add('tower_mass', Float(iotype='out', units='kg', desc='Tower mass')) assembly.add('tsr', Float(iotype='in', units='m', desc='Design tip speed ratio', group='Aero')) assembly.add('F', Float(iotype='in', desc='Rotor power loss factor', group='Aero')) assembly.add('wohler_exponent_blade_flap', Float(iotype='in', desc='Wohler Exponent blade flap', group='Rotor')) assembly.add('nSigma4fatFlap', Float(iotype='in', desc='', group='Loads')) assembly.add('nSigma4fatTower', Float(iotype='in', desc='', group='Loads')) assembly.add('dLoad_dU_factor_flap', Float(iotype='in', desc='', group='Loads')) assembly.add('dLoad_dU_factor_tower', Float(iotype='in', desc='', group='Loads')) assembly.add('blade_edge_dynload_factor_ext', Float(iotype='in', desc='Extreme dynamic edgewise loads factor', group='Loads')) assembly.add('blade_edge_dynload_factor_fat', Float(iotype='in', desc='Fatigue dynamic edgewise loads factor', group='Loads')) assembly.add('PMtarget_blades', Float(1., iotype='in', desc='', group='Rotor')) assembly.add('max_tipspeed', Float(iotype='in', desc='Maximum tip speed', group='Aero')) assembly.add('n_wsp', Int(iotype='in', desc='Number of wind speed bins', group='Aero')) assembly.add('min_wsp', Float(0.0, iotype = 'in', units = 'm/s', desc = 'min wind speed', group='Aero')) assembly.add('max_wsp', Float(iotype = 'in', units = 'm/s', desc = 'max wind speed', group='Aero')) assembly.add('turbulence_int', Float(iotype='in', desc='Reference turbulence intensity', group='Plant_AEP')) # assembly.add('WeibullInput', Bool(True, iotype='in', desc='Flag for Weibull input', group='AEP')) assembly.add('weibull_C', Float(iotype = 'in', units='m/s', desc = 'Weibull scale factor', group='AEP')) assembly.add('weibull_k', Float(iotype = 'in', desc='Weibull shape or form factor', group='AEP')) assembly.add('blade_sections', Int(iotype='in', desc='number of sections along blade', group='Rotor')) assembly.add('wohler_exponent_blade_flap', Float(iotype='in', desc='Blade flap fatigue Wohler exponent', group='Rotor')) assembly.add('MaxChordrR', Float(iotype='in', units='m', desc='Spanwise position of maximum chord', group='Rotor')) assembly.add('tif_blade_root_flap_ext', Float(1., iotype='in', desc='Technology improvement factor flap extreme', group='Rotor')) assembly.add('tif_blade_root_edge_ext', Float(1., iotype='in', desc='Technology improvement factor edge extreme', group='Rotor')) assembly.add('tif_blade_root_flap_fat', Float(1., iotype='in', desc='Technology improvement factor flap LEQ', group='Rotor')) assembly.add('sc_frac_flap', Float(iotype='in', desc='spar cap fraction of chord', group='Rotor')) assembly.add('sc_frac_edge', Float(iotype='in', desc='spar cap fraction of thickness', group='Rotor')) assembly.add('safety_factor_blade', Float(iotype='in', desc='Blade loads safety factor', group='Rotor')) assembly.add('stress_limit_extreme_blade', Float(iotype='in', units='MPa', desc='Blade ultimate strength', group='Rotor')) assembly.add('stress_limit_fatigue_blade', Float(iotype='in', units='MPa', desc='Blade fatigue strength', group='Rotor')) assembly.add('AddWeightFactorBlade', Float(iotype='in', desc='Additional weight factor for blade shell', group='Rotor')) assembly.add('blade_material_density', Float(iotype='in', units='kg/m**3', desc='Average density of blade materials', group='Rotor')) assembly.add('blade_mass', Float(iotype = 'out', units = 'kg', desc = 'Blade mass')) # assembly.add('mean_wsp', Float(iotype = 'in', units = 'm/s', desc = 'mean wind speed', group='Aero')) # [m/s] assembly.add('air_density', Float(iotype = 'in', units = 'kg/m**3', desc = 'density of air', group='Plant_AEP')) # [kg / m^3] assembly.add('max_Cp', Float(iotype = 'in', desc = 'max CP', group='Aero')) assembly.add('gearloss_const', Float(iotype = 'in', desc = 'Gear loss constant', group='Drivetrain')) assembly.add('gearloss_var', Float(iotype = 'in', desc = 'Gear loss variable', group='Drivetrain')) assembly.add('genloss', Float(iotype = 'in', desc = 'Generator loss', group='Drivetrain')) assembly.add('convloss', Float(iotype = 'in', desc = 'Converter loss', group='Drivetrain')) # Outputs assembly.add('rated_wind_speed', Float(units = 'm / s', iotype='out', desc='wind speed for rated power')) assembly.add('ideal_power_curve', Array(iotype='out', units='kW', desc='total power before losses and turbulence')) assembly.add('power_curve', Array(iotype='out', units='kW', desc='total power including losses and turbulence')) assembly.add('wind_curve', Array(iotype='out', units='m/s', desc='wind curve associated with power curve')) assembly.add('aep', Float(iotype = 'out', units='mW*h', desc='Annual energy production in mWh')) assembly.add('total_aep', Float(iotype = 'out', units='mW*h', desc='AEP for total years of production')) # END SEAM Variables ---------------------- # Add SEAM components and connections assembly.add('loads', SEAMLoads()) assembly.add('tower_design', SEAMTower(21)) assembly.add('blade_design', SEAMBladeStructure()) assembly.add('aep_calc', SEAM_PowerCurve()) assembly.driver.workflow.add(['loads', 'tower_design', 'blade_design', 'aep_calc']) assembly.connect('loads.tower_bottom_moment_max', 'tower_design.tower_bottom_moment_max') assembly.connect('loads.tower_bottom_moment_leq', 'tower_design.tower_bottom_moment_leq') assembly.connect('loads.blade_root_flap_max', 'blade_design.blade_root_flap_max') assembly.connect('loads.blade_root_edge_max', 'blade_design.blade_root_edge_max') assembly.connect('loads.blade_root_flap_leq', 'blade_design.blade_root_flap_leq') assembly.connect('loads.blade_root_edge_leq', 'blade_design.blade_root_edge_leq') connect_io(assembly, assembly.aep_calc) connect_io(assembly, assembly.loads) connect_io(assembly, assembly.tower_design) connect_io(assembly, assembly.blade_design) # End SEAM add components and connections ------------- if with_new_nacelle: assembly.add('hub',HubSE()) assembly.add('hubSystem',Hub_System_Adder_drive()) if with_3pt_drive: assembly.add('nacelle', Drive3pt()) else: assembly.add('nacelle', Drive4pt()) else: assembly.add('nacelle', DriveWPACT()) assembly.add('hub', HubWPACT()) assembly.driver.workflow.add(['hub', 'nacelle']) if with_new_nacelle: assembly.driver.workflow.add(['hubSystem']) # connections to hub and hub system assembly.connect('blade_design.blade_mass', 'hub.blade_mass') assembly.connect('loads.blade_root_flap_max', 'hub.rotor_bending_moment') assembly.connect('rotor_diameter', ['hub.rotor_diameter']) assembly.connect('blade_design.blade_root_diameter', 'hub.blade_root_diameter') assembly.add('blade_number',Int(3,iotype='in',desc='number of blades', group='Aero')) assembly.connect('blade_number', 'hub.blade_number') if with_new_nacelle: assembly.connect('rated_power','hub.machine_rating') assembly.connect('rotor_diameter', ['hubSystem.rotor_diameter']) assembly.connect('nacelle.MB1_location','hubSystem.MB1_location') # TODO: bearing locations assembly.connect('nacelle.L_rb','hubSystem.L_rb') assembly.add('rotor_tilt', Float(5.0, iotype='in', desc='rotor tilt', group='Rotor')) assembly.connect('rotor_tilt','hubSystem.shaft_angle') assembly.connect('hub.hub_diameter','hubSystem.hub_diameter') assembly.connect('hub.hub_thickness','hubSystem.hub_thickness') assembly.connect('hub.hub_mass','hubSystem.hub_mass') assembly.connect('hub.spinner_mass','hubSystem.spinner_mass') assembly.connect('hub.pitch_system_mass','hubSystem.pitch_system_mass') # connections to nacelle #TODO: fatigue option variables assembly.connect('rotor_diameter', 'nacelle.rotor_diameter') assembly.connect('1.5 * aep_calc.rated_torque', 'nacelle.rotor_torque') assembly.connect('loads.max_thrust', 'nacelle.rotor_thrust') assembly.connect('aep_calc.rated_speed', 'nacelle.rotor_speed') assembly.connect('rated_power', 'nacelle.machine_rating') assembly.add('generator_speed',Float(1173.7,iotype='in',units='rpm',desc='speed of generator', group='Drivetrain')) # - should be in nacelle assembly.connect('generator_speed/aep_calc.rated_speed', 'nacelle.gear_ratio') assembly.connect('tower_top_diameter', 'nacelle.tower_top_diameter') assembly.connect('blade_number * blade_design.blade_mass + hub.hub_system_mass', 'nacelle.rotor_mass') # assuming not already in rotor force / moments # variable connections for new nacelle if with_new_nacelle: assembly.connect('blade_number','nacelle.blade_number') assembly.connect('rotor_tilt','nacelle.shaft_angle') assembly.connect('333.3 * rated_power / 1000.0','nacelle.shrink_disc_mass') assembly.connect('blade_design.blade_root_diameter','nacelle.blade_root_diameter') #moments - ignoring for now (nacelle will use internal defaults) #assembly.connect('rotor.Mxyz_0','moments.b1') #assembly.connect('rotor.Mxyz_120','moments.b2') #assembly.connect('rotor.Mxyz_240','moments.b3') #assembly.connect('rotor.Pitch','moments.pitch_angle') #assembly.connect('rotor.TotalCone','moments.cone_angle') assembly.connect('1.5 * aep_calc.rated_torque','nacelle.rotor_bending_moment_x') #accounted for in ratedConditions.Q #assembly.connect('moments.My','nacelle.rotor_bending_moment_y') #assembly.connect('moments.Mz','nacelle.rotor_bending_moment_z') #forces - ignoring for now (nacelle will use internal defaults) #assembly.connect('rotor.Fxyz_0','forces.b1') #assembly.connect('rotor.Fxyz_120','forces.b2') #assembly.connect('rotor.Fxyz_240','forces.b3') #assembly.connect('rotor.Pitch','forces.pitch_angle') #assembly.connect('rotor.TotalCone','forces.cone_angle') assembly.connect('loads.max_thrust','nacelle.rotor_force_x') #assembly.connect('forces.Fy','nacelle.rotor_force_y') #assembly.connect('forces.Fz','nacelle.rotor_force_z') if __name__ == '__main__': turbine = Turbine_SE_SEAM() #=========== SEAM inputs turbine.AddWeightFactorBlade = 1.2 turbine.blade_material_density = 2100.0 turbine.tower_bottom_diameter = 6. turbine.tower_top_diameter = 3.78 turbine.blade_edge_dynload_factor_ext = 2.5 turbine.blade_edge_dynload_factor_fat = 0.75 turbine.F = 0.777 turbine.MaxChordrR = 0.2 turbine.project_lifetime = 20.0 turbine.lifetime_cycles = 10000000.0 turbine.blade_sections = 21 turbine.PMtarget_tower = 1.0 turbine.PMtarget_blades = 1.0 turbine.safety_factor_blade = 1.1 turbine.safety_factor_tower = 1.5 turbine.stress_limit_extreme_tower = 235.0 turbine.stress_limit_fatigue_tower = 14.885 turbine.stress_limit_extreme_blade = 200.0 turbine.stress_limit_fatigue_blade = 27.0 turbine.tif_blade_root_flap_ext = 1.0 turbine.tif_blade_root_flap_fat = 1.0 turbine.tif_blade_root_edge_ext = 1.0 turbine.weibull_C = 11.0 turbine.weibull_k = 2.0 turbine.wohler_exponent_blade_flap = 10.0 turbine.wohler_exponent_tower = 4.0 turbine.dLoad_dU_factor_flap = 0.9 turbine.dLoad_dU_factor_tower = 0.8 turbine.hub_height = 90.0 turbine.max_tipspeed = 80.0 turbine.n_wsp = 26 turbine.min_wsp = 0.0 turbine.max_wsp = 25.0 turbine.nSigma4fatFlap = 1.2 turbine.nSigma4fatTower = 0.8 turbine.rated_power = 5000.0 turbine.rho_steel = 7800.0 turbine.rotor_diameter = 126.0 turbine.sc_frac_edge = 0.8 turbine.sc_frac_flap = 0.3 turbine.tsr = 8.0 turbine.air_density = 1.225 turbine.turbulence_int = 0.16 turbine.max_Cp = 0.49 turbine.gearloss_const = 0.01 # Fraction turbine.gearloss_var = 0.014 # Fraction turbine.genloss = 0.03 # Fraction turbine.convloss = 0.03 # Fraction #============== # === nacelle ====== turbine.blade_number = 3 # turbine level that must be added for SEAM turbine.rotor_tilt = 5.0 # turbine level that must be added for SEAM turbine.generator_speed = 1173.7 turbine.nacelle.L_ms = 1.0 # (Float, m): main shaft length downwind of main bearing in low-speed shaft turbine.nacelle.L_mb = 2.5 # (Float, m): main shaft length in low-speed shaft turbine.nacelle.h0_front = 1.7 # (Float, m): height of Ibeam in bedplate front turbine.nacelle.h0_rear = 1.35 # (Float, m): height of Ibeam in bedplate rear turbine.nacelle.drivetrain_design = 'geared' turbine.nacelle.crane = True # (Bool): flag for presence of crane turbine.nacelle.bevel = 0 # (Int): Flag for the presence of a bevel stage - 1 if present, 0 if not turbine.nacelle.gear_configuration = 'eep' # (Str): tring that represents the configuration of the gearbox (stage number and types) turbine.nacelle.Np = [3, 3, 1] # (Array): number of planets in each stage turbine.nacelle.ratio_type = 'optimal' # (Str): optimal or empirical stage ratios turbine.nacelle.shaft_type = 'normal' # (Str): normal or short shaft length #turbine.nacelle.shaft_angle = 5.0 # (Float, deg): Angle of the LSS inclindation with respect to the horizontal turbine.nacelle.shaft_ratio = 0.10 # (Float): Ratio of inner diameter to outer diameter. Leave zero for solid LSS turbine.nacelle.carrier_mass = 8000.0 # estimated for 5 MW turbine.nacelle.mb1Type = 'CARB' # (Str): Main bearing type: CARB, TRB or SRB turbine.nacelle.mb2Type = 'SRB' # (Str): Second bearing type: CARB, TRB or SRB turbine.nacelle.yaw_motors_number = 8.0 # (Float): number of yaw motors turbine.nacelle.uptower_transformer = True turbine.nacelle.flange_length = 0.5 #m turbine.nacelle.gearbox_cm = 0.1 turbine.nacelle.hss_length = 1.5 turbine.nacelle.overhang = 5.0 #TODO - should come from turbine configuration level turbine.nacelle.check_fatigue = 0 #0 if no fatigue check, 1 if parameterized fatigue check, 2 if known loads inputs # ================= # === run === turbine.run() print 'mass rotor blades (kg) =', turbine.blade_number * turbine.blade_design.blade_mass print 'mass hub system (kg) =', turbine.hubSystem.hub_system_mass print 'mass nacelle (kg) =', turbine.nacelle.nacelle_mass print 'mass tower (kg) =', turbine.tower_design.tower_mass # =================
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 37811, 198, 83, 5945, 500, 13, 9078, 198, 198, 41972, 416, 6858, 37400, 290, 32719, 23524, 5209, 319, 1946, 12, 486, 12, 1485, 13, 198, 15269, ...
2.720065
6,798
"""add run_type Revision ID: 5dd2ba8222b1 Revises: 079a74c15e8b Create Date: 2021-07-22 23:53:04.043651 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '5dd2ba8222b1' down_revision = '079a74c15e8b' branch_labels = None depends_on = None
[ 37811, 2860, 1057, 62, 4906, 198, 198, 18009, 1166, 4522, 25, 642, 1860, 17, 7012, 23, 23148, 65, 16, 198, 18009, 2696, 25, 657, 3720, 64, 4524, 66, 1314, 68, 23, 65, 198, 16447, 7536, 25, 33448, 12, 2998, 12, 1828, 2242, 25, 4310...
2.435714
140
from .config import add_panopticfcn_config from .panoptic_seg import PanopticFCN from .build_solver import build_lr_scheduler
[ 6738, 764, 11250, 1330, 751, 62, 6839, 8738, 291, 16072, 77, 62, 11250, 198, 6738, 764, 6839, 8738, 291, 62, 325, 70, 1330, 5961, 8738, 291, 4851, 45, 198, 6738, 764, 11249, 62, 82, 14375, 1330, 1382, 62, 14050, 62, 1416, 704, 18173...
2.863636
44
from http.client import HTTPResponse from django.shortcuts import render from django.http import HttpResponse # Create your views here. # def index(request): # return HttpResponse("Hello World!") # def greet(request, name): # return HttpResponse(f"Hello, {name.capitalize()}!")
[ 6738, 2638, 13, 16366, 1330, 7154, 51, 4805, 9774, 2591, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 198, 2, 13610, 534, 5009, 994, 13, 198, 2, 825, 6376, 7, ...
3.086022
93
## # Copyright (c) 2010-2017 Apple 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. ## """ Tests for L{txdav.common.datastore.upgrade.migrate}. """ from twext.enterprise.adbapi2 import Pickle from twext.enterprise.dal.syntax import Delete from twext.python.filepath import CachingFilePath from txweb2.http_headers import MimeType from twisted.internet.defer import inlineCallbacks, Deferred, returnValue from twisted.internet.protocol import Protocol from twisted.protocols.amp import AMP, Command, String from twisted.python.modules import getModule from twisted.python.reflect import qual, namedAny from twisted.trial.unittest import TestCase from twistedcaldav import customxml, caldavxml from twistedcaldav.config import config from twistedcaldav.ical import Component from txdav.base.propertystore.base import PropertyName from txdav.caldav.datastore.test.common import CommonTests from txdav.carddav.datastore.test.common import CommonTests as ABCommonTests from txdav.common.datastore.file import CommonDataStore from txdav.common.datastore.sql_tables import schema from txdav.common.datastore.test.util import SQLStoreBuilder from txdav.common.datastore.test.util import ( populateCalendarsFrom, StubNotifierFactory, resetCalendarMD5s, populateAddressBooksFrom, resetAddressBookMD5s, deriveValue, withSpecialValue, CommonCommonTests ) from txdav.common.datastore.upgrade.migrate import UpgradeToDatabaseStep, \ StoreSpawnerService, swapAMP from txdav.xml import element import copy
[ 2235, 198, 2, 15069, 357, 66, 8, 3050, 12, 5539, 4196, 3457, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, ...
3.421849
595
from netapp.netapp_object import NetAppObject
[ 6738, 2010, 1324, 13, 3262, 1324, 62, 15252, 1330, 3433, 4677, 10267, 198 ]
3.538462
13
import numpy as np import code from imagernn.utils import merge_init_structs, initw, accumNpDicts from imagernn.lstm_generator import LSTMGenerator from imagernn.rnn_generator import RNNGenerator
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2438, 198, 6738, 3590, 1142, 77, 13, 26791, 1330, 20121, 62, 15003, 62, 7249, 82, 11, 2315, 86, 11, 10507, 45, 79, 35, 14137, 198, 6738, 3590, 1142, 77, 13, 75, 301, 76, 62, 8612, 1352, 1...
2.955224
67
# Update the working patch and champions list from __future__ import print_function import configparser import json import os import urllib.request from datetime import datetime from slugify import slugify from collections import OrderedDict from InterfaceAPI import InterfaceAPI if __name__ == '__main__': run()
[ 2, 10133, 262, 1762, 8529, 290, 7827, 1351, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 4566, 48610, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 2956, 297, 571, 13, 25927, 198, 6738, 4818, 8079, 1330,...
3.821429
84
# Generated by Django 3.0.7 on 2020-07-09 22:12 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 22, 319, 12131, 12, 2998, 12, 2931, 2534, 25, 1065, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import unittest import csv import numpy as np from viroconcom.fitting import Fit def read_benchmark_dataset(path='tests/testfiles/1year_dataset_A.txt'): """ Reads a datasets provided for the environmental contour benchmark. Parameters ---------- path : string Path to dataset including the file name, defaults to 'examples/datasets/A.txt' Returns ------- x : ndarray of doubles Observations of the environmental variable 1. y : ndarray of doubles Observations of the environmental variable 2. x_label : str Label of the environmantal variable 1. y_label : str Label of the environmental variable 2. """ x = list() y = list() x_label = None y_label = None with open(path, newline='') as csv_file: reader = csv.reader(csv_file, delimiter=';') idx = 0 for row in reader: if idx == 0: x_label = row[1][ 1:] # Ignore first char (is a white space). y_label = row[2][ 1:] # Ignore first char (is a white space). if idx > 0: # Ignore the header x.append(float(row[1])) y.append(float(row[2])) idx = idx + 1 x = np.asarray(x) y = np.asarray(y) return (x, y, x_label, y_label)
[ 11748, 555, 715, 395, 198, 11748, 269, 21370, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 410, 7058, 1102, 785, 13, 32232, 1330, 25048, 628, 198, 4299, 1100, 62, 26968, 4102, 62, 19608, 292, 316, 7, 6978, 11639, 41989, 14, 928...
2.164038
634
# Zed Attack Proxy (ZAP) and its related class files. # # ZAP is an HTTP/HTTPS proxy for assessing web application security. # # Copyright 2012 ZAP 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. # This script tests ZAP against wavsep: http://code.google.com/p/wavsep/ # Note wavsep has to be installed somewhere - the above link is to the # project not the test suite! # # To this script: # * Install the ZAP Python API: # Use 'pip install python-owasp-zap-v2' or # download from https://github.com/zaproxy/zaproxy/wiki/Downloads # * Start ZAP (as this is for testing purposes you might not want the # 'standard' ZAP to be started) # * Access wavsep via your browser, proxying through ZAP # * Vist all of the wavsep top level URLs, eg # http://localhost:8080/wavsep/index-active.jsp # http://localhost:8080/wavsep/index-passive.jsp # * Run the Spider against http://localhost:8080 # * Run the Active Scanner against http://localhost:8080/wavsep # * Run this script # * Open the report.html file generated in your browser # # Notes: # This has been tested against wavsep 1.5 from zapv2 import ZAPv2 import datetime, sys, getopt if __name__ == "__main__": main(sys.argv[1:])
[ 2, 46159, 8307, 38027, 357, 57, 2969, 8, 290, 663, 3519, 1398, 3696, 13, 198, 2, 198, 2, 1168, 2969, 318, 281, 14626, 14, 6535, 28820, 15741, 329, 24171, 3992, 3586, 2324, 13, 198, 2, 198, 2, 15069, 2321, 1168, 2969, 7712, 4816, 1...
3.173752
541
# coding: utf-8 """ PocketSmith The public PocketSmith API # noqa: E501 The version of the OpenAPI document: 2.0 Contact: api@pocketsmith.com Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from pocketsmith.configuration import Configuration 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, Attachment): 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, Attachment): return True return self.to_dict() != other.to_dict()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 27290, 17919, 628, 220, 220, 220, 383, 1171, 27290, 17919, 7824, 220, 1303, 645, 20402, 25, 412, 33548, 628, 220, 220, 220, 383, 2196, 286, 262, 4946, 17614, 3188,...
2.553476
374
""" high-level NSQ reader class built on top of a Tornado IOLoop supporting both sync and async modes of operation. supports various hooks to modify behavior when heartbeats are received, temporarily disable the reader, and pre-process/validate messages. when supplied a list of nsqlookupd addresses, a reader instance will periodically poll the specified topic in order to discover new producers and reconnect to existing ones. sync ex. import nsq def task1(message): print message return True def task2(message): print message return True all_tasks = {"task1": task1, "task2": task2} r = nsq.Reader(all_tasks, lookupd_http_addresses=['http://127.0.0.1:4161'], topic="nsq_reader", channel="asdf", lookupd_poll_interval=15) nsq.run() async ex. import nsq buf = [] def process_message(message, finisher): global buf # cache both the message and the finisher callable for later processing buf.append((message, finisher)) if len(buf) >= 3: print '****' for msg, finish_fxn in buf: print msg finish_fxn(True) # use finish_fxn to tell NSQ of success print '****' buf = [] else: print 'deferring processing' all_tasks = {"task1": process_message} r = nsq.Reader(all_tasks, lookupd_http_addresses=['http://127.0.0.1:4161'], topic="nsq_reader", channel="async", async=True) nsq.run() """ import logging try: import simplejson as json except ImportError: import json import time import signal import socket import functools import urllib import random import tornado.ioloop import tornado.httpclient import BackoffTimer import nsq import async def get_conn_id(conn, task): return str(conn) + ':' + task def _handle_term_signal(sig_num, frame): logging.info('TERM Signal handler called with signal %r' % sig_num) tornado.ioloop.IOLoop.instance().stop() def run(): signal.signal(signal.SIGTERM, _handle_term_signal) tornado.ioloop.IOLoop.instance().start()
[ 37811, 198, 8929, 12, 5715, 10896, 48, 9173, 1398, 3170, 319, 1353, 286, 257, 48970, 314, 3535, 11224, 6493, 1111, 17510, 290, 198, 292, 13361, 12881, 286, 4905, 13, 198, 198, 18608, 2096, 2972, 26569, 284, 13096, 4069, 618, 2612, 1350,...
2.512252
857
#!/usr/bin/env python3 # -*- coding:utf-8 -*- u""" Created at 2020.09.04 by Zhang Yiming """ import warnings warnings.filterwarnings("ignore") import click from cli.climb import climb from cli.diff import diff main.add_command(climb) main.add_command(diff) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 84, 37811, 198, 41972, 379, 12131, 13, 2931, 13, 3023, 416, 19439, 575, 320, 278, 198, 37811, 198, 11748, 14601, 198, ...
2.631579
114
import os from data.raw_data_loader.base.base_raw_data_loader import Seq2SeqRawDataLoader
[ 11748, 28686, 628, 198, 6738, 1366, 13, 1831, 62, 7890, 62, 29356, 13, 8692, 13, 8692, 62, 1831, 62, 7890, 62, 29356, 1330, 1001, 80, 17, 4653, 80, 27369, 6601, 17401, 628 ]
2.90625
32
#!/usr/bin/env python # Copyright 2014 Open Connectome Project (http://openconnecto.me) # # 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. # # propagate_license.py # Created by Disa Mhembere on 2014-05-16. # Email: disa@jhu.edu __license_header__ = """ {} Copyright 2014 Open Connectome Project (http://openconnecto.me) {} {} 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. {} """ COMM_COUNT = 14 comm = {".py":"#", ".pyx":"#", "": "#", ".html":"", ".sh":"#", ".r":"#", ".m":"%", ".c":"//", ".c++":"//", ".java":"//", ".js":"//"} import argparse import os if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 15069, 1946, 4946, 8113, 462, 4935, 357, 4023, 1378, 9654, 8443, 78, 13, 1326, 8, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 341...
3.260163
492
import pytest import server
[ 11748, 12972, 9288, 198, 11748, 4382, 628, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 628 ]
1.958333
24
# Copyright (c) 2012-2022, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from .. import AWSHelperFn, If def attribute_type_validator(x): """ Property: AttributeDefinition.AttributeType """ valid_types = ["S", "N", "B"] if x not in valid_types: raise ValueError("AttributeType must be one of: %s" % ", ".join(valid_types)) return x def key_type_validator(x): """ Property: KeySchema.KeyType """ valid_types = ["HASH", "RANGE"] if x not in valid_types: raise ValueError("KeyType must be one of: %s" % ", ".join(valid_types)) return x def projection_type_validator(x): """ Property: Projection.ProjectionType """ valid_types = ["KEYS_ONLY", "INCLUDE", "ALL"] if x not in valid_types: raise ValueError("ProjectionType must be one of: %s" % ", ".join(valid_types)) return x def billing_mode_validator(x): """ Property: Table.BillingMode """ valid_modes = ["PROVISIONED", "PAY_PER_REQUEST"] if x not in valid_modes: raise ValueError( "Table billing mode must be one of: %s" % ", ".join(valid_modes) ) return x def table_class_validator(x): """ Property: Table.TableClass """ valid_table_classes = ["STANDARD", "STANDARD_INFREQUENT_ACCESS"] if x not in valid_table_classes: raise ValueError( "Table class must be one of: %s" % ", ".join(valid_table_classes) ) return x def validate_table(self): """ Class: Table """ billing_mode = self.properties.get("BillingMode", "PROVISIONED") indexes = self.properties.get("GlobalSecondaryIndexes", []) tput_props = [self.properties] tput_props.extend([x.properties for x in indexes if not isinstance(x, AWSHelperFn)]) if isinstance(billing_mode, If): if check_any("ProvisionedThroughput", tput_props): raise ValueError( "Table billing mode is per-request. " "ProvisionedThroughput property is mutually exclusive" ) return if billing_mode == "PROVISIONED": if not check_if_all("ProvisionedThroughput", tput_props): raise ValueError( "Table billing mode is provisioned. " "ProvisionedThroughput required if available" ) elif billing_mode == "PAY_PER_REQUEST": if check_any("ProvisionedThroughput", tput_props): raise ValueError( "Table billing mode is per-request. " "ProvisionedThroughput property is mutually exclusive" )
[ 2, 15069, 357, 66, 8, 2321, 12, 1238, 1828, 11, 2940, 2631, 988, 1279, 4102, 31, 431, 988, 13, 2398, 29, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 4091, 38559, 24290, 2393, 329, 1336, 5964, 13, 628, 198, 6738, 11485, 1330, ...
2.359431
1,124
import time from misty2py.robot import Misty from misty2py.utils.env_loader import EnvLoader from misty2py_skills.utils.utils import get_abs_path env_loader = EnvLoader(get_abs_path(".env")) m = Misty(env_loader.get_ip()) d = m.event("subscribe", type="BatteryCharge") e_name = d.get("event_name") time.sleep(1) d = m.event("get_data", name=e_name) # do something with the data here d = m.event("unsubscribe", name=e_name)
[ 11748, 640, 198, 198, 6738, 4020, 88, 17, 9078, 13, 305, 13645, 1330, 47330, 198, 6738, 4020, 88, 17, 9078, 13, 26791, 13, 24330, 62, 29356, 1330, 2039, 85, 17401, 198, 198, 6738, 4020, 88, 17, 9078, 62, 8135, 2171, 13, 26791, 13, ...
2.638037
163
#Map incorrect and abbreviated street names with correct/better ones import xml.etree.cElementTree as ET from collections import defaultdict import re import pprint OSMFILE = "albany.osm" street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) # UPDATE THIS VARIABLE mapping = {"rd": "Road", "Rd": "Road", "road": "Road", "Ave": "Avenue", "Ave.": "Avenue", "AVE": "Avenue", "way" : "Way", "street": "Street", "way":"Way", "Dr.":"Drive", "Blvd":"Boulevard", "rt":"Route", "Ext": "Extension", "Jay":"Jay Street", "Nott St E":"Nott Street East", "Troy-Schenetady-Road":"Troy Schenectady Road", "Troy-Schenetady Rd" :"Troy Schenectady Road", "Delatour":"Delatour Road", "Deltour": "Delatour Road", "Sparrowbush": "Sparrowbush Road" } if __name__ == '__main__': test()
[ 2, 13912, 11491, 290, 37640, 515, 4675, 3891, 351, 3376, 14, 27903, 3392, 198, 11748, 35555, 13, 316, 631, 13, 66, 20180, 27660, 355, 12152, 198, 6738, 17268, 1330, 4277, 11600, 198, 11748, 302, 198, 11748, 279, 4798, 198, 198, 2640, ...
1.823932
585
from io import TextIOWrapper import os from typing import List OUTPUT = "files/output.csv" FOLDER = "modules/week2/folders" def get_file_names(folderpath, out=OUTPUT): """takes a path to a folder and writes all filenames in the folder to a specified output file""" dir_list = os.listdir(folderpath) with open(out, "w") as file: for line in dir_list: file.write(line + "\n") def get_all_file_names(folderpath, out=OUTPUT): """takes a path to a folder and write all filenames recursively (files of all sub folders to)""" with open(out, "w") as file: write_dir_to_file(file, os.listdir(folderpath), folderpath) def print_line_one(file_names: List[str]): """takes a list of filenames and print the first line of each""" for file_name in file_names: with open(file_name) as file: print(file.readline()) def print_emails(file_names: List[str]): """takes a list of filenames and print each line that contains an email (just look for @)""" for file_name in file_names: with open(file_name) as file: for line in file.readlines(): if "@" in line: print(line) def write_headlines(md_files: List[str], out=OUTPUT): """takes a list of md files and writes all headlines (lines starting with #) to a file""" with open(out, "w") as output_file: for md_file in md_files: with open(md_file) as file: for line in file.readlines(): if line.startswith("#"): output_file.write(line)
[ 6738, 33245, 1330, 8255, 40, 3913, 430, 2848, 198, 11748, 28686, 198, 6738, 19720, 1330, 7343, 198, 198, 2606, 7250, 3843, 796, 366, 16624, 14, 22915, 13, 40664, 1, 198, 37, 3535, 14418, 796, 366, 18170, 14, 10464, 17, 14, 11379, 364,...
2.385991
671
import json from sanic import response from sanic_openapi import doc from src.plugins.authorization import authorized from src.plugins.validator import validated from src.request_models.providers import Provider from src.request_models.query_model import Query from src.resources.generic import ensure_membership_is_exists, QUERY_BODY_SCHEMA from src.resources.providers.resource import CREATE_PROVIDER_SCHEMA from src.utils import query_helpers from src.utils.json_helpers import bson_to_json
[ 11748, 33918, 198, 198, 6738, 5336, 291, 1330, 2882, 198, 6738, 5336, 291, 62, 9654, 15042, 1330, 2205, 198, 198, 6738, 12351, 13, 37390, 13, 9800, 1634, 1330, 10435, 198, 6738, 12351, 13, 37390, 13, 12102, 1352, 1330, 31031, 198, 6738,...
3.57554
139
# -*- coding: utf-8 -*- #Lista de Exerccios 08 (Pesquisa) - Questo 02 #Mayara Rysia from time import time from time import sleep from random import randint """ 2. Use as duas funes de busca binria apresentadas (iterativa e recursiva). Gere uma lista de nmeros aleatrios, ordene-os e verifique o desempenho delas. Qual os resultados? """ #Busca Binria - cdigo recursivo #Busca Binria - cdigo iterativo #ordena a lista #cria a lista if __name__ == '__main__': l = criaLista() lista = ordena(l) qtd_br = qtd_bi = 0 #Testes for i in range(5): num = randint(0, 42) print("<< Busca Recursiva >> \n") tempo_gasto_br = Teste(lista, num) print('\ttempo gasto: ', tempo_gasto_br) print('\n\n') sleep(2) print("<< Busca Iterativa >> \n") tempo_gasto_bi = Teste_it(lista, num) print('\ttempo gasto: ', tempo_gasto_bi) print('\n\n') if tempo_gasto_br < tempo_gasto_bi: qtd_br +=1 print('\n-> Busca Recursiva levou o menor tempo\n') else: qtd_bi +=1 print('\n-> Busca Iterativa levou o menor tempo\n') print("------- ------- ------- ------- -------") print("\nCONCLUSO\n\n ") if qtd_br > qtd_bi: print("Busca Binria Recursiva teve o melhor desempenho!") else: print("Busca Binria Iterativa teve o melhor desempenho!") print("Quantidade Binria Recursiva: ", qtd_br) print("Quantidade Binria Iterativa: ", qtd_bi)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 8053, 64, 390, 1475, 263, 535, 4267, 8487, 357, 47, 274, 421, 9160, 8, 532, 6785, 78, 7816, 198, 2, 6747, 3301, 371, 893, 544, 198, 6738, 640, 1330, 640, 198, 6...
2.255054
643
import codecs import markdown import os import logging from pyramid.view import view_config from pyramid.httpexceptions import HTTPOk, HTTPNotFound from sqlalchemy import func from mako.lookup import TemplateLookup import mako.exceptions logger = logging.getLogger(__name__) from ccvpn.models import DBSession, User, IcingaError, IcingaQuery, Gateway, VPNSession from ccvpn.views import account, admin, api, order # noqa def format_bps(bits): multiples = ((1e9, 'G'), (1e6, 'M'), (1e3, 'K'), (0, '')) for d, m in multiples: if bits < d: continue n = bits / (d or 1) return '{:2g}{}bps'.format(n, m)
[ 11748, 40481, 82, 198, 11748, 1317, 2902, 198, 11748, 28686, 198, 11748, 18931, 198, 6738, 27944, 13, 1177, 1330, 1570, 62, 11250, 198, 6738, 27944, 13, 2804, 24900, 11755, 1330, 14626, 18690, 11, 14626, 3673, 21077, 198, 6738, 44161, 282...
2.587302
252
import threading from typing import Any, List, Optional from rx.disposable import Disposable from rx.core.typing import Observer, Scheduler from rx.core import Observable, typing from rx.internal import DisposedException from .anonymoussubject import AnonymousSubject from .innersubscription import InnerSubscription
[ 11748, 4704, 278, 198, 6738, 19720, 1330, 4377, 11, 7343, 11, 32233, 198, 198, 6738, 374, 87, 13, 6381, 1930, 540, 1330, 3167, 1930, 540, 198, 6738, 374, 87, 13, 7295, 13, 774, 13886, 1330, 27058, 11, 27774, 18173, 198, 6738, 374, 8...
3.902439
82
import os import hydra import subprocess import logging from omegaconf import DictConfig from hydra import slurm_utils log = logging.getLogger(__name__) if __name__ == "__main__": launch()
[ 11748, 28686, 198, 11748, 25039, 198, 11748, 850, 14681, 198, 11748, 18931, 198, 6738, 267, 28917, 7807, 69, 1330, 360, 713, 16934, 198, 6738, 25039, 1330, 40066, 76, 62, 26791, 198, 198, 6404, 796, 18931, 13, 1136, 11187, 1362, 7, 834,...
3.095238
63
from flask import Flask, request, jsonify, session, url_for, redirect, render_template import joblib from flower_form import FlowerForm classifier_loaded = joblib.load("application_iris/saved_models/knn_iris_dataset.pkl") encoder_loaded = joblib.load("application_iris/saved_models/iris_label_encoder.pkl") # prediction function app = Flask(__name__) app.config['SECRET_KEY'] = 'mysecretkey' # Read models # classifier_loaded = joblib.load("saved_models/01.knn_with_iris_dataset.pkl") # encoder_loaded = joblib.load("saved_models/02.iris_label_encoder.pkl") if __name__ == '__main__': app.run(host='0.0.0.0', port=8080)
[ 6738, 42903, 1330, 46947, 11, 2581, 11, 33918, 1958, 11, 6246, 11, 19016, 62, 1640, 11, 18941, 11, 8543, 62, 28243, 198, 11748, 1693, 8019, 198, 198, 6738, 15061, 62, 687, 1330, 20025, 8479, 198, 198, 4871, 7483, 62, 14578, 796, 1693,...
2.737069
232
import math import re import unittest import urllib.error import urllib.request from .core import Quantity from .define import defined_systems si = defined_systems['si'] esu = defined_systems['esu'] emu = defined_systems['emu'] gauss = defined_systems['gauss'] if __name__ == '__main__': unittest.main()
[ 11748, 10688, 198, 11748, 302, 198, 11748, 555, 715, 395, 198, 11748, 2956, 297, 571, 13, 18224, 198, 11748, 2956, 297, 571, 13, 25927, 198, 198, 6738, 764, 7295, 1330, 39789, 198, 6738, 764, 13086, 1330, 5447, 62, 10057, 82, 198, 198...
2.861111
108
import unittest import sys import os sys.path.append(os.getcwd().replace("test", "src")) import cirrus_ngs.cfnCluster.ConnectionManager as ConnectionManager import paramiko import tempfile import re ##THIS TEST WILL NOT WORK## if __name__ == "__main__": unittest.main(module=__name__, buffer=True, exit=False)
[ 11748, 555, 715, 395, 198, 11748, 25064, 198, 11748, 28686, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 1136, 66, 16993, 22446, 33491, 7203, 9288, 1600, 366, 10677, 48774, 198, 11748, 10774, 14932, 62, 782, 82, 13, 12993, 77, 2601, 5...
3.009524
105
# -*- coding: utf-8 -*- ''' Commands for launching processes with or without OPUS interposition. ''' from __future__ import absolute_import, division, print_function import argparse import os import psutil from .. import config, server_start, utils def handle(cmd, **params): if cmd == "launch": handle_launch(**params) elif cmd == "exclude": handle_exclude(**params)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 6935, 1746, 329, 13925, 7767, 351, 393, 1231, 13349, 2937, 987, 9150, 13, 198, 7061, 6, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11...
2.877698
139
import pytest from ansible_self_service.l2_infrastructure.app_collection_config_parser import AppCollectionConfigValidationException, \ YamlAppCollectionConfigParser from ansible_self_service.l4_core.models import AppCategory, App VALID_CATEGORY_NAME = 'Misc' VALID_ITEM_NAME = 'Cowsay' VALID_ITEM_DESCRIPTION = 'Let an ASCII cow say stuff in your terminal!' VALID_CONFIG = f""" categories: {VALID_CATEGORY_NAME}: {{}} items: {VALID_ITEM_NAME}: description: | {VALID_ITEM_DESCRIPTION} categories: - {VALID_CATEGORY_NAME} image_url: https://upload.wikimedia.org/wikipedia/commons/8/80/Cowsay_Typical_Output.png playbook: playbooks/cowsay.yml params: ansible_become_password: type: secret mandatory: true requirements: > # any expression that we could use for a tasks "when" clause; items are ANDed - ansible_distribution == 'Ubuntu' """ INVALID_CONFIG = ''' this is not even YAML '''
[ 11748, 12972, 9288, 198, 198, 6738, 9093, 856, 62, 944, 62, 15271, 13, 75, 17, 62, 10745, 6410, 13, 1324, 62, 43681, 62, 11250, 62, 48610, 1330, 2034, 36307, 16934, 7762, 24765, 16922, 11, 3467, 198, 220, 220, 220, 14063, 75, 4677, ...
2.611413
368
""" Run a simple HTTP server which provides API endpoint for SFTPPlus. Usage: server.py [options] -h --help Show this help. -p --port=8000 Listen to a specific port. [default: 8080] -a --address=127.0.0.1 Listen on specific address. [default: 0.0.0.0] -c --certificate=PATH Enable HTTPS by defining the path to a file containing server key, certificate, and CA chain all PEM format and stored in a single file. -f --flaky Introduce random errors to test SFTPPlus API retry functionality. The following API endpoints are provided: * /auth-api - For the authentication API * /event-api - For the event handler API """ from __future__ import absolute_import, unicode_literals import base64 import json import ssl from random import randint from aiohttp import web from docopt import docopt # Command line handling part. arguments = docopt(__doc__) # Convert arguments to usable types. port = int(arguments["--port"]) # Need to escape the address for ipv6. address = arguments["--address"].replace(":", r"\:") is_flaky = arguments["--flaky"] certificate = arguments["--certificate"] # Set to lower values to increase the probability of a failure. _FLAKY_DEGREE = 3 # DB with accepted accounts. # Each key is the name of an user. # Each value contains the accepted password and/or SSH-key. ACCOUNTS = { # An account with some custom configuration. # Configuration that is not explicitly defined here is extracted based on # the SFTPPlus group. "test-user": { "password": "test-pass", # Just the public key value, in OpenSSH format. # Without hte key type or comments. "ssh-public-key": "AAAAB3NzaC1yc2EAAAADAQABAAAAgQC4fV6tSakDSB6ZovygLsf1iC9P3tJHePTKAPkPAWzlu5BRHcmAu0uTjn7GhrpxbjjWMwDVN0Oxzw7teI0OEIVkpnlcyM6L5mGk+X6Lc4+lAfp1YxCR9o9+FXMWSJP32jRwI+4LhWYxnYUldvAO5LDz9QeR0yKimwcjRToF6/jpLw==", "configuration": { "home_folder_path": "/tmp", # EXTRA_DATA is not yet supported. # 'extra_data': { # 'file_api_token': 'fav1_some_value', # }, }, }, # An account with default configuration extracted from # the default SFTPPlus group. # SSH-Key authentication is disabled for this user. "default-user": { "password": "default-pass", "ssh-public-key": "", "configuration": {}, }, } app = web.Application() app.add_routes( [ web.get("/", handle_root), web.post("/auth-api", handle_auth), web.post("/event-api", handle_event), ] ) ssl_context = None if certificate: ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) ssl_context.load_cert_chain(certificate, certificate) if __name__ == "__main__": web.run_app(app, host=address, port=port, ssl_context=ssl_context)
[ 37811, 198, 10987, 257, 2829, 14626, 4382, 543, 3769, 7824, 36123, 329, 14362, 7250, 17860, 13, 198, 198, 28350, 25, 198, 220, 4382, 13, 9078, 685, 25811, 60, 198, 198, 12, 71, 1377, 16794, 220, 220, 220, 220, 220, 220, 220, 220, 22...
2.486979
1,152
from .base import Flow from .view_flow import ViewFlow
[ 6738, 764, 8692, 1330, 27782, 198, 6738, 764, 1177, 62, 11125, 1330, 3582, 37535, 198 ]
3.666667
15
from config.constant import ExportItemConstant, ExportItemTypeConstant, EventConstant, TransactionConstant from ethereumetl.service.eth_event_service import EthEvent
[ 6738, 4566, 13, 9979, 415, 1330, 36472, 7449, 3103, 18797, 11, 36472, 7449, 6030, 3103, 18797, 11, 8558, 3103, 18797, 11, 45389, 3103, 18797, 198, 6738, 304, 17733, 316, 75, 13, 15271, 13, 2788, 62, 15596, 62, 15271, 1330, 9956, 9237, ...
3.97619
42
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 29113, 29113, 7804, 4242, 2235, 198, 2, 198, 2, 220, 220, 220, 4946, 1137, 47, 11, 4946, 8090, 8549, 28186, 198, 2, 220, 220, 220, 15069, 357, 34, 8, 5472, 12, 10333...
3.490909
330
import tensorflow as tf from tensorflow.keras.losses import binary_crossentropy,sparse_categorical_crossentropy from config import Configuration cfg = Configuration()
[ 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 22462, 274, 1330, 13934, 62, 19692, 298, 28338, 11, 82, 29572, 62, 66, 2397, 12409, 62, 19692, 298, 28338, 198, 6738, 4566, 1330, 28373, 198, 37581, ...
3.711111
45
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import random import json from locust import HttpLocust, TaskSequence, task, seq_task from util import ticket_generator, pool_generator, ATTRIBUTE_LIST NUM_QUERY_ATTR = 20
[ 2, 15069, 13130, 3012, 11419, 198, 2, 220, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743...
3.620192
208
#! /usr/bin/env python3 import sys import math import glob from mule_local.postprocessing.pickle_SphereDataSpectralDiff import * from mule.exec_program import * # Ugly hack! #output, retval = exec_program('ls *benchref*/*prog_h* | sort | tail -n 1 | sed "s/.*prog_h//"') #if retval != 0: # print(output) # raise Exception("Something went wrong") #output = output.replace("\n", '') #output = output.replace("\r", '') #p = pickle_SphereDataSpectralDiff(output) p = pickle_SphereDataSpectralDiff()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 25064, 198, 11748, 10688, 198, 11748, 15095, 198, 198, 6738, 285, 2261, 62, 12001, 13, 7353, 36948, 13, 27729, 293, 62, 38882, 6601, 49738, 1373, 28813, 1330, 1635, 1...
2.762431
181
"""This module contains a base runnable item.""" # ============================================================================= # IMPORTS # ============================================================================= # Future from __future__ import annotations # Standard Library from abc import ABC, abstractmethod from typing import TYPE_CHECKING, List # Imports for type checking. if TYPE_CHECKING: import pathlib import houdini_package_runner.runners.base # ============================================================================= # CLASSES # =============================================================================
[ 37811, 1212, 8265, 4909, 257, 2779, 1057, 77, 540, 2378, 526, 15931, 198, 198, 2, 38093, 25609, 198, 2, 30023, 33002, 198, 2, 38093, 25609, 198, 198, 2, 10898, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 2, 8997, 10074, 198, ...
5.692982
114
from graph.graph_server import GraphServer __all__ = ['GraphServer']
[ 198, 6738, 4823, 13, 34960, 62, 15388, 1330, 29681, 10697, 198, 198, 834, 439, 834, 796, 37250, 37065, 10697, 20520, 198 ]
3.380952
21
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2017-08-15 16:23 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import djangoplicity.archives.base import djangoplicity.archives.fields
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 24, 13, 1485, 319, 2177, 12, 2919, 12, 1314, 1467, 25, 1954, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.877358
106
''' Created on 20.07.2015 @author: stefan ''' import unittest import pickle import picklesize import copy_reg def tuple_reducer(obj): return (NewStyle_Reducer, tuple()) copy_reg.pickle(NewStyle_Reducer, tuple_reducer)
[ 7061, 6, 198, 41972, 319, 1160, 13, 2998, 13, 4626, 198, 198, 31, 9800, 25, 336, 891, 272, 198, 7061, 6, 198, 11748, 555, 715, 395, 198, 11748, 2298, 293, 198, 11748, 2298, 829, 1096, 198, 11748, 4866, 62, 2301, 628, 220, 220, 220...
2.267857
112
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Setup process.""" from io import open from os import path from setuptools import find_packages, setup with open( path.join(path.abspath(path.dirname(__file__)), "README.md"), encoding="utf-8" ) as f: long_description = f.read() setup( # Basic project information name="ttctext", version="0.0.1", # Authorship and online reference author="Satyajit Ghana", author_email="satyajitghana7@gmail.com", url="https://github.com/extensive-nlp/ttc_nlp", # Detailled description description="TTC NLP Module", long_description=long_description, long_description_content_type="text/markdown", keywords="sample setuptools development", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Natural Language :: English", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], # Package configuration packages=find_packages(exclude=("tests",)), include_package_data=True, python_requires=">= 3.6", install_requires=[ "torch>=1.9.0", "torchtext>=0.10.0", "torchmetrics>=0.4.1", "omegaconf>=2.1.0", "pytorch-lightning>=1.3.8", "gdown>=3.13.0", "spacy>=3.1.0", "pandas~=1.1.0", "seaborn>=0.11.1", "matplotlib>=3.1.3", "tqdm>=4.61.2", "scikit-learn~=0.24.2", ], # Licensing and copyright license="Apache 2.0", )
[ 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, 40786, 1429, 526, 15931, 198, 198, 6738, 33245, 1330, 1280, 198, 6738, 28686, 1330, 3108, 198, 198, 6738, 90...
2.251664
751
# flake8: noqa from .core import Fitness from .kernel_based import GlobalMinimum from .observation_based import ObservationBasedFitness, MultipleLinearRegression, SimplePolynomialRegression, MultipleLinearRegression
[ 2, 781, 539, 23, 25, 645, 20402, 198, 198, 6738, 764, 7295, 1330, 34545, 198, 6738, 764, 33885, 62, 3106, 1330, 8060, 44046, 198, 6738, 764, 672, 3168, 341, 62, 3106, 1330, 11086, 13208, 15001, 37, 3659, 11, 20401, 14993, 451, 8081, ...
3.857143
56
# Copyright (c) 2019-2020 steelpy # Python stdlib imports # package imports #from steelpy.codes.aisc.aisc360 import AISC_360_16 #from steelpy.codes.aisc.aisc335 import AISC_335_89 #from steelpy.codes.iso.ISO19902 import ISOCodeCheck from steelpy.codes.piping.pipeline import Pipeline_Assessment #from steelpy.codes.api.wsd_22ed import APIwsd22ed from steelpy.codes.dnv.pannel import CodeCheckPanel # #from steelpy.process.units.main import Units #from steelpy.material.material import Material #from steelpy.sections.tubular import Tubular from steelpy.codes.api.main import API_design
[ 2, 15069, 357, 66, 8, 13130, 12, 42334, 7771, 9078, 198, 198, 2, 11361, 14367, 8019, 17944, 198, 198, 2, 5301, 17944, 198, 2, 6738, 7771, 9078, 13, 40148, 13, 64, 2304, 13, 64, 2304, 15277, 1330, 317, 37719, 62, 15277, 62, 1433, 1...
3.072917
192
import os os.system("pip install pytorch_transformers") import nsml print(nsml.DATASET_PATH) os.system('python ./code/train.py --n-labeled 10 --data-path '+ nsml.DATASET_PATH + '/train/ --batch-size 4 --batch-size-u 8 --epochs 20 --val-iteration 1000 --lambda-u 1 --T 0.5 --alpha 16 --mix-layers-set 7 9 12 --lrmain 0.000005 --lrlast 0.00005' )
[ 11748, 28686, 198, 418, 13, 10057, 7203, 79, 541, 2721, 12972, 13165, 354, 62, 35636, 364, 4943, 198, 11748, 36545, 4029, 198, 4798, 7, 5907, 4029, 13, 35, 1404, 1921, 2767, 62, 34219, 8, 198, 198, 418, 13, 10057, 10786, 29412, 24457,...
2.551471
136
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait import math from selenium.webdriver.support.ui import Select import os import time from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC link = "http://suninjuly.github.io/explicit_wait2.html" opt = webdriver.ChromeOptions() opt.add_experimental_option('w3c', False) browser = webdriver.Chrome(chrome_options=opt) browser.implicitly_wait(5, 0.5) browser.get(link) button = browser.find_element_by_id("book") price = WebDriverWait(browser, 12).until(EC.text_to_be_present_in_element((By.ID, "price"),"10000 RUR")) button.click() browser.find_element_by_class_name("btn-primary").click() # new_window = browser.window_handles[1] # browser.switch_to.window(new_window) x_element = browser.find_element_by_id("input_value") x = x_element.text y = calc(x) browser.find_element_by_id("answer").click() browser.find_element_by_id("answer").send_keys(y) browser.find_element_by_id("solve").click()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11284, 13, 9019, 1330, 5313, 32103, 21321, 198, 11748, 10688, 198, 6738, 384,...
2.844504
373
# Generated by Django 3.2.7 on 2021-09-01 17:46 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 22, 319, 33448, 12, 2931, 12, 486, 1596, 25, 3510, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
# -*- coding: utf-8 -*- # # Copyright 2015 Benjamin Kiessling # # 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 os import json import glob import uuid import click import logging import unicodedata from click import open_file from bidi.algorithm import get_display from typing import cast, Set, List, IO, Any from kraken.lib import log from kraken.lib.exceptions import KrakenCairoSurfaceException from kraken.lib.exceptions import KrakenEncodeException from kraken.lib.exceptions import KrakenInputException APP_NAME = 'kraken' logger = logging.getLogger('kraken') if __name__ == '__main__': cli()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 1853, 14533, 21927, 408, 1359, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 74...
3.44
325
from os.path import * import glob import json import numpy as np from util.plot_utils import plot_curves, plot_multi_loss_distribution TMPJPG = expanduser("~/Pictures/") if __name__ == '__main__': exp_name = ["be", "be_768", "be_1024", "be_mid_layer_only", "origin"] keys = ["train_loss_bbox", "train_loss_ce", "train_loss_giou", "test_coco_eval_bbox"] eval_name = ["AP", "AP50", "AP75", "AP_small", "AP_mid", "AP_Big", "AR", "AR50", "AR75", "AR_small", "AR_mid", "AR_Big"] plot_multi_logs(exp_name, keys, save_name="loss", epoch=50, addition_len=eval_name[:6])
[ 6738, 28686, 13, 6978, 1330, 1635, 198, 11748, 15095, 198, 11748, 33918, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 7736, 13, 29487, 62, 26791, 1330, 7110, 62, 22019, 1158, 11, 7110, 62, 41684, 62, 22462, 62, 17080, 3890, 198, 198, ...
2.329457
258
# Copyright 2015, Ansible, Inc. # Luke Sneeringer <lsneeringer@ansible.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, unicode_literals from getpass import getpass from distutils.version import LooseVersion import click from tower_cli import models, get_resource, resources, exceptions as exc from tower_cli.api import client from tower_cli.cli import types from tower_cli.utils import debug, parser PROMPT_LIST = ['diff_mode', 'limit', 'tags', 'skip_tags', 'job_type', 'verbosity', 'inventory', 'credential']
[ 2, 15069, 1853, 11, 28038, 856, 11, 3457, 13, 198, 2, 11336, 27065, 1586, 263, 1279, 7278, 710, 1586, 263, 31, 504, 856, 13, 785, 29, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, ...
3.602041
294
from dataclasses import dataclass from typing import Any from expungeservice.models.charge import ChargeType from expungeservice.models.charge import ChargeUtil from expungeservice.models.expungement_result import TypeEligibility, EligibilityStatus
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 19720, 1330, 4377, 198, 198, 6738, 1033, 2150, 274, 712, 501, 13, 27530, 13, 10136, 1330, 20260, 6030, 198, 6738, 1033, 2150, 274, 712, 501, 13, 27530, 13, 10136, 1330, 20260, ...
3.637681
69
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: import_workload_create_instance short_description: Create NBD exports of OpenStack volumes extends_documentation_fragment: openstack version_added: "2.9.0" author: "OpenStack tenant migration tools (@os-migrate)" description: - "Take an instance from an OS-Migrate YAML structure, and export its volumes over NBD." options: auth: description: - Dictionary with parameters for chosen auth type on the destination cloud. required: true type: dict auth_type: description: - Auth type plugin for destination OpenStack cloud. Can be omitted if using password authentication. required: false type: str region_name: description: - Destination OpenStack region name. Can be omitted if using default region. required: false type: str availability_zone: description: - Availability zone. required: false type: str cloud: description: - Ignored. Present for backwards compatibility. required: false type: raw validate_certs: description: - Validate HTTPS certificates when logging in to OpenStack. required: false type: bool data: description: - Data structure with server parameters as loaded from OS-Migrate workloads YAML file. required: true type: dict block_device_mapping: description: - A block_device_mapping_v2 structure from the transfer_volumes module. - Used to attach destination volumes to the new instance in the right order. required: true type: list elements: dict ''' EXAMPLES = ''' main.yml: - name: validate loaded resources os_migrate.os_migrate.validate_resource_files: paths: - "{{ os_migrate_data_dir }}/workloads.yml" register: workloads_file_validation when: import_workloads_validate_file - name: read workloads resource file os_migrate.os_migrate.read_resources: path: "{{ os_migrate_data_dir }}/workloads.yml" register: read_workloads - name: get source conversion host address os_migrate.os_migrate.os_conversion_host_info: auth: auth_url: https://src-osp:13000/v3 username: migrate password: migrate project_domain_id: default project_name: migration-source user_domain_id: default server_id: ce4dda96-5d8e-4b67-aee2-9845cdc943fe register: os_src_conversion_host_info - name: get destination conversion host address os_migrate.os_migrate.os_conversion_host_info: auth: auth_url: https://dest-osp:13000/v3 username: migrate password: migrate project_domain_id: default project_name: migration-destination user_domain_id: default server_id: 2d2afe57-ace5-4187-8fca-5f10f9059ba1 register: os_dst_conversion_host_info - name: import workloads include_tasks: workload.yml loop: "{{ read_workloads.resources }}" workload.yml: - block: - name: preliminary setup for workload import os_migrate.os_migrate.import_workload_prelim: auth: auth_url: https://dest-osp:13000/v3 username: migrate password: migrate project_domain_id: default project_name: migration-destination user_domain_id: default validate_certs: False src_conversion_host: "{{ os_src_conversion_host_info.openstack_conversion_host }}" src_auth: auth_url: https://src-osp:13000/v3 username: migrate password: migrate project_domain_id: default project_name: migration-source user_domain_id: default src_validate_certs: False data: "{{ item }}" data_dir: "{{ os_migrate_data_dir }}" register: prelim - debug: msg: - "{{ prelim.server_name }} log file: {{ prelim.log_file }}" - "{{ prelim.server_name }} progress file: {{ prelim.state_file }}" when: prelim.changed - name: expose source volumes os_migrate.os_migrate.import_workload_export_volumes: auth: "{{ os_migrate_src_auth }}" auth_type: "{{ os_migrate_src_auth_type|default(omit) }}" region_name: "{{ os_migrate_src_region_name|default(omit) }}" validate_certs: "{{ os_migrate_src_validate_certs|default(omit) }}" ca_cert: "{{ os_migrate_src_ca_cert|default(omit) }}" client_cert: "{{ os_migrate_src_client_cert|default(omit) }}" client_key: "{{ os_migrate_src_client_key|default(omit) }}" conversion_host: "{{ os_src_conversion_host_info.openstack_conversion_host }}" data: "{{ item }}" log_file: "{{ os_migrate_data_dir }}/{{ prelim.server_name }}.log" state_file: "{{ os_migrate_data_dir }}/{{ prelim.server_name }}.state" ssh_key_path: "{{ os_migrate_conversion_keypair_private_path }}" register: exports when: prelim.changed - name: transfer volumes to destination os_migrate.os_migrate.import_workload_transfer_volumes: auth: "{{ os_migrate_dst_auth }}" auth_type: "{{ os_migrate_dst_auth_type|default(omit) }}" region_name: "{{ os_migrate_dst_region_name|default(omit) }}" validate_certs: "{{ os_migrate_dst_validate_certs|default(omit) }}" ca_cert: "{{ os_migrate_dst_ca_cert|default(omit) }}" client_cert: "{{ os_migrate_dst_client_cert|default(omit) }}" client_key: "{{ os_migrate_dst_client_key|default(omit) }}" data: "{{ item }}" conversion_host: "{{ os_dst_conversion_host_info.openstack_conversion_host }}" ssh_key_path: "{{ os_migrate_conversion_keypair_private_path }}" transfer_uuid: "{{ exports.transfer_uuid }}" src_conversion_host_address: "{{ os_src_conversion_host_info.openstack_conversion_host.address }}" volume_map: "{{ exports.volume_map }}" state_file: "{{ os_migrate_data_dir }}/{{ prelim.server_name }}.state" log_file: "{{ os_migrate_data_dir }}/{{ prelim.server_name }}.log" register: transfer when: prelim.changed - name: create destination instance os_migrate.os_migrate.import_workload_create_instance: auth: "{{ os_migrate_dst_auth }}" auth_type: "{{ os_migrate_dst_auth_type|default(omit) }}" region_name: "{{ os_migrate_dst_region_name|default(omit) }}" validate_certs: "{{ os_migrate_dst_validate_certs|default(omit) }}" ca_cert: "{{ os_migrate_dst_ca_cert|default(omit) }}" client_cert: "{{ os_migrate_dst_client_cert|default(omit) }}" client_key: "{{ os_migrate_dst_client_key|default(omit) }}" data: "{{ item }}" block_device_mapping: "{{ transfer.block_device_mapping }}" register: os_migrate_destination_instance when: prelim.changed rescue: - fail: msg: "Failed to import {{ item.params.name }}!" ''' RETURN = ''' server_id: description: The ID of the newly created server. returned: On successful creation of migrated server on destination cloud. type: str sample: 059635b7-451f-4a64-978a-7c2e9e4c15ff ''' from ansible.module_utils.basic import AnsibleModule # Import openstack module utils from ansible_collections.openstack.cloud.plugins as per ansible 3+ try: from ansible_collections.openstack.cloud.plugins.module_utils.openstack \ import openstack_full_argument_spec, openstack_cloud_from_module except ImportError: # If this fails fall back to ansible < 3 imports from ansible.module_utils.openstack \ import openstack_full_argument_spec, openstack_cloud_from_module from ansible_collections.os_migrate.os_migrate.plugins.module_utils import server if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 628, 198, 6738, 11593, 37443, 834, 1330, 357, 48546, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 8, 198, 834, 4164, 330, 31172, 834, 796, 2099, 198, 198, 15037, 34563, 62, 47123, 2885, 13563, 796, ...
2.522948
3,094
valores = [] while True: num = int(input('Digite um valor: ')) valores.append(num) cont = str(input('Quer continuar? [S/N] ')).upper() if cont == 'N': break print(f'Voc digitou {len(valores)} elememtos.') valores.sort(reverse=True) print(f'Os valores em ordem decrescente so {valores}') if 5 in valores: print('O valor 5 faz parte da lista!') else: print('O valor 5 no faz parte da lista.')
[ 2100, 2850, 796, 17635, 198, 198, 4514, 6407, 25, 198, 220, 220, 220, 997, 796, 493, 7, 15414, 10786, 19511, 578, 23781, 1188, 273, 25, 705, 4008, 198, 220, 220, 220, 1188, 2850, 13, 33295, 7, 22510, 8, 198, 220, 220, 220, 542, 79...
2.32967
182
from huobi.utils.input_checker import *
[ 198, 6738, 289, 84, 13411, 13, 26791, 13, 15414, 62, 9122, 263, 1330, 1635, 198 ]
2.733333
15
import os import option import grapeGit as git import grapeConfig import utility
[ 11748, 28686, 198, 11748, 3038, 198, 11748, 30777, 38, 270, 355, 17606, 198, 11748, 30777, 16934, 198, 11748, 10361, 198 ]
4.05
20
from abc import ABC from typing import List, Optional, Union import numpy as np from allopy import OptData from allopy.penalty import NoPenalty, Penalty __all__ = ["AbstractObjectiveBuilder", "AbstractConstraintBuilder"] def format_inputs(data: List[Union[OptData, np.ndarray]], cvar_data: Optional[List[Union[OptData, np.ndarray]]], time_unit: int): data = [d if isinstance(data, OptData) else OptData(d, time_unit) for d in data] if cvar_data is None: return [d.cut_by_horizon(3) for d in data] else: cvar_data = [c if isinstance(c, OptData) else OptData(c, time_unit) for c in cvar_data] return data, cvar_data
[ 6738, 450, 66, 1330, 9738, 198, 6738, 19720, 1330, 7343, 11, 32233, 11, 4479, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 477, 11081, 1330, 13123, 6601, 198, 6738, 477, 11081, 13, 3617, 6017, 1330, 1400, 25553, 6017, 11, ...
2.494585
277
import os import pandas as pd import matplotlib.pyplot as plt wine_df = pd.read_csv(filepath_or_buffer='~/class5-homework/wine.data', sep=',', header=None) wine_df.columns = ['Class','Alcohol','Malic_Acid','Ash','Alcalinity_of_Ash','Magnesium', 'Total_Phenols','Flavanoids','Nonflavanoid_Phenols','Proanthocyanins', 'Color_Intensity','Hue','OD280_OD315_of_Diluted_Wines','Proline'] wine_B = wine_df.drop(['Class'], axis = 1) os.makedirs('graphs', exist_ok=True) #Ploting line for alcohol plt.plot(wine_B['Alcohol'], color='g') plt.title('Alcohol by Index') plt.xlabel('Index') plt.ylabel('Alcohol') plt.savefig(f'graphs/Alcohol_by_index_plot.png', format='png') plt.clf() #Ploting line for Malic_Acid plt.plot(wine_B['Malic_Acid'], color='g') plt.title('Malic_Acid by Index') plt.xlabel('Index') plt.ylabel('Malic_Acid') plt.savefig(f'graphs/Malic_Acid_by_index_plot.png', format='png') plt.clf() #Ploting line for Ash plt.plot(wine_B['Ash'], color='g') plt.title('Ash by Index') plt.xlabel('Index') plt.ylabel('Ash') plt.savefig(f'graphs/Ash_by_index_plot.png', format='png') plt.clf() #Ploting line for Alcalinity_of_Ash plt.plot(wine_B['Alcalinity_of_Ash'], color='g') plt.title('Alcalinity_of_Ash by Index') plt.xlabel('Index') plt.ylabel('Alcalinity_of_Ash') plt.savefig(f'graphs/Alcalinity_of_Ash_by_index_plot.png', format='png') plt.clf() #Ploting line for Magnesium plt.plot(wine_B['Magnesium'], color='g') plt.title('Magnesium by Index') plt.xlabel('Index') plt.ylabel('Magnesium') plt.savefig(f'graphs/Magnesium_by_index_plot.png', format='png') plt.clf() #Ploting line for Total_Phenols plt.plot(wine_B['Total_Phenols'], color='g') plt.title('Total_Phenols by Index') plt.xlabel('Index') plt.ylabel('Total_Phenols') plt.savefig(f'graphs/Total_Phenols_by_index_plot.png', format='png') plt.clf() #Ploting line for Flavanoids plt.plot(wine_B['Flavanoids'], color='g') plt.title('Flavanoids by Index') plt.xlabel('Index') plt.ylabel('Flavanoids') plt.savefig(f'graphs/Flavanoids_by_index_plot.png', format='png') plt.clf() #Ploting line for Nonflavanoid_Phenols plt.plot(wine_B['Nonflavanoid_Phenols'], color='g') plt.title('Nonflavanoid_Phenols by Index') plt.xlabel('Index') plt.ylabel('Nonflavanoid_Phenols') plt.savefig(f'graphs/Nonflavanoid_Phenols_by_index_plot.png', format='png') plt.clf() #Ploting line for Proanthocyanins plt.plot(wine_B['Proanthocyanins'], color='g') plt.title('Proanthocyanins by Index') plt.xlabel('Index') plt.ylabel('Proanthocyanins') plt.savefig(f'graphs/Proanthocyanins_by_index_plot.png', format='png') plt.clf() #Ploting line for Color_Intensity plt.plot(wine_B['Color_Intensity'], color='g') plt.title('Color_Intensity by Index') plt.xlabel('Index') plt.ylabel('Color_Intensity') plt.savefig(f'graphs/Color_Intensity_by_index_plot.png', format='png') plt.clf() #Ploting line for Hue plt.plot(wine_B['Hue'], color='g') plt.title('Hue by Index') plt.xlabel('Index') plt.ylabel('Hue') plt.savefig(f'graphs/Hue_by_index_plot.png', format='png') plt.clf() #Ploting line for OD280_OD315_of_Diluted_Wines plt.plot(wine_B['OD280_OD315_of_Diluted_Wines'], color='g') plt.title('OD280_OD315_of_Diluted_Wines by Index') plt.xlabel('Index') plt.ylabel('OD280_OD315_of_Diluted_Wines') plt.savefig(f'graphs/OD280_OD315_of_Diluted_Wines_by_index_plot.png', format='png') plt.clf() #Ploting line for Proline plt.plot(wine_B['Proline'], color='g') plt.title('Proline by Index') plt.xlabel('Index') plt.ylabel('Proline') plt.savefig(f'graphs/Proline_by_index_plot.png', format='png') plt.clf() #plt.plot(wine_B[i], color='green') #plt.title(str(i)+' by Index') #plt.xlabel('Index') #plt.ylabel(i) #plt.savefig(f'graphs/'+str(i)+'_by_index_plot.png', format='png') #plt.clf()
[ 11748, 28686, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 39002, 62, 7568, 796, 279, 67, 13, 961, 62, 40664, 7, 7753, 6978, 62, 273, 62, 22252, 11639, 93, 14, 4871, ...
2.236267
1,693
import tensorflow as tf import numpy as np from ares.attack.base import BatchAttack from ares.attack.utils import get_xs_ph, get_ys_ph, maybe_to_array, get_unit
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 389, 82, 13, 20358, 13, 8692, 1330, 347, 963, 27732, 198, 6738, 389, 82, 13, 20358, 13, 26791, 1330, 651, 62, 34223, 62, 746, 11, 651, 62, 893...
2.910714
56
import numpy as np from functools import lru_cache from typing import Tuple
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 1257, 310, 10141, 1330, 300, 622, 62, 23870, 198, 198, 6738, 19720, 1330, 309, 29291, 628 ]
3.291667
24
import numpy as np """ Contains preprocessing code for creating additional information based on MRI volumes and true segmentation maps (asegs). Eg. weight masks for median frequency class weighing, edge weighing etc. """ def create_weight_mask(aseg): """ Main function for calculating weight mask of segmentation map for loss function. Currently only Median Frequency Weighing is implemented. Other types can be additively added to the 'weights' variable Args: aseg (numpy.ndarray): Segmentation map with shape l x w x d Returns: numpy.ndarray: Weight Mask of same shape as aseg """ if len(aseg.shape)==4: _, h,w,d = aseg.shape elif len(aseg.shape)==3: h,w,d = aseg.shape weights = np.zeros((h,w,d), dtype=float) # Container ndarray of zeros for weights weights += median_freq_class_weighing(aseg) # Add median frequency weights # Further weights (eg. extra weights for region borders) can be added here # Eg. weights += edge_weights(aseg) return weights def median_freq_class_weighing(aseg): """ Median Frequency Weighing. Guarded against class absence of certain classes. Args: aseg (numpy.ndarray): Segmentation map with shape l x w x d Returns: numpy.ndarray: Median frequency weighted mask of same shape as aseg """ # Calculates median frequency based weighing for classes unique, counts = np.unique(aseg, return_counts=True) if len(aseg.shape)==4: _, h,w,d = aseg.shape elif len(aseg.shape)==3: h,w,d = aseg.shape class_wise_weights = np.median(counts)/counts aseg = aseg.astype(int) # Guards against the absence of certain classes in sample discon_guard_lut = np.zeros(int(max(unique))+1)-1 for idx, val in enumerate(unique): discon_guard_lut[int(val)] = idx discon_guard_lut = discon_guard_lut.astype(int) # Assigns weights to w_mask and resets the missing classes w_mask = np.reshape(class_wise_weights[discon_guard_lut[aseg.ravel()]], (h, w, d)) return w_mask # Label mapping functions (to aparc (eval) and to label (train)) def map_label2aparc_aseg(mapped_aseg): """ Function to perform look-up table mapping from label space to aparc.DKTatlas+aseg space :param np.ndarray mapped_aseg: label space segmentation (aparc.DKTatlas + aseg) :return: """ aseg = np.zeros_like(mapped_aseg) labels = np.array([0, 2, 4, 5, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 24, 26, 28, 31, 41, 43, 44, 46, 47, 49, 50, 51, 52, 53, 54, 58, 60, 63, 77, 1002, 1003, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1034, 1035, 2002, 2005, 2010, 2012, 2013, 2014, 2016, 2017, 2021, 2022, 2023, 2024, 2025, 2028]) h, w, d = aseg.shape aseg = labels[mapped_aseg.ravel()] aseg = aseg.reshape((h, w, d)) return aseg # if __name__ == "__main__": # #a = np.random.randint(0, 5, size=(10,10,10)) # #b = np.random.randint(5, 10, size=(10000)) # # #map_masks_into_5_classes(np.random.randint(0, 250, size=(256, 256, 256))) # # import nibabel as nib # from data_utils.process_mgz_into_hdf5 import map_aparc_aseg2label, map_aseg2label # path = r"abide_ii/sub-28675/mri/aparc.DKTatlas+aseg.mgz" # aseg = nib.load(path).get_data() # labels_full, _ = map_aparc_aseg2label(aseg) # only for 79 classes case # # labels_full, _ = map_aseg2label(aseg) # only for 37 classes case # aseg = labels_full # # print(aseg.shape) # median_freq_class_weighing(aseg) # # print(edge_weighing(aseg, 1.5))
[ 11748, 299, 32152, 355, 45941, 198, 198, 37811, 198, 4264, 1299, 662, 36948, 2438, 329, 4441, 3224, 1321, 1912, 319, 30278, 15343, 290, 2081, 10618, 341, 8739, 357, 589, 14542, 737, 198, 36, 70, 13, 3463, 20680, 329, 14288, 8373, 1398, ...
2.280992
1,694
#!/usr/bin/python # -*- coding: utf-8 -*- ### # Copyright (2016-2020) Hewlett Packard Enterprise Development LP # # 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 pytest import mock from copy import deepcopy from hpe_test_utils import OneViewBaseFactsTest from oneview_module_loader import HypervisorClusterProfileFactsModule PROFILE_URI = '/rest/hypervisor-cluster-profiles/57d3af2a-b6d2-4446-8645-f38dd808ea4d' PARAMS_GET_ALL = dict( config='config.json' ) PARAMS_GET_BY_NAME = dict( config='config.json', name="Test Cluster Profile" ) PARAMS_GET_BY_URI = dict( config='config.json', uri="/rest/test/123" ) PARAMS_WITH_OPTIONS = dict( config='config.json', name="Test Cluster Profile", options=[ 'compliancePreview', ] ) if __name__ == '__main__': pytest.main([__file__])
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 21017, 198, 2, 15069, 357, 5304, 12, 42334, 8, 30446, 15503, 6400, 446, 14973, 7712, 18470, 198, 2, 198, 2, 49962, 739, 262,...
2.955654
451
import os import scipy import numpy as np import pandas as pd import torch from torch.autograd import Variable
[ 11748, 28686, 198, 11748, 629, 541, 88, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 28034, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 628, 628, 628 ]
3.314286
35
# Licensed under a 3-clause BSD style license - see LICENSE.rst from numpy.testing import assert_allclose from astropy.time import Time from gammapy.data import FixedPointingInfo, PointingInfo from gammapy.utils.testing import assert_time_allclose, requires_data
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 198, 6738, 299, 32152, 13, 33407, 1330, 6818, 62, 439, 19836, 198, 6738, 6468, 28338, 13, 2435, 1330, 3862, 198, 6738, 308, 6475, 12...
3.486842
76
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # from src.commands import * # import src.commands as command_modules secret_token = None db_user = None db_pass = None sessions = {} try: lines = [line.rstrip('\n') for line in open('.secret_token')] secret_token = lines[0] db_user = lines[1] db_pass = lines[2] client_id = lines[3] client_secret = lines[4] twitter_consumer_key = lines[5] twitter_consumer_secret = lines[6] twitter_access_token_key = lines[7] twitter_access_token_secret = lines[8] scraper_token = lines[9] except Exception as e: print(e) print('error reading .secret_token, make it you aut') session = get_session()
[ 6738, 44161, 282, 26599, 1330, 2251, 62, 18392, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 6246, 10297, 198, 2, 422, 12351, 13, 9503, 1746, 1330, 1635, 198, 2, 1330, 12351, 13, 9503, 1746, 355, 3141, 62, 18170, 198, 198, 21078, 62, ...
2.690299
268
import click import logging import matplotlib import matplotlib.pyplot as plt import joblib import fact.io from ..configuration import AICTConfig from ..plotting import ( plot_regressor_confusion, plot_bias_resolution, plot_feature_importances, ) if matplotlib.get_backend() == 'pgf': from matplotlib.backends.backend_pgf import PdfPages else: from matplotlib.backends.backend_pdf import PdfPages
[ 11748, 3904, 198, 11748, 18931, 198, 11748, 2603, 29487, 8019, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 1693, 8019, 198, 11748, 1109, 13, 952, 198, 198, 6738, 11485, 11250, 3924, 1330, 317, 18379, 16934, ...
2.896552
145
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import time from typing import Dict, Optional import sacremoses # type: ignore from cc_net import jsonql, text_normalizer
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, ...
3.654762
84
cont = 3 t1 = 0 t2 = 1 print('-----' * 12) print('Sequncia de Fibonacci') print('-----' * 12) valor = int(input('Quantos termos voc quer mostrar ? ')) print('~~~~~' * 12) print(f'{t1} {t2} ' , end=' ') while cont <= valor: t3 = t1 + t2 print(f' {t3}', end=' ') t1 = t2 t2 = t3 t3 = t1 cont += 1 print(' F I M')
[ 3642, 796, 513, 220, 198, 83, 16, 796, 657, 198, 83, 17, 796, 352, 198, 4798, 10786, 650, 19355, 1635, 1105, 8, 198, 4798, 10786, 4653, 80, 19524, 544, 390, 41566, 261, 44456, 11537, 198, 4798, 10786, 650, 19355, 1635, 1105, 8, 198,...
1.982558
172
########################################################################## # # MRC FGU Computational Genomics Group # # $Id$ # # Copyright (C) 2009 Andreas Heger # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ########################################################################## ''' Sra.py - Methods for dealing with short read archive files ========================================================== Utility functions for dealing with :term:`SRA` formatted files from the Short Read Archive. Requirements: * fastq-dump >= 2.1.7 Code ---- ''' import os import glob import tempfile import shutil import CGAT.Experiment as E import CGAT.Fastq as Fastq import CGAT.IOTools as IOTools def peek(sra, outdir=None): """return the full file names for all files which will be extracted Parameters ---------- outdir : path perform extraction in outdir. If outdir is None, the extraction will take place in a temporary directory, which will be deleted afterwards. Returns ------- files : list A list of fastq formatted files that are contained in the archive. format : string The quality score format in the :term:`fastq` formatted files. """ if outdir is None: workdir = tempfile.mkdtemp() else: workdir = outdir # --split-files creates files called prefix_#.fastq.gz, # where # is the read number. # If file cotains paired end data: # output = prefix_1.fastq.gz, prefix_2.fastq.gz # *special case: unpaired reads in a paired end --> prefix.fastq.gz # *special case: if paired reads are stored in a single read, # fastq-dump will split. There might be a joining # sequence. The output would thus be: # prefix_1.fastq.gz, prefix_2.fastq.gz, prefix_3.fastq.gz # You want files 1 and 3. E.run("""fastq-dump --split-files --gzip -X 1000 --outdir %(workdir)s %(sra)s""" % locals()) f = sorted(glob.glob(os.path.join(workdir, "*.fastq.gz"))) ff = [os.path.basename(x) for x in f] if len(f) == 1: # sra file contains one read: output = prefix.fastq.gz pass elif len(f) == 2: # sra file contains read pairs: # output = prefix_1.fastq.gz, prefix_2.fastq.gz assert ff[0].endswith( "_1.fastq.gz") and ff[1].endswith("_2.fastq.gz") elif len(f) == 3: if ff[2].endswith("_3.fastq.gz"): f = glob.glob(os.path.join(workdir, "*_[13].fastq.gz")) else: f = glob.glob(os.path.join(workdir, "*_[13].fastq.gz")) # check format of fastqs in .sra fastq_format = Fastq.guessFormat(IOTools.openFile(f[0], "r"), raises=False) fastq_datatype = Fastq.guessDataType(IOTools.openFile(f[0], "r"), raises=True) if outdir is None: shutil.rmtree(workdir) return f, fastq_format, fastq_datatype def extract(sra, outdir, tool="fastq-dump"): """return statement for extracting the SRA file in `outdir`. possible tools are fastq-dump and abi-dump. Use abi-dump for colorspace""" if tool == "fastq-dump": tool += " --split-files" statement = """%(tool)s --gzip --outdir %(outdir)s %(sra)s""" % locals() return statement
[ 29113, 29113, 7804, 2235, 198, 2, 198, 2, 220, 220, 337, 7397, 25503, 52, 22476, 864, 5215, 31994, 4912, 198, 2, 198, 2, 220, 220, 720, 7390, 3, 198, 2, 198, 2, 220, 220, 15069, 357, 34, 8, 3717, 33728, 679, 1362, 198, 2, 198, ...
2.646552
1,508
# Copyright (c) 2019 J. Alvarez-Jarreta and C.J. Brasher # # This file is part of the LipidFinder software tool and governed by the # 'MIT License'. Please see the LICENSE file that should have been # included as part of this software. """Represent a DataFrame to be processed with LipidFinder's workflow.""" import glob import logging import os import pandas
[ 2, 15069, 357, 66, 8, 13130, 449, 13, 36952, 12, 47511, 1186, 64, 290, 327, 13, 41, 13, 1709, 31218, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 262, 24701, 312, 37, 5540, 3788, 2891, 290, 21825, 416, 262, 198, 2, 705, 36393, 1378...
3.666667
99
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops from tensorflow.python.ops import variables from tensorflow.python.ops import array_ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import gen_fused_embedding_ops from tensorflow.python.ops.gen_fused_embedding_ops import fused_embedding_local_sparse_look_up_grad from tensorflow.python.ops.gen_fused_embedding_ops import fused_embedding_local_sparse_look_up from tensorflow.python.ops.gen_fused_embedding_ops import fused_embedding_sparse_pre_look_up from tensorflow.python.ops.gen_fused_embedding_ops import fused_embedding_sparse_post_look_up from tensorflow.python.ops.gen_fused_embedding_ops import fused_embedding_sparse_post_look_up_grad from tensorflow.python.util.tf_export import tf_export
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 30604, 1330, 39628, 198, 6738, 11192, 273, 1...
3.177936
281
# -*- coding: utf-8 -*- import sphinx_rtd_theme extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', # 'sphinx.ext.intersphinx', # 'sphinx.ext.autosummary', # 'sphinx.ext.viewcode', # 'jupyter_sphinx.embed_widgets', ] templates_path = ['_templates'] master_doc = 'index' source_suffix = '.rst' # General information about the project. project = 'ipycanvas' author = 'Martin Renou' exclude_patterns = [] highlight_language = 'python' pygments_style = 'sphinx' # Output file base name for HTML help builder. html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] htmlhelp_basename = 'ipycanvasdoc' autodoc_member_order = 'bysource'
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 599, 20079, 87, 62, 81, 8671, 62, 43810, 198, 198, 2302, 5736, 796, 685, 198, 220, 220, 220, 705, 82, 746, 28413, 13, 2302, 13, 2306, 375, 420, 3256, 198, 220...
2.373737
297
#!/usr/bin/env python3 # # Author: Yipeng Sun # License: BSD 2-clause # Last Change: Sun May 09, 2021 at 02:52 AM +0200 import numpy as np ARRAY_TYPE = 'np'
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 198, 2, 6434, 25, 575, 541, 1516, 3825, 198, 2, 13789, 25, 347, 10305, 362, 12, 565, 682, 198, 2, 4586, 9794, 25, 3825, 1737, 7769, 11, 33448, 379, 7816, 25, 4309, 3001, 1...
2.492308
65
from django import forms from .models import Reminder from clinnotes.users.models import EpisodeOfCare
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 764, 27530, 1330, 3982, 5540, 198, 6738, 5327, 17815, 13, 18417, 13, 27530, 1330, 7922, 5189, 17784, 198 ]
4.12
25
import pygame as pg from shapely.geometry import Point, Polygon from time import perf_counter # Vars A = [(100, 600), (700, 600), (400, 80)] triangles = [[(100, 600), (700, 600), (400, 80)]] SQRT_3 = 3 ** (1 / 2) WHITE = (255, 255, 255) # Graphics part pg.init() screen = pg.display.set_mode((800, 800)) # Funcs distance = lambda x, y: ((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2) ** 0.5 start = perf_counter() # Call Func generateSnowflake(A, 6) print(len(A)) # Game Loop while True: screen.fill(WHITE) A.append(A[0]) for i in range(len(A) - 1): pg.draw.line(screen, (0, 0, 0), A[i], A[i + 1]) # exit code for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() quit(0) # Updating pg.display.update() print(perf_counter() - start)
[ 11748, 12972, 6057, 355, 23241, 201, 198, 6738, 5485, 306, 13, 469, 15748, 1330, 6252, 11, 12280, 14520, 201, 198, 6738, 640, 1330, 23035, 62, 24588, 201, 198, 201, 198, 201, 198, 2, 569, 945, 201, 198, 32, 796, 47527, 3064, 11, 100...
2.05
420
from copy import deepcopy from functools import partial import sys import types # Global import of predefinedentities will cause an import loop import instanceactions from validator.constants import (BUGZILLA_BUG, DESCRIPTION_TYPES, FENNEC_GUID, FIREFOX_GUID, MAX_STR_SIZE, MDN_DOC) from validator.decorator import version_range from jstypes import JSArray, JSContext, JSLiteral, JSObject, JSWrapper NUMERIC_TYPES = (int, long, float, complex) # None of these operations (or their augmented assignment counterparts) should # be performed on non-numeric data. Any time we get non-numeric data for these # guys, we just return window.NaN. NUMERIC_OPERATORS = ('-', '*', '/', '%', '<<', '>>', '>>>', '|', '^', '&') NUMERIC_OPERATORS += tuple('%s=' % op for op in NUMERIC_OPERATORS) def _get_member_exp_property(traverser, node): """Return the string value of a member expression's property.""" if node['property']['type'] == 'Identifier' and not node.get('computed'): return unicode(node['property']['name']) else: eval_exp = traverser._traverse_node(node['property']) return _get_as_str(eval_exp.get_literal_value()) def _expand_globals(traverser, node): """Expands a global object that has a lambda value.""" if node.is_global and callable(node.value.get('value')): result = node.value['value'](traverser) if isinstance(result, dict): output = traverser._build_global('--', result) elif isinstance(result, JSWrapper): output = result else: output = JSWrapper(result, traverser) # Set the node context. if 'context' in node.value: traverser._debug('CONTEXT>>%s' % node.value['context']) output.context = node.value['context'] else: traverser._debug('CONTEXT>>INHERITED') output.context = node.context return output return node def trace_member(traverser, node, instantiate=False): 'Traces a MemberExpression and returns the appropriate object' traverser._debug('TESTING>>%s' % node['type']) if node['type'] == 'MemberExpression': # x.y or x[y] # x = base base = trace_member(traverser, node['object'], instantiate) base = _expand_globals(traverser, base) identifier = _get_member_exp_property(traverser, node) # Handle the various global entity properties. if base.is_global: # If we've got an XPCOM wildcard, return a copy of the entity. if 'xpcom_wildcard' in base.value: traverser._debug('MEMBER_EXP>>XPCOM_WILDCARD') from predefinedentities import CONTRACT_ENTITIES if identifier in CONTRACT_ENTITIES: kw = dict(err_id=('js', 'actions', 'dangerous_contract'), warning='Dangerous XPCOM contract ID') kw.update(CONTRACT_ENTITIES[identifier]) traverser.warning(**kw) base.value = base.value.copy() del base.value['xpcom_wildcard'] return base test_identifier(traverser, identifier) traverser._debug('MEMBER_EXP>>PROPERTY: %s' % identifier) output = base.get( traverser=traverser, instantiate=instantiate, name=identifier) output.context = base.context if base.is_global: # In the cases of XPCOM objects, methods generally # remain bound to their parent objects, even when called # indirectly. output.parent = base return output elif node['type'] == 'Identifier': traverser._debug('MEMBER_EXP>>ROOT:IDENTIFIER') test_identifier(traverser, node['name']) # If we're supposed to instantiate the object and it doesn't already # exist, instantitate the object. if instantiate and not traverser._is_defined(node['name']): output = JSWrapper(JSObject(), traverser=traverser) traverser.contexts[0].set(node['name'], output) else: output = traverser._seek_variable(node['name']) return _expand_globals(traverser, output) else: traverser._debug('MEMBER_EXP>>ROOT:EXPRESSION') # It's an expression, so just try your damndest. return traverser._traverse_node(node) def test_identifier(traverser, name): 'Tests whether an identifier is banned' import predefinedentities if name in predefinedentities.BANNED_IDENTIFIERS: traverser.err.warning( err_id=('js', 'actions', 'banned_identifier'), warning='Banned or deprecated JavaScript Identifier', description=predefinedentities.BANNED_IDENTIFIERS[name], filename=traverser.filename, line=traverser.line, column=traverser.position, context=traverser.context) def _function(traverser, node): 'Prevents code duplication' # Put the function off for traversal at the end of the current block scope. traverser.function_collection[-1].append(partial(wrap, traverser, node)) return JSWrapper(traverser=traverser, callable=True, dirty=True) def _func_expr(traverser, node): 'Represents a lambda function' return _function(traverser, node) def _define_with(traverser, node): 'Handles `with` statements' object_ = traverser._traverse_node(node['object']) if isinstance(object_, JSWrapper) and isinstance(object_.value, JSObject): traverser.contexts[-1] = object_.value traverser.contexts.append(JSContext('block')) return def _define_var(traverser, node): 'Creates a local context variable' traverser._debug('VARIABLE_DECLARATION') traverser.debug_level += 1 declarations = (node['declarations'] if 'declarations' in node else node['head']) kind = node.get('kind', 'let') for declaration in declarations: # It could be deconstruction of variables :( if declaration['id']['type'] == 'ArrayPattern': vars = [] for element in declaration['id']['elements']: # NOTE : Multi-level array destructuring sucks. Maybe implement # it someday if you're bored, but it's so rarely used and it's # so utterly complex, there's probably no need to ever code it # up. if element is None or element['type'] != 'Identifier': vars.append(None) continue vars.append(element['name']) # The variables are not initialized if declaration['init'] is None: # Simple instantiation; no initialization for var in vars: if not var: continue traverser._declare_variable(var, None) # The variables are declared inline elif declaration['init']['type'] == 'ArrayPattern': # TODO : Test to make sure len(values) == len(vars) for value in declaration['init']['elements']: if vars[0]: traverser._declare_variable( vars[0], JSWrapper(traverser._traverse_node(value), traverser=traverser)) vars = vars[1:] # Pop off the first value # It's being assigned by a JSArray (presumably) elif declaration['init']['type'] == 'ArrayExpression': assigner = traverser._traverse_node(declaration['init']) for value in assigner.value.elements: if vars[0]: traverser._declare_variable(vars[0], value) vars = vars[1:] elif declaration['id']['type'] == 'ObjectPattern': init = traverser._traverse_node(declaration['init']) if init is not None: _proc_objpattern(init_obj=init, properties=declaration['id']['properties']) else: var_name = declaration['id']['name'] traverser._debug('NAME>>%s' % var_name) var_value = traverser._traverse_node(declaration['init']) traverser._debug('VALUE>>%s' % (var_value.output() if var_value is not None else 'None')) if not isinstance(var_value, JSWrapper): var = JSWrapper(value=var_value, const=kind == 'const', traverser=traverser) else: var = var_value var.const = kind == 'const' traverser._declare_variable(var_name, var, type_=kind) if 'body' in node: traverser._traverse_node(node['body']) traverser.debug_level -= 1 # The "Declarations" branch contains custom elements. return True def _define_obj(traverser, node): 'Creates a local context object' var = JSObject() for prop in node['properties']: if prop['type'] == 'PrototypeMutation': var_name = 'prototype' else: key = prop['key'] if key['type'] == 'Literal': var_name = key['value'] elif isinstance(key['name'], basestring): var_name = key['name'] else: if 'property' in key['name']: name = key['name'] else: name = {'property': key['name']} var_name = _get_member_exp_property(traverser, name) var_value = traverser._traverse_node(prop['value']) var.set(var_name, var_value, traverser) # TODO: Observe "kind" if not isinstance(var, JSWrapper): return JSWrapper(var, lazy=True, traverser=traverser) var.lazy = True return var def _define_array(traverser, node): """Instantiate an array object from the parse tree.""" arr = JSArray() arr.elements = map(traverser._traverse_node, node['elements']) return arr def _define_template_strings(traverser, node): """Instantiate an array of raw and cooked template strings.""" cooked = JSArray() cooked.elements = map(traverser._traverse_node, node['cooked']) raw = JSArray() raw.elements = map(traverser._traverse_node, node['raw']) cooked.set('raw', raw, traverser) return cooked def _define_template(traverser, node): """Instantiate a template literal.""" elements = map(traverser._traverse_node, node['elements']) return reduce(partial(_binary_op, '+', traverser=traverser), elements) def _define_literal(traverser, node): """ Convert a literal node in the parse tree to its corresponding interpreted value. """ value = node['value'] if isinstance(value, dict): return JSWrapper(JSObject(), traverser=traverser, dirty=True) wrapper = JSWrapper(value if value is not None else JSLiteral(None), traverser=traverser) test_literal(traverser, wrapper) return wrapper def test_literal(traverser, wrapper): """ Test the value of a literal, in particular only a string literal at the moment, against possibly dangerous patterns. """ value = wrapper.get_literal_value() if isinstance(value, basestring): # Local import to prevent import loop. from validator.testcases.regex import validate_string validate_string(value, traverser, wrapper=wrapper) def _call_settimeout(a, t, e): """ Handler for setTimeout and setInterval. Should determine whether a[0] is a lambda function or a string. Strings are banned, lambda functions are ok. Since we can't do reliable type testing on other variables, we flag those, too. """ if not a: return if a[0]['type'] in ('FunctionExpression', 'ArrowFunctionExpression'): return if t(a[0]).callable: return return {'err_id': ('javascript', 'dangerous_global', 'eval'), 'description': 'In order to prevent vulnerabilities, the `setTimeout` ' 'and `setInterval` functions should be called only with ' 'function expressions as their first argument.', 'signing_help': ( 'Please do not ever call `setTimeout` or `setInterval` with ' 'string arguments. If you are passing a function which is ' 'not being correctly detected as such, please consider ' 'passing a closure or arrow function, which in turn calls ' 'the original function.'), 'signing_severity': 'high'} def _call_require(a, t, e): """ Tests for unsafe uses of `require()` in SDK add-ons. """ args, traverse, err = a, t, e if not err.metadata.get('is_jetpack') and len(args): return module = traverse(args[0]).get_literal_value() if not isinstance(module, basestring): return if module.startswith('sdk/'): module = module[len('sdk/'):] LOW_LEVEL = { # Added from bugs 689340, 731109 'chrome', 'window-utils', 'observer-service', # Added from bug 845492 'window/utils', 'sdk/window/utils', 'sdk/deprecated/window-utils', 'tab/utils', 'sdk/tab/utils', 'system/events', 'sdk/system/events', } if module in LOW_LEVEL: err.metadata['requires_chrome'] = True return {'warning': 'Usage of low-level or non-SDK interface', 'description': 'Your add-on uses an interface which bypasses ' 'the high-level protections of the add-on SDK. ' 'This interface should be avoided, and its use ' 'may significantly complicate your review ' 'process.'} if module == 'widget': return {'warning': 'Use of deprecated SDK module', 'description': "The 'widget' module has been deprecated due to a number " 'of performance and usability issues, and has been ' 'removed from the SDK as of Firefox 40. Please use the ' "'sdk/ui/button/action' or 'sdk/ui/button/toggle' module " 'instead. See ' 'https://developer.mozilla.org/Add-ons/SDK/High-Level_APIs' '/ui for more information.'} def _call_create_pref(a, t, e): """ Handler for pref() and user_pref() calls in defaults/preferences/*.js files to ensure that they don't touch preferences outside of the "extensions." branch. """ # We really need to clean up the arguments passed to these functions. traverser = t.im_self if not traverser.filename.startswith('defaults/preferences/') or not a: return instanceactions.set_preference(JSWrapper(JSLiteral(None), traverser=traverser), a, traverser) value = _get_as_str(t(a[0])) return test_preference(value) def _readonly_top(traverser, right, node_right): """Handle the readonly callback for window.top.""" traverser.notice( err_id=('testcases_javascript_actions', '_readonly_top'), notice='window.top is a reserved variable', description='The `top` global variable is reserved and cannot be ' 'assigned any values starting with Gecko 6. Review your ' 'code for any uses of the `top` global, and refer to ' '%s for more information.' % BUGZILLA_BUG % 654137, for_appversions={FIREFOX_GUID: version_range('firefox', '6.0a1', '7.0a1'), FENNEC_GUID: version_range('fennec', '6.0a1', '7.0a1')}, compatibility_type='warning', tier=5) def _expression(traverser, node): """ This is a helper method that allows node definitions to point at `_traverse_node` without needing a reference to a traverser. """ return traverser._traverse_node(node['expression']) def _get_this(traverser, node): 'Returns the `this` object' if not traverser.this_stack: from predefinedentities import GLOBAL_ENTITIES return traverser._build_global('window', GLOBAL_ENTITIES[u'window']) return traverser.this_stack[-1] def _new(traverser, node): 'Returns a new copy of a node.' # We don't actually process the arguments as part of the flow because of # the Angry T-Rex effect. For now, we just traverse them to ensure they # don't contain anything dangerous. args = node['arguments'] if isinstance(args, list): for arg in args: traverser._traverse_node(arg, source='arguments') else: traverser._traverse_node(args) elem = traverser._traverse_node(node['callee']) if not isinstance(elem, JSWrapper): elem = JSWrapper(elem, traverser=traverser) if elem.is_global: traverser._debug('Making overwritable') elem.value = deepcopy(elem.value) elem.value['overwritable'] = True return elem def _ident(traverser, node): 'Initiates an object lookup on the traverser based on an identifier token' name = node['name'] # Ban bits like "newThread" test_identifier(traverser, name) if traverser._is_defined(name): return traverser._seek_variable(name) return JSWrapper(JSObject(), traverser=traverser, dirty=True) def _expr_assignment(traverser, node): """Evaluate an AssignmentExpression node.""" traverser._debug('ASSIGNMENT_EXPRESSION') traverser.debug_level += 1 traverser._debug('ASSIGNMENT>>PARSING RIGHT') right = traverser._traverse_node(node['right']) right = JSWrapper(right, traverser=traverser) # Treat direct assignment different than augmented assignment. if node['operator'] == '=': from predefinedentities import GLOBAL_ENTITIES, is_shared_scope global_overwrite = False readonly_value = is_shared_scope(traverser) node_left = node['left'] traverser._debug('ASSIGNMENT:DIRECT(%s)' % node_left['type']) if node_left['type'] == 'Identifier': # Identifiers just need the ID name and a value to push. # Raise a global overwrite issue if the identifier is global. global_overwrite = traverser._is_global(node_left['name']) # Get the readonly attribute and store its value if is_global if global_overwrite: global_dict = GLOBAL_ENTITIES[node_left['name']] if 'readonly' in global_dict: readonly_value = global_dict['readonly'] traverser._declare_variable(node_left['name'], right, type_='glob') elif node_left['type'] == 'MemberExpression': member_object = trace_member(traverser, node_left['object'], instantiate=True) global_overwrite = (member_object.is_global and not ('overwritable' in member_object.value and member_object.value['overwritable'])) member_property = _get_member_exp_property(traverser, node_left) traverser._debug('ASSIGNMENT:MEMBER_PROPERTY(%s)' % member_property) traverser._debug('ASSIGNMENT:GLOB_OV::%s' % global_overwrite) # Don't do the assignment if we're facing a global. if not member_object.is_global: if member_object.value is None: member_object.value = JSObject() if not member_object.is_global: member_object.value.set(member_property, right, traverser) else: # It's probably better to do nothing. pass elif 'value' in member_object.value: member_object_value = _expand_globals(traverser, member_object).value if member_property in member_object_value['value']: # If it's a global and the actual member exists, test # whether it can be safely overwritten. member = member_object_value['value'][member_property] if 'readonly' in member: global_overwrite = True readonly_value = member['readonly'] traverser._debug('ASSIGNMENT:DIRECT:GLOB_OVERWRITE %s' % global_overwrite) traverser._debug('ASSIGNMENT:DIRECT:READONLY %r' % readonly_value) if callable(readonly_value): readonly_value = readonly_value(traverser, right, node['right']) if readonly_value and global_overwrite: kwargs = dict( err_id=('testcases_javascript_actions', '_expr_assignment', 'global_overwrite'), warning='Global variable overwrite', description='An attempt was made to overwrite a global ' 'variable in some JavaScript code.') if isinstance(readonly_value, DESCRIPTION_TYPES): kwargs['description'] = readonly_value elif isinstance(readonly_value, dict): kwargs.update(readonly_value) traverser.warning(**kwargs) return right lit_right = right.get_literal_value() traverser._debug('ASSIGNMENT>>PARSING LEFT') left = traverser._traverse_node(node['left']) traverser._debug('ASSIGNMENT>>DONE PARSING LEFT') traverser.debug_level -= 1 if isinstance(left, JSWrapper): if left.dirty: return left lit_left = left.get_literal_value() token = node['operator'] # Don't perform an operation on None. Python freaks out if lit_left is None: lit_left = 0 if lit_right is None: lit_right = 0 # Give them default values so we have them in scope. gleft, gright = 0, 0 # All of the assignment operators operators = {'=': lambda: right, '+=': lambda: lit_left + lit_right, '-=': lambda: gleft - gright, '*=': lambda: gleft * gright, '/=': lambda: 0 if gright == 0 else (gleft / gright), '%=': lambda: 0 if gright == 0 else (gleft % gright), '<<=': lambda: int(gleft) << int(gright), '>>=': lambda: int(gleft) >> int(gright), '>>>=': lambda: float(abs(int(gleft)) >> gright), '|=': lambda: int(gleft) | int(gright), '^=': lambda: int(gleft) ^ int(gright), '&=': lambda: int(gleft) & int(gright)} # If we're modifying a non-numeric type with a numeric operator, return # NaN. if (not isinstance(lit_left, NUMERIC_TYPES) and token in NUMERIC_OPERATORS): left.set_value(get_NaN(traverser), traverser=traverser) return left # If either side of the assignment operator is a string, both sides # need to be casted to strings first. if (isinstance(lit_left, types.StringTypes) or isinstance(lit_right, types.StringTypes)): lit_left = _get_as_str(lit_left) lit_right = _get_as_str(lit_right) gleft, gright = _get_as_num(left), _get_as_num(right) traverser._debug('ASSIGNMENT>>OPERATION:%s' % token) if token not in operators: # We don't support that operator. (yet?) traverser._debug('ASSIGNMENT>>OPERATOR NOT FOUND', 1) return left elif token in ('<<=', '>>=', '>>>=') and gright < 0: # The user is doing weird bitshifting that will return 0 in JS but # not in Python. left.set_value(0, traverser=traverser) return left elif (token in ('<<=', '>>=', '>>>=', '|=', '^=', '&=') and (abs(gleft) == float('inf') or abs(gright) == float('inf'))): # Don't bother handling infinity for integer-converted operations. left.set_value(get_NaN(traverser), traverser=traverser) return left traverser._debug('ASSIGNMENT::L-value global? (%s)' % ('Y' if left.is_global else 'N'), 1) try: new_value = operators[token]() except Exception: traverser.system_error(exc_info=sys.exc_info()) new_value = None # Cap the length of analyzed strings. if (isinstance(new_value, types.StringTypes) and len(new_value) > MAX_STR_SIZE): new_value = new_value[:MAX_STR_SIZE] traverser._debug('ASSIGNMENT::New value >> %s' % new_value, 1) left.set_value(new_value, traverser=traverser) return left # Though it would otherwise be a syntax error, we say that 4=5 should # evaluate out to 5. return right def _expr_binary(traverser, node): 'Evaluates a BinaryExpression node.' traverser.debug_level += 1 # Select the proper operator. operator = node['operator'] traverser._debug('BIN_OPERATOR>>%s' % operator) # Traverse the left half of the binary expression. with traverser._debug('BIN_EXP>>l-value'): if (node['left']['type'] == 'BinaryExpression' and '__traversal' not in node['left']): # Process the left branch of the binary expression directly. This # keeps the recursion cap in line and speeds up processing of # large chains of binary expressions. left = _expr_binary(traverser, node['left']) node['left']['__traversal'] = left else: left = traverser._traverse_node(node['left']) # Traverse the right half of the binary expression. with traverser._debug('BIN_EXP>>r-value'): if (operator == 'instanceof' and node['right']['type'] == 'Identifier' and node['right']['name'] == 'Function'): # We make an exception for instanceof's r-value if it's a # dangerous global, specifically Function. return JSWrapper(True, traverser=traverser) else: right = traverser._traverse_node(node['right']) traverser._debug('Is dirty? %r' % right.dirty, 1) return _binary_op(operator, left, right, traverser) def _binary_op(operator, left, right, traverser): """Perform a binary operation on two pre-traversed nodes.""" # Dirty l or r values mean we can skip the expression. A dirty value # indicates that a lazy operation took place that introduced some # nondeterminacy. # FIXME(Kris): We should process these as if they're strings anyway. if left.dirty: return left elif right.dirty: return right # Binary expressions are only executed on literals. left = left.get_literal_value() right_wrap = right right = right.get_literal_value() # Coerce the literals to numbers for numeric operations. gleft = _get_as_num(left) gright = _get_as_num(right) operators = { '==': lambda: left == right or gleft == gright, '!=': lambda: left != right, '===': lambda: left == right, # Be flexible. '!==': lambda: type(left) != type(right) or left != right, '>': lambda: left > right, '<': lambda: left < right, '<=': lambda: left <= right, '>=': lambda: left >= right, '<<': lambda: int(gleft) << int(gright), '>>': lambda: int(gleft) >> int(gright), '>>>': lambda: float(abs(int(gleft)) >> int(gright)), '+': lambda: left + right, '-': lambda: gleft - gright, '*': lambda: gleft * gright, '/': lambda: 0 if gright == 0 else (gleft / gright), '%': lambda: 0 if gright == 0 else (gleft % gright), 'in': lambda: right_wrap.contains(left), # TODO : implement instanceof # FIXME(Kris): Treat instanceof the same as `QueryInterface` } output = None if (operator in ('>>', '<<', '>>>') and (left is None or right is None or gright < 0)): output = False elif operator in operators: # Concatenation can be silly, so always turn undefineds into empty # strings and if there are strings, make everything strings. if operator == '+': if left is None: left = '' if right is None: right = '' if isinstance(left, basestring) or isinstance(right, basestring): left = _get_as_str(left) right = _get_as_str(right) # Don't even bother handling infinity if it's a numeric computation. if (operator in ('<<', '>>', '>>>') and (abs(gleft) == float('inf') or abs(gright) == float('inf'))): return get_NaN(traverser) try: output = operators[operator]() except Exception: traverser.system_error(exc_info=sys.exc_info()) output = None # Cap the length of analyzed strings. if (isinstance(output, types.StringTypes) and len(output) > MAX_STR_SIZE): output = output[:MAX_STR_SIZE] wrapper = JSWrapper(output, traverser=traverser) # Test the newly-created literal for dangerous values. # This may cause duplicate warnings for strings which # already match a dangerous value prior to concatenation. test_literal(traverser, wrapper) return wrapper return JSWrapper(output, traverser=traverser) def _expr_unary(traverser, node): """Evaluate a UnaryExpression node.""" expr = traverser._traverse_node(node['argument']) expr_lit = expr.get_literal_value() expr_num = _get_as_num(expr_lit) operators = {'-': lambda: -1 * expr_num, '+': lambda: expr_num, '!': lambda: not expr_lit, '~': lambda: -1 * (expr_num + 1), 'void': lambda: None, 'typeof': lambda: _expr_unary_typeof(expr), 'delete': lambda: None} # We never want to empty the context if node['operator'] in operators: output = operators[node['operator']]() else: output = None if not isinstance(output, JSWrapper): output = JSWrapper(output, traverser=traverser) return output def _expr_unary_typeof(wrapper): """Evaluate the "typeof" value for a JSWrapper object.""" if (wrapper.callable or (wrapper.is_global and 'return' in wrapper.value and 'value' not in wrapper.value)): return 'function' value = wrapper.value if value is None: return 'undefined' elif isinstance(value, JSLiteral): value = value.value if isinstance(value, bool): return 'boolean' elif isinstance(value, (int, long, float)): return 'number' elif isinstance(value, types.StringTypes): return 'string' return 'object' def _get_as_num(value): """Return the JS numeric equivalent for a value.""" if isinstance(value, JSWrapper): value = value.get_literal_value() if value is None: return 0 try: if isinstance(value, types.StringTypes): if value.startswith('0x'): return int(value, 16) else: return float(value) elif isinstance(value, (int, float, long)): return value else: return int(value) except (ValueError, TypeError): return 0 def _get_as_str(value): """Return the JS string equivalent for a literal value.""" if isinstance(value, JSWrapper): value = value.get_literal_value() if value is None: return '' if isinstance(value, bool): return u'true' if value else u'false' elif isinstance(value, (int, float, long)): if value == float('inf'): return u'Infinity' elif value == float('-inf'): return u'-Infinity' # Try to see if we can shave off some trailing significant figures. try: if int(value) == value: return unicode(int(value)) except ValueError: pass return unicode(value)
[ 6738, 4866, 1330, 2769, 30073, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 11748, 25064, 198, 11748, 3858, 198, 198, 2, 8060, 1330, 286, 2747, 18156, 298, 871, 481, 2728, 281, 1330, 9052, 198, 11748, 4554, 4658, 198, 6738, 4938, 1352...
2.231982
14,777
#!/usr/bin/env python """ Test code for the BBox Object """ import numpy as np import pytest from geometry_utils.bound_box import (BBox, asBBox, NullBBox, InfBBox, fromBBArray, from_points, )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 14402, 2438, 329, 262, 12597, 1140, 9515, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 198, 6738, 22939, 62, 26791, 13, 7784, 62, ...
1.440789
304
import cv2 cv2.setNumThreads(0) cv2.ocl.setUseOpenCL(False) import numpy as np import math from functools import wraps def clipped(func): """ wrapper to clip results of transform to image dtype value range """ return wrapped_function def fix_shift_values(img, *args): """ shift values are normally specified in uint, but if your data is float - you need to remap values """ if img.dtype == np.float32: return list(map(lambda x: x / 255, args)) return args def rotate(img, angle): """ rotate image on specified angle :param angle: angle in degrees """ height, width = img.shape[0:2] mat = cv2.getRotationMatrix2D((width/2, height/2), angle, 1.0) img = cv2.warpAffine(img, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101) return img def shift_scale_rotate(img, angle, scale, dx, dy): """ :param angle: in degrees :param scale: relative scale """ height, width = img.shape[:2] cc = math.cos(angle/180*math.pi) * scale ss = math.sin(angle/180*math.pi) * scale rotate_matrix = np.array([[cc, -ss], [ss, cc]]) box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ]) box1 = box0 - np.array([width/2, height/2]) box1 = np.dot(box1, rotate_matrix.T) + np.array([width/2+dx*width, height/2+dy*height]) box0 = box0.astype(np.float32) box1 = box1.astype(np.float32) mat = cv2.getPerspectiveTransform(box0, box1) img = cv2.warpPerspective(img, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101) return img def img_to_tensor(im, verbose=False): '''AVE edit''' im_out = np.moveaxis(im / (255. if im.dtype == np.uint8 else 1), -1, 0).astype(np.float32) if verbose: print ("augmentations.functiona.py.img_to_tensor(): im_out.shape:", im_out.shape) print ("im_out.unique:", np.unique(im_out)) return im_out def mask_to_tensor(mask, num_classes, verbose=False): '''AVE edit''' if num_classes > 1: mask = img_to_tensor(mask) else: mask = np.expand_dims(mask / (255. if mask.dtype == np.uint8 else 1), 0).astype(np.float32) if verbose: print ("augmentations.functiona.py.img_to_tensor(): mask.shape:", mask.shape) print ("mask.unique:", np.unique(mask)) return mask
[ 11748, 269, 85, 17, 201, 198, 33967, 17, 13, 2617, 33111, 16818, 82, 7, 15, 8, 201, 198, 33967, 17, 13, 38679, 13, 2617, 11041, 11505, 5097, 7, 25101, 8, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 10688, 201, 198, 6...
2.105134
1,227
# -*- coding: utf-8 -*- """ Created on Mon Aug 14 09:49:13 2017 @author: vmg """ import os import buildingspy.development.regressiontest as r rt = r.Tester(check_html=False)#,tool="dymola") LibPath = os.path.join("TRANSFORM") ResPath = LibPath rt.showGUI(True) rt.setLibraryRoot(LibPath, ResPath) rt.setNumberOfThreads(1) #rt.TestSinglePackage('Media.Solids.Examples.Hastelloy_N_Haynes', SinglePack=True) rt.run()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 2447, 1478, 7769, 25, 2920, 25, 1485, 2177, 198, 198, 31, 9800, 25, 410, 11296, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 6832, 9078,...
2.558282
163
# -*- coding: utf-8 -*- __author__ = "Ngoc Huynh Bao" __email__ = "ngoc.huynh.bao@nmbu.no" from ..keras.layers import Activation from ..keras.activations import deserialize from ..utils import Singleton def register_activation(key, activation): """ Register the customized activation. If the key name is already registered, it will raise a KeyError exception Parameters ---------- key: str The unique key-name of the activation activation: tensorflow.keras.activations.Activation The customized activation class """ Activations().register(key, activation) def unregister_activation(key): """ Remove the registered activation with the key-name Parameters ---------- key: str The key-name of the activation to be removed """ Activations().unregister(key)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9800, 834, 796, 366, 45, 70, 420, 11256, 2047, 71, 347, 5488, 1, 198, 834, 12888, 834, 796, 366, 782, 420, 13, 13415, 2047, 71, 13, 65, 5488, 31, 77, 202...
2.927835
291
""" Module to take a water_level reading.""" # Raspi-sump, a sump pump monitoring system. # Al Audet # http://www.linuxnorth.org/raspi-sump/ # # All configuration changes should be done in raspisump.conf # MIT License -- http://www.linuxnorth.org/raspi-sump/license.html try: import ConfigParser as configparser # Python2 except ImportError: import configparser # Python3 from hcsr04sensor import sensor from raspisump import log, alerts, heartbeat config = configparser.RawConfigParser() config.read("/home/pi/raspi-sump/raspisump.conf") configs = { "critical_water_level": config.getint("pit", "critical_water_level"), "pit_depth": config.getint("pit", "pit_depth"), "temperature": config.getint("pit", "temperature"), "trig_pin": config.getint("gpio_pins", "trig_pin"), "echo_pin": config.getint("gpio_pins", "echo_pin"), "unit": config.get("pit", "unit"), } # If item in raspisump.conf add to configs dict. If not provide defaults. try: configs["alert_when"] = config.get("pit", "alert_when") except configparser.NoOptionError: configs["alert_when"] = "high" try: configs["heartbeat"] = config.getint("email", "heartbeat") except configparser.NoOptionError: configs["heartbeat"] = 0 def initiate_heartbeat(): """Initiate the heartbeat email process if needed""" if configs["heartbeat"] == 1: heartbeat.determine_if_heartbeat() else: pass def water_reading(): """Initiate a water level reading.""" pit_depth = configs["pit_depth"] trig_pin = configs["trig_pin"] echo_pin = configs["echo_pin"] temperature = configs["temperature"] unit = configs["unit"] value = sensor.Measurement(trig_pin, echo_pin, temperature, unit) try: raw_distance = value.raw_distance(sample_wait=0.3) except SystemError: log.log_errors( "**ERROR - Signal not received. Possible cable or sensor problem." ) exit(0) return round(value.depth(raw_distance, pit_depth), 1) def water_depth(): """Determine the depth of the water, log result and generate alert if needed. """ critical_water_level = configs["critical_water_level"] water_depth = water_reading() if water_depth < 0.0: water_depth = 0.0 log.log_reading(water_depth) if water_depth > critical_water_level and configs["alert_when"] == "high": alerts.determine_if_alert(water_depth) elif water_depth < critical_water_level and configs["alert_when"] == "low": alerts.determine_if_alert(water_depth) else: pass initiate_heartbeat()
[ 37811, 19937, 284, 1011, 257, 1660, 62, 5715, 3555, 526, 15931, 198, 198, 2, 371, 5126, 72, 12, 82, 931, 11, 257, 264, 931, 8901, 9904, 1080, 13, 198, 2, 978, 7591, 316, 198, 2, 2638, 1378, 2503, 13, 23289, 43588, 13, 2398, 14, ...
2.665988
982
''' Configuration generation for running Pancreas datasets ''' import os, argparse from pipelines import method_utils, dataloading_utils from preprocess.process_train_test_data import * if __name__ == "__main__": data_dir = "~/gpu/data" ## parse arguments import argparse parser = argparse.ArgumentParser(description="Celltyping pipeline.") parser.add_argument('data_source', help="Load which dataset", choices=[ 'pancreas', 'pancreas_seg_cond', 'pancreas_custom', 'pancreas_seg_mix', 'pancreas_multi_to_multi' ]) parser.add_argument('-m', '--method', help="Run which method", choices=['MLP', 'MLP_GO', 'MLP_CP', 'GEDFN', 'ItClust', 'SVM_RBF', 'SVM_linear', 'RF'], ## remove DFN required=True) parser.add_argument('--select_on', help="Feature selection on train or test, or None of them", choices=['train', 'test']) parser.add_argument('--select_method', help="Feature selection method, Seurat/FEAST or None", choices=['Seurat', 'FEAST', 'F-test']) parser.add_argument('--n_features', help="Number of features selected", default=1000, type=int) parser.add_argument('--train', help="Specify which as train", required=True) parser.add_argument('--test', help="Specify which as test", required=True) parser.add_argument('--sample_seed', help="Downsample seed in combined individual effect", default=0, type=int) args = parser.parse_args() pipeline_dir = "pipelines/result_Pancreas_collections" result_prefix = pipeline_dir+os.sep+"result_"+args.data_source+'_'+\ args.train+'_to_'+args.test os.makedirs(result_prefix, exist_ok=True) ## create file directory if args.select_on is None and args.select_method is None: result_dir = result_prefix+os.sep+"no_feature" else: result_dir = result_prefix+os.sep+args.select_method+'_'+\ str(args.n_features)+'_on_'+args.select_on os.makedirs(result_dir, exist_ok=True) load_ind, train_adata, test_adata = load_adata(result_dir) if not load_ind: train_adata, test_adata = dataloading_utils.load_Pancreas_adata( data_dir, result_dir, args=args) ## whether to purify reference dataset purify_method = "" if "purify_dist" in args.data_source: purify_method = "distance" elif "purify_SVM" in args.data_source: purify_method = "SVM" train_adata, test_adata = dataloading_utils.process_loaded_data( train_adata, test_adata, result_dir, args=args, purify_method=purify_method) print("Train anndata: \n", train_adata) print("Test anndata: \n", test_adata) method_utils.run_pipeline(args, train_adata, test_adata, data_dir, result_dir)
[ 7061, 6, 198, 38149, 5270, 329, 2491, 49957, 260, 292, 40522, 198, 7061, 6, 198, 198, 11748, 28686, 11, 1822, 29572, 198, 198, 6738, 31108, 1330, 2446, 62, 26791, 11, 4818, 282, 1170, 278, 62, 26791, 198, 6738, 662, 14681, 13, 14681, ...
2.414676
1,172
import pandas as pd from sklearn.preprocessing import StandardScaler stand_demo()
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 8997, 3351, 36213, 198, 198, 1481, 62, 9536, 78, 3419, 198 ]
3.32
25
from prng.util.util import primitive_roots import pytest
[ 6738, 778, 782, 13, 22602, 13, 22602, 1330, 20049, 62, 19150, 198, 11748, 12972, 9288, 198 ]
3.5625
16
# https://www.hackerrank.com/challenges/xml-1-find-the-score/problem import sys import xml.etree.ElementTree as etree if __name__ == '__main__': sys.stdin.readline() xml = sys.stdin.read() tree = etree.ElementTree(etree.fromstring(xml)) root = tree.getroot() print(get_attr_number(root))
[ 198, 2, 3740, 1378, 2503, 13, 31153, 8056, 962, 13, 785, 14, 36747, 34120, 14, 19875, 12, 16, 12, 19796, 12, 1169, 12, 26675, 14, 45573, 198, 198, 11748, 25064, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 2123, 631, 198,...
2.488
125
test = int(input()) while test > 0 : n,k = map(int,input().split()) p = list(map(int,input().split())) original = 0 later = 0 for i in p : if i > k : later += k original += i else : later += i original += i print(original-later) test -= 1
[ 9288, 796, 493, 7, 15414, 28955, 201, 198, 4514, 1332, 1875, 657, 1058, 201, 198, 220, 220, 220, 299, 11, 74, 796, 3975, 7, 600, 11, 15414, 22446, 35312, 28955, 201, 198, 220, 220, 220, 279, 796, 1351, 7, 8899, 7, 600, 11, 15414, ...
1.875676
185
# -*- coding: utf-8 -*- """ Created on Mon Aug 18 22:20:01 2014 @author: baki """ import shlex from subprocess import Popen, PIPE from .Log import Log
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 2447, 1248, 2534, 25, 1238, 25, 486, 1946, 198, 198, 31, 9800, 25, 275, 8182, 198, 37811, 198, 198, 11748, 427, 2588, 198, 6738, 850, 146...
2.566667
60
import os import six import copy import pickle import random import logging from scrapy.http import Request from scrapy.exceptions import NotConfigured from scrapy.commands.genspider import sanitize_module_name from scrapy.spiders import CrawlSpider from .utils import ( add_sample, response_to_dict, get_or_create_test_dir, parse_request, parse_object, get_project_dir, get_middlewares, create_dir, ) logger = logging.getLogger(__name__)
[ 11748, 28686, 198, 11748, 2237, 198, 11748, 4866, 198, 11748, 2298, 293, 198, 11748, 4738, 198, 11748, 18931, 198, 198, 6738, 15881, 88, 13, 4023, 1330, 19390, 198, 6738, 15881, 88, 13, 1069, 11755, 1330, 1892, 16934, 1522, 198, 6738, 1...
2.783626
171
######################################################################### # _________ ___. ______________________ ___ # \_ ___ \___.__.\_ |__ ___________ / _____/\______ \ \/ / # / \ \< | | | __ \_/ __ \_ __ \/ \ ___ | _/\ / # \ \___\___ | | \_\ \ ___/| | \/\ \_\ \| | \/ \ # \______ / ____| |___ /\___ >__| \______ /|____|_ /___/\ \ # \/\/ \/ \/ \/ \/ \_/ # # import os import json import requests from collections import OrderedDict from openpyxl import Workbook from openpyxl.styles.fills import FILL_SOLID from openpyxl.styles import Color, PatternFill, Font, Border, Side from openpyxl.styles import colors from openpyxl.cell import Cell from tqdm import tqdm from glom import glom
[ 29113, 29113, 7804, 2, 198, 2, 220, 220, 220, 220, 2602, 62, 220, 220, 220, 220, 220, 220, 220, 11593, 44807, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 4841, 25947, 220, 46444, ...
2.11
400
#!/usr/bin/env python3 import torch from .lazy_tensor import LazyTensor def lazify(obj): """ A function which ensures that `obj` is a LazyTensor. If `obj` is a LazyTensor, this function does nothing. If `obj` is a (normal) Tensor, this function wraps it with a `NonLazyTensor`. """ if torch.is_tensor(obj): return NonLazyTensor(obj) elif isinstance(obj, LazyTensor): return obj else: raise TypeError("object of class {} cannot be made into a LazyTensor".format(obj.__class__.__name__)) __all__ = ["NonLazyTensor", "lazify"]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 28034, 198, 198, 6738, 764, 75, 12582, 62, 83, 22854, 1330, 406, 12582, 51, 22854, 628, 198, 198, 4299, 37296, 1958, 7, 26801, 2599, 198, 220, 220, 220, 37227, 198, 2...
2.517094
234
""" --- Day 19: Tractor Beam --- https://adventofcode.com/2019/day/19 """ from aocd import data from aoc_wim.aoc2019 import IntComputer from aoc_wim.zgrid import ZGrid from aoc_wim.search import Bisect import functools if __name__ == "__main__": print("populating 50x50 zgrid...") grid = ZGrid() x0 = 0 for y in range(50): on = False for x in range(x0, 50): z = x + y * 1j val = grid[z] = beam(z) if not on and val: on = True x0 = x if x0: m = y / x0 if on and not val: break print("part a", sum(grid.values())) grid.translate({0: ".", 1: "#"}) grid.draw() print("initial gradient is approx -->", m) print("refining gradient estimate -->", end=" ") z = left_edge_of_beam(2000, gradient=m) m = z.imag/z.real print(m) z = locate_square(beam, width=100, gradient_estimate=m) print("part b", int(z.real)*10000 + int(z.imag))
[ 37811, 198, 6329, 3596, 678, 25, 309, 40450, 25855, 11420, 198, 5450, 1378, 324, 1151, 1659, 8189, 13, 785, 14, 23344, 14, 820, 14, 1129, 198, 37811, 198, 6738, 257, 420, 67, 1330, 1366, 198, 6738, 257, 420, 62, 86, 320, 13, 64, 4...
2.045545
505
import cv2 """ checks if an image is blurry returns True if blurry, False otherwise """
[ 11748, 269, 85, 17, 628, 198, 37811, 198, 42116, 611, 281, 2939, 318, 44701, 198, 7783, 82, 6407, 611, 44701, 11, 10352, 4306, 198, 37811 ]
3.56
25
if __name__ == '__main__': main()
[ 220, 220, 220, 220, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419 ]
1.954545
22
""" Helper functions and utilities """ from datetime import datetime as dt from mrcnn import visualize import numpy as np import os import cv2 TIMESTAMP_FORMAT = "%d/%m/%Y %H:%M:%S" def mask_to_rgb(mask): """ Converts a mask to RGB Format """ colours = visualize.random_colors(mask.shape[2]) rgb_mask = np.zeros((mask.shape[0], mask.shape[1], 3)) for i in range(mask.shape[2]): for c in range(3): rgb_mask[:, :, c] = np.where(mask[:, :, i] != 0, int(colours[i][c] * 255), rgb_mask[:, :, c]) return rgb_mask def mask_to_outlined(mask): """ Converts a mask to RGB Format """ colours = visualize.random_colors(mask.shape[2]) rgb_mask = np.zeros((mask.shape[0], mask.shape[1], 3)) for i in range(mask.shape[2]): for c in range(3): rgb_mask[:, :, c] = np.where(mask[:, :, i] != 0, int(colours[i][c] * 255), rgb_mask[:, :, c]) # put edges over the top of the colours for i in range(mask.shape[2]): # Find the contour of the leaf threshold = mask[:, :, i] threshold[threshold != 0] = 255 _, contours, hierarchy = cv2.findContours(threshold.astype(np.uint8),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # Draw outline on mask if len(contours) > 0: cv2.drawContours(rgb_mask, [contours[0]], 0, (255, 255, 255), thickness=1) return rgb_mask
[ 37811, 198, 47429, 5499, 290, 20081, 198, 37811, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 355, 288, 83, 198, 198, 6738, 285, 6015, 20471, 1330, 38350, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 198, 11748, 269, 85,...
2.222222
630
import abc
[ 11748, 450, 66, 198 ]
2.75
4
import django.conf settings = Settings()
[ 11748, 42625, 14208, 13, 10414, 628, 198, 198, 33692, 796, 16163, 3419, 198 ]
3.384615
13
import asyncio import discord from discord.ext import commands from discord.ext.commands.core import has_permissions
[ 11748, 30351, 952, 198, 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 6738, 36446, 13, 2302, 13, 9503, 1746, 13, 7295, 1330, 468, 62, 525, 8481, 198 ]
4.034483
29
from .test_tensorboard_rest_api import TestTensorboardRestAPI from .test_tensorboard_server import TestTensorboardServer from .test_tensorboard_endpoints import TestTensorboardEndpoint
[ 6738, 764, 9288, 62, 83, 22854, 3526, 62, 2118, 62, 15042, 1330, 6208, 51, 22854, 3526, 19452, 17614, 198, 6738, 764, 9288, 62, 83, 22854, 3526, 62, 15388, 1330, 6208, 51, 22854, 3526, 10697, 198, 6738, 764, 9288, 62, 83, 22854, 3526,...
3.538462
52