content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def get_dependency(container, dependency_cls, **match_attrs):
""" Inspect ``container.dependencies`` and return the first item that is
an instance of ``dependency_cls``.
Optionally also require that the instance has an attribute with a
particular value as given in the ``match_attrs`` kwargs.
"""
... | e0b98143e096b7d183a56b69938afc628481329f | 602,878 |
def parseRawData(response_data) :
"""
Given the raw response data, we extract only the required data factors from this.
Parameters
----------
response_data - the raw json data from the api
Return
------
candidate_centers - the list of filtered out centers
"""
# Initialize a li... | 36e78a69b2ab90828a8f1c4cea74ac0e8f3a739e | 502,495 |
def is_valid_deck(deck_of_cards):
""" (list of int) -> bool
A valid deck contains every integer from 1 up to the number of cards in
the deck.
Return True if and only if the deck_of_cards is a valid deck of cards.
>>> is_valid_deck([1, 4, 3, 2])
True
>>> is_valid_deck([])
Fal... | 3a1dd74be6fe349a80b3522760b518ac668eea6d | 270,162 |
def get_reference_key(entity, prop_name):
"""Returns a encoded key from a ``db.ReferenceProperty`` without fetching
the referenced entity. Example::
from google.appengine.ext import db
from tipfy.appengine.db import get_reference_key
# Set a book entity with an author reference.
... | 07371df1f7c72abec384c578bdb6baa844967c22 | 249,377 |
from typing import List
from typing import Type
def get_class_from_name(class_name: str, classes: List, err_msg: str) -> Type:
"""
Return class from class name.
:param class_name: String with class name.
:param classes: List of classes to match the given class_name.
:param err_msg: Helper string ... | f7a670b021fa96e9720457982367fe8ae054ba8e | 487,036 |
def get_pred_class(lls):
"""
Get MAP - class with max likelihood assigned
Gets max key of dict passed in
:param lls: Map from class name to log likelihood
"""
return max(lls, key=lls.get) | 0c9af2e55b1d4837aaa322a25d1bb719987793a6 | 344,702 |
from typing import List
def full(board: List[List[int]]) -> bool:
"""
Checks if board is full (there is a tie)
:param board: tic tac toe board
"""
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
return False
return True | ee4bcd7bf7bc726aa83447baa8261f68a44fa3f6 | 497,514 |
def show_instruction(ticker):
"""
Displays initial instruction based on ticker insertion
:param ticker: the inserted ticker
:return: dict setting visibility of instruction
"""
if not ticker:
return {
'margin-top':'25%',
'textAlign':'center',
'color':'... | 6cb9fd8b382e93c56077d76d3f77bcfecc5bf94d | 261,270 |
def static_div(divisor):
"""
>>> class A:
... m = static_div(10)
...
>>> a = A()
>>> a.m(12345)
1234
"""
def func(divident):
return divident // divisor
return staticmethod(func) | af73500608ef82aa1ff05e338fcf7338de201cc7 | 596,170 |
def clean_brackets(
string,
brackets=(("(", ")"),),
):
"""Removes matching brackets from the outside of a string
Only supports single-character brackets
"""
while len(string) > 1 and (string[0], string[-1]) in brackets:
string = string[1:-1]
return string | d6cb7575ec0a8f4cad4c3fa859d998bc6d483d99 | 660,445 |
import re
def remove_extra_whitespace(text):
"""
Method used to remove extra whitespaces from the text
Parameters:
-----------------
text (string): Text to clean
Returns:
-----------------
text (string): Text after removing extra whitespaces.
"""
pattern = re.compil... | ad942aa425e36344323d90e3665df3bf36b34e98 | 254,095 |
def uniq(lst):
"""
this is like list(set(lst)) except that it gets around
unhashability by stringifying everything. If str(a) ==
str(b) then this will get rid of one of them.
"""
seen = {}
result = []
for item in lst:
if str(item) not in seen:
result.append(item)
... | 706ec44f340fbfca36cb1a605391e9fc32d38ca0 | 587,579 |
def merit3(EValw, Sw):
"""
Merit function calculation. Computes the merit function by selecting the
first scalar, ``Sw`` minus a weight. The weight is given by the average of
the second until last scalar. The first scalar is constructed in
`pypcaf.find_period` and `pypcaf.pca` functions. First the ... | a56379e9aa13fbdbf232b3a3ea4078bb83489001 | 606,052 |
import numbers
def isdigit(s):
"""
check if the number is a digit, including if it has a decimal place in it
Or is numeric
:param s:
:return:
"""
if isinstance(s, numbers.Number):
return True
else:
return s.replace('.','',1).replace('-', '').isdigit() | adbc844ad6d0b4b3c8fa603c21d871077026995b | 421,024 |
import json
def load_profiling_details(json_path: str) -> dict:
"""Load profiling details from json."""
with open(json_path, "r") as json_file:
data = json.load(json_file)
return data | acc19c2a2387458c203a92a7bf4f1a9bf1e76fa0 | 142,813 |
def summarize(logger):
"""
Creates a short summary on the actions that were logged by the given
Logger.
:type logger: Logger
:param logger: The logger that recorded what happened in the queue.
:rtype: string
:return: A string summarizing the status of every performed task.
"""
sum... | be2fdee12085de7913c5a3ba63d2fdad2e5caf70 | 521,796 |
def get_answer(current_row):
"""Returns the answer text value og HTML element"""
return current_row.find_all("td", class_="risp")[0].text.strip() | 14e91c250d6f28b98534fe7839e47b3650750152 | 20,106 |
from typing import Dict
from typing import Any
def unflatten_dict(
flat_dict: Dict[str, Any],
separator: str = ' '
) -> Dict[str, Any]:
"""
The inverse operator to flatten_dict.
Takes a flattened dictionary and returns a nested one.
:param flat_dict: The dictionary to be nested.
... | 0f4f41f82fddc0681eaab74f378b10901f4407ab | 252,934 |
def _find_branch(pt, targets, branches):
"""Determines which branch a pathway belongs to and returns that branch.
A ShortestPath belongs to a branch if the first surface exposed residue it reaches during the
pathway is the target of that particular branch.
Parameters
----------
pt: ShortestPat... | 6a79186fecd22c2253b67c82d83e06a0aaa6a0d2 | 596,581 |
def beautify_url(url):
"""
Remove the URL protocol and if it is only a hostname also the final '/'
"""
try:
ix = url.index('://')
except ValueError:
pass
else:
url = url[ix+3:]
if url.endswith('/') and url.index('/') == len(url)-1:
url = url[:-1]
return ur... | 5c0ba43534758eb5d90ade1531881006ef58e8a8 | 645,915 |
def calc_NPSH(P_suction, P_vapor, rho_liq):
"""Return NPSH in ft given suction and vapor pressure in Pa and density in kg/m^3."""
# Note: NPSH = (P_suction - P_vapor)/(rho_liq*gravity)
# Taking into account units, NPSH will be equal to return value
return 0.334438*(P_suction - P_vapor)/rho_liq | da7f09873023de717743fe635f4e0042009b0fa8 | 510,626 |
def split_and_clean_text(source_text: str, split: str) -> list[str]:
"""Split the text into sections and strip each individually."""
source_text = source_text.strip()
if split:
sections = source_text.split(split)
else:
sections = [source_text]
sections = [section.strip() for section ... | ec25893c4af04b0a7462127218882c0b712ac941 | 455,338 |
import json
def load_json_file(filename):
"""Read a JSON file and return the data as a dict.
Return None on failure.
"""
try:
with open(filename, "r") as file:
data = json.load(file)
return data
except Exception as e:
print(e)
return None | 5de64a66967ace3a932d7c308d6d5ea00347b082 | 427,566 |
def getPervValues(dataframe, period, on):
"""
Gets previous values of sma and requested column.
Args:
dataframe: pandas dataframe.
period: the value on this many indecies in the past.
on: requested column (e.g: Adj close, close, etc)
Returns:
dataframe containing the s... | 2fa5a05e102373031e332327144c4c2e50866a87 | 519,595 |
def num_bytes(byte_tmpl):
"""Given a list of raw bytes and template strings, calculate the total number
of bytes that the final output will have.
Assumes all template strings are replaced by 8 bytes.
>>> num_bytes([0x127, "prog_bytes"])
9
"""
total = 0
for b in byte_tmpl:
if i... | 390e74b214bb29925d5273c1685c03d9cbca9714 | 631,788 |
def runOutOfMemory(sc):
"""
Run out of memory on the workers.
In standalone modes results in a memory error, but in YARN may trigger YARN container
overhead errors.
>>> runOutOfMemory(sc)
Traceback (most recent call last):
...
Py4JJavaError:...
"""
# tag::worker_oom[]
dat... | dda5239af26a4c9c32e308262dae612b65aa4de5 | 240,764 |
import csv
def GetLinesFromDrivingLogs(dataPath, skipHeader=False):
"""
Returns the lines from a driving log with base directory `dataPath`.
If the file include headers, pass `skipHeader=True`.
"""
lines = []
with open(dataPath + '/driving_log.csv') as csvFile:
reader = csv.reader(csvF... | 5423e52f5e658bb3f3d590780484ada286fbd77b | 588,898 |
def display_duration(value):
"""
Maps a session requested duration from select index to
label."""
map = {'0':'None',
'1800':'30 Minutes',
'3000':'50 Minutes',
'3600':'1 Hour',
'5400':'1.5 Hours',
'6000':'100 Minutes',
'7200':'2 Hours',
... | 686576178b0cd695ad0c2de1cdd12890277e06da | 600,799 |
def my_map(fun1, obj, iterlist):
"""
Map() function with a non-iterable and iterable set of parameters.
Args:
fun1: Function to use with 2 arguments (obj, element)
obj: Non iterable or constant object.
iterlist: List of elements to iterate.
Returns: Return list from map(func1, o... | fe22645aa9c1151049bf6b24f75f242cbd70291b | 195,225 |
def indexesof(l, fn, opposite=0):
"""indexesof(l, fn) -> list of indexes
Return a list of indexes i where fn(l[i]) is true.
"""
indexes = []
for i in range(len(l)):
f = fn(l[i])
if (not opposite and f) or (opposite and not f):
indexes.append(i)
return indexes | c7f961701b347e0a29a16fcade3377e16f94b61f | 318,351 |
def df_diff(df1, df2, which='both'):
"""
Find rows which are different between two dataframes.
"""
_df = df1.merge(df2, indicator=True, how='outer')
diff_df = _df[_df['_merge'] != which]
return diff_df.reset_index(drop=True) | 8905aed63aca458c7beb176bbabda63ab05f4cbd | 215,071 |
def models_dict_to_list(models):
"""
Given a models dict containing subapp names as keys and models as a list of values
return an aggregated list of all models
"""
all_models = []
if isinstance(models, dict):
for _, app_models in list(models.items()):
all_m... | 1753ae5b921de87b57e5dd9571a39c4dbdecc16c | 374,555 |
def Query(cursor, sql, params=None):
"""Query against the Cursor. Params will be formatted into the sql query string if present.
Returns: list of dicts
"""
# No parameters
if not params:
cursor.execute(sql)
# Else, parameters need to be passed in too
else:
cursor.execute(sql, params)
# Get... | 9f9bbd6a526d867a960eb5a45c442a3e62f08854 | 252,092 |
def minmax(x):
"""
Returns a tuple containing the min and max value of the iterable `x`.
.. note:: this also works if `x` is a generator.
>>> minmax([1, -2, 3, 4, 1, 0, -2, 5, 1, 0])
(-2, 5)
"""
(minItem, maxItem) = (None, None)
for item in x:
if (minItem is None) or (item < m... | f2127bf8cb6d444d97f23b147590d94265b5480c | 634,826 |
def list_workers(input_data, workerlimit):
"""
Count number of threads, either length of iterable or provided limit.
:param input_data: Input data, some iterable.
:type input_data: list
:param workerlimit: Maximum number of workers.
:type workerlimit: int
"""
runners = len(input_data) ... | 9ea30a3a3fc3ebd67ffee7117d502caa9110de08 | 29,713 |
import math
def morse_energy(dist, params):
"""The Morse interaction energy
:param dist: The distance between the two interacting atoms.
:param params: The Morse parameters.
:returns: The interaction energy.
"""
de, a, r0 = params
return de * ((
math.exp(a * (r0 - dist)) - 1
... | 6f29c090eab8d5fb07b4470457007f38943403a7 | 575,598 |
def untuple_dict(the_dict):
""" convert dict with keys that are tuples
to a dict with keys that are strings
:param the_dict: ({tuple: obj})
:return: ({str: obj})
"""
def to_key(obj):
return (
f'({",".join(str(o) for o in obj)})'
if isinstance(obj, tuple)
... | 5d7f91eab99bd604a93ffe3b0176812728e56116 | 485,112 |
def get_normalized_language(language_code):
"""
Returns the actual language extracted from the given language code
(ie. locale stripped off). For example, 'en-us' becomes 'en'.
"""
return language_code.split('-')[0] | e5de7b22eb3bce36099d5cd195efe8b85b42fc11 | 315,976 |
def get_critical_process_from_monit(duthost, container_name):
"""Gets command lines of critical processes by parsing the Monit configration file
of each container.
Args:
duthost: Hostname of DuT.
container_name: Name of container.
Returns:
A list contains command lines of criti... | c26b4b788252b4e6273fb77fd14c22619fe2d125 | 578,322 |
import torch
def asymmetric_linear_quantization_params(num_bits,
saturation_min,
saturation_max,
integral_zero_point=True):
"""
Compute the scaling factor and zeropoint with the given ... | 4faf7496323a3e174309c01fde01d5ae90db1248 | 230,158 |
import re
def fix_enye(text):
"""Reconstructs 'ñ' character if it's broken.
Args:
text (string): markdown text that is going to be processed.
Returns:
string: text once it is processed.
"""
enye_regex = re.compile(r'˜ *n', re.UNICODE)
processed_text = enye_regex.sub(r'ñ', text)
return processed_text | ff4e7dbb1093d17921169410d7d49f4d02ee74a7 | 441,930 |
import itertools
def disjoint_subsets(list_a: list, groups):
"""Problem 27: Group elements of set into disjoint subsets.
Parameters
----------
list_a : list
The input list
groups
Returns
-------
Raises
------
TypeError
If the given argument is not of `list` t... | a894009dccd198113db13212af1d6d03ecbe3e44 | 428,707 |
from datetime import datetime
def get_timestamp(timestamp_format="%Y%m%d_%H%M%S"):
"""Return timestamp with the given format."""
return datetime.now().strftime(timestamp_format) | b5a53d49df7c52598e9a171936e351869ef5cf6b | 101,066 |
def find(predicate, collection):
"""
Attempts to find a match for the given predicate function in a given collection.
We return the first match only, or None if no match exists.
"""
for item in collection:
if predicate(item):
return item
return None | b09fb15fc11990a3ea7e82762bf6a53640b57787 | 153,289 |
from datetime import datetime
def unixtime_to_datestring(unix_time):
"""Convert unix timestamp into a string."""
return datetime.fromtimestamp(unix_time).strftime("%Y-%m-%d %H:%M:%S") | 2c26927af8c066eb4e0e9b3ae05fcffa35d8fa3f | 260,921 |
def jaccard(A,B):
"""[Jaccard similarity between 2 sets]
Args:
A ([set]): [description]
B ([set]): [description]
Returns:
[int]: [Jaccard Similarity]
"""
union = A.union(B)
inter = A.intersection(B)
return len(inter)/len(union) | f4ae370b150bd230e002475eac199f1b1f2f1f80 | 428,016 |
def last_name_first(n):
"""
Returns: copy of n but in the form 'last-name, first-name'
We assume that n is just two names (first and last). Middle names are
not supported.
Examples:
last_name_first('Walker White') returns 'White, Walker'
last_name_first('Walker White') return... | 27207471131aa6c0271f97a50355cfee52dfc62e | 192,565 |
def is_power_of_two(x):
""" Checks whether the input is the power of 2. """
return x & (x-1) == 0 | 64e199b8b7a53ec7cd458ffddc7f7a9d8f4992cb | 482,019 |
def balanced_sums(arr):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/sherlock-and-array/problem
Watson gives Sherlock an array of integers. His challenge is to find an element of the array such that the sum of
all elements to the left is equal to the sum of all elements to the right. For in... | 8d10a30c64b434b98b709718a729d32590b00ae8 | 371,753 |
def mayan_tzolkin_date(number, name):
"""Return a Tzolkin Mayan date data structure."""
return [number, name] | 8cfd4120ea76de36e824311f1afab752beed84a3 | 649,435 |
def add_month_year_columns(data, datetime_field):
"""Adds month and year columns to a DataFrame using a timestamp column.
:param data: The DataFrame
:type data: DataFrame
:param datetime_field: The datetime fields name
:type datetime_field: str
:returns: Altered DataFrame"""
data['year'] = ... | cdf157ae3634372803900e9e131db1d70e76d0c7 | 406,634 |
import csv
def readCSV(filename):
"""
Reads the .data file and creates a list of the rows
Input
filename - string - filename of the input data file
Output
data - list containing all rows of the csv as elements
"""
data = []
with open(filename, 'rt', encoding='utf8') ... | 65eb44a9900babeae09af340880a96f35eb9e25c | 681,389 |
import requests
def post_input_form(input_text):
"""Posts a string as a form field (application/x-www-form-urlencoded)
named 'input' to the REST API and returns the response.
"""
url = 'http://localhost:5000/parse'
return requests.post(url, data={'input': input_text}) | d2e7c9aa97ca7ef0d5f7100a74e83f2cdc6d882b | 650,842 |
import six
def let(__context__, *args, **kwargs):
""":yaql:let
Returns context object where args are stored with 1-based indexes
and kwargs values are stored with appropriate keys.
:signature: let([args], {kwargs})
:arg [args]: values to be stored under appropriate numbers $1, $2, ...
:argTy... | c1c1e55b6b514ea88594f8126c7ced7aa8b1d2e5 | 692,469 |
def gferror(reply):
"""Determines if a GF reply is an error"""
return (reply.startswith('The parser failed')
or reply.startswith('The sentence is not complete')
or reply.startswith('Warning:')
or reply.startswith('Function') and reply.endswith('is not in scope')) | c286b2c5ce399774ef0638c204f5d303bd181269 | 602,588 |
def check_solution(task, solution_string, ops_namespace=None):
"""Checks whether solution_string passes all examples in the task."""
for example_index in range(task.num_examples):
namespace = ops_namespace.copy() if ops_namespace else {}
for input_name, input_values in task.inputs_dict.items():
namesp... | 76a75e449fe39e37edb45ace1a6a29d20e695d3a | 159,297 |
from pathlib import Path
def home_directory() -> str:
"""
Return home directory path
Returns:
str: home path
"""
return str(Path.home()) | 8c9c1ccccfc547a26794e5494975e27cde4e73ef | 65,110 |
def convert_to_csv(records):
"""Convert records in list type to csv string.
Args:
records: A list of power data records each of which contains timestamp, power value,
and channel. e.g. [[12345678, 80, "SYSTEM"],[23456789, 60, "SENSOR"]].
Returns:
A string that contains all CSV reco... | 8a788f6a1325735e7747ffe3a03b44e21286aa66 | 344,563 |
def schmdt_nmbr(diffusivity, kinematic_viscosity = 10**-6):
"""
Return the Schmidt number []
Parameters
----------
kinematic_viscosity : kinematic viscosity of water (defautl 10^-6)[m²/s]
diffusivity : mass diffusivity of the chemical in water [m²/s]
"""
return kinematic_viscosity / d... | 4242e5e2775770ab13a82ce2b81902077660ff24 | 522,179 |
import struct
def get_uint32(s: bytes) -> int:
"""
Get unsigned int32 value from bytes
:param s: bytes array contains unsigned int32 value
:return: unsigned int32 value from bytes array
"""
return struct.unpack('I', s)[0] | 69f499ad9001f3313681b48a951cac4fd3c0b406 | 436,310 |
import keyword
def validate_module_name(value, convert_lowercase=False, allow_keywords=False):
"""
Validate a string to be used as python package or module name
"""
if not isinstance(value, str):
raise NameError(f'Module must be string: {value}')
if not value.isidentifier():
raise... | 0049f9b15a677cf9c508b95c8c7e8d30864f4183 | 358,687 |
def _deindent(line, indent):
"""Deindent 'line' by 'indent' spaces."""
line = line.expandtabs()
if len(line) <= indent:
return line
return line[indent:] | 6fba2ed9a8387901bd8d100d0cb98d808db44310 | 121,888 |
def csv_to_list(s):
"""Split commas separated string into a list (remove whitespace too)"""
return [x for x in s.replace(" ", "").split(",")] | fe47ecabaee49fad30d4d693e7109744e13adeeb | 398,395 |
def quartile(arr, val):
""" Return the quartile (0-3) of val in arr. """
sorted_array = sorted(arr)
interval_length = len(sorted_array) / 4.0
return int(sorted_array.index(val) / interval_length) | ae1ddeddcd03c4525764ab4d4ce2d6b10c52b3d0 | 238,480 |
def write_uleb128(num: int) -> bytearray:
""" Write `num` into an unsigned LEB128. """
if num == 0:
return bytearray(b'\x00')
ret = bytearray()
length = 0
while num > 0:
ret.append(num & 0b01111111)
num >>= 7
if num != 0:
ret[length] |= 0b10000000
... | fb13878a0c5e984cb1447dfad4536c6f9dcb9ed3 | 605,401 |
from functools import reduce
from typing import cast
def cast_schema(df, schema):
"""Enforce the schema on the data frame.
Args:
df (DataFrame): The dataframe.
schema (list): The simple schema to be applied.
Returns:
A data frame converted to the schema.
"""
spark_schema ... | 1a8412a2a3a363589c18f09e672145e94a020aab | 674,708 |
def remove_dash(item):
"""
Remove the first character in a string.
:param item: String
:return: input string, with first character removed
"""
return item[1:] | 2fbabb1b2359f6e89b69fd1d65a411e4b1012e6d | 634,273 |
from pathlib import Path
from typing import Tuple
def _is_file_with_supported_extensions(path: Path, extensions: Tuple[str, ...]) -> bool:
"""
Check if the file is supported for the media type
:param path: File path to check
:param extensions: Supported extensions for the media type
:example:
... | 0bab2e1eead6dca863d062bd9d187e6a5f54c788 | 615,808 |
def get_ip(driver, ip_site="https://api.ipify.org"):
"""
gets ip from specified page
:param driver: selenium webdriver object
:param ip_site: ip site, which only returns ip as string
:return: str of current ip address
"""
driver.get(ip_site)
return driver.find_element_by_tag_name("body")... | 9cd943aa3288d50beb90755d85ed5708a14bec5f | 161,124 |
def scale_series(series):
"""
Scales a series. Scaling involves dividing the series standard
deviation from each entry in series, resulting in a new
standard deviation of 1
Parameters
------------
series : pd.Series
Returns
----------
tuple
A tuple containing... | 689d9600227f324dc6161802573223e9f8c7649a | 322,498 |
def parse_grammar(file_path):
"""
Generate a grammar from a file describing the production rules.
Note that the symbols are inferred from the production rules.
For more information on the format of the file, please reffer to
the README.md or the the sample grammars provided in this repository.
:param file_path:... | 1dda39f139b5e032ba6610dbeb0b861de98bb928 | 173,714 |
def all_unique(x):
"""Return True if the collection has no duplications."""
return len(set(x)) == len(x) | db0ec5eaff3a9144646a470a5df335b1cf27f421 | 209,808 |
from pathlib import Path
def get_file_content(file_path: Path) -> str:
"""
Get the content of the file.
:param file_path: Path to the file you want to read.
:return: File content.
"""
with open(file_path, encoding='utf-8', errors='ignore') as file:
return file.read() | 000989f82454e6a84478f7d51677e16a3ff45a6f | 338,694 |
from typing import Dict
from typing import Any
def has_key(dictionary: Dict[str, Any], key: str) -> bool:
"""
Check whether dictionary has given key is present or not
:param dictionary: Dictionary that need to check if key present or not
:param key: Key value that need to check
:return: Boolean v... | e1bb6eae8b9758b777003a9fd937d21dcd7166a7 | 622,463 |
def neutral_mass_from_mz_charge(mz: float, charge: int) -> float:
"""
Calculate the neutral mass of an ion given its m/z and charge.
Parameters
----------
mz : float
The ion's m/z.
charge : int
The ion's charge.
Returns
-------
float
The ion's neutral mass.
... | 1212fffcf7b924768cc9c50079197ed294d937b3 | 63,430 |
from typing import Type
def _type_to_key(t: Type) -> str:
"""
Common function for transforming a class type to its associated string key
for use in configuration semantics.
:param t: Type to get the key for.
:return: String key for the input type.
"""
return f"{t.__module__}.{t.__name__}" | c88bd2ebb6b537682328d3bcc9350daa2fe54e6c | 583,652 |
def runge_kutta_ode_solver(ode, time_step, y, params):
"""4th order Runge-Kutta ODE solver.
Carnahan, B., Luther, H. A., and Wilkes, J. O. (1969).
Applied Numerical Methods. Wiley, New York.
Parameters
----------
ode : function
Ordinary differential equation function. In the Lorenz mod... | 2db376cc7a97bd808c0ea7e4b439213b8132ac09 | 595,386 |
def is_same_module_or_submodule(orig, incoming):
"""
Returns true if the incoming module is the same module as the original,
or is a submodule of the original module
"""
if incoming is None:
return False
if orig == incoming:
return True
if incoming.__name__.startswith(orig._... | a3ecf3f1d9d1546a9f8a30f9ef6609ae9e94cc6e | 627,884 |
def resample_history_df(df, freq, field):
"""
Resample the OHCLV DataFrame using the specified frequency.
Parameters
----------
df: DataFrame
freq: str
field: str
Returns
-------
DataFrame
"""
if field == 'open':
agg = 'first'
elif field == 'high':
... | 36a089470fbe56971da4763129e0c337cb149e2a | 350,821 |
import glob
def _GetCasedFilename(filename):
"""Returns the full case-sensitive filename for the given |filename|. If the
path does not exist, returns the original |filename| as is.
"""
pattern = '%s[%s]' % (filename[:-1], filename[-1])
filenames = glob.glob(pattern)
if not filenames:
return filename
... | df033b24b76ed90aa49bc4d88b4e289774bacf7a | 139,183 |
from typing import Tuple
def get_pos(target: Tuple[float, ...], area: Tuple[int, ...]) -> Tuple[int, ...]:
"""Get absolute position, given relative position and target area
Parameters
----------
target : Tuple[float, float]
Relative position
area : Tuple[int, int]
Absolute area
... | 44c469a807ca9e256f87a32bb2c03e4e0a1b9cf3 | 63,756 |
def get_pr_required_statuses(pr):
"""Gets a list off all of the required statuses for a PR to be merged."""
statuses = pr.session.get(
'https://api.github.com/repos/{}/{}/branches/{}/protection/'
'required_status_checks/contexts'.format(
pr.repository[0], pr.repository[1], pr.base.re... | c8870d5c1eb204c836ada30664232b02ca08b445 | 225,637 |
def uuid_encode(uuid):
""" Turns a UUID instance into a uuid string. """
if not uuid:
return ''
if isinstance(uuid, str):
return uuid
return uuid.hex | 8ec81fe6d4a0484dc02f4ef4f27379bcf8435897 | 361,194 |
def entitydata_delete_confirm_form_data(entity_id=None, search=None):
"""
Form data from entity deletion confirmation
"""
form_data = (
{ 'entity_id': entity_id,
'entity_delete': 'Delete'
})
if search:
form_data['search'] = search
return form_data | df473118ea31df991d65395f2e55dfdc350a24ed | 76,267 |
import hashlib
def calcChecksum(filepath):
""" Calculate MD5 of relevant information
Returns tuple of filename and calculated hash
"""
with open(filepath, "r") as fil:
cnt = fil.readlines()
relinfo = []
for line in cnt:
atm = line[12:16].rstrip().lstrip()
... | 36a84ca868dd12f1ae42a037f057f507d395455a | 103,790 |
import csv
def get_tsv_header(input):
"""Get a header of a tsv file.
Column counts of the first (header) and second (content) line are compared. If the header has
one column less than the content, then a new column is added to the beginning of the returned list
(convention in Chipster to handle ... | dc66e14da5158e691d02a8085ff1ae6ef8a9d3eb | 86,300 |
import gzip
def naive_count_lines(infile):
""" Count lines in a gzip JSON LD file """
n = 0
with gzip.open(infile, 'r') as source:
for _, n in enumerate(source, 1):
pass
return n | b1d67b214c9e1e9840a7840454c90f8edbc10a41 | 213,374 |
def dump_dict(dump):
"""Returns dict of common profiles (radial quantities)
"""
return {'y': dump.y,
'tn': dump.tn,
'xkn': dump.xkn,
'abar': dump.abar,
'zbar': dump.zbar,
} | 38877c9daa27115ac67ec9f5176f9bcccd5b8ebd | 637,356 |
def basic_listifier(item):
"""Takes strings, tuples, and lists of letters and/or numbers separated by spaces, with and without commas, and returns them in a neat and tidy list (without commas attached at the end."""
if type(item) == tuple or type(item) == list:
final = [x.replace(',','') for x in item]
... | bc78df79e896e773d3465258e9d4fa89fe8e4f15 | 360,631 |
def _cast_types(args):
"""
This method performs casting to all types of inputs passed via cmd.
:param args: argparse.ArgumentParser object.
:return: argparse.ArgumentParser object.
"""
args.x_val = None if args.x_val == 'None' else int(args.x_val)
args.test_size = float(args.test_size)
args.dual = (args.dual in... | 40285a3b93606b6503f5ad1486fb61cc61d32a8e | 99,081 |
from typing import Any
import math
def make_divisible(x: Any, divisor: int):
"""Returns x evenly divisible by divisor."""
return math.ceil(x / divisor) * divisor | bfbcfb334777a6c7214f16aa0fadd56906e2b7bc | 5,731 |
import re
def pattern_match(item : str, pattern : str, strict : bool = True) -> bool:
"""
Check if item matches with the pattern that contains
"*" wildcards and "?" question marks.
Args:
item:
The string that pattern will be applied to.
pattern:
A wildcard (gl... | fb92c1782f684e6a6fbad4890a299e5670a9487e | 692,947 |
def prepare_velo_points(pts3d_raw):
"""
Replaces the reflectance value by 1, and tranposes the array, so
points can be directly multiplied by the camera projection matrix
"""
pts3d = pts3d_raw
# Reflectance > 0
pts3d = pts3d[pts3d[:, 3] > 0 ,:]
pts3d[:,3] = 1
return pts3d.transpose() | a9a5efd5e305f1a9b160f82fe3f005f3fb2b67ac | 328,902 |
import math
def compute_idfs(documents):
"""
Given a dictionary of `documents` that maps names of documents to a list
of words, return a dictionary that maps words to their IDF values.
Any word that appears in at least one of the documents should be in the
resulting dictionary.
"""
idf = ... | 3ce13136b1b8d573976e3d9dca09929b50c5db0e | 362,582 |
import re
def clean_utterance_text(text: str) -> str:
"""Removes line breaking and extra spaces in the user utterance."""
# sometimes the user utterance contains line breaking and extra spaces
text = re.sub(r"\s+", " ", text)
# sometimes the user utterance has leading/ending spaces
text = text.str... | 8ca6f5c8b6109b5a17327ce109452a4d3bf092c7 | 313,562 |
import logging
def build_logger(name, **kwargs):
"""
Builds a logging instance with the specified name
Arguments
---------
name: name of the logger
Keyword arguments
-----------------
format: event description message format
level: lowest-severity log message logger will handle
... | 577fb63ce5a40171b2b44d03e60931afe1ab5a51 | 389,147 |
def _isCpuOnly(log):
"""check for CPU-Only mode"""
for l in log:
if "cpu" in l.lower():
return True
return False | 0840b5ae6bf5840740be4ad24e3b430013c1b09f | 223,393 |
import re
def rule_to_regex(rule: str, prefix: str = "", suffix: str = "") -> "re.Pattern":
"""Convert a rule from the mast to regular expressions.
Args:
rule (str): The line from the mast
prefix (str, optional): Regex to be prepended
suffix (str, optional): Regex to be appended
... | 64f24abd3c831d939a6a1d17375ef1c430acac2f | 177,285 |
def readFile(filepath):
"""Gets string representing the path of the file to be processed
and returns it as a list. It will omit blank lines.
Parameters
----------
filepath : str
The path of the filename to be processed
Returns
-------
lines
a list that contains the ... | d1dc54b48f7012cbf0f253154af96d673cd00259 | 44,755 |
def band_info(band_names, band_uris=None):
"""
:param list band_names: names of the bands
:param dict band_uris: mapping from names to dicts with 'path' and 'layer' specs
"""
if band_uris is None:
band_uris = {name: {'path': '', 'layer': name} for name in band_names}
return {
'i... | 34b84713a9f77cfd4570c63440719d48ca235145 | 482,060 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.