input
stringlengths
2.65k
237k
output
stringclasses
1 value
try: sf = c.parent_block().constraint_transformed_scaling_factor.get(c, default) except AttributeError: sf = default # when there is no suffix return sf def __unset_constraint_transform_applied_scaling_factor(c): """PRIVATE FUNCTION: Delete the recorded scale factor that has been used to transform constraint c....
<reponame>gabemery/gammapy # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import abc import logging from subprocess import call from tempfile import NamedTemporaryFile from copy import deepcopy from collections import Or...
<reponame>wendbv/pluvo-python from mock import call, patch import pytest import pluvo from pluvo import PluvoResultSet, DEFAULT_API_URL, DEFAULT_PAGE_SIZE import datetime class Multiple: call_nr = 0 def __init__(self, pages): self.pages = pages def results(self, *args, **kwargs): result = self.pages[self.call...
import dataclasses import datetime import enum import typing import pytest from faker import Faker from dataclasses_avroschema import AvroModel, exceptions, fields, types from . import consts faker = Faker() def test_invalid_type_container_field(): python_type = typing.Set name = "test_field" msg = f"Invalid T...
running, or printed to stdout otherwise. If `delayed` is set to False, messages are immediately printed instead. Example: def function(...): profiler = Profiler() ... do stuff ... profiler('did stuff') ... do other stuff ... profiler('did other stuff') # profiler is garbage-collected and flushed at function ...
<filename>src/deploy/osp_deployer/director.py #!/usr/bin/env python # Copyright (c) 2015-2019 Dell Inc. or its subsidiaries. # # 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.ap...
# -*- coding: utf-8 -*- from ..util import log from ..util.log import debug from ..util import urlopen import json, re import requests from bs4 import BeautifulSoup from ..util.base import clean_html user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100' de...
- start) / n_rows) # The exact end point is therefore the ncolumns*nrows away from the start end = start + n_columns * n_rows ep = np.reshape(pp[start:end], (n_rows, n_columns)) if scale == "log": ep = np.log10(ep) # Reshape the freq into n_rowss of n_columnss & create arays ef = np.reshape(ff[start:end], (n...
'ipfs key list -l'. Default:. (string) Default: self :returns: A parsed dict result of: .. code-block:: python { "Name": "<string>" "Value": "<string>" } """ endpoint = 'name/publish' args = [(ipfs_path, 'string')] return await self.client.get_parsed(endpoint, args, kwargs) async def name_pubsub_cancel(s...
import abc from collections import OrderedDict import time import gtimer as gt import numpy as np from rlkit.core import logger, eval_util from rlkit.data_management.env_replay_buffer import MultiTaskReplayBuffer,EnvReplayBuffer from rlkit.data_management.path_builder import PathBuilder from rlkit.samplers.in_place i...
# Copyright 2019 Xilinx Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
folder to save features data_type: The type of features, train/test/val crop_type: The method to crop the images. Options are 'none' (no cropping) 'bbox' (crop using bounding box coordinates), 'context' (A region containing pedestrian and their local surround) 'surround' (only the region around the pedestrian. Pe...
for next cycle of loop return result_dict, result_path def _check_manifest_matches(self, parent_trace, manifest_filename, manifest_dict, manifest_api_name, namespace, name, kind, minimal_version): ''' Helper method for self.findLatestVersionManifest. It verifies that the manifest_dict has all the fields as s...
<filename>tweetarchiver/__init__.py<gh_stars>0 import time import json import logging from hashlib import md5 from calendar import timegm from urllib.parse import urlparse from typing import Generator, BinaryIO, Optional, List, Tuple, Union, NamedTuple import requests import sqlalchemy as sqla from sqlalchemy import f...
<reponame>loco-philippe/Environnemental-Sensing # -*- coding: utf-8 -*- """ Created on Tue Aug 3 23:40:06 2021 @author: <EMAIL> The `ES.ESObservation` module contains the main class of Environmental Sensing : `Observation` class. """ from ESconstante import ES, _classval #import ESValue from ESValue import LocationV...
# -*- coding: utf-8 -*- """ Created on Fri Apr 22 15:07:09 2016 @author: advena """ #import re from datetime import datetime #import numpy as np import pandas as pd import os import sys import shutil from dateutil import parser ######################################################################## #...
<gh_stars>100-1000 import json import appscale.infrastructure as iaas from tornado.testing import AsyncHTTPTestCase, gen_test from tornado.httpclient import HTTPRequest, HTTPError from tornado.ioloop import IOLoop from mock import patch, MagicMock from appscale.agents.base_agent import AgentRuntimeException from app...
import sys, time, os, importlib, random import numpy as np import torch import torch.nn.functional as F from scipy.io import wavfile from config.args import parser from tools import load_yaml_config, load_speaker_model_parameters, reverb, reverb_np args = parser.parse_args() args = load_yaml_config(args, parser) os.en...
<filename>Lib/fontParts/test/test_anchor.py import unittest import collections from fontParts.base import FontPartsError class TestAnchor(unittest.TestCase): def getAnchor_generic(self): anchor, _ = self.objectGenerator("anchor") anchor.name = "Anchor Attribute Test" anchor.x = 1 anchor.y = 2 anchor.color = No...
0: time.sleep(0.003) if BotUtils.detect_xprompt(gamename): break try: newx, newy = Looting.grab_farloot_locations(gamename, rect)[ 0] time_taken = time.time() - loop_time movementx = confirmed[0] - newx speed = movementx/time_taken if speed != 0: time_remaining = abs( relx/speed) - time_taken rect = [newx-...
'Cisco-IOS-XR-clns-isis-cfg', False), ], 'Cisco-IOS-XR-clns-isis-cfg', 'frr-exclude-interfaces', _yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg' ), }, 'Isis.Instances.Instance.Interfaces.Interface.InterfaceAfs.InterfaceAf.TopologyName.InterfaceFrrTable.In...
extract_text(data['awardID']['awardContractID']['modNumber']) except (KeyError, TypeError): unique_string += "-none-" unique_string += "_" try: unique_string += extract_text(data['awardID']['referencedIDVID']['PIID']) except (KeyError, TypeError): unique_string += "-none-" unique_string += "_" try: unique...
'bizzenphew', 'bizzenphooey', 'bizzenpocket', 'bizzenpoof', 'bizzenpop', 'bizzenpounce', 'bizzenpow', 'bizzenpretzel', 'bizzenquack', 'bizzenroni', 'bizzenscooter', 'bizzenscreech', 'bizzensmirk', 'bizzensnooker', 'bizzensnoop', 'bizzensnout', 'bizzensocks', 'bizzenspeed', 'bizzenspinner', 'bizzenspl...
import torch import argparse import torch.nn.functional as F import copy from utils import tps import time from collections import defaultdict from torch.autograd import gradcheck LOCAL_CHECKS = False PROFILE = False class DenseCorr(torch.autograd.Function): @staticmethod def forward(ctx, feats1, feats2, xxyy, ba...
<gh_stars>0 # -*- coding: utf-8 -*- import functools import random import time from collections import namedtuple from py_zipkin._encoding_helpers import create_endpoint from py_zipkin.exception import ZipkinError from py_zipkin.logging_helper import zipkin_logger from py_zipkin.logging_helper import ZipkinLoggerHandl...
first need to check if it is Multipolygon if self.Multipolygon: #then we append all the floor and roof fottprints into one with associate height for idx1,poly1 in enumerate(DB.geometry.coordinates[:-1]): for idx2,poly2 in enumerate(DB.geometry.coordinates[idx1+1:]): if poly1 == poly2: polycoor = [] for j in poly...
import argparse import multiprocessing from queue import Empty import random import time import os import re import glob import pickle import numpy as np import time import pommerman from pommerman.agents import BaseAgent, SimpleAgent from pommerman import constants from keras.models import Model, load_model, model_f...
<reponame>oholsen/hagedag import asyncio import math from math import sin, cos, pi import cmath from dataclasses import dataclass, replace import logging import time import random import RobotMessages import RobotModel from state import State from PID import PID from Plotting import Plot from abc import ABC from shapel...
<filename>edl/kegg.py #! /usr/bin/python """ Library of methods and regular expressions for parsing files from the KEGG gene ontology """ import logging import os import re import sys logger = logging.getLogger(__name__) ############## # Classes # ############## ################ # compiled REs # ################ koRE...
<gh_stars>1-10 #!/usr/bin/env python from __future__ import print_function import matplotlib matplotlib.use('Agg') import os import heapq import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.colors as colors import matplotlib.cm as cm from numpy import * from ran...
Returns ---------- (file_handle, filename, metadata) See `modulegraph._find_module()` for details. Raises ---------- ImportError If this module is _not_ found. """ if parent is not None: # assert path is not None fullname = parent.identifier + '.' + name else: fullname = name node = self.findNode(fulln...
= [strategies]*self.num_reservoirs if type(spectral_scales) not in [list, np.ndarray]: spectral_scales = [spectral_scales]*self.num_reservoirs if type(offsets) not in [list, np.ndarray]: offsets = [offsets]*self.num_reservoirs if sparsities is not None: assert len(sparsities) == self.num_reservoirs else: sparsi...
True elif reply == QMessageBox.Cancel: self.saveToken = False if self.saveToken: for f in os.listdir('temp_audio'): os.remove('temp_audio\%s' % f) cmd = ['ffmpeg.exe', '-i', videoPath] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() try: for l in p.stdout.readlines(): # FF...
the new symmetry blocks to be added to the `basis_dict` attribute of the class, as dictionaries or `hamiltonian` objects. basis_con : :obj:`basis` Basis constructor used to build the basis objects to create the new block diagonal Hamiltonians. basis_args : tuple This argument is passed as the first arg...
from sys import exit import pygame import MathStuff as MATH import GUICreator StaticButton = GUICreator.StaticButton DynamicButton = GUICreator.DynamicButton StaticTextButton = GUICreator.StaticTextButton DynamicTextButton = GUICreator.DynamicTextButton class MathStuffGUI: """Create a GUI for my calculators.""" ...
from PIL import Image from PIL import ImageChops import datetime import screenshooter.saves class Differ: """ Differ is a service that allows the diffing of images. """ def __init__(self, user_config): if user_config is None: raise UnboundLocalError("A configuration file has not been referenced, please provide...
# -*- coding: utf-8 -*- """Copie de DLII_project.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1c4gMlzfMedMPnITOScXl3ihKCval8Rtk """ colab = True if colab: from google_drive_downloader import GoogleDriveDownloader as gdd gdd.download_file_from_g...
an Array if comma delimited string is passed, and it must contain an even number of values. :type op_Timestamp: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_Timestamp: If op_Timestamp is specified, the field named in this input will be com...
###%file:dart_kernel.py # # MyBatch Jupyter Kernel # generated by MyPython # from math import exp from queue import Queue from threading import Thread from ipykernel.kernelbase import Kernel from pexpect import replwrap, EOF from jinja2 import Environment, PackageLoader, select_autoescape,Template from abc import ABCMe...
import re import collections from enum import Enum from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI...
= drone_1.position[5] except IndexError: print("map was nut fully updated yet") class Local_Map: def __init__(self, resolution, map_origin, map_matrix): self.resolution = resolution # width, height, pixel_size self.map_origin = map_origin # [x,y,z, x,y,z,w] x, y, z and orientation: x, y, z, w self.map_matrix =...
<reponame>ocobacho/flexx """ HVLayout The HVLayout and its subclasses provide a simple mechanism to horizontally or vertically stack child widgets. This can be done in different *modes*: box mode is suited for aligning content where natural size matters. The fix mode and split mode are more suited for high-level layou...
# 11. Conference Win Pct. df_tenure['Win_Pct_Conf'] = df_tenure.apply( lambda row: row['W_Conf'] / row['G_Conf'] if row['G_Conf'] != 0 else 0, axis = 1) # if (len(df_tenure) == 1) and (int(df_tenure['G_Conf']) == 0): # df_tenure['Win_Pct_Conf'] = 0 # else: # df_tenure['Win_Pct_Conf'] = df_tenure.apply(lambda row:...
#!/usr/bin/env python # To do: # - Allow choice of gene label. # - Make transparent background. # - What if there are nan's in the probability file? """ Classes: ClusterData PlotLayout Holds layouts for each individual pieces of the plot. HeatmapLayout ColorbarLayout DendrogramLayout GeneDendrogramLayout ArrayDendr...
* gradient(theta, scaling_params['range_min'], scaling_params['range_max']) ) # Step error function elif config['angular_scaling']['err_func_type'] == "step": scaling_params = config['angular_scaling']['step'] break_points = list(zip(scaling_params['transition_pos'], scaling_params['transition_widths'])) self...
create the storages versions. """ print("Realizing setup...") # read, load, adjust configs from the file self._load_config() # check and load config file self._setup_logger() self.logger.info("Continuing setup...") self._load_app_key() self.logger.debug("Creating local storage...") self.local_storage = localst...
<reponame>typeworld/appengine # project import typeworldserver from typeworldserver import mq from typeworldserver import definitions from typeworldserver import classes from typeworldserver import helpers # other from google.cloud import ndb import logging import typeworld import typeworld.client import time import u...
import json import boto3 from datetime import datetime, timedelta from botocore.exceptions import ClientError import os import time def get_message_for_slack(event_details, event_type, affected_accounts, affected_entities, slack_webhook): message = "" summary = "" if slack_webhook == "webhook": if len(affected_en...
<filename>dev/archery/archery/release.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Versi...
"z", "delta", "extent", "origin"] # self.nlevels = 7 self.set_max_nlevels = 8 self.list_nlevels = [0 for it in range(len(self.list_iterations))] # storage self.dfile_matrix = [0 for it in range(len(self.list_iterations))] self.grid_matrix = [0 for it in range(len(self.list_iterations))] self.grid_data_matri...
self._leakDetector._index2containerId2len[self._index] = {} ids = self._leakDetector.getContainerIds() # record the current len of each container for objId in ids: yield None try: for result in self._leakDetector.getContainerByIdGen(objId): yield None container = result except Exception, e: # this container n...
<reponame>coldfix/probnum """ Continuous-Time priors for ODE solvers. Currently, they are only relevant in the context of ODEs. If needed in a more general setting, it is easy to move them to statespace module (->thoughts?) Matern will be easy to implement, just reuse the template provided by IOUP and change paramete...
self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input...
# Copyright (c) 2014 Evalf # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, s...
2} else: self.bands_rgb = {} for k in bands_rgb.keys(): band = bands_rgb[k] ind = band_prefixes.index(band) self.bands_rgb[k] = ind else: for f in self.files: extension = f.split('.')[-1] if extension == 'fz' or extension == 'gz': extension = '.'.join(f.split('.')[-2:]) if extension in self.known_file_types...
# pylint: disable=invalid-name """ SAS generic computation and sld file readers """ from __future__ import print_function import os import sys import copy import logging from periodictable import formula from periodictable import nsf import numpy as np from . import _sld2i from .BaseComponent import BaseComponent l...
Electric (Australia)", "000C82": "NETWORK TECHNOLOGIES INC", "000C83": "Logical Solutions", "000C84": "Eazix, Inc.", "000C85": "CISCO SYSTEMS, INC.", "000C86": "CISCO SYSTEMS, INC.", "000C87": "AMD", "000C88": "Apache Micro Peripherals, Inc.", "000C89": "AC Electric Vehicles, Ltd.", "000C8A": "Bose Co...
<gh_stars>0 import sys import os import glob import time from warnings import warn from threading import Event from threading import Timer from threading import Thread from threading import Lock import subprocess from astropy import units as u import Pyro4 from pocs.utils import current_time from pocs.utils.logger im...
do corpo lúteo'), ('N83.2', 'Outros cistos ovarianos e os não especificados'), ('N83.3', 'Atrofia adquirida do ovário e da trompa de Falópio'), ('N83.4', 'Prolapso e hérnia do ovário e da trompa de Falópio'), ('N83.5', 'Torção do ovário, do pedículo ovariano e da trompa de Falópio'), ('N83.6', 'Hematossalpinge'), ...
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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 l...
function: ascardlist() try: self.cat_name = cards['CAT-NAME'] return hdu except KeyError: try: self.cat_name = cards['EXTNAME'] return hdu except KeyError: self.cat_name = self.class_module.catid pass #No CAT-NAME or EXTNAME found, just return second HDU if len(fits_cat)>=2: return fits_cat[1] #Only one H...
<gh_stars>1-10 import caffe from caffe import layers as L from caffe import params as P def fc_relu_drop(bottom, fc_param, dropout_ratio=0.5): fc = L.InnerProduct(bottom, num_output=fc_param['num_output'], param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type=fc_param['weigh...
parameter `name` when calling `proxy_get_namespaced_node`") resource_path = '/api/v1/proxy/nodes/{name}'.replace('{format}', 'json') method = 'GET' path_params = {} if 'name' in params: path_params['name'] = params['name'] query_params = {} header_params = {} form_params = {} files = {} body_params = No...
transaction_type: ty.Literal[ "withdrawal", "deposit", "transfer", "reconciliation", "opening balance" ] date: datetime value_date: datetime amount: float description: str source_id: ty.Optional[int] = None source_name: ty.Optional[str] = None destination_id: ty.Optional[int] = None destination_name: ty.Optio...
<filename>examples/paper_replication/runner.py import datetime import logging import os import random import shutil import sys from collections import OrderedDict import numpy as np import pandas as pd import torch import fire import tqdm import util from aum import AUMCalculator from losses import losses from models...
(bool): Right button status. mbutton (bool): Middle button status. lbutton_pressed (bool): Left button pressed event. rbutton_pressed (bool): Right button pressed event. mbutton_pressed (bool): Middle button pressed event. wheel_up (bool): Wheel up event. wheel_down (bool): Wheel down event. """ def __init__(s...
baton, char relpath, char name, svn_string_t value, apr_pool_t pool) -> svn_error_t """ return apply(_ra.svn_ra_invoke_get_wc_prop_func, args) def svn_ra_invoke_set_wc_prop_func(*args): """ svn_ra_invoke_set_wc_prop_func(svn_ra_set_wc_prop_func_t _obj, void baton, char path, char name, svn_string_t value, apr_...
== "'": # Remove padding \x00 in the value string ValStr = "'%s'" % ValStr[1:-1].rstrip('\x00') Struct = ConfigDict['struct'] if Struct in self._StructType: # Format the array using its struct type Unit = int(Struct[4:]) // 8 Value = Array2Val(ConfigDict['value']) Loop = ConfigDict['length'] // Unit ...
from exchangelib import Q, Message, ExtendedProperty from exchangelib.errors import ErrorDeleteDistinguishedFolder, ErrorObjectTypeChanged, DoesNotExist, \ MultipleObjectsReturned, ErrorItemSave, ErrorItemNotFound from exchangelib.folders import Calendar, DeletedItems, Drafts, Inbox, Outbox, SentItems, JunkEmail, Mess...
"hum_frac = br_mr*0+0.64" '+tmpdir+'/clm_params.nc '+tmpdir+'/clm_params.nc') os.system(myncap+' -O -s "humhol_dist = br_mr*0+1.0" '+tmpdir+'/clm_params.nc '+tmpdir+'/clm_params.nc') os.system(myncap+' -O -s "qflx_h2osfc_surfrate = br_mr*0+1.0e-7" '+tmpdir+'/clm_params.nc '+tmpdir+'/clm_params.nc') os.system(myncap+...
import argparse import json import logging import os import os.path import time import argcomplete import jmespath import keyring import requests from rich.console import Console from rich.logging import RichHandler from rich.prompt import Confirm, Prompt from rich.table import Table import csv import io import yaml...
any(v < 0 for v in token_weights.values()): max_v = max(token_weights.values()) return {t:math.exp(v - max_v) for (t,v) in token_weights.items()} else: return token_weights def inverse(token_weights): '''Make small values big and big values small. All will be positive in the end, in range (1,+Infty). >>> ppri...
close(). try: message1 = "" message2 = "" with newzgy.ZgyReader(filename, iocontext = SDCredentials()) as reader: reader._fd.xx_close() reader._fd = "oops" raise RuntimeError("xyzzy") except Exception as ex: message1 = str(ex) message2 = str(ex.__cause__ or ex.__context__) assert message1.find("object has no...
# AMZ-Driverless # Copyright (c) 2019 Authors: # - <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, co...
<gh_stars>0 #!/usr/bin/env python2.7 # Copyright 2017 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This tool takes in multiple manifest files: * system image and archive manifest files from each package * Zircon's b...
def test_rm_doesnt_break_cache(self): """ Test building, removing then rebuilding a package. The package should be correctly rebuilt. """ mydir = os.path.dirname(__file__) build_path = os.path.join(mydir, './build_simple.yml') command.build('foo/bar', build_path) command.rm('foo/bar', force=True) teststore = ...
# Copyright 2020 Accenture Global Solutions Limited # # 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 agr...
test ' + test) #TODO if test=='015811':log('WARNING: skip test ' + test) #TODO if test=='015812':log('WARNING: skip test ' + test) #TODO if test=='015813':log('WARNING: skip test ' + test) #TODO if test=='015814':log('WARNING: skip test ' + test) #TODO if test=='015815':log('WARNING: skip test ' + test) #TODO if ...
from abc import ABC, abstractmethod from typing import Callable, List, Union import numpy as np from torch import Tensor from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader # Supported types of loss and metrics values: MetricValueType = Union[int, float, np.ndarray, T...
from abc import ABCMeta, abstractmethod from six import add_metaclass from cogitare.core.model import Model from cogitare.utils import not_training, training @add_metaclass(ABCMeta) class SequentialModel(Model): """ .. warning:: This module is experimental and its interface may change in future releases. Sequenti...
= subprocess.check_output(['ioreg', '-rd1', '-c', 'IOPlatformExpertDevice']) ret = re.search('"IOPlatformSerialNumber" = "(.*)"', output) if ret: return ret.group(1) # Try factory device id try: import factory_common # pylint: disable=unused-variable from cros.factory.test import testlog_goofy return testlog_...
#!/usr/bin/env python from __future__ import division, absolute_import, print_function import numpy as np from scipy import interpolate, signal def xkcd_line(x, y, xlim=None, ylim=None, mag=1.0, f1=30, f2=0.05, f3=15): """ Mimic a hand-drawn line from (x, y) data Definition ---------- def xkcd_line(x, y, xlim=N...
<gh_stars>10-100 # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details. # # Distributed under the terms of the BSD license. # # The full license is in the file LICENCE, distributed with this software. ...
<reponame>awgu/tutorials """ Language Modeling with nn.Transformer and TorchText =============================================================== This is a tutorial on training a sequence-to-sequence model that uses the `nn.Transformer <https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html>`__ module. Th...
import numpy as np import typing as _typing import torch import pickle from autogl.module.model.encoders.base_encoder import AutoHomogeneousEncoderMaintainer from ..model import ( EncoderUniversalRegistry, DecoderUniversalRegistry, BaseEncoderMaintainer, BaseDecoderMaintainer, BaseAutoModel, ModelUniversalRegi...
<gh_stars>0 import sys import math class IV: def IV(t): H = [int('6a09e667f3bcc908', 16) ^ int('a5a5a5a5a5a5a5a5', 16), int('bb67ae8584caa73b', 16) ^ int('a5a5a5a5a5a5a5a5', 16), int('3c6ef372fe94f82b', 16) ^ int('a5a5a5a5a5a5a5a5', 16), int('a54ff53a5f1d36f1', 16) ^ int('a5a5a5a5a5a5a5a5', 16), int('510e527fade...
error_message self.name = name self.region_id = region_id self.state = state self.update_time = update_time self.version = version self.vpc_id = vpc_id self.sg_id = sg_id self.cluster_domain = cluster_domain def validate(self): self.validate_required(self.cluster_id, 'cluster_id') self.validate_required(sel...
from typing import Any, Dict, Iterable, List, Optional, Tuple, Callable from math import pi as π from sympy import Matrix as Mat from numpy import ndarray from physical_education.links import Link3D, constrain_rel_angle from physical_education.system import System3D from physical_education.foot import add_foot, feet, ...
type(json) is unicode) and len(json) > 0: if json[0] == '@': # It's a variable, we replace it with the JSON data # It will return an error if the variable doesn't exist, it's intended varName = json[1:] if varData.has_key(varName): return preprocessJson(varData[varName], varData) else: raise Exception("varData ...
import math from collections import OrderedDict import logging logger = logging.getLogger(__name__) import numpy as np import torch import tensorflow as tf from paragen.generators import AbstractGenerator, register_generator from paragen.utils.io import remove from paragen.utils.runtime import Environment @register...
<reponame>MarkusRJK/IEC-60601-1-8<filename>low_prio_sound_gen.py<gh_stars>1-10 #!/usr/bin/python from __future__ import division from wavtools import getVolumes from wavtools import volumesOutOfDbRange from wavtools import hasEnoughHarmonics from wavtools import hasSignificantVolumesInsideDbRange from wavtools import...
# Copyright (c) 2018-2021, Texas Instruments # All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions ...
#!/usr/bin/env python """ Scheduling tactician. """ import os import logging import numpy as np import ephem from collections import OrderedDict as odict from obztak import get_survey from obztak.utils.projector import angsep from obztak.utils import projector as proj from obztak.ctio import CTIO from obztak.utils i...
<reponame>junxnone/aerial_wildlife_detection<filename>modules/UserHandling/backend/middleware.py ''' Provides functionality for checking login details, session validity, and the like. 2019-20 <NAME> ''' from threading import Thread from modules.Database.app import Database import psycopg2 from psycopg2 import sql ...
this statement to submit a prize.' ) return value def clean(self): return self.cleaned_data def save(self, event, handler=None): provider = '' if handler and handler.username != handler.email: provider = handler.username prize = models.Prize.objects.create( event=event, name=self.cleaned_data['name'], des...
@validate_api_v2 @request_error_handler def bulk_delete_hosts_tag(self, tag, host_ids): """ Delete a tag in bulk on multiple hosts. Only one tag can be deleted at a time :param host_ids: IDs of the hosts on which to delete the tag """ if not isinstance(host_ids, list): raise TypeError('Host IDs must be of type ...
= self.rqdata.taskData.fn_index[self.rqdata.runq_fnid[task]] the_data = bb.cache.Cache.loadDataFull(fn, self.cooker.collection.get_file_appends(fn), self.cooker.data) done.add(self.rqdata.runq_fnid[task]) bb.parse.siggen.dump_sigs(self.rqdata.dataCache, options) return def print_diffscenetasks(self): valid = ...
<filename>fastatomography/operators/default_ops.py<gh_stars>1-10 # coding=utf-8 # Copyright 2014-2019 The ODL contributors # # This file is part of ODL. # # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain o...
<reponame>mikeireland/chronostar """ A module containing all the required functions to evaluate the Bayesian posterior of a Component model given the data. The entry point function lnprob_func yields a score (higher is better) for a given model for the data. This function can be given to an emcee Sampler object for th...
* (pt.y - outPt2.pt.y) / (outPt2.prevOp.pt.y - outPt2.pt.y) + outPt2.pt.x ): result = not result outPt2 = outPt2.nextOp if outPt2 == outPt: break def _Poly2ContainsPoly1(outPt1, outPt2): pt = outPt1 if _PointOnPolygon(pt.pt, outPt2): pt = pt.nextOp while pt != outPt1 and _PointOnPolygon(pt.pt, outPt2): pt...