content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def fileflush(filed, residue, end=False):
"""
Flush a file descriptor
@params:
`filed` : The file handler
`residue`: The remaining content of last flush
`end` : The file ends? Default: `False`
"""
filed.flush()
# OSX cannot tell the pointer automatically
filed.see... | 03c0309324e0ed2db86c03967678299a6686be17 | 28,746 |
import re
def _ParsePercent(fixed_or_percent_str):
"""Retrieves percent value from string."""
if re.match(r'^\d+%$', fixed_or_percent_str):
percent = int(fixed_or_percent_str[:-1])
return percent
return None | 360741f7cb179d76e2c3bc89eb263d009734baeb | 28,747 |
import importlib
def resolve(name):
"""Convert a dotted module path to an object.
This is used to do the importing, when :class:`Tool` resolves
the path to a command implementation.
"""
if not isinstance(name,str):
return name
p = name.rfind('.')
if p > 0:
mod = name[:p]... | f133173377cac7b2ad3c3ed3d27b55c4c67bb8f2 | 28,748 |
def firm_size_quintile(firm_mcap, mcap_list):
"""
Quintile number (1-5) of firm_mcap within sorted mcap_list
Returns INTEGER
"""
firm_mcap_index = mcap_list.index(firm_mcap)
quintile_number = 1
boundary_index = (len(mcap_list) * quintile_number) // 5
while quintile_number < 5:
if... | a084eb70fc9385443a4dd49a05c563bf4699b076 | 28,749 |
import math
def debitmask(input_int,num_bits = False):
"""
| takes a bitmask and returns a list of which bits are switched.
| reads from left to right e.g. 2 = [0, 1] not [1, 0].
"""
if num_bits == False and input_int>0:
num_bits = int(math.ceil(math.log(input_int+1,2)))
elif input_int... | 68541f3b5cd14a92b44c0445e1f2856567bdb0be | 28,750 |
import pkg_resources
def gobbli_version() -> str:
"""
Returns:
The version of gobbli installed.
"""
return pkg_resources.get_distribution("gobbli").version | 2357e1fcca33e97fe970a42c20593d31c9a887c8 | 28,751 |
def patch_basic_types(basic_types, inp_version):
"""
Patch the _basic_types entry to correct ambigouities
:param schema_dict: dictionary produced by the fleur_schema_parser_functions (modified in-place)
:param inp_version: input version converted to tuple of ints
"""
if inp_version >= (0, 33):... | d20ab88119bea457f799e84448875846dcc3d077 | 28,752 |
def render_compiled(compiled, variables):
"""Render from compiled template with interpolated variables."""
template, partials = compiled
return template(variables, partials=partials) | 3c13acf96ac3b59bcd5c2a1f3f3dbc19fd210c80 | 28,753 |
def requirements(section=None):
"""Helper for loading dependencies from requirements files."""
if section is None:
filename = "requirements.txt"
else:
filename = f"requirements-{section}.txt"
with open(filename) as file:
return [line.strip() for line in file] | 2e4b7f9f4d8c8d0cd3cfa749f03785d2bba6a26b | 28,754 |
def route(rule, **options):
"""Like :meth:`Flask.route` but for nereid.
.. versionadded:: 3.0.7.0
Unlike the implementation in flask and flask.blueprint route decorator does
not require an existing nereid application or a blueprint instance. Instead
the decorator adds an attribute to the method ca... | c7f33af4e8fa10090e5b6a90532707fd59688885 | 28,755 |
def remap_column_names(data_names, name_map):
""" Remap data array column names using dictionary map.
For each column name that matches a key in name_map, the column name is replaced with
that key's value.
Args:
data_names (str, nx1 tuple): list of column names taken from structured np array
... | 4863d8b9ce1986df4bd85f543014208428ea85cb | 28,756 |
def tablefragment(m,signalRegions,skiplist,chanStr,showPercent,label="",caption=""):
"""
main function to transfer the set of numbers/names (=m provided by SysTable) into a LaTeX table
@param m Set of numbers/names provided by SysTable
@param signalRegions List of channels/regions used
@param skiplist List o... | cdb7165000aef16e718c3895a0dea45abe8764a4 | 28,757 |
def reference_to_schema_name(reference_name):
"""This function will eventually identify the schema associated with `reference_name`
unless replaced by similar functionality in the models package.
Returns None meaning "default/core schema"
"""
return None | 08acdad8df4baef2ed44c29b7974a5619038a2e1 | 28,758 |
def get_key(row, columns, numeric_column):
"""Get sort key for this row
"""
if(numeric_column):
return [int(row[column]) for column in columns]
else:
return [row[column] for column in columns] | ba03215956bbd3adb0acd9d086875c2978e48c05 | 28,759 |
def ha_write_config_file(config, path):
"""Connects to the Harmony huband generates a text file containing all activities and commands programmed to hub.
Args:
config (dict): Dictionary object containing configuration information obtained from function ha_get_config
path (str): Full path to out... | 7733430b0b64dc04cb398fc177e103e3d64d19b6 | 28,761 |
def radical(n, *args, **kwds):
"""
Return the product of the prime divisors of n.
This calls ``n.radical(*args, **kwds)``. If that doesn't work, it
does ``n.factor(*args, **kwds)`` and returns the product of the prime
factors in the resulting factorization.
EXAMPLES::
sage: radical(2... | 846549ba03bcc38cd25a49cb5a2bd51c16cc2e54 | 28,762 |
import os
def define_preview(define_input, define_along, define_across):
"""
Define information for previewing an interpolation run. Fill the relevant
dictionaries and pass it to the automatic routines. Full explanation of options
is also given in `create_inputfile.py`, block 5.
"""
# =======... | 888bd2456f8f7c5c2fa83f7407aa401557661090 | 28,763 |
def nested_conditionals(conditional_A, conditional_B, conditional_C, conditional_D):
"""
Verbose, less readable test function
"""
if (conditional_A):
if (conditional_B):
if (conditional_C) and (conditional_D):
return True
else:
return False... | 1003f0d1b73f84d0dadd26ba9052556787038214 | 28,765 |
import requests
def count():
"""
Returns the number of songs on chorus.fightthe.pw
"""
return requests.get(r'https://chorus.fightthe.pw/api/count') | 40f4e77cda56db9567aa530fdcc4fc477227e8a9 | 28,766 |
import sys
import inspect
def call_prepare_arguments(func, parser, sysargs=None):
"""Call a prepare_arguments function with the correct number of parameters.
The ``prepare_arguments`` function of a verb can either take one parameter,
``parser``, or two parameters ``parser`` and ``args``, where ``args`` a... | ebf598acf3acf0364f8b07b115863736497ee354 | 28,767 |
import os
def is_under_tmux() -> bool:
"""
Return `True` if running under tmux.
"""
return os.getenv("TMUX", "").strip() != "" | 51683e5333b02561b98913f8b6dd4c206a768549 | 28,768 |
def findPeakCluster(index, build_list, df, peak_gap):
"""
Recursively finds members of a peak cluster starting from the peak with
the smallest size.
Parameters
----------
index : TYPE Integer
DESCRIPTION. The index of df that corresponds to the
rows (i.e. peaks)... | f808d67a234df45f117b653ca16890ce9c4e982e | 28,769 |
import os
import dill
import inspect
import pickle
def pickle_custom_metrics(metrics, filename):
"""Pickle the metrics if there is callable in the list of metrics
Args:
metrics (list): List of metrics
filename (str): Path to dump the pickled file
Return:
"""
metric_callable = F... | c34179e905e8a2184c4fdddd2152d6f0e012d7b8 | 28,770 |
def clamp(low, high, x):
"""
Clamps a number to the interval [low, high]
"""
return low if x < low else (high if x > high else x) | 1393af569f83369a7aa0c22cfaded9ed8e9d112a | 28,771 |
import os
def get_command_output(cmd: str, redirect_error: bool = False) -> str:
"""Return the command line output of a command."""
try:
with os.popen(
"{}{}".format(cmd, " 2> /dev/null" if redirect_error else "")
) as f:
return f.read()
except:
return "" | 44a89f88f4fd6d2778d4bbc0cf305e5a4c82871d | 28,772 |
def valid(neighbor, rows, columns):
"""Find out if neighbor cell is valid
Args:
neighbor (List of integers): Neighboring cell position
rows (int): Number of rows on the board
columns (int): Number of columns on the board
Returns:
[boolean]: True if valid, False otherwise
... | 5f832c2a8b06aa98e378c1614078e36f8a9fc2e5 | 28,773 |
import functools
import warnings
def deprecated(func, replacement="", message="{name} is deprecated."):
"""This is decorator marks functions as deprecated."""
msg = message.format(name=func.__name__)
if replacement != "":
msg += " "
msg += replacement
@functools.wraps(func)
def wr... | 80669a19fc070f2c2aa8bfb1e9067cc65512dec3 | 28,774 |
def itb(num: int, length: int):
#print(num)
"""
Converts integer to bit array
Someone fix this please :D - it's horrible
:param num: number to convert to bits
:param length: length of bits to convert to
:return: bit array
"""
if num >= 2**length:
num = 2**length - 1
if nu... | b9866a9765c38ada3fe81d50ba4224d5823af180 | 28,775 |
def get_sample_name(filename):
"""Extract sample name from filename."""
return filename.split('/')[-1].split('.')[0] | 378dd429f0796930bfeb24e3a8fa51bcde32fb60 | 28,777 |
import re
def getTags(text):
""" Grep the tags in text and return them as a dict """
# 'Name' 'Version' 'Type' 'Author' 'Origin' 'Category' 'ID'
# 'URL' 'Desc' 'Date' 'Flags' 'RefCount' 'Signature' 'MASFile'
# 'BaseSignature' 'MinVersion'
# Name=134_JUDD
tags = {}
for line in text:
... | 92a536b36e0c9ea78bef1ffd97ff69d4e448a0ac | 28,778 |
def _filter_none_elems_from_dict(dict_: dict):
""" Given a dict (call it m), returns a new dict which contains all the
non-null (non-none) elements of m.
Args:
dict_: The dict to return the non-null elements of.
Returns:
A new dict with all the non-null elements of <dict_>.
"""
... | a8b95a1e9f36e90b5c96a4e95b05fcba069d4a93 | 28,779 |
def _event_QComboBox(self):
"""
Return QCombobox change event signal
"""
return self.currentIndexChanged | f3d220db6642f065b3c2201bab9614fa8bde288b | 28,781 |
def range_filter(field, gt=None, gte=None, lt=None, lte=None):
"""
You must specify either gt (greater than) or gte (greater than or
equal to) and either lt or lte.
"""
return {"range": {field: {
k: v for k, v in {'gt': gt, 'gte': gte, 'lt': lt, 'lte': lte}.items()
if v is not None
... | 08052a50335e8b98e32a64fb7fd2031eb9919e7e | 28,782 |
def check_layout_layers(layout, layers):
"""
Check the layer widget order matches the layers order in the layout
Parameters
----------
layout : QLayout
Layout to test
layers : napari.components.LayerList
LayersList to compare to
Returns
----------
match : bool
... | 7d5c3ed65e0588f430341345d6e0fb0856aacaeb | 28,784 |
def isSignedOff(message):
"""
Check whether a commit message contains Signed-off-by tag
"""
for line in message.splitlines():
if line.startswith('Signed-off-by'):
return True
return False | 79248d9438ac1fc1cbce18ae8af236f0960d42e2 | 28,785 |
def outsideprocess(func):
"""Annotation to mark a job function. Only functions marked with this annotation are accepted as jobs."""
func._outsideprocess = True
return func | 31848ee04170661ef319fcbbe54086c34c99f102 | 28,787 |
import logging
def create_portfolio(client, portfolio_conf, region):
"""
To create the portfolio
:param client:
:param portfolio_conf:
:param region:
:return:
"""
response = client.create_portfolio(
DisplayName=portfolio_conf['Name'],
Description=portfolio_conf['Descrip... | 892f3742da9d3d17957a0b5ca688ae74caef3cc8 | 28,788 |
def num_to_list(integer):
"""changes a number to a list - a quasi inverse of the list_to_num"""
result = [0 for _ in range(3)]
result[integer] = 1
return result | d65fb981f6f1a3f759968424e8c833d86abd63da | 28,789 |
def categorize_by_damage(hurricanes):
"""Categorize hurricanes by damage and return a dictionary."""
damage_scale = {0: 0,
1: 100000000,
2: 1000000000,
3: 10000000000,
4: 50000000000}
hurricanes_by_damage = {0:[],1:[],2:[],3:[],4:[],5:[]}
for c... | be4371b983f34bc054e5bea94c3b9d1973272cc5 | 28,792 |
from typing import List
def check_numerics(numerics: List[int], min: int, max: int) -> List[int]:
"""Check that everything in the list is in bounds"""
s = sorted(numerics)
if s[0] < min or s[-1] > max:
raise Exception(
f"Out of bounds numbers in list {numerics}, min: {min}, max: {max}... | 85588e099752167302220479244682e3129698d1 | 28,793 |
import requests
import sys
def consumer_is_healthy(burrow, consumer):
"""Return true if consumer is healthy"""
res = requests.get("{}/consumer/{}/status".format(burrow, consumer))
if res.status_code != 200:
print("Did not find consumer {}, aborting!".format(consumer))
sys.exit(1)
all_g... | e726878bd06a25eaea12a924e038b1f7179f1269 | 28,794 |
def read_file(file_path):
"""
Reads input file.
Args:
file_path (str): path of input file.
Returns:
list: content of the file.
"""
with open(file_path, 'r') as file:
return file.read().strip().split('\n') | 27008dcbd9bd9336240e68c9514ae6170c18df78 | 28,795 |
def get_cache_backend(class_path, **kwargs):
"""This method initializes the cache backend from string path informed."""
parts = class_path.split('.')
module = __import__('.'.join(parts[:-1]), fromlist=[parts[-1]])
cls = getattr(module, parts[-1])
return cls(**kwargs) | 133ff883f0705d2e7ef18f69253df33d1e1691d0 | 28,796 |
def get_attempt_data(all_gens):
"""
Extracts the attempt data of succesful generations
all_gens - dict of key nodeID
value list of (nodeID, createTime, attempts, (createID, sourceID, otherID, mhpSeq))
:return: dict of dicts
A dict with keys being nodeIDs and values be... | 8138ce8cdea37dffb45b67e4f1c046ae25754d57 | 28,797 |
import json
def read_json_file(filename):
"""Read JSON file
Read JSON file as dictionary
Args:
filename(str): Filename
Returns:
dict: Dictionary with file content
"""
with open(filename, 'r') as json_file:
json_str = json_file.read()
try:... | dbc7360d44bb964f1d59186806f552c844d311e1 | 28,798 |
def interpret_action(action, ins):
"""Interpret classifier class: return length of input to consume + output."""
if action[0] == u'R':
return (1, ins)
elif action[0] == u'D':
return int(action[1:]), u''
elif action[0] == u'C':
return len(action[1:]), action[1:]
elif action[0]... | 23cc2d14f6d49180cd6d680c266df12c95e2411f | 28,800 |
def get_kit_application_list(kit_applicationTypes):
"""
translates any application shortcut keywords and returns all applications compatible with the kit as a list
"""
all_applications = kit_applicationTypes
if "AMPS_ANY" in kit_applicationTypes.upper():
all_applications = kit_applicationTyp... | 1c2f2e79901a68490176efd6dbc400f6ad083f7c | 28,801 |
def FindFieldDefByID(field_id, config):
"""Find the specified field, or return None."""
for fd in config.field_defs:
if fd.field_id == field_id:
return fd
return None | b49766575864dac1d65a8a245827d00fcd345be1 | 28,802 |
import os
def get_supervisor_ip():
"""Return the supervisor ip address."""
if "SUPERVISOR" not in os.environ:
return None
return os.environ["SUPERVISOR"].partition(":")[0] | bf6bed7f858012c0d97d392bf775fb69c41b9ecd | 28,803 |
import numpy as np
def bootstrap(original_data, statistic, num_resamples):
"""
bootstrap some data
"""
out_data = []
for iteration in range(num_resamples):
data = np.random.choice(original_data, len(original_data))
stat = statistic(data)
out_data.append(stat)
return np.... | 8604febd55fe14bd140ff4bc3849d06879589bb0 | 28,804 |
def get_section_length(data):
"""Gets the section length from the given section data
Parses the given array of section data bytes and returns the section length.
"""
sl = (data[1] & int('00001111', 2)) << 8
sl = sl + data[2]
return sl | 2e388ec7e11288fc22a284ebad1e478c0aadbc40 | 28,805 |
def _get_cmd_with_file(fn, algo, kernelonly=False):
"""
fn: file name of matrix
"""
cmd='./main -file=%s -algo=%s' % (fn, algo)
if kernelonly:
cmd = '%s -kernelonly=1'%cmd
if algo == 'mergepath' or algo == 'fixedrow4' or algo == 'fixedrow3':
cmd = '/home/shshi/downloads/merge-spm... | 4cca3900b794f0f715851671ace6ee720db3e51b | 28,807 |
def as_an_int(num1):
"""Returns the integer value of a number passed in."""
return int(num1) | 32971d8def38efacb150ff511e400700f78c0907 | 28,808 |
def task_all():
"""Run all checks, then build the docs and release"""
return {"actions": [], "task_dep": ["tox", "docs", "build"]} | 6ac4fb358328894b608461572a4eac4258a33e7e | 28,809 |
import json
def dump_json(obj, format = 'readable'):
"""Dump json in readable or parseable format"""
# Parseable format has no indentation
indentation = None
sep = ':'
if format == 'readable':
indentation = 4
sep += ' '
return json.dumps(obj, indent = indentation, separators =... | 2b6efb9202def6651bf4deb1ebc5e34f44c6c438 | 28,810 |
def format_element(eseq):
"""Format a sequence element using FASTA format (split in lines of 80 chr).
Args:
eseq (string): element sequence.
Return:
string: lines of 80 chr
"""
k = 80
eseq = [eseq[i:min(i + k, len(eseq))]for i in range(0, len(eseq), k)]
return("\n".join(eseq)) | 1e492b341d5ecea3f44ac9fe7246964a98f016a7 | 28,811 |
def validate_reset_payload(new_user):
""" this endpoint validates password reset payload """
# Check for empty current password
if new_user['current_password'] == '':
return {'message': 'Old Password Cannot be empty'}, 400
# Check for empty current password
elif new_user['new_password'] ==... | caa23eb60bb36e4acc163a618fdeaaace2da2945 | 28,812 |
from typing import List
def _calculate_german_iban_checksum(
iban: str, iban_fields: str = "DEkkbbbbbbbbcccccccccc"
) -> str:
"""
Calculate the checksum of the German IBAN format.
Examples
--------
>>> iban = 'DE41500105170123456789'
>>> _calculate_german_iban_checksum(iban)
'4... | dd9edcc1047caae8822d7a70f02d934db67504db | 28,813 |
def readTpsLog(fn):
"""
read in a file, line by line
"""
T = ""
with open(fn, "r") as f:
lines = f.readlines()
# print ("log len:", len(lines))
for line in lines:
T += line
return T | 01c882a0c3b6fd3deab38484616935b3cebe6046 | 28,815 |
def w_acoustic_vel(T,S,Z,lat):
""" Calculate acoustic velocity of water dependent on water depth,
temperature, salinity and latitude. After Leroy et al. (2008)
J. Acoust. Soc. Am. 124(5). """
w_ac_vel = 1402.5 + 5 * T - 5.44e-2 * T**2 + 2.1e-4 * T**3 + 1.33 * S - 1.23e-2 * S * T + 8.7e-5 * S * T**2 + 1.... | d1b8cac0c2bb65d76eb0125faf981a5b1ad1e31e | 28,817 |
def find_service_by_type(cluster, service_type):
"""
Finds and returns service of the given type
@type cluster: ApiCluster
@param cluster: The cluster whose services are checked
@type service_type: str
@param service_type: the service type to look for
@return ApiService or None if not... | fd04adce95c71499e17a143d7c94c0cf1aa603c9 | 28,818 |
def get_time_string(seconds):
"""Returns seconds as Slurm-compatible time string
"""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
time_string = "{:02d}:{:02d}:{:02d}".format(int(h), int(m), int(s))
if h > 99999 or h < 0:
return "00:00:00"
return time_string | 6730744ab428dbcab0f7dfd8cf7c443e3ccfda1e | 28,820 |
import os
def file_get_uniq_name(filename, max_iter=1000):
""" Gets unique file name by adding number to the end of the file
If unique file name cannot be found, it returns an empty string
"""
i = 1
nfn = filename
fn, file_ext = os.path.splitext(filename)
while i < max_iter and os.path... | 7651026164ec04a6871dfae464dcf31891d6707c | 28,822 |
def resolve_stack_name(source_stack_name, destination_stack_path):
"""
Returns a stack's full name.
A dependancy stack's name can be provided as either a full stack name, or
as the file base name of a stack from the same environment.
resolve_stack_name calculates the dependency's stack's full name ... | ffee297a7ce1f25cecd1832ced3c8dc9fd729e90 | 28,823 |
import os
import gzip
import io
def get_fastq_file_handle(fastq,mode='rt'):
"""Return a file handle opened for reading for a FASTQ file
Deals with both compressed (gzipped) and uncompressed FASTQ
files.
Arguments:
fastq: name (including path, if required) of FASTQ file.
The file can be... | ee3f710ce330e7e8a68eb407bda251ffd57e0b73 | 28,824 |
def get_induced_subgraph(graph, nodes):
"""Get the nodes-induced subgraph G[S] for a graph G and a subset of nodes S"""
return {node: graph[node].intersection(nodes) for node in nodes} | 58955db6d38dae86f24b756a6bfc67886300eaf5 | 28,826 |
def merge_two_lists(list_one, list_two):
"""
Function merge two lists in a list. Then return the sorted list.
Input lists don't change.
:rtype: list
:return: sorted list
"""
# Copy lists by value
temp_list_one = list_one[:]
temp_list_two = list_two[:]
mergedlist = []
while... | bd0bae58ad54725b55da64404b2635e71881907f | 28,828 |
def filter_stories(stories, triggerlist):
"""
Takes in a list of NewsStory instances.
Returns: a list of only the stories for which a trigger in triggerlist fires.
"""
lists = []
for i in stories:
for triggers in triggerlist:
if triggers.evaluate(i)==True:
li... | a91aa78452fb0a75753a0687a7938a565b2b87f0 | 28,829 |
def _hexint(string):
"""Convert argument to hex."""
return int(string, 16) | 826722b30700d430a43702d1b5430638f4e96e54 | 28,830 |
def add_shellcode() -> bytes:
""" Returns shellcode generated by msfvenom"""
# msfvenom -p windows/shell_reverse_tcp lhost=eth0 lport=4444 -f hex EXITFUNC=thread -b "\x00"
shellcode = b""
shellcode += b"bba862840bdbc5d97424f45a29c9b152"
shellcode += b"315a1283eafc03f26c66fefe99e401fe"
shellcode ... | c77413d7d5f2e392916266cf91919475670e3f59 | 28,831 |
def filter(rec, labels):
"""returns record with only detected objects that appear in label list"""
count = 0
new_rec = {
"file": rec["file"],
}
for label in labels:
if label in rec.keys():
count += 1
new_rec[label] = rec[label]
if count:
return new... | fbf3fe37721e2ed9e31ed734637615c937fa3461 | 28,832 |
def find_max(dictIn, keyIn):
"""Get max value here."""
maxValue = max(dictIn[keyIn].values())
#print("max value is -", maxValue, "- among values ", dictIn[keyIn].values())
listMax = []
strTemp = ""
"""Add to the list of max pairs here."""
for k,v in dictIn[keyIn].items():
#... | 7a76c9793baad279b123cea6baba8fc61fa6ff54 | 28,835 |
def remove_namespace(tree):
"""
Namespace can make Splunk output ugly. This function removes namespace from all elements
e.g element.tag = '{http://schemas.microsoft.com/win/2004/08/events/event}System'
:param tree: xml ElementTree Element
:return: xml ElementTree Element with namespace removed
... | b2f4431ffcd33b26321271ea55da24386c10adac | 28,836 |
def check_eat_self(pos, snake):
"""If True, it does not eat itself; if False, it eats itself."""
if pos in snake:
return False
else:
return True | 0815373ab3e47b9bfaaadee96d20e4df6e20cae3 | 28,837 |
import logging
def setup_logger(name, log_file="log/dump.txt", log_level=logging.INFO):
""" return a logger with log_file """
logger = logging.getLogger(name)
fh = logging.FileHandler(log_file, mode='a')
# fh = logging.FileHandler("log/dump.txt", mode='a')
fh.setLevel(level=log_level)
fh.setFormatter(logging.For... | 35ff291a4295fac7463d4459308cb15dee12d36e | 28,838 |
import os
def get_path_separator():
"""
Returns the appropriate file path separator depending on operating
system. That is, when run on UNIX-like systems it returns a forward slash
('/'), and for Windows it returns a backslash ('\')
:return: String. The file path separator for the current operatin... | 4a5b9947e6aef55d5dcda10317cbea9d210e7534 | 28,839 |
def elide_sequence(s, flank=5, elision="..."):
"""Trims the middle of the sequence, leaving the right and left flanks.
Args:
s (str): A sequence.
flank (int, optional): The length of each flank. Defaults to five.
elision (str, optional): The symbol used to represent the part trimmed. De... | df318fec488dec46e0f99a0c035b0a962be59844 | 28,840 |
from typing import Mapping
def find_path(g: Mapping, src, dst, path=None):
"""find a path from src to dst nodes in graph
>>> g = dict(a='c', b='ce', c='abde', d='c', e=['c', 'z'], f={})
>>> find_path(g, 'a', 'c')
['a', 'c']
>>> find_path(g, 'a', 'b')
['a', 'c', 'b']
>>> find_path(g, 'a', ... | ea3c48ef552b1393448c36579b11c5bc09c5cced | 28,841 |
def get_reset_time(headers):
"""
Get the reset header.
"""
reset_time = headers.get("X-Rate-Limit-Reset", None)
if reset_time is None:
reset_time = headers.get("X-RateLimit-Reset", None)
if reset_time is None:
return None
try:
reset_time = int(reset_time)
except... | f116b7606fa69628aa6078731f51872764c44f1b | 28,842 |
import requests
def is_connected():
"""Verifies whether network connectivity is up.
:returns: True if connected else False.
"""
for _ in range(3):
try:
r = requests.get("http://www.github.com/", proxies={}, timeout=3)
r.raise_for_status()
return True
... | 75df5621bce8133a3c667c0eef8178eb7c509628 | 28,844 |
import argparse
def create_parser(args):
""" Function which add the command line arguments required for the command line input
of text similarity index processor"""
# Create the parser
cos_parser = argparse.ArgumentParser(description='EagleVision')
# Add the arguments
cos_parser.add_argument(... | 2cbc71c96eb0a128f9ae044df0838eb82db3a98d | 28,845 |
def standard_exception_view(self, request):
"""We want the webob standard responses for any webob-based HTTP exception.
Applies to subclasses of :class:`webob.HTTPException`.
"""
# webob HTTPException is a response already
return self | cd7dbcf3118244a0ef338e0476e25f4c1d01dd8f | 28,847 |
from typing import Any
from typing import Dict
def metadata(user_model: Any) -> Dict:
"""
Call the user model to get the model metadata
Parameters
----------
user_model
User defined class instance
Returns
-------
Model Metadata
"""
if hasattr(user_model, "metadata"):
... | 6fa8df5a8d842c8fbccfa6d8447732da4263a124 | 28,848 |
def get_nuts_category(year):
"""
Function that returns the nuts2 year in place for a year
"""
if year >= 2016:
return f"nuts2_2016"
elif year >= 2013:
return f"nuts2_2013"
elif year >= 2010:
return f"nuts2_2010"
elif year >= 2006:
return f"nuts2_2006"
else... | 1f8ca85787065e4aa1455931a5a3cfec05baa5f0 | 28,849 |
import os
def collect_module_files(module_name, relative_path_in_module):
"""Return a list of tuples of (absolute_file_path, zip_target_path)"""
loaded_module = __import__(module_name, globals(), locals(), [], 0)
module_path = os.path.dirname(loaded_module.__file__)
if len(relative_path_in_module) == ... | c337d49827336a491e469d4e89433549c04b3ee4 | 28,850 |
def get_lr(optimizer):
"""
----------
Author: Damon Gwinn
----------
Hack to get the current learn rate of the model
----------
"""
for param_group in optimizer.param_groups:
return param_group['lr'] | e3989ecc8df9b02d52fd30f64a1c216c8cea58f4 | 28,851 |
def rgb_clamp(colour_value):
"""
Clamp a value to integers on the RGB 0-255 range
"""
return int(min(255, max(0, colour_value))) | f4dce9746fecd32cb432f03a056451a34d6f265a | 28,852 |
import pyarrow
def _is_column_extension_type(ca: "pyarrow.ChunkedArray") -> bool:
"""Whether the provided Arrow Table column is an extension array, using an Arrow
extension type.
"""
return isinstance(ca.type, pyarrow.ExtensionType) | 606c2fad0486df8f4995925021111eb1cb78f3c4 | 28,853 |
def Get_Desired_Values(i_rank, l_data):
"""Retrieve desired values of a coin in list returned by GetJSON()"""
l_coin_values = []
l_key = [
"rank",
"name",
"symbol",
"price_btc",
"price_usd",
"price_eur",
"market_cap_usd",
... | 3b81959420bf45f0c313d2ba24e1e3f0642e4b05 | 28,854 |
import re
def split_by_list(txt, seps):
"""
:param txt: text to be split
:param seps: list of separators
:return: List including the separators
"""
seps_str = '(' + '|'.join(seps) + ')'
return re.split(seps_str, txt) | 9d91703d4954186b85b68bc6ec746fc417f335ca | 28,855 |
def new_dict(key, value):
"""Construct a new dict.
Parameters
----------
key, value : TypeRef
Key type and value type of the new dict.
"""
# With JIT disabled, ignore all arguments and return a Python dict.
return dict() | 61a40b1b5009e87cfbdc5cd4197830dde0abf4f9 | 28,859 |
def construct_yaml_fields(signatures, function_operation_id_root,
file_operation_id_root, server_root_url):
"""
Parse the signatures of functions to a dictionary that is used to generate yaml files.
f = {0: {'name': 'linear-regression',
'request_method': 'post',
... | a7c52279eb9900aa415ba75838b3af63d1f8a94a | 28,861 |
import logging
def __logger():
"""Retrieves the module-level logger object."""
return logging.getLogger(__name__) | ef580617dcf54f2767fdeb471d97b70e1d222105 | 28,863 |
import string
import random
def generate_password(length: int) -> str:
"""Return random password of specified length."""
choice = string.ascii_letters + string.digits
password = ""
for character in random.choices(choice, k=length):
password += character
return password | 3ef64b60ea893fe37aad5ca41cad6f1363f48412 | 28,864 |
def build_geometry(self):
"""Compute the curve (Line) needed to plot the Slot.
The ending point of a curve is the starting point of the next curve in
the list
Parameters
----------
self : SlotM17
A SlotM17 object
Returns
-------
curve_list: list
Empty list (no lamin... | a56a4f90b5b6677f5b74ba11694818604543c352 | 28,866 |
def overlaps(a, b):
"""Return true if two circles are overlapping.
Usually, you'll want to use the 'collides' method instead, but
this one can be useful for just checking to see if the player has
entered an area or hit a stationary oject.
(This function is unoptimized.)
"""
dx = a.x - b.x... | d7d1a5e110415895f5891a9c14124d50a5b68f69 | 28,867 |
def wrap_it_in_a_link(html, url):
""" Wrap a link around some arbitrary html
Parameters:
html - the html around which to wrap the link
url - the URL to link to
Returns:
The same html but with a link around it
"""
return "<a href='" + url + "'>" + html + "</a>" | 606ca401982a4f5474e03063e26e402e690557fc | 28,871 |
def mostVisited(node):
"""
i.p.v. best child te bepalen door de formule nog een keer te gebruiken kan je ook de meest bezochte node geven als beste volgende actie.
Het verschil tussen deze manier and bestChild() manier is niet groot.
(source: http://ccg.doc.gold.ac.uk/ccg_old/papers/browne_tciaig12_1.p... | 441e8968ddf5a80a0a3cca610f9e5dcb86722ed4 | 28,872 |
def is_even(number: int):
"""Return True if the number is even and false otherwise"""
return number % 2 == 0 | 0fe6ff55e5a84caedda3523bad02b8d144ab0657 | 28,873 |
def merge_tfds(*terms_d):
""" mege_tfds(): is getting a set of term-frequency dictionaries as list of
arguments and return a dictionary of common terms with their sum of frequencies
of occurred in all dictionaries containing these terms. """
tf_d = dict()
tf_l = list()
for tr_dict in t... | 9f36206a77795fd471566819b4a5b5ddaeddaaf9 | 28,874 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.