content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def read_header(ds):
"""Read a RAMSES output header file."""
folder = './'
iout = int(str(ds)[-5:])
hname = '{0}/output_{1:05d}/header_{1:05d}.txt'.format(folder, iout)
with open(hname, 'r') as hfile:
htxt = hfile.read()
header_re = re.compile("Total number of particles\s+(... | 3d19aa144e25ab2bfccf0ec422ba3a4db4542b20 | 645,153 |
def collect_vertices(geometry):
"""Returns all vertices within the given geometry as a list."""
vertices = []
vertices_iter = geometry.vertices()
while vertices_iter.hasNext():
vertices.append(vertices_iter.next())
return vertices | 19381cb28a475e62f47240a1cadef481a5f34a44 | 645,154 |
import re
def stresses(s):
"""Get the vowel stresses for a given string of CMUdict phones.
Returns only the vowel stresses (i.e., digits) for a given phone string.
.. doctest::
>>> import pronouncing
>>> pronouncing.stresses(pronouncing.phones_for_word('obsequious')[0])
'0100'
... | add2f1cebe5b3c94d480d1681b4eb2db8e9b8271 | 645,155 |
import zlib
def adler32_checksum(filepath):
""" Modified from md5_checksum function. This uses the adler32
algorithm to generate a running checksum.
This should be faster than md5 ideally.
"""
with open(filepath, 'rb') as fh:
curr_chksum = 0
while True:
data = fh.read... | 48aec90e98fa5d5fa3e7291f0df607b095506c33 | 645,156 |
def errToLogX(x, y=None, dx=None, dy=None):
"""
calculate error of Log(x)
:param x: float value
:param dx: float value
"""
if dx is None:
dx = 0
# Check that the x point on the graph is zero
if x != 0:
dx = dx / x
else:
raise ValueError("errToLogX: divide b... | 14f42698e684bd378186dbc64785b6bd81751b7a | 645,157 |
def convert_keys_to_variable_names(dict_):
"""
Change keys in dict to comply with PEP8 for variable names.
Keys are converted to all lower case and spaces replaced with underscores.
Parameters
----------
dict_ : :class:`dict`
Dictionary the keys should be renamed in
Returns
--... | de6e9d69fce1ec1b7672159e096793ba0687459d | 645,158 |
import binascii
def pem_to_der(pem_str):
"""Convert a PEM string to DER format"""
lines = pem_str.strip().splitlines()
der = binascii.a2b_base64(''.join(lines[1:-1]))
return der | 6b551c1852aa587152a6ce9c29c68c0044239dd7 | 645,159 |
def build_config(anisotropic, coupled_sym):
"""
Gets training configuration.
Args:
anisotropic (bool): if True, use an anisotropic graph manifold.
coupled_sym (bool): if True, use coupled symmetric layers.
cnn (bool): if True, use a convolutional neural network.
Returns:
... | 39b628d6b92e378c8653df7b92576581c302c309 | 645,161 |
def hashFunc(s):
"""
Call some hashfunc and return the result.
Goes "hashy hashy".
"""
return abs(hash(s)) | 9a7e43f036ee5bd2aeef32260b87d3bb8d70a63a | 645,162 |
def ordered_merge(*pole,**sel):
"""Vraceni listu cisel"""
select=[]
vysledky=[]
listy=[]
if 'selector' not in sel:
return select
else:
select = sel["selector"]
for i in pole:
listy.append(list(i))
for a in select:
vysledky.append(listy[a][0])
listy... | 27b8c313290306bdb6fa43e1f2110727c8f402ce | 645,164 |
import os
def decorate_name(name, decorations=''):
"""
Properly decorate a grid name.
:param name: file name
:param decorations: file decorations, semicolon delimited
:returns: decorated file name
.. versionadded:: 9.1
"""
if name is None:
return None
r... | 5f8c79f86f39de94c90c1899d119b306717a5a77 | 645,165 |
def _remove_edge(grid, edge_ids, neighbors, components, e):
"""
Remove an edge from a spanning tree.
"""
k = edge_ids[e]
v1 = grid[0, k].item()
v2 = grid[1, k].item()
neighbors[v1].remove(v2)
neighbors[v2].remove(v1)
components[v1] = 1
pending = [v1]
while pending:
v1... | 57a9bc0f90e6dbe68f94b86e965417e294935311 | 645,166 |
def gen_package(package_base, sub_package):
"""
package_base: base/common package
sub_package: sub package paths as list (not string)
"""
package = package_base
if sub_package:
package = package + '.' + '.'.join(sub_package)
return package | 878a5c75851d775bf9c34cd3a92b11debb2ff0f7 | 645,167 |
import os
def image_number(image_name):
"""Return the number for an image"""
return int(os.path.basename(image_name).split('.')[0][-4:]) | 3ca22b4b688ab6ddcbb7aea8d0590472cdf4f674 | 645,168 |
def parse_requirements(filename):
"""Given a filename, strip empty lines and those beginning with #."""
with open(filename) as rfd:
output = []
for line in rfd:
line = line.strip()
if line != '' and not line.startswith('#'):
output.append(line)
ret... | f4989867b217e694f9c05be25c9b213ec1dd4b7b | 645,169 |
import json
def convert_context_to_json(context):
"""Convert the context dictionary into a JSON object. note: this is *EXTREMELY* naive; in reality, you'll need to do much more complex handling to ensure that arbitrary objects -- such as Django model instances or querysets -- can be serialized as JSON."""
ret... | 25dc5c064c0e4fef4a6a790e763395deb589052a | 645,170 |
import os
def build_maildir_tar(results, tar, basename):
"""Returns tar file with messages from SearchQuerySet in maildir format"""
for result in results:
arcname = os.path.join(basename, result.object.email_list.name, result.object.hashcode)
tar.add(result.object.get_file_path(), arcname=arcn... | be253feeb0c2cbf9552d21d5fb00797f94cc6aec | 645,171 |
def strD(arr, sep="\n", cep=":\n", caption=""):
""" returns a string representation of a dict object for printing """
res="=-=-=-=-==-=-=-=-={}DICT #[{}] : {}{}=-=-=-=-==-=-=-=-={}".format(sep, len(arr), caption, sep, sep)
for k,v in arr.items():
res+=str(k) + cep + str(v) + sep
return res + "=-... | 09040a7ecffdf6af1638d1c11c3bf669116396f1 | 645,172 |
def get_gene_class(gene):
"""
Return the class of a gene.
Available options are Core or Non-core.
"""
core_genes = ['pif-0', 'pif-1', 'pif-2',
'pif-3', 'pif-4', 'pif-5',
'pif-6', 'pif-7', 'pif-8',
'dnapol', 'desmoplakin',
'dnahe... | 1dfb95d0e97565c3f0e2000d315d0d635a8ed73a | 645,174 |
def sort_sat_types(obs, constellation):
"""
Create lists for each satellite constellation type.
Using the chosen satellite constellation (G/R/E/C):
Assign satellites from the RINEX file to a corresponding list.
If using Mixed option, it creates four separate lists instead,
to hold 4 types of co... | 122f384c19a2cdcf7a244c250d1d4bc6fe8cca0e | 645,175 |
def _create_database_sql(database_name):
"""Return a tuple of statements to create the database with the given name.
:param database_name: Database name
:type: str
:rtype: tuple
"""
tmpl = "create database {} with owner = dcc_owner template = template0 " \
"encoding = 'UTF8' lc_collat... | 48fc179d282750d162eb7544cf4b594d0e2f0729 | 645,176 |
def generate_indices(low_val, high_val):
"""
given a list and a law value and high value, generate four indices that cut the interval by four
"""
step = int(round((high_val - low_val) / 4))
return low_val, low_val + step, low_val + 2 * step, low_val + 3 * step, high_val | 66f8109e4da0e4d5ae8ccc347bfdb80d125020b1 | 645,177 |
def gather_stream_parameters(streams):
"""
Helper function for gathering the stream parameters into a datastructure
and sticking the stream tag into the trace stats dictionaries.
Args:
streams (list):
list of StationStream objects.
Returns:
dict. Dictionary of the strea... | 46c3559b5cfdb09cca579f1688103872824b1cf5 | 645,178 |
def drop_columns(cols):
"""Drop columns in a DataFrame."""
def dropper(data):
return data.drop(columns=cols)
return dropper | e93b1e45b9eda800aa812a41a02c78f459d65172 | 645,179 |
def GetModulePath(obj):
"""Returns the module path string for obj, None if its builtin.
The module path is relative and importable by ImportModule() from any
installation of the current release.
Args:
obj: The object to get the module path from.
Returns:
The module path name for obj if not builtin ... | 2d98b63d49c177353edf92bd722e19dadb5b7d82 | 645,180 |
import torch
def uniform_sample_shape(batch_size, mean_shape, delta_betas_range):
"""
Uniform sampling of shape parameter deviations from the mean.
"""
l, h = delta_betas_range
delta_betas = (h-l)*torch.rand(batch_size, mean_shape.shape[0], device= mean_shape.device) + l
shape = delta_betas + ... | 8d8d5880e5963231661f49b1f0fd91d6fffe0f7e | 645,181 |
def merge(lst1, lst2):
"""Merges two sorted lists into a single sorted list.
Returns new list. lst1 and lst2 are destroyed in the process."""
result = []
while lst1 or lst2:
if not lst1:
return result + lst2
elif not lst2:
return result + lst1
if lst1[0] ... | a6599d8d0d1f845fb7a2c4d31a4bdc81034ceba0 | 645,182 |
import re
def natural(s, _split_re=re.compile(r"(\d+)", flags=re.UNICODE)):
""" for natural sorting. now with unicode support!"""
return tuple((int(c) if c.isdecimal() else c) for c in _split_re.split(s)) | bebd44d7e878f6964e01a0c2930756437623e446 | 645,183 |
def depth(expr):
"""
depth(expr) finds the depth of the mathematical expr formatted as a list.
depth is defined as the deepest level of nested operations within the expression.
"""
if not isinstance(expr, list):
raise TypeError("depth() : expr must be of type list")
else:
exprlen... | 15da365f83432093ea42b60dc3b2f49da206d9fd | 645,184 |
from typing import Dict
import pkg_resources
def get_current_environment_requirements() -> Dict[str, str]:
"""Return package requirements for current python process.
Returns:
A dict of package requirements for current environment
"""
return {
distribution.key: distribution.version
... | e9916b718d9ded2da2105306b7e2cc426ccc208e | 645,185 |
def Sample_n_Hold_Plot(_holds,_period,_end):
"""Starting from a list of points: create the corresponding piecewise-constant x- and y-axis data
Return: piecewise x-axis-data, piecewise y-axis-data"""
square_sig = []
square_x = []
for i in range(0,len(_holds)-1):
square_x += [i*_period] + [(i+... | c569b1f4673d8480711e82fc62ba454adf1aa56c | 645,186 |
def ordinal(n):
""" Converts numbers into ordinal strings """
return (
"%d%s" %
(n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4])) | f8f7bbc3488ae66b67da1e2fd9061540c27b8698 | 645,187 |
def calculate_ttnw(m):
"""
Utility function to calculate days until next watering. Based on a linear
regression model involving soil moisture and time. Other models do suggest a
correlation between temp, lux, and humidity but there wasn't enough data to
get anything really better than the lm.
:... | 37af5e076a812b110bd7f0e757300810ae216b81 | 645,188 |
import argparse
def parse_args():
"""Parse the args."""
parser = argparse.ArgumentParser(
description='storage drl')
parser.add_argument('--agent', type=str, required=False,
default='dqn',
help='choose agent from [dqn, a2c, ppo]')
parser.add_argu... | 742badf525fba6b3402b08debec3b251dc3b39c4 | 645,189 |
import requests
def make_api_call(query):
"""
Builds api object
"""
base_url = "https://query.yahooapis.com/v1/public/yql"
params = {'q': query, 'format': 'json'}
req = requests.get(url=base_url, params=params)
return req.json() | 41b20971a555d7c699175f018ccd3268bf446b66 | 645,190 |
def squareroot(n: int) -> str:
"""Return string vertion of int prepended with a unicode radical symbol.
Useful for pretty printing elements of, for example, a quadratic field.
Example:
>>> print(squareroot(5))
√5
"""
return u"\u221A"+str(n) | b154d04698c291ace2457dab005169306614f0eb | 645,191 |
def get_foo(dummy_context, request):
""" View callable
"""
return {
'uri_parameter': request.matchdict['uri_parameter'],
} | 5e469d483abbfd2fb912ca010282d759bebfbc9b | 645,192 |
import os
import shutil
def prepareDirectories(container):
"""
return the output directory base for all unit tests
This utility method is used to provide other tests the location to store
output files. Two paths are provided by this call - the document
directory and a doctree directory. This meth... | d802dcac27f34aa88c2ae11eb23c576d6ed23382 | 645,193 |
def auth_alias_to_official_habitica_name(auth_info_name: str):
"""
Function that returns habitica official names for the CLI cmd:
hopla get_user user-authenticate [alias]
"""
if auth_info_name in ["e-mail", "mail"]:
return "email"
return auth_info_name | f5db0de1febd7d493f8f15d0f7c565e570a2fbd3 | 645,194 |
def abbrev(information, info, l=0):
"""
return true if the info is an abbreviation of information
with minimum length l
"""
if l>0:
length = l
else:
length = len(info)
cond1 = (len(information) >= len(info))
cond2 = (len(info) >= length)
cond3 = (information[:len(info)] == info)
return cond1 and cond2 an... | 7d8f0a82a419efc349d5f1d8a9c90dba3789cb4e | 645,195 |
def play_qgame(p1, p2, goal):
"""
Takes the 2 starting places & the goal, returns the number of wins for p1 & p2.
"""
# this is a good idea: setting all values first
# also never seen making a dict using list comprehension before
states = {
(x, y, z, w): 0
for x in range(1, 11)
... | c4a6918d471e3edc80627df9402c5e3c4ca69100 | 645,196 |
def SubtractSum(n):
""" subtract_sum == PEP8 (forced PascalCase by Codewars) """
return 'apple' | f37ab92f1213bff306ccab3485b1186e569fb050 | 645,197 |
def get_maximum_telemetry_message_size(client):
"""
Returns the maximum message size (in bytes) the client can support
"""
if client.settings.language == "java" and client.settings.transport == "amqpws":
# java amqpws limitation. Actual number is unknown. This just blocks 63K+ tests.
#... | 5aa4b7e17526b22ff0ac1cbc567ce130aa15cf91 | 645,198 |
import torch
def gershgorin_bounds(H):
"""
Given a square matrix ``H`` compute upper
and lower bounds for its eigenvalues (Gregoshgorin Bounds).
"""
H_diag = torch.diag(H)
H_diag_abs = H_diag.abs()
H_row_sums = H.abs().sum(dim=1)
lb = torch.min(H_diag + H_diag_abs - H_row_sums)
ub ... | c26cd15a781d4317558fa844ccf3bde61f36d3dd | 645,199 |
def _getSource(parent):
"""Finds the highest level CommandGroup of parent"""
try:
return parent._source
except AttributeError:
return parent | 0eb29c62a31c1c2cce8714da6cb8e321c1f1d19e | 645,200 |
import torch
def r_factor(predict, target):
"""
Crystallographic convention R-factor for each member of the dataset
https://dictionary.iucr.org/R_factor
"""
return torch.mean(
torch.abs((target - predict)).sum(dim=1) / torch.abs(predict).sum(dim=1)
) | 90cf5386b38aee24f252e98ca7a2388ea6562dfb | 645,201 |
def to_bytes(s):
"""
Turns the string with suffix of KiB/MiB/GiB into bytes.
:param s: the string (NUM SUFFIX)
:type s: str
:return: the number of bytes
:rtype: int
"""
factor = 1
if s.endswith(" KiB"):
factor = 1024
s = s[:-4].strip()
elif s.endswith(" MiB"):
... | f44c9eef5715a7ed68161045d1bc4c018a9d862c | 645,202 |
import socket
def find_unused_port(base=1025, maxtries=10000):
"""Helper function. Finds an unused server port"""
if base > 65535:
base = 1025
for _ in range(maxtries):
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serversocket.bind(("localhost",... | 1af439ac6882b760ce5a6b0abded895c8b0d1d12 | 645,203 |
def capitalize(line):
"""Capitalize the first char in a string
string.capitalize messes up deliberate upper cases in the strings so
here's a dedicated function.
Args:
line (str): The string to capitalize
Returns:
str: The capitalized string
"""
return line[0].upper() + l... | 4737d6db527866229673be381ebd3a27e6970874 | 645,204 |
import csv
def parse_csv_data(csv_filename: str) -> list:
"""A function thats takes in the name of a csv file and returns a list of strings for the rows in the file"""
rows = [] # a list containing the strings for the rows
with open("{}".format(csv_filename)) as csv_file:
csv_reader = csv.reade... | b3f5c951b1296090b5aba6b81725670baf68fe1f | 645,205 |
from typing import List
def to_factorial_base(n: int) -> List[int]:
"""
Convert a nonnegative integer to its representation in the `factorial
number system <https://en.wikipedia.org/wiki/Factorial_number_system>`_
(represented as a list of digits in descending order of place value, not
including t... | bcee7f9165267bfb9370f0b1256cae4ed7f04237 | 645,206 |
def normalize (bbox):
"""
Normalizes EPSG:4326 bbox order. Returns normalized bbox, and whether it was flipped on horizontal axis.
"""
flip_h = False
bbox = list(bbox)
while bbox[0] < -180.:
bbox[0] += 360.
bbox[2] += 360.
if bbox[0] > bbox[2]:
bbox = (bbox[0],bbox[1],bbox[2]... | 3713b1c4c9d12a9c6d0de5308382bf9464ec672c | 645,207 |
def bandwidth_converter(
number, *, from_unit, to_unit, from_time="seconds", to_time="seconds"
):
"""
Bandwidth Calculator.
Convert data rate from one unit to another.
Arguments:
number (int): number to be converted
Keyword arguments:
from_unit (str): convert from this da... | 93068fb52bc3cd04615749e61a6ecea54b2eda0f | 645,208 |
def checkNull(dummy_dictionary):
"""Given a dictionary, checks if any of the values is null"""
return None in list(dummy_dictionary.values()) | cb19c755a39df123e944ea1ae2b4c1d721161071 | 645,209 |
import re
def camel_case_to_snake_case(s):
"""Convert string in CamelCase to snake_case.
Args:
s (str): String in CamelCase.
Returns:
str: String in snake_case.
"""
_underscorer1 = re.compile(r"(.)([A-Z][a-z]+)")
_underscorer2 = re.compile("([a-z0-9])([A-Z])")
subbed = _und... | 7ad89d0f7ff5d4c5669ccdab13cda98bdfa4e502 | 645,211 |
def get_yesno_input(text):
"""
Gets a yes/no input from the user. The user can type "y" for yes or "n" for no.
:param text: Text to ask user (the yes-no question)
:return: True for yes and False for no
"""
while True:
user_input = input(text + " [y/n] ")
if user_input[0] == 'y':
... | 0af3456fca58596af12e0db0ada080a8cadf1035 | 645,212 |
import argparse
def cmd_parser():
"""
Read Command line arguments
"""
parser = argparse.ArgumentParser(prog='',
description='Create snapshots from trajectory in folder structure')
parser.add_argument('-wd',
help='The top-level working directory containing the snapshot subfolders',
default='./', me... | 73680843630605af179e8f6ab466a8cfe2e298e2 | 645,213 |
import sys
def inside_venv() -> bool:
"""
Determine whether current Python interpreter is running inside a virtual environment.
"""
return (
hasattr(sys, 'real_prefix') or (
hasattr(sys, 'base_prefix')
and sys.base_prefix != sys.prefix
)
) | 3264a733673543fd48e77554ccd9ddaea8b92be8 | 645,214 |
def get_accel_y(fore_veh, back_veh, ego_vy, idm_model):
"""
A wrapper around IDM, given a front and a back vehicle (and the absolute
speed), and a longitudinal driver model, this function returns the
desired acceleration of the back vehicle.
Arguments
fore_vehicle:
A vehicle object, f... | 847cc4c7ed02bb27dcfb0bfed966ad2699cd90b6 | 645,215 |
def memoized_tarai(x, y, z, acc=None):
"""Self-made memoized version of tarai(x, y, z)"""
if x <= y:
return y
if acc is None:
acc = dict()
else:
val = acc.get((x, y, z), None)
if val is not None:
return val
val = memoized_tarai(
memoized_tarai(x ... | 0893b6ccac72be11cbbcb747799ff7ba17647eb5 | 645,216 |
def append_df_columns(dataframe1, dataframe2, dataframe2_col_name, new_appended_col_name):
"""Appends a column of data from one dataframe to another dataframe
Args:
dataframe1 (df): Dataframe to append new column on
dataframe2 (df): Dataframe to pull column of data from
dataframe2_col_na... | ff1af8848cbc0c4767d91299895dbc0631c6cb54 | 645,217 |
def is_valid_key(key):
"""
Return false if key is not alphnumeric or start with letter
"""
if key == "": return False
# check if no invalid charaters
if key.isalnum():
# check if first char is letter
return key[:1].isalpha()
return False | 6a0337167f3ef960ab39f3527da84349830a2291 | 645,218 |
import re
import os
def get_chrom_from_file(filename):
"""
Extract chromosome from filename
"""
m = re.match(r"^(chr[^.]+)\.(.+).bedGraph.gz", os.path.basename(filename))
if m:
return m.groups()
else:
raise Exception("Unable to determine chromosome prefix") | 43aad28d519b5900479a101bb90b185cf6ec7ef6 | 645,220 |
def is_text(response):
"""Determines whether the item downloaded is a text file or something else."""
if ".txt" in response.headers.get("content-type", ""):
return True
return False | 637b5ae1f0b4b545234b3974b8536d93cc0c4661 | 645,221 |
def search4vowels(word):
""" Display any vowel found in an asked-for word. """
vowels = set("aeiou")
found = vowels.intersection(set(word))
return bool(found) | 04976ee2a0df743760af3c46ab416a896efbe881 | 645,222 |
def removeEmptyItems(data):
"""This method removes a empty items from a dictionary"""
removeKeys = []
for key, value in data.items():
if value == "":
removeKeys.append(key)
for key in removeKeys:
data.pop(key)
return data | 0b510057939df6963e62168b314d171a27826e41 | 645,223 |
import timeit
def depthwise_conv_timer_mxnet(c, n, k, ctx):
"""Benchmark convolution in MXNet
c : input, output channels
n : input width and height
k : kernel width and height
"""
timer = timeit.Timer(
setup='import d2ltvm\n'
'import mxnet as mx\n'
'c, n, k, p, s = %d,... | c927503c399c0005010a0165679a5cfd2dec20b3 | 645,224 |
def get_file_content(file_path):
"""Return content of a file."""
return open(file_path).read().strip() | f5047e4ca47f5cc36b5d13e7823f4db3a363d45f | 645,225 |
def get_parameters_doc(doc):
"""
Extracts the documentation of the parameters
"""
if not doc:
return doc
found = False
parameters = []
for line in doc.split("\n"):
words = line.split()
if not found and len(words) == 1 and words[0].startswith("Parameter"):
... | f9fcb08f07da1fe28c3536d5365191783856745b | 645,228 |
import pathlib
def get_base_dir():
"""Get base directory.
Returns
-------
: pathlib.Path
Base directory path.
"""
return pathlib.Path(__file__).parent.parent | 5dbffcc09963466ba3b88d6d1f3b49247e793226 | 645,229 |
def version(request, pytestconfig):
""" :return: 'version' value """
version = request.config.getoption("--influxdb_version")
if not version:
version = pytestconfig.getini('influxdb_version')
return version | 1e9537f58aff6553531de4d81afd679912feb430 | 645,230 |
def get_unique_instruments_in_channel(notes_in_channel):
""" Utility function to get an ordered set of unique instruments in the channel """
all_instruments = []
for notes in notes_in_channel:
all_instruments.append(notes.program)
return sorted(set(all_instruments)) | 6e69f143886456a3667ac997222227cdbfdccdd1 | 645,231 |
def compute_quantity_of_acids(oneLetterCodes, collected_acids):
"""
computes quantity for each aminoacid
Parameters
----------
oneLetterCodes : list of Strings/Chars
contains oneLetterCode for each aminoacid
collected_acids : list
contains position in peptide,
wether it ... | 8f97ea0c24b24a6bdf3754cad224c9f4e89bf756 | 645,233 |
def attr(elem, attr):
"""An html attribute from an html element. E.g. <a href="">, then
attr(elem, "href") will get the href or an empty string."""
try:
return elem[attr]
except:
return "" | 42f34cf67bb5b59ed9f9ace0005ed37aebf079b0 | 645,236 |
def nonrigid_rotations(spc_mod_dct_i):
""" dtermine if a nonrigid rotation model is specified and further
information is needed from the filesystem
"""
rot_model = spc_mod_dct_i['rot']['mod']
return bool(rot_model == 'vpt2') | 76a88cea5c7416dcf2cc539fe5becffbf4f51994 | 645,237 |
def data_filter_with_cluster(adata, groups, method, action='save'):
"""
:param adata: andata对象
:param groups: 分组类别列表
:param action: save|move 选择保留还是移除groups
:return:
"""
if action == 'save':
new_adata = adata[adata.obs[method].isin(groups), :]
else:
new_adata = adata[~ada... | fad6370c9a4c2c37a863dc68c566044506ea7987 | 645,238 |
import math
def vd(inc, sd):
"""
Calculate vertical distance.
:param inc: (float) inclination angle in degrees
:param sd: (float) slope distance in any units
"""
return abs(sd * math.sin(math.radians(inc))) | 730a1d7ae82c79b327af7e6452a498ff8a04868a | 645,240 |
import requests
def get_score_list(token):
"""
获取所有的奖励数据
:param token
:return: dict
"""
data = f"token={token}" \
"&method=gainScoreCircleList" \
f"¶m=%7B%22token%22%3A%22{token}%22%7D"
headers = {
'content-type': 'application/x-www-form-urlencoded'
}
... | ed907e750f297533e345610d26ec3408a0e560bb | 645,241 |
def module_import(app_path):
"""
Imports a module in a given path.
:param str app_path:
A string that contains the path of the module and it's name.
:returns: A reference to the module in the given path.
"""
module = __import__(app_path)
for part in app_path.split('.')[1:]:
... | 8da8c0a6bd35fc5edf174d8751b28122394312b9 | 645,242 |
def canonize_dtypes_and_names(a=None, t=None, y=None, w=None, X=None):
"""
Housekeeping method that assign names for unnamed series and canonizes their data types.
Args:
a (pd.Series|None): Treatment assignment of size (num_subjects,).
t (pd.Series|None): Followup duration, size (num_subjec... | 84f7392a215392715a1c43de18585a748f3c4147 | 645,243 |
import os
def get_val_files(directory, suffix):
"""
Get files in the test directory matching the given suffix (excluding extension) and return them
in a dict where the key is the iteration number.
:param directory: directory to look in
:type directory: str
:param suffix: suffix of files to fi... | 3a7f0e8c367f402c03885377e5c5625252f07d8e | 645,244 |
def build_gen_args(parser):
"""Build gen arguments."""
parser.add_argument("--model_file", type=str, required=True)
parser.add_argument("--out_file", type=str, required=True)
parser.add_argument("--num_sentences", type=int, default=5)
parser.add_argument("--batch_size", type=int, default=100)
pa... | 202854eba24307e62bba7ff00065000b751108d1 | 645,245 |
def intervalComparison(x, lowerBound, upperBound):
"""
classify a value relative to the interval between two bounds:
returns -1 when below the lower bound
returns 0 when between the bounds (inside the interval)
returns +1 when above the upper bound
"""
if (x < lowerBound): return -1
if (x > upperBound): return... | 8725473f029540ee67c48f9cea3f342d7ea28182 | 645,247 |
import itertools
def make_range(start, end):
"""Return a generator of the time steps to iterate over"""
if end is None:
return itertools.count(start=start, step=1)
else:
return range(start, end) | 8e8f5e4561c2b1781ad2c0ec96c20c9e0a91e374 | 645,248 |
import inspect
def deduce_protobuf_types(fn):
"""
Try to extract the class names that are attached as the typing annotation.
:param fn: the function with the annotated parameters.
:return: a list of classes or None.
"""
spec = inspect.getfullargspec(fn)
if not spec:
return None
... | b11b3bdfa5acdcfbfd9958017f583e6bc3b3386f | 645,249 |
import subprocess
def is_running(name, all_users=False):
"""
Determine if process with name is running.
:param `name`: process name
"""
cmd = ["ps", "ux"]
if all_users:
cmd[1] = "aux"
try:
ps = subprocess.Popen(
cmd, stdout=subprocess.PIPE, encoding="utf8"
... | 9166c38f76f08e9d485bed0ceb71a84dfec63b38 | 645,251 |
import math
def inverse_mercator(xy):
"""
Given coordinates in spherical mercator, return a lon,lat tuple.
"""
lon = (xy[0] / 20037508.34) * 180
lat = (xy[1] / 20037508.34) * 180
lat = 180 / math.pi * \
(2 * math.atan(math.exp(lat * math.pi / 180)) - math.pi / 2)
return (lon, lat) | 39c33ca87c475efa5f21366f176429800c478f87 | 645,252 |
import collections
def filter_words(line, count):
""" Filter words in documents less than count. """
cnt = collections.Counter()
for sentence in line:
cnt.update(sentence)
s = set(word for word in cnt if cnt[word] < count)
l_temp = [[word for word in sentence if word not in s] for sentenc... | 6a91cbbe9ec3e50efef992406217a888ad386d4b | 645,254 |
async def safe_read(cluster, attributes, allow_cache=True, only_cache=False):
"""Swallow all exceptions from network read.
If we throw during initialization, setup fails. Rather have an entity that
exists, but is in a maybe wrong state, than no entity. This method should
probably only be used during in... | 3678c883268e2f96830075cacf161a62d3b9947e | 645,255 |
def ngrams(tokens, n):
"""
Reference
---------
http://www.locallyoptimal.com/blog/2013/01/20/elegant-n-gram-generation-in-python/
"""
if n < 1:
raise ValueError("The number of grams should be >= 1.")
return zip(*[tokens[i:] for i in range(n)]) | 379fa7452bf9ea6861dbeb9687f1bb3071a9e671 | 645,258 |
def loop_detection(head):
"""Loop detection using two pointer method
:param head head of the linked list
:returns Node at the beginning of the intersection, False if no intersection
"""
if head is None:
return False
fast = slow = head
while fast is not None and fast.next is not... | 81b860427a2bb91b9505423d57a0ac2d0bfa320c | 645,260 |
import logging
def run_find_query(session, queries: list, concepts: list) -> dict:
"""
Purpose:
Excute the graql query
Args:
session: The Grakn session
queries: the queriesto run
concepts: The concepts we are looking for
Returns:
ent_map: Answers to the queries b... | 2b881ea8e358ae2f657196d0a0380b2d4d8af464 | 645,261 |
def HTML_WRAP(app):
"""
Wraps the output of app in HTML
"""
def gen(environ, start_response):
"""The standard WSGI interface"""
yield "<html>\n"
yield "<body>\n"
for i in app(environ, start_response):
yield i
yield "</body>\n"
yield "</html>\n"... | 2fb040efa16686f4d13c5c233301972034e95a6f | 645,262 |
def _user_info(user):
"""Format a user."""
return {
"id": user.id,
"name": user.name,
"is_owner": user.is_owner,
"is_active": user.is_active,
"system_generated": user.system_generated,
"group_ids": [group.id for group in user.groups],
"credentials": [{"typ... | 99505e0d721ff3c289a25a9903bc21d304cbd3de | 645,263 |
def filter_data(all_data):
"""
Remove all the students not applying for this current year
"""
# Remove all students not from this academic year
YEAR_COLUMN = 'Entry Year'
THIS_YEAR = '2018/9'
filtered_data = all_data.loc[all_data[YEAR_COLUMN] == THIS_YEAR]
return filtered_data | 3209ab740153105c45f1a16bd8e7cbcaca1000ca | 645,264 |
def curried_to_binary(f):
"""Constructs a function from a given higher order function and returns its first order counterpart.
The given higher order function, `f` is must be a unary function
Returns an async function iff `f` is async, else returns a sync function.
>>> inc = lambda i: i + 1
>>> f =... | 1e3ab7a49236293958d436fed41227e083a8a34a | 645,265 |
import socket
def _check_free_port(port):
"""
Checks if a port no. if free or not.
.. warning::
The function does not guarantee if the port will remiain free by the time it
will be used,
"""
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.c... | 460c67ea2550f9f2d73f6f63b3ab7cc4f4f6d999 | 645,266 |
def perc_numeric(seq):
"""
Compute what percentage of a sentence contains numerical values
:param seq: input sequence
:return: percentage of sentence containing numbers
"""
counter = 0
for word in seq:
word = str(word.encode('utf-8'))
if word.isnumeric():
counte... | ea37bd147c3e5f1b17b75daf70917dd9c5b70ab2 | 645,267 |
def create_metric_loss(loss_name, feature_dim, num_classes):
"""
度量学习 - 损失函数入口
loss_name: 损失函数名称
feature_dim: 特征维度
num_classes: 类别数
"""
try:
method = eval(loss_name)
return method(feature_dim, num_classes)
except:
raise NotImplemented | 96827856b6be045f571116321b376cea716baf7f | 645,268 |
def rank_ref(model, history, reftick, refpoi):
""" running the testing stage
"""
rank = model.predict(history, reftick)
return rank.index(refpoi) + 1 | ca29ee34ffd349f3b9a5e8e5a1e1953c961c7c86 | 645,269 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.