content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import requests
import json
def fetch_entanglement_graph(host="proxy", port=8000, path="/dict"):
"""
Fetches the entanglement graph from a running instance of playcloud.
Args:
host(str, optional): Host of the playcloud instance
port(int, optional): Port number of the listening playcloud in... | 6e5c522405d01809989ce354acce3816d65ca879 | 335,274 |
def format_BUILD_MAP_UNPACK_WITH_CALL(oparg):
"""The lowest byte of oparg is the count of mappings, the relative
position of the corresponding callable f is encoded in the second byte
of oparg."""
rel_func_pos, count = divmod(oparg, 256)
return ("%d mappings, function at %d" % (count, count + rel_fu... | b7176dcdd412aa64cf73e055cc9f0f3efce3f6bf | 576,628 |
def aggregate_norm_comparison(factor_df, M_matrix):
"""
Aggregate factor information with cosine similarity matrix, which contains the
true norm.
"""
return factor_df.groupby(['kernel', 'factor', 'iter']).agg('sum').merge(
M_matrix.set_index(['kernel', 'factor', 'iter']),
left_index=... | 060dcd08e2147be49d40d04af802daf3286cfe02 | 99,018 |
def find_threshold_crossings(arr, _threshold):
"""
Find all indices at which a threshold is crossed from above and from below
in an array. Used for finding indices to compute ap widths and half widths.
"""
#print("threshold = {}".format(_threshold))
ups = []
downs = []
for i, _ in enumer... | 907a6ab3f1c8e058f968064765168e399e497b4a | 259,307 |
def process_cutoff_line(list_):
"""Process a cutoff line."""
cutoffs = []
for i in [1, 2]:
if list_[i] == 'None':
cutoffs += [None]
else:
cutoffs += [float(list_[i])]
return cutoffs | 4e7c22a5304901b35edddd2e27ccb11714186f02 | 332,549 |
def seven_seg(a: bool, b: bool, c: bool, d: bool, e: bool, f: bool, g: bool) -> str:
"""Given a set of 7 boolean values corresponding to each segment, returns
a string representation of a 7 segment display.
The display looks like this:
_
|_|
|_|
And the mapping of the booleans... | 49ca9e4c3a98a7ac64744a968e90efa58a3f44a0 | 381,614 |
def truncate(s, eps):
"""
Find the smallest k such that sum(s[:k]**2) \geq 1-eps.
"""
mysum = 0.0
k=-1
while (mysum < 1-eps):
k += 1
mysum += s[k]**2
return k+1 | fc9b5984316e969961b496fd54425e4f52f025ff | 704,032 |
def from_bytes(array: bytes) -> str:
"""Decodes the string from UTF-8."""
return array.decode("utf-8") | 4782da935e9d849105c4116dabbb21abd67e047f | 381,883 |
def bounds_check(values, lower, upper):
"""Perform a simple bounds check on an array.
:param values: an array of values.
:param lower: the lower bound of the valid range.
:param upper: the upper bound of the valid range.
:type values: array[float]
:type lower: float
:type upper: float
... | c99882cdbf33116e29ee80b9bd065893e236e076 | 424,085 |
def government_furloughing(t, states, param, t_start_compensation, t_end_compensation, b_s):
"""
A function to simulate reimbursement of a fraction b of the income loss by policymakers (f.i. as social benefits, or "tijdelijke werkloosheid")
Parameters
----------
t : pd.timestamp
current dat... | 2ed0cc447df832290b59eb048b09bb8dd8373438 | 332,309 |
def handle_store(event):
"""Handle a C-STORE request event."""
# Decode the C-STORE request's *Data Set* parameter to a pydicom Dataset
ds = event.dataset
# Add the File Meta Information
ds.file_meta = event.file_meta
# Save the dataset using the SOP Instance UID as the filename
ds.save_as... | 4bd11106e1bb7b2c17931a710daa7133d5e8e9e3 | 547,631 |
def check_parens(string, pairs="()"):
"""
Check a string for non-matching braces or other character pairs and return
a list of failures, or an empty set if everything is OK.
`if check_parens(string, brackets):` is a good way to find bad brackets in
a string.
Pairs should be a string of paired ... | 35b05bd2560f1252f04257919f9f50cdcda9b53a | 416,656 |
def count_model_parameters(model):
"""Count trainable parameters of a given model
Args:
model(object): torch model object
Returns:
trainable_parameters(int): number of trainable parameters
"""
return sum(p.numel() for p in model.parameters() if p.requires_grad) | 17b32f0e37f9f47fca4de17ee4cfc27cbaa12b02 | 71,667 |
def intfs_only(s1code):
"""Given s1code, keep only interfaces (.h); ignore implementations (.f90)."""
return [(l, f, c) for l, f, c in s1code if f.endswith(".h")] | 2e43d16d87aa7b427f58622d973229c082e9a67d | 633,449 |
def reciprocal_rank(sort_data):
""" calculate reciprocal rank
If our returned result is 0, 0, 0, 1, 1, 1
The rank is 4
The reciprocal rank is 1/4
Args:
sort_data: List of tuple, (score, gold_label); score is in [0, 1], glod_label is in {0, 1}
Return:
reciprocal rank
"""
... | 9217533c2ff1dcca83e44c28a7851c25932fbba0 | 465,464 |
import re
def remove_numbers(tweet):
"""
Replaces all numbers in a tweet with the word
'number'.
INPUT:
tweet: original tweet as a string
OUTPUT:
tweet with all numbers removed
"""
words = re.split(r'\s+', tweet)
new_words = []
for word in words:
if bool(re... | 833d94513f5e845149f788494ff50ee929c7d36d | 383,325 |
def add_local_pi_info(data, pi_id, pi_name, location):
"""
Take a dictionary of data read from a sensor and add information relating
to the pi from which the data was being collected
Returns a dictionary with the extra information
"""
if data is not None:
data['location'] = location
... | f8243068c247a78b24cb03732279680f86ea9dff | 322,100 |
def exclude(values, quality_flags=None):
"""
Return a timeseries with all questionable values removed.
All NaN values will be removed first and then iff `quality_flag` is set
(not 0) the corresponding values will also be removed.
Parameters
----------
values : pandas.Series
Timeseri... | cc6ef9b69b035854fc3bd28873b49c4f6742e5ca | 354,359 |
import requests
import json
def get_request(url):
"""Simple GET Request.
Args:
url (str): URL with parameters to GET request to.
Returns:
dict: Dictionary form of a JSON response.
"""
r = requests.get(url)
return json.loads(r.text) | 732d6cd54be1e56e610ebec2a07dcd046ed8dbf1 | 543,098 |
def get_unicode_code_points(string):
"""Returns a string of comma-delimited unicode code points corresponding
to the characters in the input string.
"""
return ', '.join(['U+%04X' % ord(c) for c in string]) | dada87ad2fef1948fd899fc39bd1abe7c105ac6c | 690,854 |
def coords_to_float(coord):
"""Convert a latitude or longitude coordinate from a string to a float, taking into account N, E, S, W.
For example, '48.2S' to -48.2
Parameters
----------
coord : str
The string form of the coordinate
Returns
-------
float
The coordinate in... | 2eafa12802cd1932ce54419414287f0a8ed0dac0 | 601,307 |
import base64
def encode_str_for_draft(input_str):
"""
Given a string, return UTF-8 representation that is then base64 encoded.
"""
if isinstance(input_str, str):
binary = input_str.encode('utf8')
else:
binary = input_str
return base64.b64encode(binary) | a8010bf9dfeed5d145dfb0ad81a4cc3bd34c6bad | 504,696 |
def processing_lines(
lines: list, skip_lines: list = ["# Databricks notebook source\n"]
):
"""Apply logic to transform databricks specific lines to jupyter lines.
Args:
lines (list): contains each line of code
skip_lines (list, optional): Lines to be skipped. Defaults to ["# Databricks not... | 5760c97410a1bfa3f464ee88c471d1c6c6687013 | 497,936 |
def andTruthTable() -> None:
"""And truth table.
Prints a truth table for the and operator.
Returns:
None. Only prints out a table.
"""
print(" _______________________________\n",
"|A and B | Evaluates to:|\n",
"|_______________|______________|\n",
"|F... | 2e10a431932c304c9720a1599db1ea3e26f14505 | 382,220 |
from typing import Tuple
def get_classes(config: dict) -> Tuple[str, str]:
"""
Return human readable model and dataset classes from the given config.
:param config: configuration dict
:return: a tuple of (model.class, dataset.class)
"""
return config['model']['class'], config['dataset']['clas... | db3e49052ba2ee22e2ae4ddb9b214af454abf5a4 | 544,470 |
def tuple_or_list(target):
"""Check is a string object contains a tuple or list
If a string likes '[a, b, c]' or '(a, b, c)', then return true,
otherwise false.
Arguments:
target {str} -- target string
Returns:
bool -- result
"""
# if the target is a tuple or ... | f29d4685b8e8bbb0c7e5c800a34a226782cdc7ae | 679,866 |
import math
def _getOS(box1, box2):
"""Compute orientation similarity between two 3D boxes"""
angle_diff = box1['rotation_y'] - box2['rotation_y']
return (1 + math.cos(angle_diff)) / 2 | 1d41444885df4aab208ea344405062f96e026334 | 299,352 |
def base32_decode(base32_value: str) -> int:
"""
Convert base32 string to integer
Example 'A' -> 10
"""
return int(base32_value, 32) | 3abebc1d84830a016c8beb880a3aedb14838c428 | 619,177 |
def _is_correct_task(task: str, db: dict) -> bool:
"""
Check if the current data set is compatible with the specified task.
Parameters
----------
task
Regression or classification
db
OpenML data set dictionary
Returns
-------
bool
True if the task and the da... | 49790d8e2b7a16ee9b3ca9c8bc6054fde28b3b6f | 4,641 |
def get_weight_op(weight_schedule):
"""Returns a function for creating an iteration dependent loss weight op."""
return lambda iterations: weight_schedule(iterations) | c3f4a01159a6a4b3ed309bf094b1821a542ada32 | 23,137 |
def load_html(starthtml, endhtml):
"""Load beginning and ending HTML to go in outpul file"""
start_html = starthtml.read()
end_html = endhtml.read()
return(start_html, end_html) | 6b67d50b44d59c56d2df4246ed49fd9570b43f34 | 545,437 |
def nice_number(num):
"""If num can be an int, make it an int."""
if int(num) == num:
return int(num)
else:
return num | 97e45021519b39c44f540d96204373a6d59690d0 | 564,180 |
import inspect
def get_stack_level() -> int:
"""
Return the stack level in Python.
"""
return len(inspect.stack(0)) | a6f66f9e548023a3536616df69cf75c24294a694 | 521,674 |
def get_smallest_divs(soup):
"""Return the smallest (i.e. innermost, un-nested) `div` HTML tags."""
return [
div for div in soup.find_all("div") if not div.find("div") and div.text.strip()
] | f3181c7f3cd5b4c82f060780e23dcf34028316e8 | 47,281 |
def namespace(api, name, description):
"""Return namespace name for the given module."""
return api.namespace(
'/'.join(name.split('.')[3:]).replace('_', '-'),
description=description
) | 0694a157a0d2d2c4e3aec83076c76f04fd5336d8 | 523,631 |
import random
def get_tweet(in_file):
""" Open up input file read all quotes into a list, return random quote """
possible = []
for tweet in in_file.read().split("DELIM"):
possible.append(tweet.strip())
return random.choice(possible) | bff12f0ccf5d0a8d5297456b67eac861afc6d10b | 244,060 |
def check_cloud(path: str):
"""Naive check to if the path is a cloud path"""
if path.startswith("s3:"):
return True
return False | f622fd3b479a2bca7e2ed405c861a5ae528b65a8 | 572,298 |
from typing import List
def has_class(rr_list: List) -> bool:
"""Determines if the list contains a resource class."""
return any(r_class in rr_list for r_class in ('IN', 'CS', 'CH', 'HS')) | f26be46349c9f586f3270193487df61963570bb2 | 303,209 |
import re
def cleanse_column(column):
"""
Template function for cleansing column names.
Columns beginning with / or _ will have these removed.
Columns containing spaces, /, (, ), - will be replaced with underscores.
Multiple _ in a row will be replaced with a single _
:param column: String col... | 7979c3a324500c5aa3a8e361d6cbf5efcd867334 | 340,913 |
def invert_dictionary(dictionary):
"""Invert a dictionary.
NOTE: if the values of the dictionary are not unique, the function returns the one of the mappings
Args:
dictionary (dict): A dictionary
Returns:
dict: inverted dictionary
Examples:
>>> d = {"a": 1, "b... | 28f3aef9b4f377f40cb68f87277d34f2e2817eda | 598,348 |
def collect_reducer_set(values):
"""Return the set of values
>>> collect_reducer_set(['Badger', 'Badger', 'Badger', 'Snake'])
['Badger', 'Snake']
"""
return sorted(list(set(values))) | c83e87711cf2f6543c3658493d9feb7f6d5f080a | 364,936 |
def set_kwargs_from_dflt(passed: dict, dflt: dict) -> dict:
"""Updates ++passed++ dictionary to add any missing keys and
assign corresponding default values, with missing keys and
default values as defined by ++dflt++"""
for key, val in dflt.items():
passed.setdefault(key, val)
return pass... | 3c0555c3276a20adbbc08f1a398605c6e6d37bd9 | 658,608 |
def _VarsToLines(variables):
"""Converts |variables| dict to list of lines for output."""
if not variables:
return []
s = ['vars = {']
for key, tup in sorted(variables.iteritems()):
hierarchy, value = tup
s.extend([
' # %s' % hierarchy,
' "%s": %r,' % (key, value),
'',
... | 238db698f6027acc7855212b531f1c79a3ac137d | 172,225 |
def register(name: str, registry: dict):
"""
Register a class or a function with name in registry.
For example:
CLS = {}
@register("a", CLS)
class A(object):
def __init__(self, a=1):
self.a = a
cls_a = CLS['a'](1)
In this way you can build... | b1238babbbbc986cee1b1eaae6468ab027081467 | 647,197 |
def yesno(ans):
"""Convert user input (Yes or No) to a boolean"""
ans = ans.lower()
if ans == 'y' or ans == 'yes':
return True
else:
return False | 15f74a66ae82742cf74254db7f3dc1a6682dc38c | 114,736 |
def step2_form_factory(mixin_cls, entry_form_class, attrs=None):
"""
Combines a form mixin with a form class, sets attrs to the resulting class.
This is used to provide a common behavior/logic for all wizard content
forms.
"""
if attrs is None:
attrs = {}
# class name is hardcoded t... | 5f51919f042642718815809d05493d55593627bd | 347,628 |
def _join_type_and_checksum(type_list, checksum_list):
"""
Join checksum and their correlated type together to the following format:
"checksums": [{"type":"md5", "checksum":"abcdefg}, {"type":"sha256", "checksum":"abcd12345"}]
"""
checksums = [
{
"type": c_type,
"chec... | 7f09ee72c6f51ad87d75a9b5e74ad8ef4776323f | 706,195 |
import logging
def _loggerBySpec(logger):
"""Logger maybe a logger, logger name, or None for default logger, returns the
logger."""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
return logger | f5a71eccdd53a30c725b602046effecb558738e6 | 404,955 |
def validate_token(token):
"""
Just a utility method that makes sure provided token follows a 'Bearer token' spec
:param token: A JWT token to be validated
:return: The token itself, None if not valid
:rtype: str
"""
if token:
# Token should be string with 'Bearer token'
toke... | cbeb8733bba3a8c77a635e160e7b3ce0cf7323b6 | 207,218 |
from datetime import datetime
import re
def parse_nowcast(text):
"""
Parses the immediate aurora forecast.
http://services.swpc.noaa.gov/text/aurora-nowcast-map.txt
"""
time = datetime.max # forecast time remains far in the future if time not found in the file
data = []
for line in map(l... | 64255c019b89e62766eccb109b0320bbaa3d3f1d | 232,973 |
def is_alarms_table(table):
""" True if table of alarms notifications """
phrase = 'alarm'
return phrase == table.short_title[:len(phrase)].lower() | 9d6d2d5ff2bb34fd834ce57262b1f740aa28b023 | 606,547 |
from datetime import datetime
def get_time_range(delta):
"""Return time range by delta."""
end = datetime.now().timestamp()
start = end - delta
return start, end | 402c98aea6e961af0d8756be0c4833225468c562 | 311,121 |
def postprocess_data(raw_data, decoded):
"""
Remove generation artifacts and postprocess outputs
:param raw_data: loaded data
:param decoded: model outputs
"""
raw_data['target'] = [x.replace('\n', ' ') for x in raw_data['target']]
raw_data['decoded'] = [x.replace('<n>', ' ') for x in decod... | 1de79a3e6ef1e3d253f94b327c4bfde144d993e9 | 507,595 |
from typing import List
import logging
def is_method(string_method: str, methods: List[str]) -> bool:
"""
Test if string_method is a method in methods
:param string_method: String to test
:type string_method: string
:param methods: list of available methods
:type methods: list of strings
... | f897c06320f67cd1dfcdcc294857fee1a5429e48 | 419,298 |
import socket
def port_check(host, port, timeout=2):
"""
Perform a basic socket connect to 'host' on 'port'.
Args:
host: String of the host/ip to connect to
port: integer of the port to connect to on 'host'
timeout: integer indicating timeout for connecting. Default=2
Returns... | 743738cc2ccb712207a9df3889834c52a491cb45 | 527,180 |
def get_name_arg(argd, *argnames, default=None):
""" Return the first argument value given in a docopt arg dict.
When not given, return default.
"""
val = None
for argname in argnames:
if argd[argname]:
val = argd[argname].lower().strip()
break
return val if v... | df0e43032c99df127030d59b3d8393a1c82e60cd | 231,968 |
def ebc_to_srm(ebc: float) -> float:
"""
Convert from European Brewing Convention (EBC) color system to
Standard Reference Method (SRM) color system.
"""
return ebc / 1.97 | cea03fa3688e5a9a23431e7802b8fe510c089f72 | 213,940 |
from typing import Iterable
def check_all_dicts(iterable_dict: Iterable[dict]):
"""Check if Iterable contains all dictionaries
Args:
iterable_dict (Iterable[dict]): Iterable of dictionaries
"""
# Check if dict
def check_dict(d):
return isinstance(d, dict)
# Check if all insta... | 0e87989d600d303e9bdadf04725c398841bcd214 | 30,839 |
def replicaset_config(client):
"""
Return the replicaset config document
https://docs.mongodb.com/manual/reference/command/replSetGetConfig/
"""
rs = client.admin.command('replSetGetConfig')
return rs | 5d2b3e2801fa96b6186a24edb00d849285dd9045 | 166,900 |
def clog2(x):
"""Ceiling log 2 of x.
>>> clog2(0), clog2(1), clog2(2), clog2(3), clog2(4)
(0, 0, 1, 2, 2)
>>> clog2(5), clog2(6), clog2(7), clog2(8), clog2(9)
(3, 3, 3, 3, 4)
>>> clog2(1 << 31)
31
>>> clog2(1 << 63)
63
>>> clog2(1 << 11)
11
"""
x -= 1
i = 0
w... | e3cceb918d048fd796685fc43850d93369f82ef2 | 95,235 |
def nameAndVersion(aString):
"""Splits a string into the name and version number.
Name and version must be seperated with a hyphen ('-')
or double hyphen ('--').
'TextWrangler-2.3b1' becomes ('TextWrangler', '2.3b1')
'AdobePhotoshopCS3--11.2.1' becomes ('AdobePhotoshopCS3', '11.2.1')
'Microsoft... | 79b5680c998313260f6f64bddc2ff9ee236453fd | 408,481 |
import unicodedata
import re
def text_to_slug(value, joiner="-"):
"""
Normalize a string to a "slug" value, stripping character accents and removing non-alphanum characters.
A series of non-alphanumeric characters is replaced with the joiner character.
"""
# Strip all character accents: decompose... | dad52fc9e9a7781125d3c08495d421c3daa3750a | 556,593 |
def qualified_column(column_name: str, alias: str = "") -> str:
"""
Returns a column in the form "table.column" if the table is not
empty. If the table is empty it returns the column itself.
"""
return column_name if not alias else f"{alias}.{column_name}" | 9920d71e94c0e17bd7a5ce5d0f5c4fabdacfab5e | 124,197 |
def includes(collection, sought, start=None):
"""Is sought in collection, starting at index start?
Return True/False if sought is in the given collection:
- lists/strings/sets/tuples: returns True/False if sought present
- dictionaries: return True/False if *value* of sought in dictionary
If strin... | a786b7190cd684b4fae780edf9113a077ab9f12a | 574,475 |
def im_fits_path(source, band, epoch, stoke, base_path=None):
"""
Function that returns path to im-file for given source, epoch, band and
stokes parameter.
:param base_path: (optional)
Path to route of directory tree. If ``None`` then use current directory.
(default: ``None``)
"""
... | 33e52dcb28fd98e290d3546e44208fbb9665f6a8 | 57,856 |
import importlib
def class_name_to_type(classname):
"""
Turns the class name into a type.
:param classname: the class name to convert (a.b.Cls)
:type classname: str
:return: the type
:rtype: type
"""
p = classname.split(".")
m = ".".join(p[:-1])
c = p[-1]
return getattr(im... | 3cf11ff27fb41f5fb2b65084d60a518f0965a741 | 319,440 |
def addDegrees(heading, change):
"""
Calculate a new heading between 0 and 360 degrees
:param heading: Initial compass heading
:param change: Degrees to add
:return: New heading between 0 and 360 degrees
"""
heading += change
return heading % 360 | 3af817cefb867706d4fd586e13a92b84b04f80b8 | 304,568 |
def complex_to_coord(num, flip=600):
"""
Transform a complex number to pygame coordinate.
Parameters
----------
num : complex
The complex number to transformm.
flip : int, optional
The height of the drawing, or the height of the original
pygame window. That is, the maxim... | 3d537f81f368db38f458f755a466c958c1c8150a | 465,277 |
import math
def mean(data):
"""
Calculates the mean of a data set
Args:
data: the list with the data
"""
n = len(data)
if (n > 0) :
result = math.fsum(data) / n
return result | 37af41822db8596c19b9cf3a3f97c96ad1cdf49b | 144,707 |
def first4_last4_every_other_removed(seq):
"""With the first and last 4 items removed, and every other item in between"""
return seq[4:-4:2] | 8e12112d97f7be2a50ecd6159f1295d100809f67 | 495,455 |
import re
def _check_if_item_allowed(item_name, allow_patterns, disallow_patterns):
"""
Check if an item with ``item_name`` is allowed based on ``allow_patterns``
and ``disallow_patterns``.
Parameters
----------
item_name: str
Name of the item.
allow_patterns: list(str)
Se... | 6a14239913140130eb8ce0d12a797039a7625172 | 43,394 |
import fnmatch
def _match_in_cache(cache_tree, list_of_names):
"""
:type cache_tree: defaultdict
:description cache_tree: a defaultdict initialized with the tree() function. Contains names
of entries in the kairosdb, separated by "." per the graphite convention.
:type li... | e559125f4b62a87956e0d30f5d8c3e4b2c7abef8 | 26,956 |
def get_corresponding_letter(index, sentence):
"""
Get the letter corresponding to the index in the given sentence
:param index: the wanted index.
:param sentence: the reference sentence.
:return: the corresponding letter if found, 'None' otherwise.
"""
if index < len(sentence.letters):
... | 4bc6df4228d2e8fc9fdd7ce2791c33d5f2a96257 | 673,829 |
def calDensityIG(MW, CoSp):
"""
calculate: density of ideal gas (IG) [kg/m^3]
args:
MW: molecular weight [kg/mol]
CoSp: concentration species [mol/m^3]
"""
try:
# density
den = MW*CoSp
return den
except Exception as e:
pass | 34fa96a3425975e2d80ddbe24753148746a7ea67 | 218,694 |
def nested_select(d, v, default_selected=True):
"""
Nestedly select part of the object d with indicator v. If d is a dictionary, it will continue to select the child
values. The function will return the selected parts as well as the dropped parts.
:param d: The dictionary to be selected
:param v: Th... | 84aa16adfb324fef8452966087cbf446d57893d2 | 11,575 |
def verify_user_prediction(user_inputs_dic: dict, correct_definition_dic: dict):
"""
Verifies user prediction json against correct json definition
returns true if correct format, false if not
"""
if user_inputs_dic.keys() != correct_definition_dic.keys():
return False
for user_key, use... | de1d2b579ab312929f64196467a3e08874a5be42 | 14,735 |
import codecs
def hex(b):
"""Convert the given bytes to hexadecimal string representation.
Parameters
----------
b : bytes
The byte string to convert
Returns
-------
str
Hexadecimal string
"""
return codecs.encode(b, "hex").decode("ascii") | 0aa07627e97474ffa9af259197b6c5ff4042940a | 426,158 |
import math
def rad_to_deg(r):
"""Radians to degrees
"""
return r * 180.0 / math.pi | d993a2ee9549af0d629d107015f0cd86ca8854ab | 470,229 |
import uuid
def build_request_body(method, params):
"""Build a JSON-RPC request body based on the parameters given."""
data = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": str(uuid.uuid4())
}
return data | 372df70bd17e78f01de5f0e537988072ac9716cc | 699,892 |
from typing import Iterable
from typing import Union
from pathlib import Path
from typing import Optional
import re
from typing import Collection
from typing import Set
def find_files(
paths: Iterable[Union[str, Path]],
include: Optional[re.Pattern],
excludes: Optional[Collection[re.Pattern]],
) -> Set[Pa... | 15ebdf322ad05e6e21d2c2878e2591533befef82 | 312,132 |
def is_query_parameter_value(value) -> bool:
"""
Checks if a value is a query parameter value.
:param value: The value to check.
:return: True if the value is a query parameter value,
False if not.
"""
# Must be a string or list of strings
return isinstance(valu... | 8e5b3b67e352532056b47a316b010111820aa806 | 308,224 |
import torch
def concat_and_flatten(items):
"""
Concatenate feature vectors together in a way that they can be handed into
a linear layer
:param items A list of ag.Variables which are vectors
:return One long row vector of all of the items concatenated together
"""
return torch.cat(items, ... | 9dcbcbb21bcc995abd641feec6d227543e08c082 | 247,526 |
def parse_unit(unit):
"""Parse a unit string
Parameters
----------
unit : str
String describing a unit (e.g., 'mm')
Returns
-------
factor : float
Factor that relates the base unit to the parsed unit.
E.g., `parse_unit('mm')[0] -> 1e-3`
baseunit : str
Ph... | 0ada612f10ac515651d6713e4a30cd6be4341b0a | 595,331 |
def getTreeString(x, y, z, numLogs):
""" Returns a Malmo string to use in the mission XML to create a tree. """
leavesHeight = y + 4
treeHeight = y + numLogs
return """
<DrawingDecorator>
<DrawSphere x="{x}" y="{yLeaves}" z="{z}" radius="3" type="leaves" />
<DrawLine x1="{x}" y1="{y}" z1="{z}" x... | 204680a811a98843f38abcdf028387e84277add2 | 537,936 |
import json
def nfa_json_importer(input_file: str) -> dict:
""" Imports a NFA from a JSON file.
:param str input_file: path+filename to JSON file;
:return: *(dict)* representing a NFA.
"""
file = open(input_file)
json_file = json.load(file)
transitions = {} # key [state in states, actio... | a821e29a6e02b14f381e737550ac00c61da9509c | 525,423 |
def calc_time_factor(start_breach, end_breach):
"""
calculates the fraction of island height to be reduced during simulation
:param start_breach: start time (island should be inundated here)
:param end_breach: end time
:return: return the timing ratio
"""
total_time = abs(end_breach - start_... | c57e91445674dce3f6ec58dd63c809d374cb84ad | 361,729 |
def _replace_reserved_char(s):
"""Return the given string with all its brackets and # replaced by _."""
for c in '()[]{}#':
s = s.replace(c, '_')
return s | 32b74b3a36577378ca23e8982e001595599f4c48 | 614,456 |
def after_request(response):
"""Define acceptable response headers."""
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,POST')
return response | 709061cd1bae2dad04cc34170d745261d0223f1e | 649,305 |
def merge_2_dictionnaries(dict1, dict2):
""" Merge two dictionnaries together by adding the values """
result = dict1
for k, v in dict2.items():
result[k] = (result.get(k) or 0) + v
return result | ca4e1834460bb27374f74532bde59627f9e99d51 | 245,738 |
def keys_as_sorted_list(dict):
"""
sorted keys of the dict
:param dict: dict input
:return: sorted key list
"""
return sorted(list(dict.keys())) | db8ba319724115a5b410eb7bad2847ef23d2977e | 339,862 |
def nop(arch = None):
"""Returns a no operation instruction."""
if arch in ['i386', 'amd64']:
return 'nop'
elif arch in ['arm', 'thumb']:
return 'orr r4, r4, r4'
elif arch in ['mips']:
return 'or $ra, $ra, $ra' | 6afb0e4bcfff5e4cf34bd7a02d74e65bf7635473 | 288,380 |
def get_version(client):
"""Return ES version number as a tuple"""
version = client.info()['version']['number']
return tuple(map(int, version.split('.'))) | c4a5f3d3e4e6326b6a7f5eed20d3e3e5b3c408c8 | 60,677 |
def chunkify(lst, n):
"""
e.g.
lst = range(13) & n = 3
return = [[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]]
"""
return [lst[i::n] for i in range(n)] | 641faa77c32934c4d110357f47a2ce96ad687faa | 209,554 |
def vsum(pos, delta):
"""Sums two vectors in tuple/list format"""
return (pos[0]+delta[0],pos[1]+delta[1]) | 0a10a7cea9d3bfa9f939ed392c6c4aa36e1de589 | 390,627 |
def _split_header(code):
"""Extract the Implectus header from a generated code string."""
lines = code.splitlines()
assert len(lines) > 3
assert lines[0].startswith("# # Autogenerated"), "Missing header"
assert lines[1].startswith("# This file was"), "Missing header"
assert lines[2].startswith("... | 77873a071c747dff96f36f11514a8e1b8693daa9 | 230,980 |
import torch
def mask_fill(
fill_value: float,
tokens: torch.Tensor,
embeddings: torch.Tensor,
padding_index: int,
) -> torch.Tensor:
"""
Function that masks embeddings representing padded elements.
:param fill_value: the value to fill the embeddings belonging to padded tokens.
:param... | e89e2a0f807765694ff68109b7d1a5adfec0297b | 670,567 |
import re
def convert_to_lowercase_and_underscore(name):
"""
The Shared Memory is in CamelCase - convert the names to Python Standard lowercase with underscores
http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case
I have already changed the names in si... | 268e643e476c754b1bd785967e909d90351d5dee | 558,403 |
import importlib
def import_module(libname):
""" Function import module using string representation """
return importlib.import_module(libname) | 1fe10e5c655a363a45ea742e33dd9d23a221b178 | 120,350 |
def drop_info(df):
"""Takes a dataframe and drop rows whitout an splitted `info`
length diferrent than four.
Parameters
----------
df :
The dataframe to search.
Returns
-------
The dataframe processed.
"""
before = df.shape
print(f'Shape before dropping: {befo... | fb18f874eaf925c6651aa912009749806fc0b1f4 | 586,733 |
def document_metas_from_data(document_data, claimant):
"""
Return a list of document meta dicts for the given document data.
Returns one document meta dict for each document metadata claim in
document_data.
Each dict can be used to init a DocumentMeta object directly::
document_meta = Doc... | a7060fe7b17f06e6bbf4ea2748315fec7392fbe8 | 143,419 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.