repository_name
stringlengths
7
107
function_path
stringlengths
4
190
function_identifier
stringlengths
1
236
language
stringclasses
1 value
function
stringlengths
9
647k
docstring
stringlengths
5
488k
function_url
stringlengths
71
285
context
stringlengths
0
2.51M
license
stringclasses
5 values
quantopian/qdb
qdb/comm.py
RemoteCommandManager.command_list
python
def command_list(self, tracer, payload): if not self.payload_check(payload, 'list'): return self.next_command.tailcall(tracer) filename = payload.get('file') or tracer.default_file try: if tracer.skip_fn(filename): raise KeyError if not (payl...
List the contents of a file and defer to user control.
https://github.com/quantopian/qdb/blob/c25018d2f0979589a38a07667478cb6022d57ed9/qdb/comm.py#L556-L599
from __future__ import print_function from abc import ABCMeta, abstractmethod import atexit from bdb import Breakpoint import errno from functools import partial import json import os from pprint import pprint import signal import socket from struct import pack, unpack from textwrap import dedent from logbook import Lo...
Apache License 2.0
dojoteef/dvae
dvae/models/factory.py
ModelFactoryFunction.define_model
python
def define_model(self, graph, reuse=None, **kwargs): pass
Return a new model.
https://github.com/dojoteef/dvae/blob/93665f17b346a3f42dea7c607e4c5f8365b5895d/dvae/models/factory.py#L91-L93
from __future__ import absolute_import from __future__ import division from __future__ import print_function from abc import abstractmethod from abc import abstractproperty from abc import ABCMeta as AbstractBaseClass from six import iteritems from six.moves import xrange import tensorflow as tf from dvae.datasets.da...
Apache License 2.0
speleo3/pymol-psico
psico/electrostatics.py
validate_apbs_exe
python
def validate_apbs_exe(exe): import os, subprocess if exe: exe = cmd.exp_path(exe) else: try: import freemol.apbs exe = freemol.apbs.get_exe_path() except: pass if not exe: exe = cmd.exp_path('$SCHRODINGER/utilities/apbs') ...
Get and validate apbs executable. Raise CmdException if not found or broken.
https://github.com/speleo3/pymol-psico/blob/4e5402b4dca9a509b34a03691f12dc49e93c4973/psico/electrostatics.py#L47-L73
from __future__ import print_function from pymol import cmd, CmdException template_apbs_in = ''' read mol pqr "{pqrfile}" end elec mg-auto mol 1 fgcent {fgcent} # fine grid center cgcent mol 1 # coarse grid center fglen {fglen} cglen {cglen} dime {dime} lpbe # l=linear, n...
BSD 2-Clause Simplified License
harmon758/harmonbot
Discord/cogs/cryptography.py
Cryptography.encode_blake2b
python
async def encode_blake2b(self, ctx, *, message: str): digest = crypto_hashes.Hash(crypto_hashes.BLAKE2b(64), backend = openssl_backend) digest.update(message.encode("UTF-8")) await ctx.embed_reply(digest.finalize())
64-byte digest BLAKE2b
https://github.com/harmon758/harmonbot/blob/def3849beabdaea5e0f9c594dcf6d6d8980782bd/Discord/cogs/cryptography.py#L175-L179
from discord.ext import commands import hashlib import sys from typing import Optional import zlib from cryptography.hazmat.backends.openssl import backend as openssl_backend from cryptography.hazmat.primitives import hashes as crypto_hashes import pygost.gost28147 import pygost.gost28147_mac import pygost.gost34112012...
MIT License
jaegertracing/jaeger-client-python
jaeger_client/thrift_gen/jaeger/Collector.py
Client.submitBatches
python
def submitBatches(self, batches): self._seqid += 1 future = self._reqs[self._seqid] = concurrent.Future() self.send_submitBatches(batches) return future
Parameters: - batches
https://github.com/jaegertracing/jaeger-client-python/blob/a6c973158bf9b02cd7f5a966ccfd29ab86c44a5b/jaeger_client/thrift_gen/jaeger/Collector.py#L70-L78
import six from six.moves import xrange from thrift.Thrift import TType, TMessageType, TException, TApplicationException import logging from .ttypes import * from thrift.Thrift import TProcessor from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol im...
Apache License 2.0
zhaozhibin/dl-based-intelligent-diagnosis-benchmark
AE_Datasets/R_NA/datasets/XJTU.py
data_load
python
def data_load(filename,label): fl = pd.read_csv(filename) fl = fl["Horizontal_vibration_signals"] fl = fl.values fl = fl.reshape(-1,1) data=[] lab=[] start,end=0,signal_size while end<=fl.shape[0]: data.append(fl[start:end]) lab.append(label) start +=signal_size ...
This function is mainly used to generate test data and training data. filename:Data location
https://github.com/zhaozhibin/dl-based-intelligent-diagnosis-benchmark/blob/6dca48f36c2a0bceaad8329089100045fe440bbb/AE_Datasets/R_NA/datasets/XJTU.py#L53-L70
import os import pandas as pd from sklearn.model_selection import train_test_split from datasets.SequenceDatasets import dataset from datasets.sequence_aug import * from tqdm import tqdm signal_size=1024 label1 = [i for i in range(0,5)] label2 = [i for i in range(5,10)] label3 = [i for i in range(10,15)] def get_files(...
MIT License
micom-dev/micom
micom/community.py
Community.__init__
python
def __init__( self, taxonomy, model_db=None, id=None, name=None, rel_threshold=1e-6, solver=None, progress=True, max_exchange=100, mass=1, ): super(Community, self).__init__(id, name) logger.info("building new micom mode...
Create a new community object. `micom` builds a community from a taxonomy which may simply be a list of model files in its simplest form. Usually, the taxonomy will contain additional information such as annotations for the individuals (for instance phylum, organims or species) and abun...
https://github.com/micom-dev/micom/blob/b8e3eda8a97ed2fe08e1416711d3a4f1f98bc3a9/micom/community.py#L40-L299
import re import pickle import cobra import pandas as pd from optlang.symbolics import Zero from micom.db import load_zip_model_db, load_manifest from micom.util import ( load_model, join_models, add_var_from_expression, adjust_solver_config, clean_ids, compartment_id, COMPARTMENT_RE, ) from...
Apache License 2.0
geophysics-ubonn/reda
lib/reda/eis/units.py
get_label
python
def get_label(parameter, ptype, flavor=None, mpl=None): if flavor is not None: if flavor not in ('latex', 'mathml'): raise Exception('flavor not recognized: {}'.format(flavor)) else: if mpl is None: raise Exception('either the flavor or mpl must be provided') rend...
Return the label of a given SIP parameter Parameters ---------- parameter : str type of parameter, e.g. rmag|rpha|cre|cim ptype : string material|meas. Either return the material property (e.g. resistivity) or the measurement parameter (e.g., impedance) flavor : string, opti...
https://github.com/geophysics-ubonn/reda/blob/5be52ecb184f45f0eabb23451f039fec3d9537c5/lib/reda/eis/units.py#L47-L90
labels = { 'rmag': { 'material': { 'latex': r'$|\rho|~[\Omega m]$', 'mathml': r'$|\rho| [\Omega m]$', }, 'meas': { 'latex': r'$|Z|~[\Omega]$', 'mathml': r'$|Z| [\Omega]$', }, }, 'rpha': { 'material': { 'latex...
MIT License
microsoft/univl
modules/until_module.py
PreTrainedModel.from_pretrained
python
def from_pretrained(cls, config, state_dict=None, *inputs, **kwargs): model = cls(config, *inputs, **kwargs) if state_dict is None: return model model = cls.init_preweight(model, state_dict) return model
Instantiate a PreTrainedModel from a pre-trained model file or a pytorch state dict. Download and cache the pre-trained model file if needed.
https://github.com/microsoft/univl/blob/0a7c07f566a3b220731f4abcaa6e1ee59a686596/modules/until_module.py#L166-L177
import logging import numpy as np import torch from torch import nn import torch.nn.functional as F import math from modules.until_config import PretrainedConfig logger = logging.getLogger(__name__) def gelu(x): return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) def swish(x): return x * torch.sigmoid(x) ACT...
MIT License
genomoncology/related
src/related/validators.py
regex
python
def regex(match_string): return _RegexValidator(match_string)
A validator that executes each validator passed as arguments.
https://github.com/genomoncology/related/blob/3799cde862b8c9500931706f5f1ce5576028f642/src/related/validators.py#L42-L46
from attr import attr, attributes import re @attributes(repr=False, slots=True) class _CompositeValidator(object): validators = attr() def __call__(self, inst, attr, value): for validator in self.validators: validator(inst, attr, value) def __repr__(self): return ( "<...
MIT License
iperdance/ipercore
iPERCore/tools/trainers/lwg_trainer.py
LWGTrainer.optimize_D
python
def optimize_D(self, fake_bg, fake_tsf_imgs): bs, nt, c, h, w = fake_tsf_imgs.shape fake_tsf_imgs = fake_tsf_imgs.view(bs * nt, c, h, w) real_tsf_imgs = self._real_tsf.reshape(bs * nt, c, h, w) tsf_cond = self._input_G_tsf[:, :, -3:].view(bs * nt, -1, h, w) fake_input_D = torch.c...
Args: fake_bg (torch.Tensor): fake_tsf_imgs (torch.Tensor): Returns:
https://github.com/iperdance/ipercore/blob/1c15b8208a4313c91ce6bf7a97a15fe43cee4a74/iPERCore/tools/trainers/lwg_trainer.py#L791-L832
import abc import torch import torch.nn.functional as F from collections import OrderedDict from iPERCore.models.networks import NetworksFactory from iPERCore.models.networks.criterions import VGGLoss, FaceLoss, LSGANLoss, TVLoss, TemporalSmoothLoss from iPERCore.tools.utils.filesio.cv_utils import tensor2im from .base...
Apache License 2.0
demetoir/allgans
util/Stacker.py
Stacker.max_pooling
python
def max_pooling(self, filter_): return self.add_layer(max_pooling, filter_)
add max pooling layer
https://github.com/demetoir/allgans/blob/2f972db5e9a65f18aee0695d817f4acc221e54da/util/Stacker.py#L104-L106
from util.tensor_ops import * class Stacker: def __init__(self, start_layer=None, reuse=False, name="stacker"): self.reuse = reuse self.layer_count = 1 self.last_layer = start_layer self.layer_seq = [start_layer] self.name = name def add_layer(self, func, *args, **kwargs)...
MIT License
paddlepaddle/paddle
python/paddle/fluid/entry_attr.py
EntryAttr._to_attr
python
def _to_attr(self): raise NotImplementedError("EntryAttr is base class")
Returns the attributes of this parameter. Returns: Parameter attributes(map): The attributes of this parameter.
https://github.com/paddlepaddle/paddle/blob/056b87414880e0520bb4560fc40d5b62db9c5175/python/paddle/fluid/entry_attr.py#L31-L38
from __future__ import print_function __all__ = ['ProbabilityEntry', 'CountFilterEntry'] class EntryAttr(object): def __init__(self): self._name = None
Apache License 2.0
garoe/tf_mvg
mvg_distributions/covariance_representations/covariance_conv.py
PrecisionConvCholFilters.np_off_diag_mask
python
def np_off_diag_mask(self): assert self.recons_filters_precision.shape[1:3].is_fully_defined() n = self.recons_filters_precision.shape[1].value n_width = int(np.sqrt(n)) nb = self.recons_filters_precision.shape[2].value nf = int(np.sqrt(nb)) kernel = np.zeros((nf, nf), dt...
Returns a ndarray of [n,n] that is 1 of the off-diagonal elements in L
https://github.com/garoe/tf_mvg/blob/01bc681a8b3aac5dcf0837d481b963f4968eb777/mvg_distributions/covariance_representations/covariance_conv.py#L567-L585
import numpy as np import tensorflow as tf from mvg_distributions.covariance_representations.covariance_matrix import Covariance, SampleMethod from mvg_distributions.utils.variable_filter_functions import conv2d_samples_linear_combination_filters from mvg_distributions.utils.unpooling import unpooling2d_zero_filled imp...
MIT License
redcokedevelopment/teapot.py
teapot/cogs/music.py
Music.queue
python
async def queue(self, ctx, page: int = 1): player = self.bot.lavalink.player_manager.get(ctx.guild.id) if not player.queue: return await ctx.send('Nothing queued.') items_per_page = 10 pages = math.ceil(len(player.queue) / items_per_page) start = (page - 1) * items_pe...
Shows the player's queue.
https://github.com/redcokedevelopment/teapot.py/blob/aa4e92d7a1bf6f997051ae3422ba52fc034e317b/teapot/cogs/music.py#L140-L160
import math import re import discord import lavalink from discord.ext import commands import teapot url_rx = re.compile('https?:\\/\\/(?:www\\.)?.+') class Music(commands.Cog): def __init__(self, bot): self.bot = bot if not hasattr(bot, 'lavalink'): bot.lavalink = lavalink.Client(bot...
MIT License
kirthevasank/nasbot
nn/nn_comparators.py
_get_conv_filter_size_cost
python
def _get_conv_filter_size_cost(labi, labj, conv_scale): conv_diff = float(abs(int(labi[-1]) - int(labj[-1]))) return conv_scale * np.sqrt(conv_diff)
Returns the cost for comparing two different convolutional filters.
https://github.com/kirthevasank/nasbot/blob/3c745dc986be30e3721087c8fa768099032a0802/nn/nn_comparators.py#L27-L30
import numpy as np from gp.kernel import ExpSumOfDistsKernel, SumOfExpSumOfDistsKernel from nn import neural_network from utils.oper_utils import opt_transport DFLT_TRANSPORT_DIST = 'lp' DFLT_CONN_COST_FUNC = 'linear' DFLT_KERN_DIST_POWERS = 1 REPLACE_COST_INF_WITH = 7.65432e5 CONV_RES_RAW_COST_FRAC = 0.9 CNN_STRUCTURA...
MIT License
aws/aws-iot-device-sdk-python
AWSIoTPythonSDK/core/greengrass/discovery/providers.py
DiscoveryInfoProvider.configureCredentials
python
def configureCredentials(self, caPath, certPath, keyPath): self._ca_path = caPath self._cert_path = certPath self._key_path = keyPath
**Description** Used to configure the credentials for discovery request. Should be called before the discovery request happens. **Syntax** .. code:: python myDiscoveryInfoProvider.configureCredentials("my/ca/path", "my/cert/path", "my/key/path") **Parameters** *ca...
https://github.com/aws/aws-iot-device-sdk-python/blob/a67eadfcbf9d229229b18435fb7a109685250854/AWSIoTPythonSDK/core/greengrass/discovery/providers.py#L145-L173
from AWSIoTPythonSDK.exception.AWSIoTExceptions import DiscoveryInvalidRequestException from AWSIoTPythonSDK.exception.AWSIoTExceptions import DiscoveryUnauthorizedException from AWSIoTPythonSDK.exception.AWSIoTExceptions import DiscoveryDataNotFoundException from AWSIoTPythonSDK.exception.AWSIoTExceptions import Disco...
Apache License 2.0
santhisenan/sdn_ddos_simulation
ddpg/replay_buffer.py
ReplayBuffer.sample_batch
python
def sample_batch(self, batch_size=32): _available_batch_length = self._count if self._count < batch_size else batch_size batch = random.sample(self._buffer, _available_batch_length) _states = np.array([_experience[0] for _experience in batch]) _actions = np.array([_experience[...
If the number of elements in the replay memory is less than the required batch_size, then return only those elements present in the memory, else return 'batch_size' number of elements.
https://github.com/santhisenan/sdn_ddos_simulation/blob/be0f812de4d2e0668f1266a71172948123e3750c/ddpg/replay_buffer.py#L24-L44
from collections import deque import random import numpy as np class ReplayBuffer(object): def __init__(self, buffer_size): self._buffer_size = buffer_size self._count = 0 self._buffer = deque() def insert(self, _experience): if(self._count <= self._buffer_size): sel...
MIT License
hyde/hyde
setup.py
find_package_data
python
def find_package_data( where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories, only_in_packages=True, show_ignored=False): out = {} stack = [(convert_path(where), '', package, only_in_packages)] while stack: where, pr...
Return a dictionary suitable for use in ``package_data`` in a distutils ``setup.py`` file. The dictionary looks like:: {'package': [files]} Where ``files`` is a list of all the files in that package that don't match anything in ``exclude``. If ``only_in_packages`` is true, then top-level...
https://github.com/hyde/hyde/blob/7f415402cc3e007a746eb2b5bc102281fdb415bd/setup.py#L26-L104
from setuptools import setup, find_packages from hyde.version import __version__ from distutils.util import convert_path from fnmatch import fnmatchcase import os import sys PROJECT = 'hyde' try: long_description = open('README.rst', 'rt').read() except IOError: long_description = '' standard_exclude = ('*.py',...
MIT License
openfun/marsha
src/backend/marsha/core/serializers/video.py
ThumbnailSerializer.get_urls
python
def get_urls(self, obj): if obj.uploaded_on: base = f"{settings.AWS_S3_URL_PROTOCOL}://{settings.CLOUDFRONT_DOMAIN}/{obj.video.pk}" urls = {} stamp = time_utils.to_timestamp(obj.uploaded_on) for resolution in settings.VIDEO_RESOLUTIONS: urls[resolu...
Urls of the thumbnail. Parameters ---------- obj : Type[models.Thumbnail] The thumbnail that we want to serialize Returns ------- Dict or None The urls for the thumbnail. None if the thumbnail is still not uploaded to S3 with success.
https://github.com/openfun/marsha/blob/550be08d7cad91579cd1cc2548ea95751113f15d/src/backend/marsha/core/serializers/video.py#L250-L272
from datetime import timedelta from urllib.parse import quote_plus from django.conf import settings from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils import timezone from django.utils.text import slugify from botocore.signers import CloudFrontSigner from rest_framework imp...
MIT License
compas-dev/compas
src/compas/datastructures/network/matrices.py
network_adjacency_matrix
python
def network_adjacency_matrix(network, rtype='array'): key_index = network.key_index() adjacency = [[key_index[nbr] for nbr in network.neighbors(key)] for key in network.nodes()] return adjacency_matrix(adjacency, rtype=rtype)
Creates a node adjacency matrix from a Network datastructure. Parameters ---------- network : obj Network datastructure object to get data from. rtype : {'array', 'csc', 'csr', 'coo', 'list'} Format of the result. Returns ------- array-like Constructed adjacency mat...
https://github.com/compas-dev/compas/blob/d795a8bfe9f21ffa124d09e37e9c0ed2e3520057/src/compas/datastructures/network/matrices.py#L33-L51
from __future__ import absolute_import from __future__ import division from __future__ import print_function from compas.numerical import adjacency_matrix from compas.numerical import degree_matrix from compas.numerical import connectivity_matrix from compas.numerical import laplacian_matrix __all__ = [ 'network_ad...
MIT License
laixintao/pingtop
pingtop/ping.py
checksum
python
def checksum(source_string): sum = 0 count_to = int((len(source_string) / 2) * 2) for count in range(0, count_to, 2): this = source_string[count + 1] * 256 + source_string[count] sum = sum + this sum = sum & 0xffffffff if count_to < len(source_string): sum = sum + ord(s...
I'm not too confident that this is right but testing seems to suggest that it gives the same answers as in_cksum in ping.c
https://github.com/laixintao/pingtop/blob/75353119db1af8635fec85a9bf38722e152c426c/pingtop/ping.py#L110-L134
__version__ = "0.2" import os import select import socket import struct import sys import time ICMP_ECHO_REQUEST = 8
MIT License
zimbra-community/python-zimbra
pythonzimbra/communication.py
Communication.gen_request
python
def gen_request(self, request_type="json", token=None, set_batch=False, batch_onerror=None): if request_type == "json": local_request = RequestJson() elif request_type == "xml": local_request = RequestXml() else: raise UnknownRequestType() ...
Convenience method to quickly generate a token :param request_type: Type of request (defaults to json) :param token: Authentication token :param set_batch: Also set this request to batch mode? :param batch_onerror: Onerror-parameter for batch mode :return: The request
https://github.com/zimbra-community/python-zimbra/blob/1b4b1e0650bfab52f8df402f217ad5873f01d610/pythonzimbra/communication.py#L59-L89
from __future__ import unicode_literals import sys if sys.version < '3': import urllib2 as ur import urllib2 as ue else: import urllib.request as ur import urllib.error as ue from pythonzimbra.request_json import RequestJson from pythonzimbra.request_xml import RequestXml from pythonzimbra.respo...
BSD 2-Clause Simplified License
partho-maple/coding-interview-gym
leetcode.com/python/457_Circular_Array_Loop.py
Solution.circularArrayLoop
python
def circularArrayLoop(self, nums): for i in range(len(nums)): is_forward = nums[i] >= 0 slow, fast = i, i while True: slow = self.find_next_index(nums, is_forward, slow) fast = self.find_next_index(nums, is_forward, fast) if (...
:type nums: List[int] :rtype: bool
https://github.com/partho-maple/coding-interview-gym/blob/f11c78b6e42d1014296fc0f360aa6fc530600493/leetcode.com/python/457_Circular_Array_Loop.py#L2-L26
class Solution(object):
MIT License
mpi4jax/mpi4jax
examples/shallow_water.py
get_initial_conditions
python
def get_initial_conditions(): u0_global = 10 * jnp.exp( -((yy_global - 0.5 * length_y) ** 2) / (0.02 * length_x) ** 2 ) v0_global = jnp.zeros_like(u0_global) coriolis_global = CORIOLIS_F + yy_global * CORIOLIS_BETA h_geostrophy = np.cumsum(-dy * u0_global * coriolis_global / GRAVITY, axis=0)...
For the initial conditions, we use a horizontal jet in geostrophic balance.
https://github.com/mpi4jax/mpi4jax/blob/e3ed6f00a5552099f260c6b1f68588917461403b/examples/shallow_water.py#L139-L170
import os import sys import math import time import warnings from contextlib import ExitStack from collections import namedtuple from functools import partial import numpy as np from mpi4py import MPI try: import tqdm except ImportError: warnings.warn("Could not import tqdm, can't show progress bar") HAS_TQ...
MIT License
elsonidoq/fito
fito/data_store/base.py
BaseDataStore.get_id
python
def get_id(self, spec): raise NotImplementedError()
Get's the internal id of a given spec, it should raise KeyError if spec not in self
https://github.com/elsonidoq/fito/blob/e76ab0a9a4eb954b6d88c190cb57d112f94739e1/fito/data_store/base.py#L82-L86
from fito import config import warnings from functools import wraps from fito import Spec from fito.data_store.rehash_ui import RehashUI from fito.operation_runner import FifoCache, OperationRunner from fito.operations.decorate import as_operation from fito.specs.base import get_import_path from fito.specs.fields impor...
MIT License
dedsecinside/awesome-scripts
APIs/Telegram API/telethon/client/telegrambaseclient.py
TelegramBaseClient._create_exported_sender
python
async def _create_exported_sender(self: 'TelegramClient', dc_id): dc = await self._get_dc(dc_id) sender = MTProtoSender(None, loggers=self._log) await sender.connect(self._connection( dc.ip_address, dc.port, dc.id, loggers=self._log, pr...
Creates a new exported `MTProtoSender` for the given `dc_id` and returns it. This method should be used by `_borrow_exported_sender`.
https://github.com/dedsecinside/awesome-scripts/blob/856835e5ff5f8a6af2d74bb25800c620feb712e3/APIs/Telegram API/telethon/client/telegrambaseclient.py#L666-L693
import abc import re import asyncio import collections import logging import platform import time import typing from .. import version, helpers, __name__ as __base_name__ from ..crypto import rsa from ..entitycache import EntityCache from ..extensions import markdown from ..network import MTProtoSender, Connection, Con...
MIT License
libcity/bigscity-libcity-datasets
old_backup/nyc_taxi_od.py
convert_to_trajectory
python
def convert_to_trajectory(df): start = df[['drive_id', 'PULocationID', 'tpep_pickup_datetime']] end = df[['drive_id', 'DOLocationID', 'tpep_dropoff_datetime']] start.columns = ['driveid', 'geo_id', 'time_str'] end.columns = ['driveid', 'geo_id', 'time_str'] trajectory_data = pd.concat((start, end), ...
:param df: all data :return: df['driveid', 'geo_id', 'time', 'timestamp']
https://github.com/libcity/bigscity-libcity-datasets/blob/9d686af4731d7db821298345734926c0437703e6/old_backup/nyc_taxi_od.py#L95-L107
import json import math import os from datetime import datetime import numpy as np import pandas as pd old_time_format = '%Y-%m-%d %H:%M:%S' new_time_format = '%Y-%m-%dT%H:%M:%SZ' def get_data_url(input_dir_flow, start_year, start_month, end_year, end_month): pattern = input_dir_flow + "/yellow_tripdata_%d-%02d.csv...
Apache License 2.0
ericsson/codechecker
codechecker_common/skiplist_handler.py
SkipListHandler.__call__
python
def __call__(self, source_file_path: str) -> bool: return self.should_skip(source_file_path)
Check if the given source should be skipped.
https://github.com/ericsson/codechecker/blob/d2db1b49e8a2b775d41436406b5a2e5d9af76c0f/codechecker_common/skiplist_handler.py#L105-L109
import fnmatch import re import os from codechecker_common.logger import get_logger LOG = get_logger('system') class SkipListHandler: def __init__(self, skip_file_content=""): self.__skip = [] if not skip_file_content: skip_file_content = "" self.__skip_file_lines = [line.strip()...
Apache License 2.0
docusign/docusign-python-client
docusign_esign/models/commission_number.py
CommissionNumber.anchor_x_offset
python
def anchor_x_offset(self): return self._anchor_x_offset
Gets the anchor_x_offset of this CommissionNumber. # noqa: E501 Specifies the X axis location of the tab, in anchorUnits, relative to the anchorString. # noqa: E501 :return: The anchor_x_offset of this CommissionNumber. # noqa: E501 :rtype: str
https://github.com/docusign/docusign-python-client/blob/c6aeafff0d046fa6c10a398be83ba9e24b05d4ea/docusign_esign/models/commission_number.py#L803-L811
import pprint import re import six from docusign_esign.client.configuration import Configuration class CommissionNumber(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute n...
MIT License
lsapan/docker-swarm-demo
secrets.py
secret
python
def secret(name, strip=True): with open(secret_path(name), 'r') as f: val = f.read() if strip: val = val.strip() return val
Returns the value of a secret from the docker container.
https://github.com/lsapan/docker-swarm-demo/blob/f6b905fbbbe4b74d62a4af664f9a677f3cb03b8e/secrets.py#L18-L26
import os class SecretNotFoundError(IOError): pass def secret_path(name): secret_path = f'/run/secrets/{name}' if not os.path.isfile(secret_path): raise SecretNotFoundError(name) return secret_path
MIT License
uvjustin/alarmdotcom
custom_components/alarmdotcom/alarm_control_panel.py
AlarmDotCom._validate_code
python
def _validate_code(self, code): check = self._code is None or code == self._code if not check: _LOGGER.warning("Wrong code entered") return check
Validate given code.
https://github.com/uvjustin/alarmdotcom/blob/8b7288bfd1c21a5687cd2359753f0d2efceca726/custom_components/alarmdotcom/alarm_control_panel.py#L215-L220
import logging import re from pyalarmdotcomajax import Alarmdotcom, AlarmdotcomADT, AlarmdotcomProtection1 import voluptuous as vol import homeassistant.components.alarm_control_panel as alarm try: from homeassistant.components.alarm_control_panel import AlarmControlPanelEntity except ImportError: from homeassi...
MIT License
synbiodex/pysbol2
sbol2/componentdefinition.py
ComponentDefinition.linearize
python
def linearize(self, components=None): raise NotImplementedError("Not yet implemented")
TODO document :param components: An optional list of component definitions or URIs. If None, an empty list of ComponentDefinitions is assumed. :return: None
https://github.com/synbiodex/pysbol2/blob/127b92d60ecf6f9b6cb8fbf9657bb578bc983090/sbol2/componentdefinition.py#L887-L895
import os import posixpath from typing import Union from rdflib import URIRef from .component import Component from .config import Config, ConfigOptions from .constants import * from .toplevel import TopLevel from .property import OwnedObject, ReferencedObject, URIProperty from .sbolerror import SBOLError, SBOLErrorCod...
Apache License 2.0
flyteorg/flytekit
flytekit/models/literals.py
RetryStrategy.__init__
python
def __init__(self, retries): self._retries = retries
:param int retries: Number of retries to attempt on recoverable failures. If retries is 0, then only one attempt will be made.
https://github.com/flyteorg/flytekit/blob/6c032035563ae645b0b93558b3fe3362080057ea/flytekit/models/literals.py#L15-L20
from datetime import datetime as _datetime import pytz as _pytz from flyteidl.core import literals_pb2 as _literals_pb2 from google.protobuf.struct_pb2 import Struct from flytekit.common.exceptions import user as _user_exceptions from flytekit.models import common as _common from flytekit.models.core import types as _c...
Apache License 2.0
practical-data-science/ecommercetools
ecommercetools/utilities/metrics.py
average_tickets_to_resolve
python
def average_tickets_to_resolve(total_tickets, total_resolutions): return total_tickets / total_resolutions
Returns the average number of tickets required to resolve an issue. Args: total_tickets (int): Total chats, emails, or tickets in the period. total_resolutions (int): Total chats, emails, or tickets resolved in the period. Returns: Average number of tickets it takes to resolve an issue...
https://github.com/practical-data-science/ecommercetools/blob/b00175d7775dc4f6ad57b52702a0b2acce3425fc/ecommercetools/utilities/metrics.py#L732-L743
import math from datetime import datetime def tax(gross_revenue, tax_rate=0.2): return gross_revenue * tax_rate def net_revenue(gross_revenue, tax_rate=0.2): total_tax = tax(gross_revenue, tax_rate) return gross_revenue - total_tax def aov(total_revenue, total_orders): return total_revenue / total_order...
MIT License
rapid7/vm-console-client-python
rapid7vmconsole/models/review.py
Review.to_dict
python
def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value ...
Returns the model properties as a dict
https://github.com/rapid7/vm-console-client-python/blob/55e1f573967bce27cc9a2d10c12a949b1142c2b3/rapid7vmconsole/models/review.py#L181-L206
import pprint import re import six class Review(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition....
MIT License
googlecloudplatform/tensorflow-recommendation-wals
airflow/plugins/gae_admin_plugin.py
AppEngineAdminHook.get_version_identifiers
python
def get_version_identifiers(self, project_id, service_id): request = self._gaeadmin.apps().services().versions().list(appsId=project_id, servicesId=service_id) versions = [] while request is not None: versions_doc = request.execute() ...
Get list of versions of a service on App Engine Engine. Args: project_id: project id service_id: service id Returns: the list of version identifiers if successful and raises an error otherwise.
https://github.com/googlecloudplatform/tensorflow-recommendation-wals/blob/2116cd21e4cc77b7380cccc9fee6f2ed606119db/airflow/plugins/gae_admin_plugin.py#L121-L140
from airflow.contrib.hooks.gcp_api_base_hook import GoogleCloudBaseHook from airflow.exceptions import AirflowException from airflow.models import BaseOperator from airflow.plugins_manager import AirflowPlugin from airflow.utils.decorators import apply_defaults from apiclient.discovery import build from datetime import...
Apache License 2.0
ebagdasa/federated_adaptation
utils/text_load.py
Corpus.tokenize_train
python
def tokenize_train(self, path): files = os.listdir(path) per_participant_ids = list() per_participant_ids_test = list() per_participant_different_words = list() per_participant_voc_size = list() for file in tqdm(files[:self.authors_no]): if 'checkpoint' in fil...
We return a list of ids per each participant. :param path: :return:
https://github.com/ebagdasa/federated_adaptation/blob/0c0ae97445fddc635c427ae100854bc70a00a11c/utils/text_load.py#L49-L82
import os import torch import json import re from tqdm import tqdm import random filter_symbols = re.compile('[a-zA-Z]*') class Dictionary(object): def __init__(self): self.word2idx = {} self.idx2word = [] def add_word(self, word): raise ValueError("Please don't call this method, so we w...
MIT License
laszukdawid/pyemd
PyEMD/EEMD.py
EEMD.eemd
python
def eemd(self, S: np.ndarray, T: Optional[np.ndarray] = None, max_imf: int = -1) -> np.ndarray: if T is None: T = get_timeline(len(S), S.dtype) scale = self.noise_width*np.abs(np.max(S)-np.min(S)) self._S = S self._T = T self._N = len(S) self._scale = scale ...
Performs EEMD on provided signal. For a large number of iterations defined by `trials` attr the method performs :py:meth:`emd` on a signal with added white noise. Parameters ---------- S : numpy array, Input signal on which EEMD is performed. T : numpy array...
https://github.com/laszukdawid/pyemd/blob/3d8ec292cd2ba8cba327d3e0ad576366a8ead6ff/PyEMD/EEMD.py#L141-L212
from __future__ import print_function import logging import numpy as np from collections import defaultdict from multiprocessing import Pool from typing import Dict, List, Optional, Sequence, Tuple, Union from PyEMD.utils import get_timeline class EEMD: logger = logging.getLogger(__name__) noise_kinds_all = ["n...
Apache License 2.0
biolink/kgx
kgx/utils/kgx_utils.py
expand
python
def expand( curie: str, prefix_maps: Optional[List[dict]] = None, fallback: bool = True ) -> str: default_curie_maps = [ get_jsonld_context("monarch_context"), get_jsonld_context("obo_context"), ] if prefix_maps: uri = expand_uri(curie, prefix_maps) if uri == curie and fa...
Expand a given CURIE to an URI, based on mappings from `prefix_map`. This method will return the CURIE as the IRI if there is no mapping found. Parameters ---------- curie: str A CURIE prefix_maps: Optional[List[dict]] A list of prefix maps to use for mapping fallback: bool ...
https://github.com/biolink/kgx/blob/247d113d5b593f078afce1951c63eee2a8cc1248/kgx/utils/kgx_utils.py#L264-L299
import importlib import re import time import uuid from enum import Enum from typing import List, Dict, Set, Optional, Any, Union import stringcase from linkml_runtime.linkml_model.meta import ( TypeDefinitionName, ElementName, SlotDefinition, ClassDefinition, TypeDefinition, Element, ) from bmt...
BSD 3-Clause New or Revised License
nok/sklearn-porter
sklearn_porter/utils/Shell.py
Shell._run
python
def _run(method, cmd, cwd=None, shell=True, universal_newlines=True, stderr=STDOUT): if not cmd: error_msg = 'Passed empty text or list' raise AttributeError(error_msg) if isinstance(cmd, six.string_types): cmd = str(cmd) if shell: if ...
Internal wrapper for `call` amd `check_output`
https://github.com/nok/sklearn-porter/blob/8658c6567e28c570d96ab2e858c510f84b1d94dc/sklearn_porter/utils/Shell.py#L13-L31
import six from subprocess import call from subprocess import check_output from subprocess import STDOUT class Shell(object): @staticmethod
MIT License
chuckus/chromewhip
chromewhip/protocol/emulation.py
Emulation.setDefaultBackgroundColorOverride
python
def setDefaultBackgroundColorOverride(cls, color: Optional['DOM.RGBA'] = None, ): return ( cls.build_send_payload("setDefaultBackgroundColorOverride", { "color": color, }), Non...
Sets or clears an override of the default background color of the frame. This override is used if the content does not specify one. :param color: RGBA of the default background color. If not specified, any existing override will be cleared. :type color: DOM.RGBA
https://github.com/chuckus/chromewhip/blob/7249f64f96df3c6ca0859a3da06ce7ddcebbfded/chromewhip/protocol/emulation.py#L112-L126
import logging from typing import Any, Optional, Union from chromewhip.helpers import PayloadMixin, BaseEvent, ChromeTypeBase log = logging.getLogger(__name__) from chromewhip.protocol import dom as DOM from chromewhip.protocol import page as Page from chromewhip.protocol import runtime as Runtime class ScreenOrientati...
MIT License
facelessuser/subclrschm
subclrschm/lib/gui/custom_statusbar.py
CustomStatusBar.__init__
python
def __init__(self, parent, name, fields=None): field_array = [-1] if not fields else fields[:] super(CustomStatusBar, self).__init__( parent, id=wx.ID_ANY, style=wx.STB_DEFAULT_STYLE, name=name ) self.sb_setup(field_array)
Init the CustomStatusBar object.
https://github.com/facelessuser/subclrschm/blob/52cf5bc39bac6e3dd6d44061cd0c005cdc9a41d1/subclrschm/lib/gui/custom_statusbar.py#L259-L269
from __future__ import unicode_literals from collections import OrderedDict import wx import wx.lib.agw.supertooltip from .. import util if wx.VERSION > (2, 9, 4): def monkey_patch(): import inspect import re target_line = re.compile(r'([ ]{8})(maxWidth = max\(bmpWidth\+\(textWidth\+self._...
MIT License
nlesc/yeap16-ai-3d-printing
deepy3d/util.py
get_closest_factors
python
def get_closest_factors(number): a = int(np.sqrt(number)) while number % a != 0: a -= 1 b = number/a if a == 1 or b == 1: a, b = get_closest_factors(number + 1) return a, b
Find the 2 factors of a number that are closest together.
https://github.com/nlesc/yeap16-ai-3d-printing/blob/4f15c1851d819290dc7a922c9470a76ff458945c/deepy3d/util.py#L40-L53
import numpy as np def block_index(num_blocks, len_list): if num_blocks < 1: ValueError('Number of blocks must be larger or equal to 1') if len_list < num_blocks: ValueError('Length of list must be larger than number of blocks.') lin_list = np.linspace(0, num_blocks, len_list, endpoint=False...
Apache License 2.0
tonyfischetti/sake
sakelib/build.py
write_shas_to_shastore
python
def write_shas_to_shastore(sha_dict): if sys.version_info[0] < 3: fn_open = open else: fn_open = io.open with fn_open(".shastore", "w") as fh: fh.write("---\n") fh.write('sake version: {}\n'.format(constants.VERSION)) if sha_dict: fh.write(yaml.dump(sha_di...
Writes a sha1 dictionary stored in memory to the .shastore file
https://github.com/tonyfischetti/sake/blob/818f1b1ad97a0d7bcf2c9e0082affb2865b25f26/sakelib/build.py#L116-L130
from __future__ import unicode_literals from __future__ import print_function import glob import hashlib import io import locale from multiprocessing import Pool import networkx as nx import os.path import shlex from subprocess import Popen, PIPE import sys import yaml from . import acts from . import constants ERROR_F...
MIT License
flow-dev/robustvideomatting
inference.py
auto_downsample_ratio
python
def auto_downsample_ratio(h, w): return min(512 / max(h, w), 1)
Automatically find a downsample ratio so that the largest side of the resolution be 512px.
https://github.com/flow-dev/robustvideomatting/blob/b8848d58188fcc1e56edc7c8636aabdae1971284/inference.py#L154-L158
import torch import os from torch.utils.data import DataLoader from torchvision import transforms from typing import Optional, Tuple from tqdm.auto import tqdm from inference_utils import VideoReader, VideoWriter, ImageSequenceReader, ImageSequenceWriter def convert_video(model, input_source: str, ...
Apache License 2.0
avast/retdec-regression-tests-framework
tests/parsers/c_parser/stmts/statement_tests.py
StatementTests.get_return_stmt
python
def get_return_stmt(self, code): func = self.insert_into_function_body(code) return func.return_stmts[0]
Returns the first return stmt in the given code.
https://github.com/avast/retdec-regression-tests-framework/blob/a8d024475bf76cd6acdee3c9df3a3d38a2ec63df/tests/parsers/c_parser/stmts/statement_tests.py#L52-L55
from unittest import mock from regression_tests.parsers.c_parser.stmts.break_stmt import BreakStmt from regression_tests.parsers.c_parser.stmts.continue_stmt import ContinueStmt from regression_tests.parsers.c_parser.stmts.do_while_loop import DoWhileLoop from regression_tests.parsers.c_parser.stmts.empty_stmt import E...
MIT License
openshift/kuryr-kubernetes
kuryr_kubernetes/controller/drivers/base.py
PodSubnetsDriver.get_subnets
python
def get_subnets(self, pod, project_id): raise NotImplementedError()
Get subnets for Pod. :param pod: dict containing Kubernetes Pod object :param project_id: OpenStack project ID :return: dict containing the mapping 'subnet_id' -> 'network' for all the subnets we want to create ports on, where 'network' is an `os_vif.network.Ne...
https://github.com/openshift/kuryr-kubernetes/blob/7b2e7f83b91fa711d1a506c451be8f1143cdcd86/kuryr_kubernetes/controller/drivers/base.py#L148-L158
import abc from kuryr.lib._i18n import _ from stevedore import driver as stv_driver from kuryr_kubernetes import config _DRIVER_NAMESPACE_BASE = 'kuryr_kubernetes.controller.drivers' _DRIVER_MANAGERS = {} _MULTI_VIF_DRIVERS = [] class DriverBase(object): @classmethod def get_instance(cls, specific_driver=None, ...
Apache License 2.0
kcyu2014/eval-nas
search_policies/cnn/random_policy/nasbench_weight_sharing_policy.py
NasBenchWeightSharingPolicy.run
python
def run(self): train_queue, valid_queue, test_queue, criterion = self.initialize_run() args = self.args model, optimizer, scheduler = self.initialize_model() fitness_dict = {} self.optimizer = optimizer self.scheduler = scheduler logging.info(">> Begin the search ...
Procedure of training. This run describes the entire training procedure. :return:
https://github.com/kcyu2014/eval-nas/blob/385376a3ef96336b54ee7e696af1d02b97aa5c32/search_policies/cnn/random_policy/nasbench_weight_sharing_policy.py#L141-L177
import os import gc import logging import operator import IPython import shutil import numpy as np import torch from functools import partial from collections import namedtuple, OrderedDict, deque import utils from search_policies.cnn.cnn_general_search_policies import CNNSearchPolicy from search_policies.cnn.enas_poli...
MIT License
virgesmith/ukcensusapi
ukcensusapi/Nomisweb.py
_get_api_key
python
def _get_api_key(cache_dir): filename = cache_dir / "NOMIS_API_KEY" if os.path.isfile(str(filename)): with open(str(filename), "r") as file: content = file.readlines() return None if len(content) == 0 else content[0].replace("\n","") return os.environ.get("NOMIS_API_KEY")
Look for key in file NOMIS_API_KEY in cache dir, falling back to env var
https://github.com/virgesmith/ukcensusapi/blob/b78a753375665d1aa05c0d30813d7e533834d015/ukcensusapi/Nomisweb.py#L21-L31
import os import json import hashlib import warnings from pathlib import Path from collections import OrderedDict from urllib import request from urllib.error import HTTPError from urllib.error import URLError from urllib.parse import urlencode from socket import timeout import pandas as pd import ukcensusapi.utils as ...
MIT License
clericpy/torequests
torequests/dummy.py
Loop.wait_all_tasks_done
python
def wait_all_tasks_done(self, timeout=NotSet, delay: float = 0.5, interval: float = 0.1): timeout = self._timeout if timeout is NotSet else timeout timeout = timeout or float("inf") start_time = time_time() ...
Block, only be used while loop running in a single non-main thread. Not SMART!
https://github.com/clericpy/torequests/blob/e57ce331aa850db45c198dc90b9d01e437384b61/torequests/dummy.py#L302-L316
from asyncio import (Future, Queue, Task, TimeoutError, as_completed, gather, get_event_loop, iscoroutine, new_event_loop, sleep, wait, wait_for) from asyncio.futures import _chain_future from concurrent.futures import ALL_COMPLETED from functools import wraps from time import ...
MIT License
ying-wen/malib_deprecated
malib/utils/tf_utils.py
soft_variables_update
python
def soft_variables_update( source_variables, target_variables, tau=1.0, sort_variables_by_name=False, name=None ): if tau < 0 or tau > 1: raise ValueError("Input `tau` should be in [0, 1].") updates = [] op_name = "soft_variables_update" if name is not None: op_name = "{}_{}".format(...
Performs a soft/hard update of variables from the source to the target. For each variable v_t in target variables and its corresponding variable v_s in source variables, a soft update is: v_t = (1 - tau) * v_t + tau * v_s When tau is 1.0 (the default), then it does a hard update: v_t = v_s Args:...
https://github.com/ying-wen/malib_deprecated/blob/875338b81c4d87064ad31201f461ef742db05f25/malib/utils/tf_utils.py#L7-L48
import tensorflow as tf EPS = 1e-6
MIT License
dedsecinside/awesome-scripts
Machine Learning & AI/Linear_Regression_with_Gradient_Descent.py
r2_alpha
python
def r2_alpha(r2, alphas): plt.plot(alphas, r2) plt.title('R^2 vs. Learning Rate') print(max(r2)) print(np.linspace(0.001,1,10)[r2.index(max(r2))])
Plot r2 alpha Args: r2: (todo): write your description alphas: (array): write your description
https://github.com/dedsecinside/awesome-scripts/blob/856835e5ff5f8a6af2d74bb25800c620feb712e3/Machine Learning & AI/Linear_Regression_with_Gradient_Descent.py#L150-L165
import random import matplotlib.pyplot as plt import numpy as np def sse(n,a0,a1,x,y): s=0 mean=np.mean(y) for i in range(n): s+=(a0+a1*x[i]-mean)**2 return s/(2*n) def cost(n,a0,a1,x,y,ch,p=2): s=0; if ch=='sum-of-squares': for i in range(n): s+=(a0+a1*x[i]-y[i])**2 ...
MIT License
ing-bank/skorecard
skorecard/features_bucket_mapping.py
merge_features_bucket_mapping
python
def merge_features_bucket_mapping(a: FeaturesBucketMapping, b: FeaturesBucketMapping) -> FeaturesBucketMapping: assert isinstance(a, FeaturesBucketMapping) assert isinstance(b, FeaturesBucketMapping) cols_in_both = [col for col in a.columns if col in b.columns] cols_in_a = [col for col in a.columns if c...
Merge two sets of sequentual FeatureBucketMapping. If there are unique features, we'll add them as-in.
https://github.com/ing-bank/skorecard/blob/8ab8d38db9385aab049a7a8bef4d5f235d3f46ce/skorecard/features_bucket_mapping.py#L161-L186
import yaml import dataclasses from skorecard.bucket_mapping import BucketMapping, merge_bucket_mapping class FeaturesBucketMapping: def __init__(self, maps=[]): self.maps = {} if isinstance(maps, list): for bucketmap in maps: self.append(bucketmap) if isinstance(...
MIT License
awslabs/aws-data-api
vendor/tornado/template.py
BaseLoader.__init__
python
def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None, whitespace=None): self.autoescape = autoescape self.namespace = namespace or {} self.whitespace = whitespace self.templates = {} self.lock = threading.RLock()
Construct a template loader. :arg str autoescape: The name of a function in the template namespace, such as "xhtml_escape", or ``None`` to disable autoescaping by default. :arg dict namespace: A dictionary to be added to the default template namespace, or ``None``. ...
https://github.com/awslabs/aws-data-api/blob/81f6ad1fd89935fcec600ced2b404f37d87254fe/vendor/tornado/template.py#L385-L411
from __future__ import absolute_import, division, print_function import datetime import linecache import os.path import posixpath import re import threading from tornado import escape from tornado.log import app_log from tornado.util import ObjectDict, exec_in, unicode_type, PY3 if PY3: from io import StringIO else...
Apache License 2.0
purestorage-openconnect/py-pure-client
pypureclient/flasharray/FA_2_1/models/volume_response.py
VolumeResponse.__init__
python
def __init__( self, items=None, ): if items is not None: self.items = items
Keyword args: items (list[Volume]): Returns a list of all items after filtering. The values are displayed for each name where meaningful. If `total_only=true`, the `items` list will be empty.
https://github.com/purestorage-openconnect/py-pure-client/blob/2d9fdef0b73321cea9613e7d1eb881b42845099b/pypureclient/flasharray/FA_2_1/models/volume_response.py#L43-L52
import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flasharray.FA_2_1 import models class VolumeResponse(object): swagger_types = { 'items': 'list[Volume]' } attribute_map = { 'items': 'items' } required_...
BSD 2-Clause Simplified License
docusign/docusign-python-client
docusign_esign/models/login_account.py
LoginAccount.is_default
python
def is_default(self): return self._is_default
Gets the is_default of this LoginAccount. # noqa: E501 This value is true if this is the default account for the user, otherwise false is returned. # noqa: E501 :return: The is_default of this LoginAccount. # noqa: E501 :rtype: str
https://github.com/docusign/docusign-python-client/blob/c6aeafff0d046fa6c10a398be83ba9e24b05d4ea/docusign_esign/models/login_account.py#L187-L195
import pprint import re import six from docusign_esign.client.configuration import Configuration class LoginAccount(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name ...
MIT License
rikonor/vanguard-api
seleniumapis/browser/browser.py
Browser.find_element_by_any
python
def find_element_by_any(self, search_term): return self.find_element_by_id(search_term) or self.find_element_by_name(search_term)
Find an element by a search term Try ID, then fallback to Name
https://github.com/rikonor/vanguard-api/blob/5462b2327cacad68bedb945dc323d534ebbdfeee/seleniumapis/browser/browser.py#L37-L43
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.common.exceptions import * from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC clas...
MIT License
tamasgal/km3pipe
km3pipe/io/daq.py
DAQPump.seek_to_frame
python
def seek_to_frame(self, index): pointer_position = self.frame_positions[index] self.blob_file.seek(pointer_position, 0)
Move file pointer to the frame with given index.
https://github.com/tamasgal/km3pipe/blob/c10fa39f72f3a8e384025712344378012fae5115/km3pipe/io/daq.py#L231-L234
from collections import namedtuple from io import BytesIO import json import math import struct from struct import unpack import time import pprint from urllib.request import urlopen, URLError import numpy as np from thepipe import Module, Blob from km3pipe.dataclasses import Table from km3pipe.sys import ignored from ...
MIT License
vitrioil/speech-separation
src/loader/data.py
Signal.augment_audio
python
def augment_audio(self, augmenter: Callable, *args, **kwargs): self.audio = augmenter(self.audio, *args, **kwargs)
Change the audio via the augmenter method.
https://github.com/vitrioil/speech-separation/blob/65a532d36cf0725d622f18ef058cf5a537c01070/src/loader/data.py#L65-L69
import os import cv2 import librosa import numpy as np from pathlib import Path from typing import Callable, Tuple, List EMBED_DIR = [Path("../data/train/embed")] SPEC_DIR = [Path("../data/train/spec")] def get_frames(video): frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) frame_width = int(video.get(cv2...
MIT License
jakecover/distest
distest/TestInterface/_reply.py
assert_reply_contains
python
async def assert_reply_contains(self, contents, substring): response = await self.wait_for_reply(contents) return await self.assert_message_contains(response, substring)
Send a message and wait for a response. If the response does not contain the given substring, fail the test. :param str contents: The content of the trigger message. (A command) :param str substring: The string to test against. :returns: The reply. :rtype: discord.Message :raises: ResponseDidNo...
https://github.com/jakecover/distest/blob/8810c884546a37a67881ddf3fbeed03b6eccebe5/distest/TestInterface/_reply.py#L22-L33
from asyncio import sleep from inspect import signature, _ParameterKind from typing import Dict from discord import Embed, Message async def assert_reply_equals(self, contents, matches): response = await self.wait_for_reply(contents) return await self.assert_message_equals(response, matches)
MIT License
thingsboard/python_tb_rest_client
tb_rest_client/models/models_pe/report_config.py
ReportConfig.to_dict
python
def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value ...
Returns the model properties as a dict
https://github.com/thingsboard/python_tb_rest_client/blob/87c6a3703974fc8a86e4c72c444168ee2b758ecb/tb_rest_client/models/models_pe/report_config.py#L300-L325
import pprint import re import six class ReportConfig(object): swagger_types = { 'base_url': 'str', 'dashboard_id': 'str', 'name_pattern': 'str', 'state': 'str', 'timewindow': 'str', 'timezone': 'str', 'type': 'str', 'use_current_user_credentials': '...
Apache License 2.0
xilinx/pyxir
python/pyxir/contrib/dpuv1/dpuv1_op_support.py
mean_op_support
python
def mean_op_support(X, bXs, tXs): axes = X.attrs['axes'] keepdims = X.attrs['keepdims'] return len(axes) == 2 and keepdims
Check whether we can execute the provided Mean operator on the dpuv1 target
https://github.com/xilinx/pyxir/blob/bef661d6d77adcdbd2cf4163f2cf3a1d31d40406/python/pyxir/contrib/dpuv1/dpuv1_op_support.py#L212-L220
import math import pyxir import logging logger = logging.getLogger('pyxir') @pyxir.register_op_support_check('dpuv1', 'BatchNorm') def batchnorm_op_support(X, bXs, tXs): axis = X.attrs['axis'] channels = X.shapes[axis] return channels >= 1 and channels <= 4096 @pyxir.register_op_support_check('dpuv1', 'Bias...
Apache License 2.0
kriaga/health-checker
HealthChecker/venv/Lib/site-packages/nltk/data.py
normalize_resource_name
python
def normalize_resource_name(resource_name, allow_relative=True, relative_path=None): is_dir = bool(re.search(r'[\\/.]$', resource_name)) or resource_name.endswith(os.path.sep) if sys.platform.startswith('win'): resource_name = resource_name.lstrip('/') else: resource_name = re.sub(r'^/+', '/...
:type resource_name: str or unicode :param resource_name: The name of the resource to search for. Resource names are posix-style relative path names, such as ``corpora/brown``. Directory names will automatically be converted to a platform-appropriate path separator. Directory traili...
https://github.com/kriaga/health-checker/blob/3d9ce933f131bcbb897103b0f509cc45393cae4a/HealthChecker/venv/Lib/site-packages/nltk/data.py#L210-L254
from __future__ import print_function, unicode_literals from __future__ import division from abc import ABCMeta, abstractmethod from six import add_metaclass import functools import textwrap import io import os import re import sys import zipfile import codecs from gzip import GzipFile, READ as GZ_READ, WRITE as GZ_WRI...
MIT License
bigmlcom/bigmler
bigmler/resourcesapi/batch_anomaly_scores.py
create_batch_anomaly_score
python
def create_batch_anomaly_score(anomaly, test_dataset, batch_anomaly_score_args, args, api=None, session_file=None, path=None, log=None): if api is None: api = bigml.api.BigML() message = dated("Creating batch an...
Creates remote batch anomaly score
https://github.com/bigmlcom/bigmler/blob/91973ca1e752954302bf26bb22aa6874dc34ce69/bigmler/resourcesapi/batch_anomaly_scores.py#L74-L106
import sys import bigml.api from bigmler.utils import (dated, get_url, log_message, check_resource, check_resource_error, log_created_resources) from bigmler.reports import report from bigmler.resourcesapi.common import set_basic_batch_args, map_fields, update_json_args from bigmler.resour...
Apache License 2.0
loudnate/openaps-predict
openapscontrib/predict/predict.py
ceil_datetime_at_minute_interval
python
def ceil_datetime_at_minute_interval(timestamp, minute): nsecs = timestamp.minute * 60 + timestamp.second + timestamp.microsecond * 1e-6 seconds = minute * 60 delta = (nsecs // seconds) * seconds + seconds - nsecs if delta < seconds: return timestamp + datetime.timedelta(seconds=delta) else:...
From http://stackoverflow.com/questions/13071384/python-ceil-a-datetime-to-next-quarter-of-an-hour :param timestamp: :type timestamp: datetime.datetime :param minute: :type minute: int :return: :rtype: datetime.datetime
https://github.com/loudnate/openaps-predict/blob/a2da82148318d86b0935a1fca596477d84dd8247/openapscontrib/predict/predict.py#L50-L71
from collections import defaultdict import datetime from dateutil.parser import parse from functools32 import lru_cache import math from numpy import arange from scipy.stats import linregress from models import Unit class Schedule(object): def __init__(self, entries): self.entries = entries @lru_cache()...
MIT License
edx-unsupported/edx-load-tests
loadtests/student_notes/locustfile.py
BaseNotesTask._create_many_notes
python
def _create_many_notes(self, num_notes): for _ in xrange(num_notes): self._create_note()
Create many notes within the course for the current user.
https://github.com/edx-unsupported/edx-load-tests/blob/1a6dc891d2fb72575f354521988a531489f30032/loadtests/student_notes/locustfile.py#L202-L207
import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) from contextlib import contextmanager from copy import copy import json from locust import HttpLocust, task, TaskSet import logging import random from helpers import settings settings.init(__name__, required_data=[ 'co...
Apache License 2.0
bobotig/thermalprinter
thermalprinter/thermalprinter.py
ThermalPrinter.upside_down
python
def upside_down(self, state=False): state = bool(state) if state is not self._upside_down: self._upside_down = state self.send_command(Command.ESC, 123, int(state))
Turns on/off upside-down printing mode.
https://github.com/bobotig/thermalprinter/blob/4cf697049d6c4fbad31ba8ea6842e0a4bc1b35ad/thermalprinter/thermalprinter.py#L624-L630
from atexit import register from time import sleep from serial import Serial from .constants import (BarCodePosition, CharSet, Chinese, CodePage, CodePageConverted, Command) from .exceptions import (ThermalPrinterValueError, ThermalPrinterCommunicationError) from .valida...
MIT License
flask-admin/flask-admin
flask_admin/contrib/appengine/form.py
AdminModelConverter.convert_GeoPtProperty
python
def convert_GeoPtProperty(self, model, prop, kwargs): return GeoPtPropertyField(**kwargs)
Returns a form field for a ``ndb.GeoPtProperty``.
https://github.com/flask-admin/flask-admin/blob/e39f786374ce0e60db93f583efacb4672de0025c/flask_admin/contrib/appengine/form.py#L8-L10
from wtforms_appengine.ndb import ModelConverter from .fields import GeoPtPropertyField from flask_admin.model.form import converts class AdminModelConverter(ModelConverter): @converts('GeoPt')
BSD 3-Clause New or Revised License
chrklemm/sesmg
program_files/create_objects.py
Sinks.create_sink
python
def create_sink(self, de: dict, timeseries_args: dict): self.nodes_sinks.append( solph.Sink(label=de['label'], inputs={ self.busd[de['input']]: solph.Flow(**timeseries_args)}))
Creates an oemof sink with fixed or unfixed timeseries. :param de: dictionary containing all information for the creation of an oemof sink. At least the following key-value-pairs have to be included: - 'label' ...
https://github.com/chrklemm/sesmg/blob/382ffd600b98d3cc6df53abed0cb3526187cb1cf/program_files/create_objects.py#L693-L718
from oemof import solph import logging import os import pandas as pd from feedinlib import * import demandlib.bdew as bdew import datetime import numpy def buses(nodes_data: dict, nodes: list) -> dict: busd = {} for i, b in nodes_data['buses'].iterrows(): if b['active']: bus = solph.Bus(labe...
MIT License
facebookresearch/nevergrad
nevergrad/parametrization/core.py
as_parameter
python
def as_parameter(param: tp.Any) -> Parameter: if isinstance(param, Parameter): return param else: return Constant(param)
Returns a Parameter from anything: either the input if it is already a parameter, or a Constant if not This is convenient for iterating over Parameter and other objects alike
https://github.com/facebookresearch/nevergrad/blob/1981997603e361b1fd5b5e2aeb8173c4eae6aef0/nevergrad/parametrization/core.py#L469-L477
import uuid import warnings import numpy as np import nevergrad.common.typing as tp from nevergrad.common import errors from . import utils from ._layering import ValueProperty as ValueProperty from ._layering import Layered as Layered from ._layering import Level as Level P = tp.TypeVar("P", bound="Parameter") class P...
MIT License
cainmagi/mdnt
data/deprecated/h5py.py
H5SupSaver.dump
python
def dump(self, keyword, data): if self.f is None: raise OSError('Should not dump data before opening a file.') self.f.create_dataset(keyword, data=data, **self.__kwargs) if self.logver > 0: print('Dump {0} into the file. The data shape is {1}.'.format(keyword, data.shape)...
Dump the dataset with a keyword into the file. Arguments: keyword: the keyword of the dumped dataset. data: dataset, should be a numpy array.
https://github.com/cainmagi/mdnt/blob/4affd8a83698ce6786c04dddacdcf7415f8c5f90/data/deprecated/h5py.py#L73-L84
import h5py import numpy as np import tensorflow as tf import os REMOVE_DEPRECATION = False def depcatedInfo(): try: raise DeprecationWarning('This library has been deprecated.') except Exception as e: if not REMOVE_DEPRECATION: raise e class H5SupSaver: def __init__(self, fileNa...
MIT License
tektoncd/experimental
sdk/python/tekton_pipeline/models/v1beta1_pipeline_list.py
V1beta1PipelineList.api_version
python
def api_version(self, api_version): self._api_version = api_version
Sets the api_version of this V1beta1PipelineList. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/...
https://github.com/tektoncd/experimental/blob/0ba4e7a2b9d45ed4accaecbb34dac006d665796a/sdk/python/tekton_pipeline/models/v1beta1_pipeline_list.py#L95-L104
import pprint import re import six from tekton_pipeline.configuration import Configuration class V1beta1PipelineList(object): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name...
Apache License 2.0
qkaiser/cottontail
cottontail/rabbitmq_management.py
RabbitMQManagementClient.get_request
python
def get_request(self, path): response = requests.get( "{}://{}:{}/api/{}".format(self._scheme, self._host, self._port, path), auth=(self._username, self._password), verify=False, timeout=5 ) if response.status_code == 200: return respon...
Wrapper for GET requests to the API. Args: path (str): REST path appended to /api Returns: HTTP response JSON object. Raises: UnauthorizedException
https://github.com/qkaiser/cottontail/blob/b7f5222959cf6229ef33d7369e5e8881e6181727/cottontail/rabbitmq_management.py#L60-L87
try: from urllib.parse import quote except ImportError: from urllib import quote import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) class UnauthorizedAccessException(Exception): pass class RabbitMQManagem...
BSD 3-Clause New or Revised License
nsls-ii/pyxrf
pyxrf/core/tests/test_quant_analysis.py
_create_file_with_ref_standards
python
def _create_file_with_ref_standards(*, wd): sd = _standard_data_sample[0] file_path = os.path.join(wd, ".pyxrf", "quantitative_standards.yaml") standard_data = [] for n in range(2): sd_copy = copy.deepcopy(sd) sd_copy["serial"] += f"{n}" sd_copy["name"] = f"Test reference standar...
r""" Create a file with user-defined standards based on ``_standard_data_sample[0]``. The file contains the descriptions of 2 standards with identical sets of elements/compounds with slightly different densities. The created file is placed at the standard default location ``<wd>/.pyxrf/quantiative_stan...
https://github.com/nsls-ii/pyxrf/blob/0aa4e175f541edfaa8f71daf54b54a07e4ab2b04/pyxrf/core/tests/test_quant_analysis.py#L727-L767
import os import pytest import jsonschema import copy import numpy as np import numpy.testing as npt import time as ttime import re from pyxrf.core.utils import convert_time_from_nexus_string from pyxrf.core.xrf_utils import validate_element_str, generate_eline_list, split_compound_mass from pyxrf.core.quant_analysis i...
BSD 3-Clause New or Revised License
pyconll/pyconll
pyconll/tree/_treebuilder.py
TreeBuilder._assert_initialization_status
python
def _assert_initialization_status(self) -> None: if self.root is None: raise ValueError( 'The TreeBuilder has not created a root for the Tree yet')
Asserts the initialization invariant on the root of this builder. Raises: ValueError: If the TreeBuilder's root has not been initialized.
https://github.com/pyconll/pyconll/blob/a69b1bfb884aab7b449e19a7cc8850dcf7e985c0/pyconll/tree/_treebuilder.py#L203-L212
from typing import Any, Generic, TypeVar from pyconll.tree.tree import Tree T = TypeVar('T') class TreeBuilder(Generic[T]): def __init__(self) -> None: self.root: Any = None self.current: Any = None self.constructed: bool = False def create_root(self, data: T) -> None: self.root ...
MIT License
merll/docker-map
dockermap/map/client.py
MappingDockerClient.restart
python
def restart(self, container, instances=None, map_name=None, **kwargs): return self.run_actions('restart', container, instances=instances, map_name=map_name, **kwargs)
Restarts instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance names to stop. If not specified, will restart all instances as specified in the configuration (or just one default instance). :type inst...
https://github.com/merll/docker-map/blob/54e325595fc0b6b9d154dacc790a222f957895da/dockermap/map/client.py#L284-L300
from __future__ import unicode_literals import logging import sys from ..exceptions import PartialResultsError from .action import simple, script, update from .config.client import ClientConfiguration from .config.main import ContainerMap from .config.utils import get_map_config_ids from .exceptions import ActionExcept...
MIT License
pyannote/pyannote-database
pyannote/database/protocol/speaker_recognition.py
SpeakerRecognitionProtocol.train
python
def train(self, yield_name=False): generator = self.trn_iter() for name, item in generator: if yield_name: yield name, self.preprocess(item) else: yield self.preprocess(item)
Iterate over the training set This will yield dictionaries with the followings keys: * database: str unique database identifier * uri: str unique recording identifier * channel: int index of resource channel to use * speaker: str unique speaker identifier as well as keys coming from the provided preprocessor...
https://github.com/pyannote/pyannote-database/blob/7391b48e70f087dd963776d37257321bed1e313a/pyannote/database/protocol/speaker_recognition.py#L95-L125
from .protocol import Protocol class SpeakerRecognitionProtocol(Protocol): def trn_iter(self): raise NotImplementedError( "Custom speaker recognition protocol " 'should implement "trn_iter".' ) def trn_enroll_iter(self): raise NotImplementedError( "Custom speaker ...
MIT License
chaffelson/whoville
whoville/cloudbreak/models/rds_config_response.py
RDSConfigResponse.cluster_names
python
def cluster_names(self, cluster_names): self._cluster_names = cluster_names
Sets the cluster_names of this RDSConfigResponse. list of clusters which use config :param cluster_names: The cluster_names of this RDSConfigResponse. :type: list[str]
https://github.com/chaffelson/whoville/blob/f71fda629c9fd50d0a482120165ea5abcc754522/whoville/cloudbreak/models/rds_config_response.py#L284-L293
from pprint import pformat from six import iteritems import re class RDSConfigResponse(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and...
Apache License 2.0
smartelect/smartelect
civil_registry/tests/factories.py
CitizenFactory._setup_next_sequence
python
def _setup_next_sequence(cls): return 1
Set up an initial sequence value for Sequence attributes. Returns: int: the first available ID to use for instances of this factory. Note: If we don't override this, then DjangoModelFactory bases the initial value on the max PK of the corresponding model, which in my case i...
https://github.com/smartelect/smartelect/blob/d6d35f2fa8f60e756ad5247f8f0a5f05830e92f8/civil_registry/tests/factories.py#L52-L63
from datetime import date import random import string import factory import factory.fuzzy from civil_registry.models import Citizen, TempCitizen from libya_elections.constants import MALE def get_nid(stub): from register.tests.factories import get_unused_gender_appropriate_national_id return get_unused_gender_a...
Apache License 2.0
http-apis/hydra-python-agent
hydra_agent/tests/test_redis.py
Tests.collection_endpoints
python
def collection_endpoints(self): print("testing collection endpoints with db=0 ...") query = ('GRAPH.QUERY','apigraph', "MATCH (p:collection) RETURN p") redis_db = redis.StrictRedis(host='localhost', port=6379, db=0) redis_reply = [[[b'p.id', b'p.operations', b'p.type'], [b'vocab:EntryPoi...
Test for testing the data stored in collection endpoints `redis_reply` is data which will get from redis_db_0 on `query` execution.
https://github.com/http-apis/hydra-python-agent/blob/e2bcd51f3cbf0700cd44e5e392e3c21af2cbd2a3/hydra_agent/tests/test_redis.py#L26-L43
import unittest import redis from unittest.mock import MagicMock class Tests: def entry_point(self): print("testing entrypoint with db=0 ...") query = ('GRAPH.QUERY','apigraph', "MATCH (p:id) RETURN p") redis_db = redis.StrictRedis(host='localhost', port=6379, db=0) redis_reply = [[[...
MIT License
ollo69/ha_tuya_custom
custom_components/tuya_custom/__init__.py
TuyaDevice.object_id
python
def object_id(self): return self._tuya.object_id()
Return Tuya device id.
https://github.com/ollo69/ha_tuya_custom/blob/66b8722afc9c771318b8c67865907e5ac0aac602/custom_components/tuya_custom/__init__.py#L380-L382
import asyncio from datetime import timedelta import logging from .tuyaha.tuyaapi import ( DEFAULTREGION, TuyaApi, TuyaAPIException, TuyaAPIRateLimitException, TuyaFrequentlyInvokeException, TuyaNetException, TuyaServerException, ) import voluptuous as vol from homeassistant.config_entries i...
Apache License 2.0
erigones/esdc-ce
api/serializers.py
BaseSerializer.get_field_key
python
def get_field_key(self, field_name): return field_name
Return the key that should be used for a given field.
https://github.com/erigones/esdc-ce/blob/f83a62d0d430e3c8f9aac23d958583b0efce4312/api/serializers.py#L356-L360
from __future__ import unicode_literals import copy import datetime import inspect import types from collections import OrderedDict from decimal import Decimal from django.apps import apps from django.core.paginator import Page from django.db import models from django.forms import widgets from django.utils import six f...
Apache License 2.0
hathornetwork/hathor-core
hathor/stratum/stratum.py
StratumProtocol.create_job_tx
python
def create_job_tx(self, jobid: UUID) -> BaseTransaction: if self.mine_txs and self.factory.tx_queue: funds_hash = self.factory.tx_queue[0] tx = self.factory.mining_tx_pool[funds_hash] tx.timestamp = self.factory.get_current_timestamp() tx.parents = self.manager.ge...
Creates a BaseTransaction for the designated miner job. :return: created BaseTransaction :rtype: BaseTransaction
https://github.com/hathornetwork/hathor-core/blob/b8bd2428b9fab4f53dfc4d92de230ffae48fbf46/hathor/stratum/stratum.py#L640-L667
from abc import ABC, abstractmethod from hashlib import sha256 from itertools import count from json import JSONDecodeError from math import log from multiprocessing import Process, Queue as MQueue from multiprocessing.sharedctypes import Array, Value from os import cpu_count from string import hexdigits from time impo...
Apache License 2.0
jasonmcintosh/rabbitmq-zabbix
scripts/rabbitmq/api.py
RabbitMQAPI.check_aliveness
python
def check_aliveness(self): return self.call_api('aliveness-test/%2f')['status']
Check the aliveness status of a given vhost.
https://github.com/jasonmcintosh/rabbitmq-zabbix/blob/8ecadfdd2cab6154eb7ab73ce4e7bb39b21b61c1/scripts/rabbitmq/api.py#L209-L211
from __future__ import unicode_literals import io import json import optparse import socket import urllib2 import subprocess import os import logging class RabbitMQAPI(object): def __init__(self, user_name='guest', password='guest', host_name='', port=15672, conf='/etc/zabbix/zabbix_agentd.conf', s...
Apache License 2.0
bennylope/django-organizations
src/organizations/utils.py
model_field_attr
python
def model_field_attr(model, model_field, attr): fields = dict([(field.name, field) for field in model._meta.fields]) return getattr(fields[model_field], attr)
Returns the specified attribute for the specified field on the model class.
https://github.com/bennylope/django-organizations/blob/55808ad7e4b23ef4612c9226cadce46d514c9a79/src/organizations/utils.py#L89-L94
from itertools import chain def default_org_model(): from organizations.models import Organization return Organization def model_field_names(model): return list( set( chain.from_iterable( (field.name, field.attname) if hasattr(field, "attname") ...
BSD 2-Clause Simplified License
westpa/westpa
lib/west_tools/westtools/wipi.py
__get_data_for_iteration__.successful_trajectories
python
def successful_trajectories(self): state_changes = np.where(self.raw['states'][:,:-1] != self.raw['states'][:,1:]) walkers = state_changes[0] new_states = state_changes[1] + 1 old_states = state_changes[1] walker = {} for z, (i, j) in enumerate(zip(old_states, new_states)...
Returns which trajectories are successful.
https://github.com/westpa/westpa/blob/cda177c5dea2cee571d71c4b04fcc625dc5f689c/lib/west_tools/westtools/wipi.py#L427-L450
import numpy as np import os, sys import scipy.sparse as sp from westtools import Plotter import itertools class WIPIDataset(object): def __init__(self, raw, key): self.__dict__ = {} self.raw = raw self.name = key def __repr__(self): if isinstance(self.__dict__['raw'], dict): ...
MIT License
hszhao/pointweb
lib/pointops/functions/pointops.py
pairwise_distances
python
def pairwise_distances(x, y=None): x_norm = (x ** 2).sum(1).view(-1, 1) if y is not None: y_t = torch.transpose(y, 0, 1) y_norm = (y ** 2).sum(1).view(1, -1) else: y_t = torch.transpose(x, 0, 1) y_norm = x_norm.view(1, -1) dist = x_norm + y_norm - 2.0 * torch.mm(x, y_t) ...
Input: x is a Nxd matrix y is an optional Mxd matirx Output: dist is a NxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:] if y is not given then use 'y=x'. i.e. dist[i,j] = ||x[i,:]-y[j,:]||^2
https://github.com/hszhao/pointweb/blob/f31fe05616c3c068f6c1870170a3caaf1f7d8abb/lib/pointops/functions/pointops.py#L346-L363
from typing import Tuple import torch from torch.autograd import Function import torch.nn as nn import pointops_cuda class FurthestSampling(Function): @staticmethod def forward(ctx, xyz, m): assert xyz.is_contiguous() b, n, _ = xyz.size() idx = torch.cuda.IntTensor(b, m) temp = t...
MIT License
probcomp/bayeslite
src/core.py
bayesdb_table_has_column
python
def bayesdb_table_has_column(bdb, table, name): bayesdb_table_guarantee_columns(bdb, table) sql = 'SELECT COUNT(*) FROM bayesdb_column WHERE tabname = ? AND name = ?' return cursor_value(bdb.sql_execute(sql, (table, name)))
True if the table named `table` has a column named `name`. `bdb` must have a table named `table`. If you're not sure, call :func:`bayesdb_has_table` first. WARNING: This may modify the database by populating the ``bayesdb_column`` table if it has not yet been populated.
https://github.com/probcomp/bayeslite/blob/211e5eb3821a464a2fffeb9d35e3097e1b7a99ba/src/core.py#L82-L93
from bayeslite.exception import BQLError from bayeslite.sqlite3_util import sqlite3_quote_name from bayeslite.util import casefold from bayeslite.util import cursor_value def bayesdb_has_table(bdb, name): qt = sqlite3_quote_name(name) cursor = bdb.sql_execute('PRAGMA table_info(%s)' % (qt,)) try: cu...
Apache License 2.0
zagaran/mongolia
mongolia/database_collection.py
DatabaseCollection.__init__
python
def __init__(self, path=None, objtype=None, query=None, sort_by=ID_KEY, ascending=True, page=0, page_size=None, read_only=False, projection=None, field=None, **kwargs): if objtype: self.OBJTYPE = objtype if path: self.PATH = path if not q...
Loads a list of DatabaseObjects from path matching query. If nothing matches the query (possibly because there is nothing in the specified mongo collection), the created DatabaseCollection will be an empty list and have bool(returned object) == False NOTE: The path and objtype ...
https://github.com/zagaran/mongolia/blob/18d921017123b9edb7b70b01d8cfb3eb491b4cb6/mongolia/database_collection.py#L67-L161
import json from pymongo import ASCENDING, DESCENDING from mongolia.constants import ID_KEY, GT from mongolia.database_object import DatabaseObject from mongolia.json_codecs import MongoliaJSONEncoder class DatabaseCollection(list): OBJTYPE = DatabaseObject PATH = None
MIT License
diofant/diofant
diofant/simplify/radsimp.py
rcollect
python
def rcollect(expr, *vars): if expr.is_Atom or not expr.has(*vars): return expr else: expr = expr.__class__(*[rcollect(arg, *vars) for arg in expr.args]) if expr.is_Add: return collect(expr, vars) else: return expr
Recursively collect sums in an expression. Examples ======== >>> expr = (x**2*y + x*y + x + y)/(x + y) >>> rcollect(expr, y) (x + y*(x**2 + x + 1))/(x + y) See Also ======== collect, collect_const, collect_sqrt
https://github.com/diofant/diofant/blob/05c50552b0e0533f1dbf2ec05e65b6c45b7e2c11/diofant/simplify/radsimp.py#L387-L412
from collections import defaultdict from ..core import (Add, Derivative, I, Integer, Mul, Pow, Rational, expand_mul, expand_power_base, gcd_terms, symbols) from ..core.compatibility import iterable from ..core.exprtools import Factors from ..core.function import _mexpand from ..core.mul import _keep...
BSD 3-Clause New or Revised License
cityofsantamonica/mds-provider
mds/db/loaders.py
Records.load
python
def load(self, source, **kwargs): if isinstance(source, dict): source = [source] df = pd.DataFrame.from_records(source) super().load(df, **kwargs)
Load data from one or more MDS Provider records. Parameters: source: dict, list One or more dicts of type record_type. record_type: str The type of MDS data. table: str The name of the database table to insert this data into....
https://github.com/cityofsantamonica/mds-provider/blob/02abcb227c35cdfe78a39e35b3157f7c2916c028/mds/db/loaders.py#L193-L216
import string import pandas as pd from ..db import sql from ..fake import util from ..files import DataFile from ..schemas import STATUS_CHANGES, TRIPS, EVENTS, VEHICLES, Schema from ..versions import UnexpectedVersionError, Version class DataFrame(): def load(self, source, **kwargs): record_type = kwargs.p...
MIT License
google/cauliflowervest
cauliflowervest/server/handlers/maintenance.py
_update_schema
python
def _update_schema(model, cursor=None, num_updated=0): query = model.all() if cursor: query.with_cursor(cursor) updated = 0 for p in query.fetch(limit=_BATCH_SIZE): _reinsert_entity(model, p.key()) updated += 1 if updated > 0: num_updated += updated logging.info( 'Put %d %s entitie...
Add tag field.
https://github.com/google/cauliflowervest/blob/d3f52501ebed8b9a392350c8e177bbc602a6a09d/cauliflowervest/server/handlers/maintenance.py#L41-L63
import httplib import logging from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import deferred from cauliflowervest import settings as base_settings from cauliflowervest.server.handlers import base_handler from cauliflowervest.server.models import base from cauliflowe...
Apache License 2.0
jmchilton/galaxy-central
galaxy/datatypes/sniff.py
is_bed
python
def is_bed(headers, skip=0): try: if not headers: return False for hdr in headers[skip:]: try: map(int, [ hdr[1], hdr[2] ]) except: return False return True except: return False
Checks for 'bedness' >>> fname = get_test_fname('test_tab.bed') >>> headers = get_headers(fname, sep='\\t') >>> is_bed(headers) True >>> fname = get_test_fname('interval.bed') >>> headers = get_headers(fname, sep='\\t') >>> is_bed(headers) False
https://github.com/jmchilton/galaxy-central/blob/31e2fd3a32b06ddfba06ae5b044efdce1d93f08c/galaxy/datatypes/sniff.py#L221-L246
import logging, sys, os, csv, tempfile, shutil, re log = logging.getLogger(__name__) def get_test_fname(fname): path, name = os.path.split(__file__) full_path = os.path.join(path, 'test', fname) return full_path def stream_to_file(stream): fd, temp_name = tempfile.mkstemp() while 1: chunk = ...
MIT License
smartbgp/yabgp
yabgp/message/open.py
Open.construct
python
def construct(self, my_capability): capas = b'' if 'afi_safi' in my_capability: capas += Capability(capa_code=1, capa_length=4).construct(my_capability) if my_capability.get('cisco_route_refresh'): capas += Capability(capa_code=128, capa_length=0).construct(my_capability)...
Construct a BGP Open message
https://github.com/smartbgp/yabgp/blob/f073633a813899cd9b413bc28ea2f7737deee141/yabgp/message/open.py#L232-L265
import struct import netaddr from yabgp.common import exception as excp from yabgp.common import constants as bgp_cons class Open(object): def __init__(self, version=None, asn=None, hold_time=None, bgp_id=None, opt_para_len=None, opt_paras=None): self.version = version self.asn = as...
Apache License 2.0
pbattaglia/scenesim
scenesim/physics/bulletbase.py
BulletBase.add_ghostnode
python
def add_ghostnode(node): name = "%s-ghost" % node.getName() ghost = NodePath(BulletGhostNode(name)) ghost.reparentTo(node) return ghost
Adds a child ghostnode to a node as a workaround for the ghost-static node collision detection problem.
https://github.com/pbattaglia/scenesim/blob/2633c63bc5cb97ea99017b2e25fc9b4f66d72605/scenesim/physics/bulletbase.py#L582-L588
from collections import Iterable from contextlib import contextmanager from functools import update_wrapper from itertools import combinations, izip from math import isnan, sqrt from warnings import warn import numpy as np from panda3d.bullet import (BulletBaseCharacterControllerNode, BulletBodyNode, ...
MIT License
onshape-public/onshape-clients
python/onshape_client/oas/models/bt_microversion_info.py
BTMicroversionInfo.openapi_types
python
def openapi_types(): return { "microversion": (str,), }
This must be a class method so a model may have properties that are of type self, this ensures that we don't create a cyclic import Returns openapi_types (dict): The key is attribute name and the value is attribute type.
https://github.com/onshape-public/onshape-clients/blob/20843a00c628e516e7219e17a23ec4ef2bf9f16f/python/onshape_client/oas/models/bt_microversion_info.py#L66-L77
from __future__ import absolute_import import re import sys import six import nulltype from onshape_client.oas.model_utils import ( ModelComposed, ModelNormal, ModelSimple, date, datetime, file_type, int, none_type, str, validate_get_composed_info, ) class BTMicroversio...
MIT License
decred/tinydecred
decred/decred/dcr/blockchain.py
LocalNode.header
python
def header(self, blockHash): try: return self.headerDB[blockHash] except database.NoValueError: header = self.rpc.getBlockHeader(blockHash, verbose=False) self.headerDB[header.cachedHash()] = header return header
Get the header, from the headerDB if possible, otherwise fetch from RPC. Args: blockHash (ByteArray): The block header hash. Returns: BlockHeader: The block header.
https://github.com/decred/tinydecred/blob/f7f7d9f7da8d49d9ae9a72e5579b07a3b8572267/decred/decred/dcr/blockchain.py#L66-L81
import time from decred.dcr import addrlib, rpc from decred.dcr.wire.msgblock import BlockHeader from decred.util import database, helpers from decred.util.encode import ByteArray log = helpers.getLogger("blockchain") class LocalNode: def __init__(self, netParams, dbPath, url, user, pw, certPath=None): self...
ISC License
muneebalam/scrapenhl2
scrapenhl2/plot/app/player_page.py
generate_table
python
def generate_table(dataframe): return html.Table( [html.Tr([html.Th(col) for col in dataframe.columns])] + [html.Tr([html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(len(dataframe))])
Transforms a pandas dataframe into an HTML table
https://github.com/muneebalam/scrapenhl2/blob/a9867f03d002773da852fc150f2976adc2ba8c25/scrapenhl2/plot/app/player_page.py#L24-L31
import pandas as pd import datetime import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go import scrapenhl2.scrape.schedules as schedules import scrapenhl2.scrape.players as players import scrapenhl2.plot.rolling_cf_...
MIT License
seldonio/alibi
alibi/explainers/cfrl_tabular.py
CounterfactualRLTabular._diversity
python
def _diversity(self, X: np.ndarray, Y_t: np.ndarray, C: Optional[List[Dict[str, List[Union[str, float]]]]], num_samples: int = 1, batch_size: int = 100, patience: int = 1000, tolerance: f...
Generates a set of diverse counterfactuals given a single instance, target and conditioning. Parameters ---------- X Input instance. Y_t Target label. C List of conditional dictionaries. If `None`, it means that no conditioning was used during...
https://github.com/seldonio/alibi/blob/ef757b9579f85ef2e3dfc7088211969616ee3fdb/alibi/explainers/cfrl_tabular.py#L377-L497
from alibi.api.interfaces import Explainer, Explanation from alibi.utils.frameworks import has_pytorch, has_tensorflow from alibi.explainers.cfrl_base import CounterfactualRL, Postprocessing, _PARAM_TYPES from alibi.explainers.backends.cfrl_tabular import sample, get_conditional_vector, get_statistics import numpy as n...
Apache License 2.0