content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def replace_talents(talent_string, data):
"""Replaces the talents variable with the talent string given"""
if "talents=" in data:
data = re.sub(
r'talents=.*', "talents={}".format(talent_string), data, 1)
else:
data.replace(
"spec=shadow", "spec=shadow\nta... | 8d86af9e31d3fd4f3fd8afad2104c213ffa1e743 | 666,110 |
def shift_scale_loc(grid,loc):
""" This fuction takes a location which is an array then backtransforms the
shift and scaling applied to it in the process of estimation.
"""
loc_copy = loc.copy()
if grid.dim == 2:
loc_copy[0] = loc_copy[0]/grid.b0-grid.shifts[0]
loc_copy[1] = loc_copy... | 7e3a42cb1cf75c34d1ea8c6dcbecb866028483e0 | 666,111 |
import torch
from typing import Tuple
def get_pair_embedding(
pair_info: torch.Tensor,
embedding: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
We are working with N pairs, the k'th pair is (a_k,b_k).
Args:
- pair_info: (N,6) array representing (bi,hi,wi, bj,hj,wj)
... | dc0af39d581980b73b3dc46cf881e8a1439063fa | 666,112 |
def check_api():
"""Test route to check if service is up and running
Returns:
str: message to indicate service status
"""
return "Sentiment Analysis API is up & running!" | 534eb77170eb00cea3d4e25538c4ad33429394ad | 666,113 |
def varyansHesapla(dizi,ortalama):
"""Karmaşıklığı O(n)"""
varyansdegeri = 0
for i in range(len(dizi)):
varyansdegeri += (ortalama - dizi[i]) ** 2
return varyansdegeri / len(dizi) | 557975e8ec21601a8d2f0eec3bd1d58f37d9c926 | 666,114 |
def join_array_dispatcher(*args, **kwargs):
"""Dispatcher for functions where first argument is a sequence."""
try:
return args[0][0]
except (TypeError, ValueError):
# user passed an empty sequence, or something non-iterable
# try to infer backend from first argument as fallback
... | 2f0e06e42409f642a1e01a30f51c1ebce70d2338 | 666,115 |
def TabSpacer(number_spaces, string):
"""Configuration indentation utility function."""
blank_space = ' '
return (blank_space * number_spaces) + string | d85e013daa7da875bfe2ca9805dacd13fe1169d0 | 666,116 |
import os
def get_icon_path(file_name):
"""
Get an icon path based on file name. All paths in the XBMLANGPATH variable
processed to see if the provided icon can be found.
:param str file_name:
:return: Icon path
:rtype: str/None
"""
for directory in os.environ["XBMLANGPATH"].split(os.... | b52937ffbae3d2ddcf803252532c449131a94c56 | 666,117 |
def iroot(a, b):
"""Function to calculate a-th integer root from b. Example: iroot(2, 4) == 2
Parameters:
a: int
Root power
b: int
Number to calculate root from
Returns:
result: int
Integer a-th root of b
"""
if b < 2:
... | 6704b7d0b663008c5a4e9d235d90aabcc9ca063d | 666,120 |
def get_values_matching_key(doc, key):
"""
Returns iterator of values in 'doc' with the matching 'key'.
"""
def _get_values(doc, key):
if doc is not None:
if key in doc:
yield doc[key]
for z in doc.items():
v = z[1]
if isi... | da7beea651f2e8ffa461c9f60d577628815d323d | 666,121 |
def lmap(f, x):
"""list(map(f, x)). Converts a map into a list containing (key,value) pairs."""
return list(map(f, x)) | 6753395b6c7e624f7a56d06520c4d965a420b114 | 666,122 |
def posix_get_last_error(space):
""" posix_errno - Alias of posix_get_last_error """
""" posix_get_last_error - Retrieve the error number set by
the last posix function that failed """
return space.newint(space.get_errno()) | 9bb5bf9f5e4e60921afba16360439cab279e4950 | 666,123 |
import ast
def redis_hgetall(duthost, db_id, key):
"""
Get all field name and values for a given key in given redis dataabse
:param duthost: DUT host object
:param db_id: ID of redis database
:param key: Redis Key
:return: A dictionary, key is field name, value is field value
"""
cmd =... | a083912cfa5b635a4a96fe23ac6b0f7df49cd9a0 | 666,124 |
def angle2NDE(angle):
""" Converts an angle in degrees from an East due North coordinate system to a North due East coordinate system
Calling this function again will convert it back, since: x = angle2NDE(angle2NDE(x))
Arguments:
angle: [float] angle to be converted in degrees.
Returns:
... | 9618279d98bd21c3a4b7caf159048c18b1946d80 | 666,125 |
def get_hostlist_by_range(hoststring, prefix='', width=0):
"""Convert string with host IDs into list of hosts.
Example: Cobalt RM would have host template as 'nid%05d'
get_hostlist_by_range('1-3,5', prefix='nid', width=5) =>
['nid00001', 'nid00002', 'nid00003', 'nid00005']
"... | 53b6e0464acc635a3cb76962ec3ff71bd566ac1e | 666,126 |
def fib(n):
"""
Finding the Fibonacci sequence with seeds of 0 and 1
The sequence is 0,1,1,2,3,5,8,13,..., where
the recursive relation is fib(n) = fib(n-1) + fib(n-2)
:param n: the index, starting from 0
:return: the sequence
"""
n = n//1 if n>=1 else 0 # ensure n is non-negative integer
if n>1:
... | e54a8103994d25ff404d2f1b43c3d1134af8375a | 666,127 |
def delta_encode_values(df, total, scale=100):
"""Convert a dataframe from acres to delta-encoded integer scalar values,
where original values are first scaled.
This can be used to express percent where scale = 100.
Values are packed into a caret-delimited string with 0 values omitted, e.g.,
'<bas... | 2e44253e0aadad4f6525a5578f40c855d61cde22 | 666,128 |
def celsius2kelvin(celsius):
"""
Convert temperature in degrees Celsius to degrees Kelvin.
:param celsius: Degrees Celsius
:return: Degrees Kelvin
:rtype: float
"""
return celsius + 273.15 | 4826bbdee8e50356649a1adb7294ec12824186d3 | 666,129 |
def quick_FASTA_reader(file):
"""Simple FASTA reader, returning a list of string tuples.
The single argument 'file' should be the filename of a FASTA format file.
This function will open and read in the entire file, constructing a list
of all the records, each held as a tuple of strings (the sequence n... | a6cf80d320db2e41b924d0020e89582aa1659c57 | 666,130 |
def compare_svg(
current,
previous,
up_color="default",
down_color="default",
neutral_color="default",
):
"""Compare current and previous value and return an SVG based on the result."""
colors = {
"good": "#5e9732",
"bad": "#c41230",
"neutral": "#fdc010",
"def... | cc29caf83b98e726678feb4fe8093cf0331a0fcc | 666,132 |
def create_variable(df, name, label, label_map, default_value=0):
"""
Create a new variable (column) in the specified dataframe. The label of
this variable will be appended the global label map.
Parameters
----------
df : pandas DataFrame
dataframe to add variable/column to
name... | e64bb8f8393b75a1c981b4db7d026691c924212f | 666,133 |
from typing import List
def parse_dns(dns: bytes) -> List[bytes]:
"""Parse the output of grab_dns, returning a list of parsed values that we would like to search.
:param dns: Output of grab_dns
:type dns: bytes
:return: A list of parsed values (Record Name, CNAME, A (HOST))
:rtype: List[bytes]
... | 35808143534d210013e4dec5f52917dcc6ca2ad5 | 666,134 |
def get_reference_columns():
"""
return a test reference data column definition
"""
return {
'wavelength': {
'description': 'wavelength',
'required_column': True,
'unit': 'nm',
'type': 'float32',
'required_range': {'unit': 'nm', 'min':... | 0be34c0dd31fd7fbbb66eebcd54afb08a250d3a4 | 666,135 |
import argparse
def parse_args():
"""
Parses arguments from the command line.
"""
parser = argparse.ArgumentParser(description='Extracts epitope annotations from mmCIF files.')
# Arguments
parser.add_argument('pdb_dir', help='Path to directory with mmCIF files.')
parser.add_argument(... | 64348edb6c7ee36f0616733e1e4a6554e1a1278a | 666,136 |
import re
def normalise(s):
"""
Tokenize on parenthesis, punctuation, spaces and American units followed by a slash.
We sometimes give American units and metric units for baking recipes. For example:
* 2 tablespoons/30 mililiters milk or cream
* 2 1/2 cups/300 grams all-purpose flour
... | 4d91af491dda8a08523ad4b8c467a15c07248cd6 | 666,137 |
import re
def fix_empty_methods(source):
"""
Appends 'pass' to empty methods/functions (i.e. where there was nothing but
a docstring before we removed it =).
Example:
.. code-block:: python
# Note: This triple-single-quote inside a triple-double-quote is also a
# pyminifier self... | d49181f65e76bda84ffd9b71187944a728d0f2f2 | 666,138 |
def __deserialize_primitive(data, klass):
"""
Deserializes string to primitive type.
"""
try:
return klass(data)
except UnicodeEncodeError:
return data # This might have to be marked as unicode somehow
except TypeError:
return data | 25b3b7676434ea91a3184c3242f55e41821e6860 | 666,139 |
import collections
def _sort_almost_sorted(almost_sorted_deque, key):
"""
Sort a deque like that where only the first element is potentially unsorted and should probably be last and the rest
of the deque is sorted in descending order.
:param collections.deque almost_sorted_deque: The deque of size n... | 93d282f6cc0fd4df16480b0ebbc33d132bd3cc0e | 666,140 |
import os
def guess_realpath(path):
"""Checks for a file in a path, or in a local path"""
basename = os.path.basename(path)
# first test the path
if os.path.isfile(basename): # try locally
return os.path.realpath(basename)
elif os.path.isfile(path): # good, it exists
return os.pat... | 29206cecab21f22b323b469b1c4ccdec44292286 | 666,141 |
def _is_newer(path, ref):
"""
Tests whether path is newer than ref where ref is either another path or a
date.
>>> Path('/usr/bin/python').is_newer(0)
True
"""
mtime = path.stat().st_mtime
try: return mtime > ref
except TypeError:
try: return mtime > ref.timestamp
exc... | edb0d275b3e040d9c55d2cd7df1fd1b05ae6973f | 666,142 |
def disagreement_priority(info_dict, acc_bar=0.5):
"""
Everyone node points at the most different member that is not itself.
Triggers if accuracies are high enough.
"""
refs = []
acc_list = info_dict["accuracy"]
disagree_dict = info_dict["disagreement_rate"]
for i in range(0, len(acc_lis... | 082b11192e30dc915e24ab8e21765d1580f5ad3f | 666,143 |
import torch
def mix_irrep_cplx(w, z):
""" Mix SO3part with complex weights. """
wr, wi = w.unbind(-1)
zr, zi = z.unbind(-1)
real = torch.matmul(wr, zr) - torch.matmul(wi, zi)
imag = torch.matmul(wr, zi) + torch.matmul(wi, zr)
return torch.stack([real, imag], -1) | 6f8452cdd709559113247133bbd4650e908daed6 | 666,144 |
def mean_of_list(vals):
"""
avg value of a list
:param vals:
:return:
"""
return sum(vals)/float(len(vals)) if vals else 0 | 428aae859dbec8ef20fea39287cdd2ec84c60e88 | 666,145 |
def poi_vs_all(true_pep_iz, prep_result):
"""
true_pep_iz refers to the full set of all peptides.
This function returns remapped values of true_pep_iz such that
each peptide that is from a POI keeps its true_pep_i
whereas all other peptides are remapped to class 0, ie "OTHER"
"""
df = prep... | 50a979f8f6304d0869eaec1bfe19f5f4d0e2f2ef | 666,146 |
def is_collection_summary_editable(collection_summary, user_id=None):
"""Checks if a given user may edit an collection by checking
the given domain object.
"""
return user_id is not None and (
user_id in collection_summary.editor_ids
or user_id in collection_summary.owner_ids
or ... | 94462b90592f4ac5e8f2ce290193a838dcf5b888 | 666,147 |
import os
def add_suffix(fullname, suffix):
"""
Add suffix to a full file name.
"""
name, ext = os.path.splitext(fullname)
return name + '_' + suffix + ext | 2eee2d68805c933e2bba7a322337f3553322f3e4 | 666,148 |
def format_trade_flow(amount, unit, from_location, to_location, activity_type, flow_object, time, counter, mapping_dict):
"""
Model trade using a separate `transport activity <https://schema.org/TransferAction>`__. We need two ``flow`` instances for each trade: one is the production flow in the originating coun... | 4849ed131d71ce4a4378c4c9f92e8e83c01e46e5 | 666,149 |
import argparse
import os
def parse_user_arguments(*args, **kwds):
"""
Parses the arguments of the program
"""
parser = argparse.ArgumentParser(
description = "Filter network",
epilog = "@oliva's lab 2017")
parser.add_argument('-n','--network_file',dest='network_file',action ... | e9dae0adaf92c95c783288d53db33b9bde277b32 | 666,150 |
from typing import Dict
from typing import Any
import yaml
import os
def load_yaml_settings(yaml_file: str) -> Dict[str, Any]:
"""
Loads a standard YAML settings file. Any entry marked with
a "$" sign is an environment variable.
Parameters
----------
yaml_file
Filename or full path to ... | 6cbd219564fef5554464c226c9f53d6d70e04805 | 666,151 |
def count_less(count, a):
"""is a[0] shorter than a[1]?"""
if len(a[0]) < len(a[1]):
return count + 1
return count | e735f57d440c319c83af5c32ac5fc390ff99ed3f | 666,152 |
import json
def dumps( data ):
"""Serializes the incoming object as a json string"""
return json.dumps( data ) | 9f0e96cc80387909918a9aca97f5ca3bb3b41b6d | 666,153 |
def _check_filetype(filetype):
"""Checks that the filetype is compatible before trying to process it."""
return 'Mach-O' in filetype and 'ARM64' in filetype | 0deccb89a6cd3d8836b18117c3a6dc6249b3d4bc | 666,154 |
def is_required(param):
"""
:param param:
:return:
"""
if "?" in param:
return False
else:
return True | 42440ee2312abcb9c9150247215961d60d689879 | 666,155 |
def load(fl, normalise=False):
"""
load airfoil
args:
fl (str): filename
kwargs:
normalise (bool): flag determining whether the airfoil is normalised to
unit length
returns:
[(x,y),...] airfoil point coordinates
"""
d = []
print("loading airfoil %s" % ... | 4032a703a66465799aadfa08dd7888682b0a767d | 666,156 |
from pathlib import Path
def is_filelike(obj):
"""Filename or file object?
"""
if isinstance(obj, (bytes, str, Path)):
return False
res = True
for a in ("read", "tell", "seek"):
res = res and hasattr(obj, a)
if not res:
raise ValueError("Invalid object passed as file")
... | 385863db7602af32c50727b09713ad7f9fa99705 | 666,158 |
def _check_ncluster_nquestions(n_questions, n_pairs, n_clusters):
"""
Args:
n_questions (int):
n_clusters (int):
n_pairs (int):
Returns:
boolean
"""
if n_questions > n_pairs:
return False
elif n_questions * n_clusters > n_pairs:
return False
... | 3272ad51c759d912588133b9ac615b1969769da8 | 666,160 |
def validate4(s,a):
"""validate4(s, a): for loop with generator and (l in a)"""
for x in ((l in a) for l in s):
if not x:
return False
return True | eddd7731e561828bd1b70fe9925cf213e1e36300 | 666,161 |
def ids_from_names(ctx, names):
"""Given a list of string trait names, returns a dict, keyed by those
string names, of the corresponding internal integer trait ID.
:raises: ValueError when names is empty.
:param ctx: designer_family.context.RequestContext object
:param names: list of string trait ... | cd6d3b4e1e9b760f1e3f7eefad168dc6b67678bb | 666,162 |
def optparse_main(interface_object, local_argv):
"""Construct and execute an interface object"""
optparse_cmd = interface_object()
result = optparse_cmd(local_argv[1:])
return 0 | 6c718d82bd54cea2586abead85c1112768d8969b | 666,164 |
def list_uniq(seq, key=None):
"""
Removes duplicate elements from a list while preserving the order of the rest.
>>> uniq([9,0,2,1,0])
[9, 0, 2, 1]
The value of the optional `key` parameter should be a function that
takes a single argument and returns a key to test the uniqueness.
... | d9385dad029663fb2c8dce0d5c9b488a6f39ae5f | 666,165 |
def neighbor_equality(w1, w2):
"""
Test if the neighbor sets are equal between two weights objects
Parameters
----------
w1 : W
instance of spatial weights class W
w2 : W
instance of spatial weights class W
Returns
-------
Boolean
Notes
-----
Only se... | 6465f06151d8bf3505cc6f9fe1e9e3b7319e7878 | 666,166 |
def _check_convert_version(tup):
"""create a PEP 386 pseudo-format conformant string from tuple tup"""
ret_val = str(tup[0]) # first is always digit
next_sep = "." # separator for next extension, can be "" or "."
nr_digits = 0 # nr of adjacent digits in rest, to verify
post_dev = False # are we ... | 857996307ef22c6e7bd81b73679755b03e746b0d | 666,167 |
def echo(sample: str):
"""
Sample GET request
Returns: Echos back whatever was sent
"""
return sample | 5b8b7d69b87bce625daee55ead33a46c187e022c | 666,168 |
import numpy as np
def to_numpy_matrix(G, edge_sign = 1.0, not_edge_sign = 0.0):
"""
Returns the graph adjacency matrix as a NumPy matrix.
Parameters
----------
edge_sign : float
Sign for the position of matrix where there is an edge
not_edge_sign : float
Sign for the pos... | 5e25c1f1cb6f7042bc4c24dd27c5d307497150ff | 666,169 |
def unpack_numpy(var, count, dtype, buff):
"""
create numpy deserialization code
"""
return var + " = numpy.frombuffer(%s, dtype=%s, count=%s)"%(buff, dtype, count) | 837980113bbadcf23845dcb98e55f60a0e9fc977 | 666,170 |
def role_edit(id=None):
"""
编辑角色
"""
return 'role/edit' | 7d7c89e62d5d3b8b24efd7f60d4103f74fca6bac | 666,172 |
def _cdp_split_single_times_read_aligns(split_alignment_dict, pos):
"""
Dict. of times a read aligns to all references
{read: times aligned}
"""
srna_align_counts = {}
for aligned_sRNAs in list(split_alignment_dict.values())[pos]:
for aligned_sRNA, count in aligned_sRNAs.items():
... | a214d6dc1cb5cc8d278030a1e2c5daf5fa852c61 | 666,173 |
def clean_location_text(text: str) -> str:
"""
Clean location before using fuzzy string match
"""
text = text.replace("แขวง", " ")
text = text.replace("เขต", " ")
text = text.replace("อำเภอ", " ")
text = text.replace("ตำบล", " ")
text = text.replace("ต.", " ")
text = text.replace("ตฺ... | c2ab0fafd1c07292a52bfba6db0021dd2f601f51 | 666,175 |
def count_str(string):
"""
Build a dict of letter frequency for a string.
:param string:
:return: New dictionary.
"""
tt = {}
for ch in string:
tt[ch] = string.count(ch)
return tt | 77151ba9172b1ee1ce967f82119555ec376d0cb8 | 666,176 |
def svg_from_file(pathname):
""" Read SVG string from a file """
f = open(pathname, 'r')
svg = f.read()
f.close()
return(svg) | 136b560af57f2d4b0f533cbfb18b7160c678f103 | 666,177 |
import imghdr
def detect_format_from_data(data):
"""Try to detect the format of the given binary data and return None if it fails."""
fmt = None
try:
if b'<svg' in data[:500]:
fmt = 'svg'
elif data.startswith(b'%PDF'):
fmt = 'pdf'
elif data.startswith(b'%!PS... | 6f20cd562a2aeef8205873ddcd49313adf8dc284 | 666,178 |
def atom_to_csv(self):
"""Return Atom as a comma-separated string of its properties."""
return f"{self.chain},{self.atomid},{self.resid},{self.icode},{self.name}" | 89af5589412eae124a1b1191c8934482d7cfc989 | 666,179 |
import os
from shutil import copyfile
import shlex
import subprocess
def convert_to_wav(filename, output, sr=22050):
"""Convert a file to 16-bit 22050hz wav."""
base, ext = os.path.splitext(filename)
if filename == output:
backup = f"{base}-backup{ext}"
copyfile(filename, backup)
f... | 8f0b5c7210646477834472ba83a2ef7bdf582775 | 666,180 |
def drag_force(c_d,A,rho,v):
"""
Calculate drag force given c_d,A,rho,v:
rho -> density of fluid
A -> Frontal area
c_d -> Drag coefficient
v -> Velocity of bicycle
"""
return 0.5*c_d*rho*A*v**2 | f31caac5b43ad0387ededb225effa31b6f06b86c | 666,181 |
import time
def try_until(func, count=1, sleep=0.5):
"""
Tries to execute the specified function a number of times.
@param func callable to execute
@param count number of times to try (default 1)
@param sleep seconds to sleep after failed attempts, if any
(defaul... | 823cdddc6fed72ae4a63dd77b7eca1ace597f927 | 666,182 |
def docker_mem_used(container_id):
"""
Bytes of memory used from the docker container.
Note: If you have problems with this command you have to enable memory control group.
For this you have to add the following kernel parameters: `cgroup_enable=memory swapaccount=1`.
See: https://docs.docker.com/e... | a58bde5871894d5f52bd230ad070fa0396df6d34 | 666,183 |
import six
def create_mashup_dict(image_meta):
"""
Returns a dictionary-like mashup of the image core properties
and the image custom properties from given image metadata.
:param image_meta: metadata of image with core and custom properties
"""
def get_items():
for key, value in six.... | 976e1f92d1dcac4a8bdc2b03c799d76fbd9c146f | 666,184 |
def preprocess_data(df, target_map):
"""
General element-wise cleanup of full data set
:return: df, cleaned data
"""
# Strip whitespace
object_cols = df.select_dtypes(include=['object']).columns
for col in object_cols:
df[col] = df[col].apply(lambda x: str.strip(x))
# map targe... | 9a77803a636a284307e130409f9760ab40aff267 | 666,185 |
import click
import configparser
def get_token(config_auth):
"""
Extract token from auth config and do the checks
config_auth: ConfigParser with loaded configuration of auth
"""
if config_auth is None:
click.secho('Auth configuration not supplied!', err=True)
exit(1)
try:
... | ed2635dd7078bb4b5e68b2340f5aaf1b212ab49f | 666,186 |
def convert_list_to_tuple(shp):
"""Check the type of the shape, if is list, convert to tuple"""
if not isinstance(shp, (list, tuple)):
raise ValueError(f"The shape variable should be a list or tuple, but got {type(shp)}")
if isinstance(shp, list):
shp = tuple(shp)
return shp | 4f9489a5c97139383810de73fdc5826ef49d733b | 666,187 |
def _align_mask(value, mask):
""" Alignment mask """
return ((value)+(mask))&~(mask) | 43c5ecafabb59e164f3df6b322fbb34338853cdb | 666,188 |
def get_wind_degrees(value):
"""
Returns the wind direction in degrees from a dict containing degrees and direction
"""
try:
new_value = float(value['degrees'])
except (TypeError, KeyError):
return value
return new_value | 07db665a7ed31c7dcf6a5c91558ab7dd966f03f5 | 666,189 |
def load_pretrained_word2vec(infile):
"""Load the pre-trained word2vec from file."""
if isinstance(infile, str):
infile = open(infile)
word2vec_list = {}
for idx, line in enumerate(infile):
if idx == 0:
vocab_size, dim = line.strip().split()
else:
tks = l... | ffa340cda4648d541d7338975b3951f5f50c7328 | 666,191 |
import random
def freq_mask(spec, F=30, num_masks=1, replace_with_zero=False):
"""
https://ai.googleblog.com/2019/04/specaugment-new-data-augmentation.html
"""
cloned = spec.copy()
num_mel_channels = cloned.shape[0] #H
for i in range(0, num_masks):
f = random.randrange(0, ... | d31b26af23c96f239a03469a52e6c8a9a5a8e9fa | 666,192 |
import os
def string_from_file(value):
"""
Read a string from a file or return the string unchanged.
If the string begins with '@', the remainder of the string
will be treated as a path to the file to be read. Precede
the '@' with a '\' to treat it as a literal.
"""
assert isinstance(va... | c20ac9f88dbc229fd57626ed48f480b5bf52f5c3 | 666,193 |
def strip_hash_bookmark_from_url(url):
"""Strip the hash bookmark from a string url"""
return (url or '').split('#')[0] | c31f569b147d4e9bd74e932856b1a2e168e05bb3 | 666,194 |
import subprocess
def find_git_root():
"""
Returns a string containing the absolut path to the tiscamera directory.
Assumes a git checkout has been done.
"""
repo_dir = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'],
stdout=subprocess.PIPE).communicate()[0... | 3a389e426b8939cdcc34d839b27e33ecf3c917b7 | 666,195 |
def get_adjacents(i, j, matrix):
"""given a matrix and a couple of indices finds indexes of points
adjacent to given input
Args:
i ([int]): [index of row]
j ([int]): [index of column]
matrix ([numpy array]): [matrix of measurements]
Returns:
[list]: [list of adjacent in... | 4223d55397d4a4697f4ed08b55674279dfb2dfaa | 666,196 |
def get_conditions(xml_data_model, tag_name='nodeset', conditions='relevant', max_str=10):
"""
Get the conditional tag values that should be met before the tag under consideration should be checked
:param xml_data_model: data model list read from ODK config (read_odk_data_model)
:param tag_name: column ... | 77aff4c5a006fd44aeefd4198554f2ba79661e07 | 666,197 |
from typing import Optional
def get_fullname(namespace: Optional[str], name: str) -> str:
"""
Constructs a fullname from a namespace and a name.
"""
if namespace:
return namespace + "." + name
else:
return name | 5bc82836186089368eeeea66c206d8f09b006ba6 | 666,198 |
import os
def xonsh_data_dir(env):
"""Ensures and returns the $XONSH_DATA_DIR"""
xdd = os.path.expanduser(os.path.join(env.get('XDG_DATA_HOME'), 'xonsh'))
os.makedirs(xdd, exist_ok=True)
return xdd | ea34f127921c7cb3dd72a02d7644f9f6d4db574a | 666,199 |
def to_sense_key(syn):
"""
Returns the sense key for the given synset.
@param syn - Synset
@return Corresponding sense key as string
"""
return syn.lemmas()[0].key() | 06b34bef01c72122dc4e24261d57da5a32de9490 | 666,200 |
def generate_exploit() -> str:
"""This function returns the payload that will print `hacked`.
Our payload should cause `run.py` to print out `hacked`.
Warnings:
1. `run.py` should print `hacked`, and the testing will be case *sensitive*
2. This time, `run.py` must NOT crash
Returns:
... | 2ae39c8aeac5f113f0c69082539a83acc3c5b35c | 666,201 |
def source2id(source_words, vocab):
"""
将源文转化成id
:param source_words:
:param vocab:
:return:
"""
ids = []
oovs = []
unk_id = vocab.UNK
for w in source_words:
i = vocab[w]
if i == unk_id:
if w not in oovs:
oovs.append(w)
oov_... | f31c062a85716d6c4259a26dbacd758388b5a2b9 | 666,203 |
from collections import Counter
def fix_dup_names(names):
"""
:param names:
:return:
"""
names_upper = [x.upper() for x in names]
dup_names = {item: 0 for item, count in
Counter(names_upper).items() if count > 1}
renamed_names = []
for name in names_upper:
if... | ec5f6c5714f8f93688c29963361aa94bca2d7314 | 666,205 |
import re
def parse_logs(response):
""" Parses the travis log.
:params response: text from the ci log
:return: dict that contains error information
"""
start = "FAILURE: Build failed with an exception."
end = "BUILD FAILED"
# capture the substring between two strings
capture_error ... | 4f3ac8561401d14bce51600d20adc6130479bb3a | 666,206 |
import os
def make_dir(path_of_new_dir):
"""
Makes a directory at the given path. (> str)
"""
try:
os.makedirs(path_of_new_dir)
return path_of_new_dir
except:
return 'Error while making the new folder' | d83e9df2f98db8fcb912adcce74f14abadcb47e0 | 666,207 |
def range_tag(value, min_value=0):
"""
tag that return a range
"""
if value:
return range(min_value, value)
return range(min_value) | 40868779767d4d9dd80504cb06f77e876368bf0e | 666,208 |
def can_import(name):
"""Attempt to __import__ the specified package/module, returning
True when succeeding, otherwise False"""
try:
__import__(name)
return True
except ImportError:
return False | 7b02767184e73935c92b9e0e15769bb73ac24d95 | 666,209 |
import os
def postgres_uri() -> str:
"""Connection URI for PostgreSQL database."""
value = os.environ.get("POSTGRES_URI")
if value:
return value
raise EnvironmentError('Required environment variable "POSTGRES_URI" is missing') | 6addd2f84ebbf78206d08b18bf97a6e0b5f07bb1 | 666,210 |
import os
import glob
import shutil
def _prepare_camera_detection(dataset_dir, camera_output_dir, id_):
"""Copy camera detection."""
camera_detection_path = os.path.join(dataset_dir, "detections", "camera")
camera_new_path = os.path.join(camera_output_dir, f"{int(id_):06d}.txt")
camera_old_path = list... | a8b0abf60cd4c9048ec478749713e1ebeaddaba7 | 666,211 |
def _find(root: dict, word: str) -> dict:
"""Find the node after following the path in a trie given by {word}.
:arg root: Root of the trie.
:arg word: A word.
:returns: The node if found, {} otherwise.
"""
node = root
for char in word:
if char not in node:
return {}
... | c8fc53ab5ef855822086a1db258521e4c351768a | 666,212 |
import re
def all_matches(iterable, pattern):
"""
Get all of the items that match a pattern.
Args:
iterable (Iterable[str])
pattern (str or regular expression)
Returns:
List[str]
"""
result = []
for string in iterable:
match = re.search(pattern, string)
... | a30bde68c282d1a47d7a76615eb722b50ac398b9 | 666,213 |
import inspect
def _methods_of(cls):
"""Get all callable methods of a class that don't start with underscore.
:returns: a list of tuples of the form (method_name, method)
"""
# The idea of unbound methods exists in Python 2 and was removed in
# Python 3, so "inspect.ismethod" is used here for Pyt... | e1a88029f1c10ff7d09f37d9960c7474a995b67c | 666,214 |
def reblock_by2(df, ntimes, c=None):
"""
Reblocks data according to “Error estimates on averages of correlated data”,
H. Flyvbjerg, H.G. Petersen, J. Chem. Phys. 91, 461 (1989).
"""
newdf = df.copy()
if c is not None:
newdf = newdf[c]
for i in range(ntimes):
m = newdf.shape[0... | ee9aa4186501a93a8caf5d60a3858c30c76a2c2a | 666,215 |
def conv(x, h):
""" Perform the convolution operation between two input signals. The output signal length
is the sum of the lenght of both input signal minus 1."""
length = len(x) + len(h) - 1
y = [0]*length
for i in range(len(y)):
for j in range(len(h)):
if i-j >= 0 and i-j < ... | 0940efe21c61be035396856f385af4d51b67f296 | 666,216 |
def diff(a1, a2, shift):
"""
Compute the diff after shifting array a2 by shift
"""
if len(a1) != len(a2):
raise ValueError("Diff, input arrays must be same length, got {} and {}".format(len(a1), len(a2)))
return a1[:(-shift)] - a2[shift:] | 2fd47e43e6b41c9f606378d370f04308e8db3883 | 666,217 |
from typing import Optional
import random
def make_monster_name(is_titan: Optional[bool] = False) -> str:
"""
Generate a normal boss's name
Parameters
----------
is_titan : bool
If the boss is a titan
Returns
-------
str
The name of the boss
"""
# Boss is a t... | 9faf5b2835cc73523c840f610490e65f73363a93 | 666,218 |
import torch
def _get_pyramid_gaussian_kernel() -> torch.Tensor:
"""Utility function that return a pre-computed gaussian kernel."""
return torch.tensor([
[1., 4., 6., 4., 1.],
[4., 16., 24., 16., 4.],
[6., 24., 36., 24., 6.],
[4., 16., 24., 16., 4.],
[1., 4., 6., 4., 1.... | 75114ecdbbcf79ebfa3dbc39efccaff0d288c452 | 666,219 |
def readme():
"""Use README file as long_description"""
with open('README.md') as readme_f:
return readme_f.read() | 553644498c7e2e33704084bcdfa1fd062d37c364 | 666,220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.