content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def get_scenario():
"""
Get scenario
"""
try:
scenario = os.environ['DEPLOY_SCENARIO']
except KeyError:
logger.error("Impossible to retrieve the scenario")
scenario = "Unknown_scenario"
return scenario | dc8ce4bb231ff9174f59f27a5a2dee618d6d4647 | 6,000 |
from typing import Optional
from typing import Callable
import requests
def make_request(
endpoint: str, method: str = "get", data: Optional[dict] = None, timeout: int = 15
) -> Response:
"""Makes a request to the given endpoint and maps the response
to a Response class"""
method = method.lower()
... | 8dd88583f61e5c42689461dd6d316297d910f197 | 6,001 |
import socket
def _is_rpc_timeout(e):
""" check whether an exception individual rpc timeout. """
# connection caused socket timeout is being re-raised as
# ThriftConnectionTimeoutError now
return isinstance(e, socket.timeout) | ec832bec086b59698eed12b18b7a37e5eb541329 | 6,002 |
def fake_quantize_with_min_max(inputs,
f_min,
f_max,
bit_width,
quant_zero=True):
"""The fake quantization operation kernel.
Args:
inputs: a tensor containing values to be quantized.
... | 2034dbe02d50ce0317dc4dbb6f2ed59137e671d2 | 6,003 |
def lorentzian(coordinates, center, fwhm):
"""
Unit integral Lorenzian function.
Parameters
----------
coordinates : array-like
Can be either a list of ndarrays, as a meshgrid coordinates list, or a
single ndarray for 1D computation
center : array-like
Center of the lorentzian. Should be the same sh... | 8631ef30f0fd50ac516f279cd130d6d9b099d953 | 6,004 |
def _to_gzip_base64(self, **kwargs):
""" Reads the file as text, then turns to gzip+base64"""
data = self.read_text(**kwargs)
return Base.b64_gzip_encode(data) | bb3e01bcac5e551d862629e79f4c54827ca3783c | 6,005 |
import traceback
def get_recipe_data(published=False, complete_data=False):
"""Return published or unpublished recipe data."""
try:
Changed = User.alias()
recipes = recipemodel.Recipe.select(
recipemodel.Recipe, storedmodel.Stored,
pw.fn.group_concat(tagmodel.Tag.tagnam... | 35afc8247912bd6814b5f4e76716f39d9f244e90 | 6,006 |
def html_anchor_navigation(base_dir, experiment_dir, modules):
"""Build header of an experiment with links to all modules used for rendering.
:param base_dir: parent folder in which to look for an experiment folders
:param experiment_dir: experiment folder
:param modules: list of all loaded modules
... | 1fea16c0aae2f73be713271de5f003e608cee7e9 | 6,007 |
from re import M
def connect_and_play(player, name, channel, host, port,
logfilename=None, out_function=None, print_state=True,
use_debugboard=False, use_colour=False, use_unicode=False):
"""
Connect to and coordinate a game with a server, return a string describing
the result.
"""
... | 2b8a9fe1e0e2edeb888e57d7ffd9cc59e3bd4e4e | 6,008 |
import typing
def _to_int_and_fraction(d: Decimal) -> typing.Tuple[int, str]:
"""convert absolute decimal value into integer and decimal (<1)"""
t = d.as_tuple()
stringified = ''.join(map(str, t.digits))
fraction = ''
if t.exponent < 0:
int_, fraction = stringified[:t.exponent], stringifi... | d1f83df06ae42cdc3e6b7c0582397ee3a79ff99b | 6,009 |
import json
def json_to_obj(my_class_instance):
"""
Получает на вход JSON-представление,
выдает на выходе объект класса MyClass.
>>> a = MyClass('me', 'my_surname', True)
>>> json_dict = get_json(a)
>>> b = json_to_obj(json_dict)
<__main__.MyClass object at 0x7fd8e9634510>
"""
some... | 1f881e609f1c895173f4c27ebdaf413a336a4b8f | 6,010 |
def all_tags(path) -> {str: str}:
"""Method to return Exif tags"""
file = open(path, "rb")
tags = exifread.process_file(file, details=False)
return tags | 29132ad176ba68d7026ebb78d9fed6170833255e | 6,011 |
def static(request):
"""
Backport django.core.context_processors.static to Django 1.2.
"""
return {'STATIC_URL': djangoSettings.STATIC_URL} | cf74daed50e7e15f15fbe6592f36a523e388e11e | 6,012 |
def genBoard():
"""
Generates an empty board.
>>> genBoard()
["A", "B", "C", "D", "E", "F", "G", "H", "I"]
"""
# Empty board
empty = ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
# Return it
return empty | c47e766a0c897d3a1c589a560288fb52969c04a3 | 6,013 |
def _partition_at_level(dendrogram, level) :
"""Return the partition of the nodes at the given level
A dendrogram is a tree and each level is a partition of the graph nodes.
Level 0 is the first partition, which contains the smallest snapshot_affiliations, and the best is len(dendrogram) - 1.
The higher the level ... | b179127076c386480c31a18a0956eb30d5f4ef2a | 6,014 |
import logging
import collections
import sys
def filter_multi_copy_clusters(idx):
"""
{cluster_id : {taxonomy : {genomeid : [gene_uuid,...]}}}
"""
logging.info('Filtering out multi-copy genes...')
clust_cnt = collections.defaultdict(dict)
to_remove = []
for cluster_id,v in idx.items():
... | 0c4122fb6119f827bd7b61debc12701064ec7d34 | 6,015 |
def generate_ab_data():
"""
Generate data for a second order reaction A + B -> P
d[A]/dt = -k[A][B]
d[B]/dt = -k[A][B]
d[P]/dt = k[A][B]
[P] = ([B]0 - [A]0 h(t)) / (1 - h(t)) where
h(t) = ([B]0 / [A]0) e^(kt ([B]0 - [A]0))
Data printed in a .csv file
"""
times = np.linspace(0... | d36521953129b5e002d3a3d2bcf929322c75470c | 6,016 |
import typing
def autocomplete(segment: str, line: str, parts: typing.List[str]):
"""
:param segment:
:param line:
:param parts:
:return:
"""
if parts[-1].startswith('-'):
return autocompletion.match_flags(
segment=segment,
value=parts[-1],
sho... | 8d929e96684d8d1c3ad492424821d27c4d1a2e66 | 6,017 |
def elast_tri3(coord, params):
"""Triangular element with 3 nodes
Parameters
----------
coord : ndarray
Coordinates for the nodes of the element (3, 2).
params : tuple
Material parameters in the following order:
young : float
Young modulus (>0).
poisson ... | 5a0381bb7961b811650cc57af7317737995dd866 | 6,018 |
import torch
def make_offgrid_patches_xcenter_xincrement(n_increments:int, n_centers:int, min_l:float, patch_dim:float, device):
"""
for each random point in the image and for each increments, make a square patch
return: I x C x P x P x 2
"""
patches_xcenter = make_offgrid_patches_xcenter(n_center... | dc7fe393e6bee691f9c6ae399c52668ef98372c4 | 6,019 |
def load_gazes_from_xml(filepath: str) -> pd.DataFrame:
"""loads data from the gaze XML file output by itrace.
Returns the responses as a pandas DataFrame
Parameters
----------
filepath : str
path to XML
Returns
-------
pd.DataFrame
Gazes contained in the xml file
... | b1fd17eace5ea253ce82617f5e8c9238a78d925a | 6,020 |
def axis_rotation(points, angle, inplace=False, deg=True, axis='z'):
"""Rotate points angle (in deg) about an axis."""
axis = axis.lower()
# Copy original array to if not inplace
if not inplace:
points = points.copy()
# Convert angle to radians
if deg:
angle *= np.pi / 180
... | dccb663a9d8d4f6551bde2d6d26868a181c3c0a7 | 6,021 |
async def unhandled_exception(request: Request, exc: UnhandledException):
"""Raises a custom TableKeyError."""
return JSONResponse(
status_code=400,
content={"message": "Something bad happened" f" Internal Error: {exc.message!r}"},
) | bff466190f5804def1416ee6221dccb3739c7dec | 6,022 |
def register_view(request):
"""Render HTTML page"""
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, "Account was cre... | c129a561c31c442ca091cfe38cb2f7a27f94a25d | 6,023 |
def luv2rgb(luv, *, channel_axis=-1):
"""Luv to RGB color space conversion.
Parameters
----------
luv : (..., 3, ...) array_like
The image in CIE Luv format. By default, the final dimension denotes
channels.
Returns
-------
out : (..., 3, ...) ndarray
The image in R... | bac8e7155f2249135158786d39c1f2d95af22fc8 | 6,024 |
def deposit_fetcher(record_uuid, data):
"""Fetch a deposit identifier.
:param record_uuid: Record UUID.
:param data: Record content.
:returns: A :class:`invenio_pidstore.fetchers.FetchedPID` that contains
data['_deposit']['id'] as pid_value.
"""
return FetchedPID(
provider=Depos... | c4505eff50473204c5615991f401a45cc53779a1 | 6,025 |
import time
def make_filename():
""""This functions creates a unique filename."""
unique_filename = time.strftime("%Y%m%d-%H%M%S")
#unique_filename = str(uuid.uuid1())
#unique_filename = str(uuid.uuid1().hex[0:7])
save_name = 'capture_ferhat_{}.png'.format(unique_filename)
return(save_name) | bf16b642884381d795148e045de2387d0acaf23d | 6,026 |
import re
def compareLists(sentenceList, majorCharacters):
"""
Compares the list of sentences with the character names and returns
sentences that include names.
"""
characterSentences = defaultdict(list)
for sentence in sentenceList:
for name in majorCharacters:
if re.searc... | 4b41da794ff936a3769fe67580b989e0de343ee7 | 6,027 |
import re
def is_live_site(url):
"""Ensure that the tool is not used on the production Isaac website.
Use of this tool or any part of it on Isaac Physics and related websites
is a violation of our terms of use: https://isaacphysics.org/terms
"""
if re.search("http(s)?://isaac(physics|chemis... | 407624a049e92740eb82753d941780a446b1facf | 6,028 |
def score_false(e, sel):
"""Return scores for internal-terminal nodes"""
return e*(~sel).sum() | 077cd38c6d1186e2d70fd8a93f44249b0cef2885 | 6,029 |
import os
import tkinter as tk
import tkinter.font as TkFont
from .BiblioSys import DISPLAYS,GUI_DISP
def Select_multi_items(list_item,mode='multiple', fact=2, win_widthmm=80, win_heightmm=100, font_size=16):
"""interactive selection of items among the list list_item
Args:
list_item (list): lis... | ba0eacf5d05e0a51ef5a2415ef94a39d395afbdf | 6,030 |
import logging
import numpy
def retrieveXS(filePath, evMin=None, evMax=None):
"""Open an ENDF file and return the scattering XS"""
logging.info('Retrieving scattering cross sections from file {}'
.format(filePath))
energies = []
crossSections = []
with open(filePath) as fp:
... | 388986facd75540983870f1f7e0a6f51b6034271 | 6,031 |
import string
def _parse_java_simple_date_format(fmt):
"""
Split a SimpleDateFormat into literal strings and format codes with counts.
Examples
--------
>>> _parse_java_simple_date_format("'Date:' EEEEE, MMM dd, ''yy")
['Date: ', ('E', 5), ', ', ('M', 3), ' ', ('d', 2), ", '", ('y', 2)]
... | 3fe42e4fc96ee96c665c3c240cb00756c8534c84 | 6,032 |
import logging
def rekey_by_sample(ht):
"""Re-key table by sample id to make subsequent ht.filter(ht.S == sample_id) steps 100x faster"""
ht = ht.key_by(ht.locus)
ht = ht.transmute(
ref=ht.alleles[0],
alt=ht.alleles[1],
het_or_hom_or_hemi=ht.samples.het_or_hom_or_hemi,
#GQ=ht.samples.GQ,
HL=ht.samples.H... | 3e879e6268017de31d432706dab9e672e85673aa | 6,033 |
import collections
def _sample_prior_fixed_model(formula_like, data=None,
a_tau=1.0, b_tau=1.0, nu_sq=1.0,
n_iter=2000,
generate_prior_predictive=False,
random_state=None):
"""Sample from prior ... | 1e57cd3f8812e28a8d178199d3dd9c6a23614dc0 | 6,034 |
from typing import Any
async def validate_input(
hass: core.HomeAssistant, data: dict[str, Any]
) -> dict[str, str]:
"""Validate the user input allows us to connect.
Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
"""
zeroconf_instance = await zeroconf.async_get_ins... | 5ececb6dfc84e232d413b2ada6c6076a75420b49 | 6,035 |
def closeWindow(plotterInstance=None):
"""Close the current or the input rendering window."""
if not plotterInstance:
plotterInstance = settings.plotter_instance
if not plotterInstance:
return
if plotterInstance.interactor:
plotterInstance.interactor.ExitCallback()
... | af3df7fa07069413c59f498529f4d21a9b88e9f4 | 6,036 |
def _format_stages_summary(stage_results):
"""
stage_results (list of (tuples of
(success:boolean, stage_name:string, status_msg:string)))
returns a string of a report, one line per stage.
Something like:
Stage: <stage x> :: SUCCESS
Stage: <stage y> :: FAILED
Stage: <s... | 2f5c757342e98ab258bdeaf7ffdc0c5d6d4668ca | 6,037 |
import json
def pack(envelope, pack_info):
"""Pack envelope into a byte buffer.
Parameters
----------
envelope : data structure
pack_info : packing information
Returns
-------
packet : bytes
"""
ptype = pack_info.ptype
packer = packers[ptype]
payload = packer.pack(en... | 5202e9eef7fc658157798d7f0d64820b1dfa3ac3 | 6,038 |
import tempfile
def tmpnam_s():
"""Implementation of POSIX tmpnam() in scalar context"""
ntf = tempfile.NamedTemporaryFile(delete=False)
result = ntf.name
ntf.close()
return result | a8c193a0e1ed6cd386dda9e0c084805cbed5f189 | 6,039 |
def timezone_lookup():
"""Force a timezone lookup right now"""
TZPP = NSBundle.bundleWithPath_("/System/Library/PreferencePanes/"
"DateAndTime.prefPane/Contents/"
"Resources/TimeZone.prefPane")
TimeZonePref = TZPP.classNamed_('TimeZoneP... | a78a7f32f02e4f6d33b91bb68c1330d531b0208e | 6,040 |
def rollingCPM(dynNetSN:DynGraphSN,k=3):
"""
This method is based on Palla et al[1]. It first computes overlapping snapshot_communities in each snapshot based on the
clique percolation algorithm, and then match snapshot_communities in successive steps using a method based on the
union graph.
[1] P... | b4050544cd8a98346f436c75e5c3eeeb9a64c030 | 6,041 |
def penalty_eqn(s_m, Dt):
"""
Description:
Simple function for calculating the penalty for late submission of a project.
Args:
:in (1): maximum possible score
:in (2): difference between the date of deadline and the date of assignment of the project (in hours)
:out (1): rounded result of ... | 694a2b77c1612d7036c46768ee834043a1af3902 | 6,042 |
import re
def stop(name=None, id=None):
"""
Stop (terminate) the VM identified by the given id or name.
When both a name and id are provided, the id is ignored.
name:
Name of the defined VM.
id:
VM id.
CLI Example:
.. code-block:: bash
salt '*' vmctl.stop name=... | 3dbb2771f7407f3a28a9249551268b9ba23d906e | 6,043 |
def ky_att(xs, b, Mach, k0, Att=-20):
"""
Returns the spanwise gust wavenumber 'ky_att' with response at 'xs' attenuated by 'Att' decibels
Parameters
----------
xs : float
Chordwise coordinate of reference point, defined in interval (-b, +b].
b : float
Airfoil semi chord.
... | 78d62081d0849d035953a694bbb7a0fcf956f76b | 6,044 |
from typing import Optional
def has_multiline_items(strings: Optional[Strings]) -> bool:
"""Check whether one of the items in the list has multiple lines."""
return any(is_multiline(item) for item in strings) if strings else False | 75dd6ce7d7152a200ff12c53104ff839a21d28f4 | 6,045 |
from typing import Optional
from typing import Tuple
import inspect
def eval_ctx(
layer: int = 0, globals_: Optional[DictStrAny] = None, locals_: Optional[DictStrAny] = None
) -> Tuple[DictStrAny, DictStrAny]:
"""获取一个上下文的全局和局部变量
Args:
layer (int, optional): 层数. Defaults to 0.
globals_ (Op... | 81b782596bcc29f1be4432cc1b95230ac952bf2b | 6,046 |
import os
import re
def find_ports(device):
"""
Find the port chain a device is plugged on.
This is done by searching sysfs for a device that matches the device
bus/address combination.
Useful when the underlying usb lib does not return device.port_number for
whatever reason.
"""
bus... | aec31745b0d28ea58803242faca43258e8a78dd6 | 6,047 |
def extract_vcalendar(allriscontainer):
"""Return a list of committee meetings extracted from html content."""
vcalendar = {
'vevents': findall_events(allriscontainer),
}
if vcalendar.get('vevents'):
base_url = allriscontainer.base_url
vcalendar['url'] = find_calendar_url(base_ur... | f792ae3d8826d37b2fba874524ec78ac502fb1f0 | 6,048 |
def rnn_helper(inp,
length,
cell_type=None,
direction="forward",
name=None,
reuse=None,
*args,
**kwargs):
"""Adds ops for a recurrent neural network layer.
This function calls an actual implementation of ... | d6d457a10bd921560a76bc54a083271c82b144ec | 6,049 |
def get_data(dataset):
"""
:return: encodings array of (2048, n)
labels list of (n)
"""
query = "SELECT * FROM embeddings WHERE label IS NOT NULL"
cursor, connection = db_actions.connect(dataset)
cursor.execute(query)
result_list = cursor.fetchall()
encodings = np.zeros((2... | 9f23631c6e263f99bab976e1225adbb448323783 | 6,050 |
def read_hdr(name, order='C'):
"""Read hdr file."""
# get dims from .hdr
h = open(name + ".hdr", "r")
h.readline() # skip line
l = h.readline()
h.close()
dims = [int(i) for i in l.split()]
if order == 'C':
dims.reverse()
return dims | 57daadfdf2342e1e7ef221cc94f2e8f70c504944 | 6,051 |
def IsTouchDevice(dev):
"""Check if a device is a touch device.
Args:
dev: evdev.InputDevice
Returns:
True if dev is a touch device.
"""
keycaps = dev.capabilities().get(evdev.ecodes.EV_KEY, [])
return evdev.ecodes.BTN_TOUCH in keycaps | 6fd36c4921f3ee4bf37c6ce8bcaf435680fc82d5 | 6,052 |
def load_users():
"""
Loads users csv
:return:
"""
with open(USERS, "r") as file:
# creates dictionary to separate csv values to make it easy to iterate between them
# the hash() function is used to identify the values in the csv, as they have their individual hash
# keys, a... | 255745d36b5b995dfd9a8c0b13a154a87ab6f25e | 6,053 |
import re
import sys
def main(argv):
"""
Push specified revision as a specified bookmark to repo.
"""
args = parse_arguments(argv)
pulled = check_output([args.mercurial_binary, 'pull', '-B', args.bookmark, args.repo]).decode('ascii')
print(pulled)
if re.match("adding changesets", pulled... | 83bb61ab9a1a1fcd138782b268d78a1f63164131 | 6,054 |
def clustering_consistency_check(G):
""" Check consistency of a community detection algorithm by running it a number of times.
"""
Hun = G.to_undirected()
Hun = nx.convert_node_labels_to_integers(Hun,label_attribute='skeletonname')
WHa = np.zeros((len(Hun.nodes()),len(Hun.nodes())))
for i ... | 917bb7a23b651821389edbcc62c81fbe4baf3d08 | 6,055 |
def l2_normalize_rows(frame):
"""
L_2-normalize the rows of this DataFrame, so their lengths in Euclidean
distance are all 1. This enables cosine similarities to be computed as
dot-products between these rows.
Rows of zeroes will be normalized to zeroes, and frames with no rows will
be returned... | 889c2f4473fdab4661fecdceb778aae1bb62652d | 6,056 |
import socket
def canonical_ipv4_address(ip_addr):
"""Return the IPv4 address in a canonical format"""
return socket.inet_ntoa(socket.inet_aton(ip_addr)) | edacc70ccc3eef12030c4c597c257775d3ed5fa4 | 6,057 |
def _build_dynatree(site, expanded):
"""Returns a dynatree hash representation of our pages and menu
hierarchy."""
subtree = _pages_subtree(site.doc_root, site.default_language, True, 1,
expanded)
subtree['activate'] = True
pages_node = {
'title': 'Pages',
'key': 'system:page... | 38dd222ed5cde6b4d6bff4a632c6150666580b92 | 6,058 |
import logging
def check_tie_condition(board):
""" tie = if no empty cells and no win """
logging.debug('check_tie_condition()')
# is the board full and no wins
empty_cells = board.count('-')
logging.debug(f'Number of empty cells {empty_cells}')
tie = (empty_cells == 0)
return tie | 81325de769d401d1dd11dcf60f490bb76653b6e9 | 6,059 |
def aggregator(df, groupbycols):
"""
Aggregates flowbyactivity or flowbysector df by given groupbycols
:param df: Either flowbyactivity or flowbysector
:param groupbycols: Either flowbyactivity or flowbysector columns
:return:
"""
# tmp replace null values with empty cells
df = replace... | f8333087efc4a48d70aa6e3d727f73a7d03c8252 | 6,060 |
def unpack(X):
""" Unpack a comma separated list of values into a flat list """
return flatten([x.split(",") for x in list(X)]) | 1033fd5bdcd292a130c08a8f9819bf66a38fccac | 6,061 |
def doize(tock=0.0, **opts):
"""
Decorator that returns Doist compatible decorated generator function.
Usage:
@doize
def f():
pass
Parameters:
tock is default tock attribute of doized f
opts is dictionary of remaining parameters that becomes .opts attribute
o... | 0c4a4220546b8c0cbc980c10de0476c9fc6c7995 | 6,062 |
import codecs
import yaml
import logging
def get_env(path):
"""
Read the environment file from given path.
:param path: Path to the environment file.
:return: the environment (loaded yaml)
"""
with codecs.open(path, 'r', 'UTF-8') as env_file:
conf_string = env_file.read()
env ... | 92118337c73a2d01df27242145687619dc7571a7 | 6,063 |
def make_chained_transformation(tran_fns, *args, **kwargs):
"""Returns a dataset transformation function that applies a list of
transformations sequentially.
Args:
tran_fns (list): A list of dataset transformation.
*args: Extra arguments for each of the transformation function.
**kw... | 5f24e030df74a0617e633ca8f8d4a3954674b001 | 6,064 |
def configure_optimizer(learning_rate):
"""Configures the optimizer used for training.
Args:
learning_rate: A scalar or `Tensor` learning rate.
Returns:
An instance of an optimizer.
Raises:
ValueError: if FLAGS.optimizer is not recognized.
"""
if FLAGS.optimizer == 'adadelta':
optim... | bf7dd03c4133675d58428a054cc16e7be41e88b4 | 6,065 |
import functools
def train_and_evaluate(config, workdir):
"""Runs a training and evaluation loop.
Args:
config: Configuration to use.
workdir: Working directory for checkpoints and TF summaries. If this
contains checkpoint training will be resumed from the latest checkpoint.
Returns:
Trainin... | 87f1dba561563acc0033663a30f105fe4056d235 | 6,066 |
def increment(i,k):
""" this is a helper function for a summation of the type :math:`\sum_{0 \leq k \leq i}`,
where i and k are multi-indices.
Parameters
----------
i: numpy.ndarray
integer array, i.size = N
k: numpy.ndarray
integer array, k.size = N... | 1ac8ef592376fbfa0d04cdd4b1c6b29ad3ed9fbd | 6,067 |
def sample_lopt(key: chex.PRNGKey) -> cfgobject.CFGObject:
"""Sample a small lopt model."""
lf = cfgobject.LogFeature
rng = hk.PRNGSequence(key)
task_family_cfg = para_image_mlp.sample_image_mlp(next(rng))
lopt_name = parametric_utils.choice(
next(rng), [
"LearnableAdam", "LearnableSGDM", "L... | b52a7640532ed8ce7760474edbd9832d93e7bdc3 | 6,068 |
import numpy
import time
def gen_df_groupby_usecase(method_name, groupby_params=None, method_params=''):
"""Generate df groupby method use case"""
groupby_params = {} if groupby_params is None else groupby_params
groupby_params = get_groupby_params(**groupby_params)
func_text = groupby_usecase_tmpl.... | 3a4f5745744299db354c17198d3175ad8b7ce4e4 | 6,069 |
import os
def hydra_breakpoints(in_bam, pair_stats):
"""Detect structural variation breakpoints with hydra.
"""
in_bed = convert_bam_to_bed(in_bam)
if os.path.getsize(in_bed) > 0:
pair_bed = pair_discordants(in_bed, pair_stats)
dedup_bed = dedup_discordants(pair_bed)
return run... | 8df6dc1e4b8649cf9059c9871955fc7e24ff01b6 | 6,070 |
import csv
def merge_csvfiles(options):
""" Think of this as a 'join' across options.mergefiles on equal values of
the column options.timestamp. This function takes each file in
options.mergefiles, reads them, and combines their columns in
options.output. The only common column should be options.time... | 171b448c2b49584ce5a601f7d8789d7198fdf935 | 6,071 |
import html
def row_component(cards):
"""
Creates a horizontal row used to contain cards.
The card and row_component work together to create a
layout that stretches and shrinks when the user changes the size of the window,
or accesses the dashboard from a mobile device.
See https://developer.... | baa9f86bcac786a94802d003b1abcc75686e08d8 | 6,072 |
def recCopyElement(oldelement):
"""Generates a copy of an xml element and recursively of all
child elements.
:param oldelement: an instance of lxml.etree._Element
:returns: a copy of the "oldelement"
.. warning::
doesn't copy ``.text`` or ``.tail`` of xml elements
"""
newelement =... | 981f0c5ccdeacc1d82ebbde2de6f51298e82fa14 | 6,073 |
def NameExpansionIterator(command_name,
debug,
logger,
gsutil_api,
url_strs,
recursion_requested,
all_versions=False,
cmd_supports_recursi... | d84575c5e26e489853f3ead760af60cc15c7a84c | 6,074 |
import hashlib
def KETAMA(key):
"""
MD5-based hashing algorithm used in consistent hashing scheme
to compensate for servers added/removed from memcached pool.
"""
d = hashlib.md5(key).digest()
c = _signed_int32
h = c((ord(d[3])&0xff) << 24) | c((ord(d[2]) & 0xff) << 16) | \
c((... | 6baec2ea79a166389625b19c56cbcd3734e819b7 | 6,075 |
import calendar
def add_months(dt, months):
"""
月加减
"""
month = dt.month - 1 + months
year = dt.year + month / 12
month = month % 12 + 1
day = min(dt.day, calendar.monthrange(year, month)[1])
return dt.replace(year=year, month=month, day=day) | 5770c1b61e53fc692f3b13efef203d2f5d544b80 | 6,076 |
def _decomposer_interp(fp, x=None, xp=None):
"""Do the actual interpolation for multiprocessing"""
return np.interp(x, xp, fp) | eef6debf668c62f4d817a0b3697019d0bd4007c9 | 6,077 |
import tensorflow as tf
from nn4omtf import utils
import numpy as np
def create_nn(x, x_shape, is_training):
"""
Args:
x: input hits array
x_shape: input tensor shape for single event
is_training: placeholder for indicating train or valid/test phase
Note: Only code in `create_nn` ... | 8c7a4ce128e434e964b951ca6fe65722c9936be9 | 6,078 |
import os
from unittest.mock import call
def create_new_case(case_dir):
"""Creates new case directory"""
# Check that the specified case directory does not already exist
if os.path.exists(case_dir):
call(["rm", "-r", "snappy"])
#raise RuntimeError(
# 'Refusing to write to ex... | b9aba60caa0862e09037b16712f35ff5ca993143 | 6,079 |
def generate_outlier_bounds_iqr(df, column, multiplier=1.5):
"""
Takes in a dataframe, the column name, and can specify a multiplier (default=1.5). Returns the upper and lower bounds for the
values in that column that signify outliers.
"""
q1 = df[column].quantile(.25)
q3 = df[column].quantile(.... | 7f096d5f5cf2417cbc161713715a39560efd140a | 6,080 |
import random
def generate_data(Type):
"""
随机生成CAN帧中所包含的数据
:param Type: 需要生成数据的类型
:return: 生成的随机数据序列,长度为8,如['88', '77', '55', '44', '22', '11', '33'', '44']
"""
data = []
if Type == 1:
# 生成反馈帧单体电池Cell1-24电压信息
standard_vol = 35
offset = random.randint(0, 15)
... | 3a920be4b7ef5c5c3e258b3e3c79bc028004179a | 6,081 |
def counting_sort(array):
"""
SORTING FUNCTION USING COUNTING SORT ALGORITHM
ARG array = LIST(ARRAY) OF NUMBERS
"""
## counter lists has elements for every
maximum = max(array)
counter = [0]*(maximum+1)
for i in range(len(array)):
counter[array[i]] += 1
for i in range(1, ma... | 986e2f9277fa71dcd9897ac409653009c651c49f | 6,082 |
import math
from PIL import ImageColor
def indexedcolor(i, num, npersat=15, lightness=60):
"""Returns an rgb color triplet for a given index, with a finite max 'num'.
Thus if you need 10 colors and want to get color #5, you would call this with (5, 10).
The colors are "repeatable".
"""
nsats = int... | 418a875bc8ae50ce21f9667f46718863ba0f55e3 | 6,083 |
def make_customer_satisfaction(branch_index='A'):
"""Create average customer satisfaction heat map"""
customer_satisfaction = make_heat_map(branch_index, 'mean(Rating)', 'Average Satisfaction')
return customer_satisfaction | b891b74a8942da7c212ba7112ffb865deb52aec2 | 6,084 |
def extract_infos(fpath):
"""Extract information about file"""
try:
pe = pefile.PE(fpath)
except pefile.PEFormatError:
return {}
res = {}
res['Machine'] = pe.FILE_HEADER.Machine
res['SizeOfOptionalHeader'] = pe.FILE_HEADER.SizeOfOptionalHeader
res['Characteristics'] = pe.FIL... | f7f3cbef72f7b9d05c25e2aabde33c7a814d05bd | 6,085 |
def calibrate_eye_in_hand(calibration_inputs):
"""Perform eye-in-hand calibration.
Args:
calibration_inputs: List of HandEyeInput
Returns:
A HandEyeOutput instance containing the eye-in-hand transform
"""
return HandEyeOutput(
_zivid.calibration.calibrate_eye_in_hand(
... | d8bc7b8cfe821809c441d3151297edf7f8267803 | 6,086 |
from typing import Optional
def get_intersect(A: np.ndarray, B: np.ndarray, C: np.ndarray, D: np.ndarray) -> Optional[np.ndarray]:
"""
Get the intersection of [A, B] and [C, D]. Return False if segment don't cross.
:param A: Point of the first segment
:param B: Point of the first segment
:param C... | 1c3fab6d189f218e9f5f7e6648a46a9e53683366 | 6,087 |
from typing import Callable
def _make_vector_laplace_scipy_nd(bcs: Boundaries) -> Callable:
""" make a vector Laplacian using the scipy module
This only supports uniform discretizations.
Args:
bcs (:class:`~pde.grids.boundaries.axes.Boundaries`):
|Arg_boundary_conditions|
... | 3cda36d53755c84fcb47259ade64752610aeffbe | 6,088 |
def dot_to_dict(values):
"""Convert dot notation to a dict. For example: ["token.pos", "token._.xyz"]
become {"token": {"pos": True, "_": {"xyz": True }}}.
values (iterable): The values to convert.
RETURNS (dict): The converted values.
"""
result = {}
for value in values:
path = res... | a2c56a01b179d27eabc728d6ff2ec979885d5feb | 6,089 |
def _draw_edges(G, pos, nodes, ax):
"""Draw the edges of a (small) networkx graph.
Params:
G (nx.classes.*) a networkx graph.
pos (dict) returned by nx.layout methods.
nodes (dict) of Circle patches.
ax (AxesSubplot) mpl axe.
Return:
... | 28a207a190a7066656518de7c8e8626b2f534146 | 6,090 |
def benjamini_hochberg_stepup(p_vals):
"""
Given a list of p-values, apply FDR correction and return the q values.
"""
# sort the p_values, but keep the index listed
index = [i[0] for i in sorted(enumerate(p_vals), key=lambda x:x[1])]
# keep the p_values sorted
p_vals = sorted(p_vals)
q... | 7cff2e8d28cda37c4271935ef2e6fb48441137c3 | 6,091 |
def remove_transcription_site(rna, foci, nuc_mask, ndim):
"""Distinguish RNA molecules detected in a transcription site from the
rest.
A transcription site is defined as as a foci detected within the nucleus.
Parameters
----------
rna : np.ndarray, np.int64
Coordinates of the detected ... | 3f6fe083cb85dbf2f7bc237e750be57f13398889 | 6,092 |
def hexagonal_numbers(length: int) -> list[int]:
"""
:param len: max number of elements
:type len: int
:return: Hexagonal numbers as a list
Tests:
>>> hexagonal_numbers(10)
[0, 1, 6, 15, 28, 45, 66, 91, 120, 153]
>>> hexagonal_numbers(5)
[0, 1, 6, 15, 28]
>>> hexagonal_numbers(0... | 632e60505cb17536a17b20305a51656261e469f5 | 6,093 |
def get_free_remote_port(node: Node) -> int:
"""Returns a free remote port.
Uses a Python snippet to determine a free port by binding a socket
to port 0 and immediately releasing it.
:param node: Node to find a port on.
"""
output = node.run("python -c 'import socket; s=socket.soc... | 4cdb0f62909abae1af8470611f63fcc9f5495095 | 6,094 |
from typing import Tuple
from typing import List
import tqdm
def read_conll_data(data_file_path: str) -> Tuple[List[Sentence], List[DependencyTree]]:
"""
Reads Sentences and Trees from a CONLL formatted data file.
Parameters
----------
data_file_path : ``str``
Path to data to be read.
... | 6bee76277fb6a15d03c5c80a5d083920a4412222 | 6,095 |
from typing import Optional
def get_algo_meta(name: AlgoMeta) -> Optional[AlgoMeta]:
"""
Get meta information of a built-in or registered algorithm.
Return None if not found.
"""
for algo in get_all_algo_meta():
if algo.name == name:
return algo
return None | 3a568356d56d26192a1e38be6ec5dd57b52a9bba | 6,096 |
def do_eval(sess,input_ids,input_mask,segment_ids,label_ids,is_training,loss,probabilities,vaildX, vaildY, num_labels,batch_size,cls_id):
"""
evalution on model using validation data
"""
num_eval=1000
vaildX = vaildX[0:num_eval]
vaildY = vaildY[0:num_eval]
number_examples = len(vaildX)
e... | f3059d0dbbf00c0d0a93273dbf3f1335d2feefeb | 6,097 |
def read_gbt_target(sdfitsfile, objectname, verbose=False):
"""
Give an object name, get all observations of that object as an 'obsblock'
"""
bintable = _get_bintable(sdfitsfile)
whobject = bintable.data['OBJECT'] == objectname
if verbose:
print("Number of individual scans for Object %... | 1215fdccee50f0ab5d135a5cccf0d02da09410e2 | 6,098 |
def regression_target(label_name=None,
weight_column_name=None,
target_dimension=1):
"""Creates a _TargetColumn for linear regression.
Args:
label_name: String, name of the key in label dict. Can be null if label
is a tensor (single headed models).
weight... | 064954b58b57caeb654ed30f31b9560ab01d7c42 | 6,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.