content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def split(inp,n):
"""
Splits an input list into a list of lists.
Length of each sub-list is n.
:param inp:
:param n:
:return:
"""
if len(inp) % n != 0:
raise ValueError
i = j = 0
w = []
w2 = []
while i<len(inp):
# print(i,j)
if j==n:
j ... | 72feefc7ab6dc5288f12f5defb1d44ea2c7d95e8 | 60,701 |
def _fullname(obj):
"""Get the fully qualified class name of an object."""
if isinstance(obj, str):
return obj
cls = obj.__class__
module = cls.__module__
if module == "builtins": # no need for builtin prefix
return cls.__qualname__
return module + "." + cls.__qualname__ | 8923c1de66ba50b6bfb340839ec1c8239f313688 | 60,704 |
def adjusted_classes(y_scores, threshold):
"""
This function adjusts class predictions based on the prediction threshold (t).
Will only work for binary classification problems.
Inputs:
y_scores (1D array): Values between 0 and 1.
threshold (float): probability threshold
Returns:
... | 84a1c33fa10141ca8c7b16bb194e46fd5254856f | 60,706 |
def get_ec2_instance(cloud_connection, region, instance_filters):
"""
Find and return an EC2 object based on criteria given via `instance_filters` parameter.
:param cloud_connection: object: Cloud Connection object
:param region: string: The AWS region where the instances are located.
... | 3b0a9d536114cb1769a3f758df7df1fcf904b365 | 60,707 |
def chocolate_feast(n, c, m):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/chocolate-feast/problem
Function that calculates how many chocolates Bobby can purchase and eat. Problem stated below:
Little Bobby loves chocolate. He frequently goes to his favorite 5&10 store, Penny Auntie, to b... | be400b13b15fbed6d21a95a7cbc35fd474ed7fb7 | 60,708 |
import math
def calc_angle_between_two_locs(lon1_deg, lat1_deg, lon2_deg, lat2_deg):
"""
This function reads in two coordinates (in degrees) on the surface of a
sphere and calculates the angle (in degrees) between them.
"""
# Import modules ...
# Convert to radians ...
lon1_rad = math.ra... | 1ffa72e64696fc800de3fbf93bfb01a13ce14d22 | 60,709 |
def parse_time(value: str) -> int:
"""
Parses the string into a integer representing the number of milliseconds.
"""
if value.endswith("ms"):
return int(float(value.replace("ms", "")))
return int(float(value.replace("s", "")) * 1000) | 99dde4ccf874ec73d5785715ca5367b9d2535491 | 60,711 |
import re
def parse_macro_spec(macro_spec):
"""
Parse a macro specification and return a dictionary of key-value pairs
:param macro_spec: Macro string in the format "key=value,key=value,..."
"""
if macro_spec:
return dict(re.findall("(\w+)=([^,]*)", macro_spec))
else:
return {} | 0bd6ecbbb35e4214900b2f2b818a95672fb2cdd3 | 60,712 |
import importlib
def get_member(member_path: str):
"""
Import a module and retrieve a member from a module dot notation path
separated by an ``:`` with the instance name.
(eg: ``package.module:instance``)
:param member_path: A string path with pattern
``package.module:member``
:retur... | 835ae6dd7c30bd1b435c2e8d5172dc04c0b19a5a | 60,715 |
import hashlib
def compute_text_md5(text):
""" Compute md5sum as hexdigest
:param text: the input string
:rtype string
"""
m = hashlib.md5()
m.update(text)
return m.hexdigest() | 8d6b0b9484fd28beff6cc6fccdedd7ab0570470b | 60,718 |
from datetime import datetime
def make_timestamp(minutes_ago):
"""Make POSIX timestamp representing now minutes `minutes_ago`."""
minute_1 = 60
return datetime.now().timestamp() - (minutes_ago * minute_1) | 8ede4844dceade1c121c3d582e1d3a8e33c46d00 | 60,719 |
def save(context, key, value):
"""
Saves any value to the template context.
Usage::
{% save "MYVAR" 42 %}
{{ MYVAR }}
"""
context.dicts[0][key] = value
return '' | 4623d867a91941abe9b4d9b80944d80831187669 | 60,720 |
import re
def match(string, patterns):
"""Given a string return true if it matches the supplied list of
patterns.
Parameters
----------
string : str
The string to be matched.
patterns : None or [pattern, ...]
The series of regular expressions to attempt to match.
"""
i... | 7477412a3619e19d24885adfa56c451c92c74f4d | 60,722 |
def get_gettext(o):
"""
In python 2 return the ugettext attribute. In python 3 return gettext.
"""
return o.gettext | ba74557088e90bbf7a69ce7e1b466728aa13375f | 60,729 |
def require_model(f):
"""Decorator to perform check that the model handle exists in the service.
"""
def wrapper(*args, **kwargs):
"""Function wrapper to perform model handle existence check."""
if args[0].config.handle():
return f(*args, **kwargs)
raise Exception("API r... | a38d0afb4cb68e2f2d8b651493f72dbf30c6d713 | 60,730 |
def _getHierBenchNameFromFullname(benchFullname):
"""
Turn a bench name that potentially looks like this:
'foodir/bench_algos.py::BenchStuff::bench_bfs[1-2-False-True]'
into this:
'foodir.bench_algos.BenchStuff.bench_bfs'
"""
benchFullname = benchFullname.partition("[")[0] # strip any... | c9bbc6882f2c702a110d1b81b8c47eace72409b9 | 60,731 |
def hostname( location ):
"""Extracts the hostname."""
end = location.find(':')
if -1 == end:
host = location
else:
host = location[0:end]
return host | 80245838573d480bdc57b8c16a28f3522e7b2cfa | 60,732 |
import re
def error_065_image_desc_with_br(text):
"""Fix the error and return (new_text, replacements_count) tuple."""
return re.subn(r"(\[\[Файл:[^\]]+)\s*<br>\s*(\]\])", "\\1\\2", text) | 36a69c6c7951480b6642b69db1c465c273545811 | 60,733 |
import copy
def subj_or_obj_in_annotations(annotations, item, rel, item_in_mod):
""" Looks for item in the second pos of annotations AND rel in the first
pos of the annotation. If both are found, it creates a new annotation
[rel, item, item_in_mod] and returns it. Otherwise, it returns None"""
annotat... | 03cfd197dc878536e6f697adf59e6107f1015699 | 60,738 |
import json
def refresh(series_id):
"""
Params:
series_id [int] - id for the series as designated by apple
Returns:
JSON object with keys "success" (either 0 or 1) and "episode"
that contains the entire episode object.
Given a series_id, checks to see if we should request apple
to get new epis... | 119428af519400d77777bd1418b6ce3eeba0e112 | 60,739 |
def _obj_exists(r, queue, obj):
"""Returns whether the obj exists in the given queue."""
size = r.llen(queue)
# No reason to call lrange if we aren't even dealing with a list, for
# example.
if size == 0:
return False
###
# Hopefully this isn't so wildly inefficient that it blows u... | c621c03331db60ae2105d094410e10c4a48e678d | 60,743 |
def year_type(s):
"""Validate the type of year argument.
Args:
s (str): The parsed argument.
Returns:
int: Year if valid.
Raises:
ValueError: If `s` is not a valid year.
"""
y = int(s)
if y < 1950:
raise ValueError('Year should be provided in four-digit fo... | d18848a60582e877867c7032030d36e3d35d78bf | 60,748 |
def _next_page_state(page_state, took):
"""Move page state dictionary to the next page"""
page_state['page_num'] = page_state['page_num'] + 1
page_state['took'] = page_state['took'] + took
return page_state | edf4a4d0540683fe4b92c6428200c418b5bf41b9 | 60,752 |
def to_month_only_dob(date):
"""
Convert dates of birth into month and year of birth starting from 1st of each month for anonymity
return blank if not in the right format
"""
try:
date = date.strftime("%Y-%m-01")
except ValueError:
date = ""
except TypeError:
date = "... | d6e38593cb5f636c5d93e7cf5901056196d712c2 | 60,753 |
import functools
import operator
def combine_probability_matrices(matrices):
"""given a sequence of probability matrices, combine them into a
single matrix with sum 1.0 and return it"""
distribution = functools.reduce(operator.mul, matrices)
# normalize
return distribution / distribution.sum() | e27e702226188238d49fd285e5171af06a40bead | 60,754 |
def makebinstr(binning):
"""Return a string for the binning"""
binning=binning.strip().split()
return '%sx%s' % (binning[0], binning[1]) | 59b59a368eea95418a22b2898f3c2fa8f34f37f2 | 60,755 |
import json
def toJSON(py_object):
"""Convert an object to JSON string using its __dict__
:param py_object: object to create a JSON string of
"""
return json.dumps(py_object, default=lambda o: o.__dict__) | ef6a5ab78bb96ad7e3ad29cabf02811fcf16aa6b | 60,759 |
def is_european(point):
"""Returns true if the continent code for the given point is Europe."""
return point['AddressInfo']['Country']['ContinentCode'] == 'EU' | 16132f97416c7cd36202a1462956f5a5cc345ddc | 60,762 |
def attr(*args, **kwargs):
"""
Set the given attributes on the decorated test class, function or method.
Replacement for nose.plugins.attrib.attr, used with pytest-attrib to
run tests with particular attributes.
"""
def decorator(test):
"""
Apply the decorator's arguments as argu... | 6091c81a24fe549bc6e7cd8a4b98c94f4617157a | 60,769 |
from typing import List
from typing import Optional
from typing import Tuple
def merge_template_tokens(
template_ids: List[int],
token_ids: List[int],
max_length: Optional[int] = None
) -> Tuple[List[int], List[int]]:
""" Merge template and token ids
Args:
- template_ids: List[int], template... | 2286be670b7856ee4e82ac80a6d649ca2511eb47 | 60,770 |
def run_model(model):
"""Run a BCMD Model.
Parameters
----------
model : :obj:`bayescmd.bcmdModel.ModelBCMD`
An initialised instance of a ModelBCMD class.
Returns
-------
output : :obj:`dict`
Dictionary of parsed model output.
"""
model.create_initialised_input()
... | c08fe4b0f90f07ee1f9a77062fd09822a1fec477 | 60,773 |
import platform
def get_python_version() -> str:
"""Find and format the python implementation and version.
:returns:
Implementation name, version, and platform as a string.
"""
return "{} {} on {}".format(
platform.python_implementation(),
platform.python_version(),
pl... | 8daf0b8e2153e37dcdfca396f9af32699a42d81d | 60,776 |
def __call_cls_method_if_exists(cls, method_name):
"""Returns the result of calling the method 'method_name' on class 'class' if the class
defined such a method, otherwise returns None.
"""
method = getattr(cls, method_name, None)
if method:
return method() | a078c004c8852c562ef0b8cff8096e34bf4e9f80 | 60,780 |
def avg_polysemy(polysemy_dict):
"""
compute average polysemy
.. doctest::
>>> avg_polysemy(defaultdict(int, {1: 2, 2: 2}))
1.5
:param collections.defaultdict polysemy_dict: mapping from polysemy class
to number of instances in that class
:rtype: float
:return: average pol... | 7582e2e422fe6556c2bf573dec93c81241eb7643 | 60,783 |
def recalc_dhw_vol_to_energy(vol, delta_t=35, c_p_water=4182, rho_water=995):
"""
Calculates hot water energy in kWh/a from input hot water volume in
liters/apartment*day
Parameters
----------
vol : float
Input hot water volume in liters/apartment*day
delta_t : float, optional
... | 75bd85e68949303d66ee658e8bd4698b7f86ec2f | 60,791 |
def _cf_log(log_effect, *args, **kwargs):
"""
Log cloud feeds message with a "cloud_feeds" tag parameter.
"""
kwargs['cloud_feed'] = True
return log_effect(*args, **kwargs) | 5e8513b409c44c3ee190b3392a99f39a9cc53784 | 60,792 |
def norm_color(s):
"""
>>> norm_color('red')
'Red'
>>> norm_color('Dark red')
'Dark Red'
>>> norm_color('dkred')
'Dark Red'
>>> norm_color('trred')
'Trans-Red'
>>> norm_color('trdkblue')
'Trans-Dark Blue'
>>> norm_color('rb')
'Reddish Brown'
>>> norm_color(' trdkb... | 937894af7f84b117ef075dd9f56092de82cc8289 | 60,800 |
import torch
def get_device(arguments):
"""
Sets the device that will be used to training and testing.
:param arguments: A ArgumentParser Namespace containing "gpu".
:return: A PyTorch device.
"""
# Checks if the GPU is available to be used and sets the .
if arguments.gpu and torch.cuda.i... | aa500a146aaa262186b27a8f9e712749437f090c | 60,804 |
import re
def get_chiral_indices_from_str(Ch):
"""Return the chiral indicies `n` and `m`.
Parameters
----------
Ch : str
string of the form 'NNMM' or "(n, m)". Extra spaces are acceptable.
Returns
-------
sequence
2-tuple of chiral indices `n` and `m`
"""
try:
... | e36f2cc3adc73d98340ff2565968321e9ac7009b | 60,805 |
def vec_dot(a, b, length=None):
"""Dot product of vectors *a* and *b*."""
if length is None:
length = len(a)
return sum(a[i] * b[i] for i in range(length)) | 42eb7ba84ad709fd492d1bb706863ca712e293b0 | 60,807 |
def get_smell_value(row, smells_frame, smell, key='test_name', verbose=False):
"""
Returns the value for the given smell for a particular test
:param row: the data frame row for the test
:param smells_frame: the frame with all the smells
:param smell: the kind of smell
:param key: the key to loo... | 504458e28ac96abed94dcc5c3bc0cc9cf577dca7 | 60,809 |
def pointsAroundP(P, width, height):
""" Return a list of points surround P provided that P is within the bounds of the area
"""
Px,Py = P
if not(Px >= 0 and Px < width and Py >= 0 and Py < height):
return []
result = [
(Px-1, Py),
(Px+1, Py),
(Px, Py-1),
(Px... | b9b2e5a43a6435a908a0c8f6dfd174b141b63c62 | 60,810 |
def format_helptext(value):
"""Handle formatting for HELPTEXT field.
Apply formatting only for token with value otherwise supply with newline"""
if not value:
return "\n"
return "\t {}\n".format(value) | 426fa6ee036c5a8376645d6455c1681b1200e174 | 60,812 |
def escape(term):
"""
escapes a term for use in ADQL
"""
return str(term).replace("'", "''") | a1abeacacbfc8b72a15898379e52ebf8cba8ccb9 | 60,814 |
from typing import Union
def _generate_shortcut_linux(name : str, working_dir:str, path:str, executable:Union[str,bool], icon:str) -> str:
"""The steps to generate an icon for windows
Parameters
----------
name : str;
The name of the shortcut
working_dir : str
The path to the dir... | d96f765452f67ba40300408c9b7378c9adc3355a | 60,815 |
from typing import Dict
from typing import List
def isValidWord(word: str, hand: Dict[str, int], wordList: List[str]) -> bool:
"""Verify if word answer is in wordList and in hand
Does not mutate hand or wordList.
Args:
word: guest user
hand: current letter in a hand
wordList:... | 1e45f8e4ba9e0e0352e3be4a8d87e1a96a440ef4 | 60,818 |
def string_char(char):
"""Turn the character into one that can be part of a filename"""
return '_' if char in [' ', '~', '(', ')', '/', '\\'] else char | e318811d68858ff090447fa0e0e0aab9133461c8 | 60,823 |
def create_bigpath(nets):
""" Return a list with lists of wires from every net.
"""
bigpath = []
for net in nets:
bigpath.append(net.wires)
return bigpath | 5070dcedc021314238b3e5c85be0d6efcc379652 | 60,827 |
def rgbint2rgbfloat(i):
"""
Convert a rgb integer value (0-255) to a rgb float value (0.0-1.0).
Args:
i (int): Integer value from 0 to 255
Returns:
float: Float value from 0.0 to 1.0
"""
return i / 255 | 5e6e597d412cd2262defbb204bb097693270fff9 | 60,828 |
def flatten_dictionary(dictionary, separator=':', flattened_dict=None, parent_string=''):
"""
Flattens nested dictionary into a single dictionary:
{'hello': {'world': 1,
'moon': 2}}
becomes:
{'hello:world': 1,
'hello:moon': 2}
Uses recursion to flatten as man... | 6e5df742d9a9a0693cdf71469e5eee2b9f1fdd8d | 60,830 |
def rgb_to_hex(color_RGB):
"""Takes a sequence of 3 elements (each one a integer from 0 to 255), representing a RGB color.
Returns the HTML representation of the color (hexadecimal): #RRGGBB
"""
color_hex = hex((color_RGB[0] << 16) | (color_RGB[1] << 8) | (color_RGB[2])) # Convert the color values t... | d97249b2abfcd930c1491f8ff5caa34e5965dcc0 | 60,835 |
def _mark_transition_type(lookup_dict, lulc_from, lulc_to):
"""Mark transition type, given lulc_from and lulc_to.
Args:
lookup_dict (dict): dictionary of lookup values
lulc_from (int): lulc code of previous cell
lulc_to (int): lulc code of next cell
Returns:
carbon (str): d... | 10493de924b4184dd384e739963e2854fed54e0e | 60,836 |
import re
def GuessDataType(value, column_id=None):
"""Guess the DSPL data type of a string value.
Defaults to 'string' if value is not an obvious integer, float, or date.
Also, does not try to detect boolean values, which are unlikely to be used
in DSPL tables.
Args:
value: A string to be evaluated.
... | cbfc17280664f9b6499b4d883a3ed084b4f934f5 | 60,837 |
from typing import Dict
from typing import List
def _custom_text_tokenizer(text: str, lang: str,
dictionary_terms: Dict[str, str]) -> List[str]:
"""Helper function to split text by a comma."""
del lang
del dictionary_terms
return text.split(',') | 8489d1d02e06670938ae73ac650ee0c08c0892ec | 60,838 |
def volpiano_characters(*groups):
"""Returns accepted Volpiano characters
The characters are organized in several groups: bars, clefs, liquescents,
naturals, notes, flats, spaces and others. You can pass these group
names as optional arguments to return only those subsets:
>>> volpiano_characters(... | af361f302fc531828655e1274e7c0868969c2fdc | 60,839 |
def page_loaded_condition(driver):
"""Expected condition for page load."""
return driver.execute_script("return document.readyState") == 'complete' | 915bb10e443fcf12cde1e3a4945d9cf2a7c2ed2d | 60,840 |
def is_reference(d):
"""
Returns a boolean indicating whether the passed argument is reference.
A reference is a fict in the form {'#': soul}
"""
return isinstance(d, dict) and "#" in d | 0528cf3d39e26a76fb3108657bee13f8993057b9 | 60,844 |
def CodedBlockPattern(mb_type):
"""
>>> CodedBlockPattern(0)
(None, None)
>>> CodedBlockPattern(12)
(2, 0)
>>> CodedBlockPattern(13)
(0, 15)
"""
if mb_type > 25:
raise Exception('unknown mb_type %d' % (mb_type))
if mb_type == 0 or mb_type == 25:
return None, None
... | 7d0e6fae32e26c4950e220c02cd7b0c6c650f46d | 60,846 |
def get_md_links(link_list):
"""Return an unordered list of links in markdown syntax."""
html_links = "\n"
for link in link_list:
html_links += "* [{title}]({url})\n".format(**link)
return html_links | dbb146c5f744f3d5cd764d7867e2666dea954a00 | 60,847 |
def _to_11_bit(data):
"""
Convert a bytearray to an list of 11-bit numbers.
Args:
data (bytes): bytearray to convert to 11-bit numbers
Returns:
int[]: list of 11-bit numbers
"""
buffer = 0
num_of_bits = 0
output = []
for i in range(len(data)):
buffer |= data... | 0369c4b8b442475a8aa94bad439edaf67db1ad4e | 60,852 |
def e_sudeste(arg):
"""
e_sudeste: direcao --> logico
e_sudeste(arg) tem o valor verdadeiro se arg for o elemento 'SE' e falso
caso contrario.
"""
return arg == 'SE' | 482abc2671902eb92c6bd9fcd62f78a9783b1eb2 | 60,853 |
def get_root(w):
"""
Simple method to access root for a widget
"""
next_level = w
while next_level.master:
next_level = next_level.master
return next_level | 4bbdf5c38da114adea9213e2903eae44c1ce6d2c | 60,854 |
import re
def _readd_double_slash_removed_by_path(path_as_posix: str) -> str:
"""Path(...) on an url path like zip://file.txt::http://host.com/data.zip
converts the :// to :/
This function readds the ://
It handles cases like:
- https://host.com/data.zip
- C://data.zip
- zip://file.txt::... | c50a0974ebdd3e442c819296ac888b019969e4db | 60,855 |
def first(S):
""" Simply return the first item from a collection (using next(iter(S))) """
return next(iter(S)) | 7ccd05d1adae32cf3c1b92740098751707991541 | 60,858 |
def get_target_indice_from_leaves(targets, sent):
"""
Find the indice of the target words in the terminal sequence of a parsed sentence.
"""
target_indice = []
idx = 0
current_target = targets[idx]
for k, w in enumerate(sent):
if w == current_target:
target_indice.append(... | b02a0173c33faae687a91b09e99d7ef5b54168d1 | 60,864 |
def config_get(config, section, option, default=None, raw=0, vars=None):
"""Get a value from the configuration, with a default."""
if config.has_option(section, option):
return config.get(section, option, raw=raw, vars=None)
else:
return default | 8efb96fddeb4e3734d4a367ee07035e3cbb20050 | 60,865 |
def get_var_name(string: str) -> str:
"""Gets the name from an argument variable.
Args:
string: Input variable declaration
Returns:
The name of the arguments variable as a string, e.g. "int x" -> "x".
"""
var = string.strip()
# Not an actual variable
if var in ("void", "..."):
return ""
... | 836bd3bc74da2f0add83429f4585da3281040965 | 60,867 |
def trim_txt(txt, limit=10000):
"""Trim a str if it is over n characters.
Args:
txt (:obj:`str`):
String to trim.
limit (:obj:`int`, optional):
Number of characters to trim txt to.
Defaults to: 10000.
Returns:
:obj:`str`
"""
trim_line =... | 197dd9da07d8a5a42a33246431f50b6bae25b6bf | 60,873 |
def list_to_string(list_of_elements):
"""
Converts the given list of elements into a canonical string representation for the whole list.
"""
return '-'.join(map(lambda x: str(x), sorted(list_of_elements))) | 8502409ba67e96bae7d6de8565391a090395edec | 60,878 |
def rounder(numbers, d=4):
"""Round a single number, or sequence of numbers, to d decimal places."""
if isinstance(numbers, (int, float)):
return round(numbers, d)
else:
constructor = type(numbers) # Can be list, set, tuple, etc.
return constructor(rounder(n, d) for n in numbers) | d452714168867e2dd8568039bbdb3f54314299af | 60,880 |
import torch
def data_parallel_wrapper(model, cur_device, cfg):
"""Wraps a given model into pytorch data parallel.
Args:
model (torch.nn.Module): Image classifier.
cur_device (int): gpu_id
cfg : Reference to config.
Returns:
torch.nn.Dataparallel: model wrapped in dp.
... | 238a0d47936cb84f640df34ce420ab5cfa054be6 | 60,882 |
def get_next_player(players, currentplayer):
"""Returns the next player in an ordered list.
Cycles around to the beginning of the list if reaching the end.
Args:
players -- List
currentplayer -- Element in the list
"""
i = players.index(currentplayer) + 1
return players[i % len(... | a2bc14e0c19a5bf7f7931d557b785b6a62c8caf4 | 60,883 |
import re
import random
def get_patches(path, n=0):
"""Get selected number of patch IDs from given directory path.
If number is not provided, i.e. is zero, all patch IDs are returned.
:param path: Directory path where patches are
:type path: Path
:param n: Number of patch IDs to retrieve, default... | 02268f0b469155db0e57d4206a68a2d00e578e4e | 60,885 |
import networkx as nx
def get_most_central_node(G):
"""
Calculate the closeness centrality for all nodes of graph. Return maximum node
:param G: graph
:return: node with maximal closeness centrality
"""
closeness = nx.closeness_centrality(G)
return max(closeness, key=closeness.get) | 277ba9e7ef855a5d342e82e7723c8c58e240037c | 60,886 |
import math
def calcular_distancia_tierra(t1: float, g1: float, t2: float, g2: float) -> float:
""" Distancia entre dos puntos en la Tierra
Parámetros:
t1 (float): Latitud del primer punto en la Tierra
g1 (float): Longitud del primero punto en la Tierra
t2 (float): Latitud del segundo punto ... | 16f2448ecb4dc5dce9afa4ccac0ac8a99091e2b9 | 60,887 |
from typing import Any
import functools
def qualname(obj: Any) -> str:
"""Get the fully qualified name of an object.
Based on twisted.python.reflect.fullyQualifiedName.
Should work with:
- functools.partial objects
- functions
- classes
- methods
- modules
"""... | 1c2d4fee79f102904d6383c6b4e67d7476a89e1d | 60,890 |
def unquote(string, encoding='utf-8', errors='replace'):
"""Replace %xx escapes by their single-character equivalent. The optional
encoding and errors parameters specify how to decode percent-encoded
sequences into Unicode characters, as accepted by the bytes.decode()
method.
By default, percent-enc... | a6b71447fb6e41a2fd8fc37020d7caac1d4a7bc6 | 60,892 |
from typing import Tuple
def count_in_freq(freq_tuple: Tuple[str, str]) -> int:
"""Return the count from the statistic half of the tuple returned from most_common or least_common
Parameters
----------
freq_tuple : Tuple[str, str]
tuple containing stats given as (count/total, percent) from mos... | 127677e3bae94f7b60a8d4d340fdacdec6bbde8a | 60,893 |
def create_list(text):
"""Create and return a list of the words present in story."""
text_list = text.split()
return text_list | c501ce4b60cbca9c49b9cf5fd0f2a0e700b873e8 | 60,895 |
def infer_ensembl_vdj_chain(gene_name):
""" Infer e.g., TRA or IGH from the ensembl gene name """
return gene_name[0:3] | 2f0f759bd072d1c1fb9748a439b23715d106f456 | 60,898 |
def ensure_list(specifier):
"""
if specifier isn't a list or tuple, makes specifier into a list containing just specifier
"""
if not isinstance(specifier, list) and not isinstance(specifier, tuple):
return [specifier,]
return specifier | 152c21d31839566c10479a8322dd9cc6ea3487ca | 60,900 |
def calcMemUsage(counters):
"""
Calculate system memory usage
:param counters: dict, output of readMemInfo()
:return: system memory usage
"""
used = counters['total'] - counters['free'] - \
counters['buffers'] - counters['cached']
total = counters['total']
# return used*100 / tot... | f38487df7118c113152c8796db183c3beabc197c | 60,902 |
def find_ngrams(single_words, n):
"""
Args:
single_words: list of words in the text, in the order they appear in the text
all words are made of lowercase characters
n: length of 'n-gram' window
Returns:
list of n-grams from input text list, or an empty list if ... | ed0fd4d89f95424b0fbf4180d8a2aa0aedfefb2c | 60,903 |
def _length(stream):
"""Returns the size of the given file stream."""
original_offset = stream.tell()
stream.seek(0, 2) # go to the end of the stream
size = stream.tell()
stream.seek(original_offset)
return size | 8520dee110a8fbab37f9c296c6d73bda1c167f2b | 60,915 |
import json
def read_json(fpath):
""" read json file
"""
return json.load(open(fpath)) | 6b78c352d4139bb7924214b61f6e69096a7a9b33 | 60,918 |
def ldrag(self, nk1="", nk2="", nk3="", nk4="", nk5="", nk6="", nl1="",
nl2="", nl3="", nl4="", nl5="", nl6="", **kwargs):
"""Generates lines by sweeping a keypoint pattern along path.
APDL Command: LDRAG
Parameters
----------
nk1, nk2, nk3, . . . , nk6
List of keypoints in the ... | 5efc57953a6d90902fbf0275e789508849f6858e | 60,921 |
def filter_metric_by_category(metrics, category):
"""Returns the metric list filtered by metrics that have the specified category.
@param metrics: The list of the metrics.
@param category: The category name, or None if should match for all metrics that have None as category.
@type metrics: list of Metr... | 5ff456442240d8edb066de9add4e226f11703c7c | 60,926 |
def str_from_int(func):
"""Function to be used as a decorator for a member method which
returns some type convertible to `int` and accepts no arguments.
The return value will be converted first to an `int` then to a
`str` and is expanded with leading zeros on the left to be at least
2 digits.
""... | 8d22ed6f794fd1e17cab729be2819fbf6f572331 | 60,928 |
from contextlib import suppress
def suppress2d(D_dict, threshold):
"""
Two dimensional of suppress(D, threshold) that suppresses values with absolutes values less than threshold
in a dictionary of dictionaries such as is returned by forward2d(listlist)
:param D_dict: dictionary of dictionaries
:pa... | 38ae48be224c007f87800cc12a9fb7687ec08f37 | 60,929 |
def shift_time_events(events, ids, tshift, sfreq):
"""Shift an event
Parameters
----------
events : array, shape=(n_events, 3)
The events
ids : array int
The ids of events to shift.
tshift : float
Time-shift event. Use positive value tshift for forward shifting
t... | 7348e9daaffafdeff76639d0b609ad20e9e4258e | 60,937 |
def int_to_dtype(x, n, signed):
"""
Convert the Python integer x into an n bit signed or unsigned number.
"""
mask = (1 << n) - 1
x &= mask
if signed:
highest_bit = 1 << (n-1)
if x & highest_bit:
x = -((~x & mask) + 1)
return x | 4767828f6a26b50ced70d887532fb0900542095b | 60,944 |
def fatorial(num=1, show=0):
"""
-> Função fatorial
param num: Numero determinado para calcular seu fatorial
param show: Opção para mostrar ou não o calculo realizado
"""
resultado = 1
for c in range(num, 0, -1):
resultado *= c
if show:
print(f'{c}', end=' ')
... | 2633420c5b0cb1f506231dc6b33fd0bc37e648ec | 60,948 |
from pathlib import Path
from typing import List
def find_conf_files(input_dir: Path) -> List[Path]:
"""Obtains paths for the 'conf*.csv' files containing the Hamiltonians."""
conf_files = sorted([f for f in input_dir.iterdir() if f.name[:4] == "conf"])
if conf_files == []:
raise FileNotFoundError... | 1aded3be2fc2d093b374785284287f7ba0654814 | 60,952 |
def get_feature_directory_name(settings_dict):
"""Get the directory name from the supplied parameters and features."""
dir_string = "%s_%d_%d_%d_%d" % (
settings_dict["feature"],
settings_dict["fft_sample_rate"],
settings_dict["stft_window_length"],
settings_dict["stft_hop_length... | 5b0a72a4e1c38637119e54022e1b23a7a5482988 | 60,954 |
def previous_month(date):
"""
Return the previous month for a given date
"""
year = date[0]
month = date[1]
new_year = year
new_month = month - 1
if new_month == 0:
new_year -= 1
new_month = 12
return (new_year, new_month) | 3220ada2fcd967d977bc0b2eb087375a3722164b | 60,955 |
def nasnet_dual_path_scheme_ordinal(block,
x,
_,
training):
"""
NASNet specific scheme of dual path response for an ordinal block with dual inputs/outputs in a DualPathSequential
block.
Parameter... | 49bca5c63a990de4e5d86b676addf63fb773bd66 | 60,959 |
import requests
def load_template_from_url(url):
"""Load a Jinja2 template from a URL"""
# fetch the template from the URL as a string
response = requests.get(url)
if response.status_code != 200:
raise Exception(
"Could not fetch the configuration template from the URL {}".format(
... | 4f5de53f620ace86d1448c5edf6060fb3cfa2949 | 60,963 |
import re
import string
def clean_text(text: str) -> str:
"""
Transform all text to lowercase, remove white spaces and special symbols.
Args:
text (str): Text to process.
Returns:
str: Processed text.
"""
# Transform all text to lowercase
text = text.lower()
# Remove ... | fdd61e7a0edb56ca5714359b0fa38a915efdb696 | 60,965 |
import torch
def meshgrid(shape):
"""
Wrapper for PyTorch's meshgrid function
"""
H, W = shape
y, x = torch.meshgrid(torch.arange(H), torch.arange(W))
return x, y | bb92d510589197c801329496c608a9b4e07471ac | 60,966 |
import json
def lambda_handler(event, context):
"""Sample Lambda function placed into a Step Function State Machine.
Parameters
----------
event: dict, required
context: object, required
Lambda Context runtime methods and attributes
Context doc: https://docs.aws.amazon.com/lambda... | 01f182cbff8581f0d4716b8a2e2b39ba3f89c226 | 60,970 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.