content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def get_device(model):
"""
Extract the device to run on from the model.
:param model: The model to train.
:return: String. The name of the device.
"""
if next(model.parameters()).is_cuda:
return 'cuda:{}'.format(torch.cuda.current_device())
else:
return 'cpu' | 587c71966da8c115883977c87b79449d6d586658 | 645,618 |
def buyholdsell(n):
"""
Param n is a number.
Function will decide if the number is worth buying, holding, or selling.
"""
if (n) in range(1, 30):
return "I'm buying"
elif (n) in range(30, 71):
return "I'm holding"
elif (n) in range(70, 101):
return "I'm selling"
... | c8f545fe2c0b8d13ddf5000070c62e2da8ffabb4 | 645,619 |
from typing import List
def opt_filter_string(filter_string: str, id_list: List[int]):
""" Generate string for option-based filter.
Generates a filter for filtering for specific rows based on the unique
element ID that will be added to the main SQL query.
Args:
filter_string: Start of the fi... | 6ef5680d95bc2ac3e894002e599b11ba2c634366 | 645,620 |
def load_dico_as_dict(dico_path):
"""
Load a dico as a dict
:param: dico_path: path of the dict
:return: a dict
"""
id = 0
dico = dict()
with open(dico_path, 'r') as fd:
for word in fd:
dico[id] = word.strip()
id += 1
return dico | 7f4f4c4ea0d5cd78a98531454b2d79f892a1084c | 645,626 |
def build_os_environment_string(env):
""" Creates a string of the form export key0=value0;export key1=value1;... for use in
running commands with the specified environment
:Parameter variables: a dictionay of environmental variables
:Returns string: a string that can be prepended to a command to run the comman... | c622b532b4a497c4af854e88236584abc9802e12 | 645,628 |
def remove_prefixes_of_others(values):
"""
Removes strings that are prefixes of other strings and returns the result.
"""
to_remove = set()
for value in values:
for other_value in values:
if other_value != value and other_value.startswith(value):
to_remove.add(va... | cd4c943ed46b564639041b22e69e5c3fd4d0aa8b | 645,629 |
def diff_mic(pos1, pos2, cell):
"""Minimum image convention relative vector (orthorhombic cell only)"""
diff = pos2 - pos1
for i in range(3):
diff[i] -= round(diff[i]/cell[i])*cell[i]
return diff | ea63817262321024bff29439354efeaaf8c58bb4 | 645,630 |
def int2name(i):
""" Convert integer to Excel column name. """
div = i + 1
name = ""
while div > 0:
mod = (div - 1) % 26
name = chr(65 + mod) + name
div = (div - mod) // 26
return name | 1a7a0a1f3f580a034a170029ee8e66fc30a33ab8 | 645,631 |
def _state_diff(state, previous_state):
"""A dict to show the new, changed and removed attributes between two states
Parameters
----------
state : dict
previous_state : dict
Returns
-------
dict
with keys 'new', 'changed' and 'removed' for each of those with content
"""
... | d9bb207beab1362ffc1d096e0cb4b7c0c54e124a | 645,638 |
from typing import Dict
from typing import Optional
def compose_custom_response(
resp: Dict,
success_message: str = "Operation successful.",
fail_message: str = "Operation failed.",
) -> Dict:
"""Enhances a dictionarised Misty2pyResponse with `success_message` in case of success and with `fail_message... | 9dfd6fb1be5f4a8d1306ce13d059b3987e9bd551 | 645,639 |
import math
def pixels_per_degree(display_diagonal_mm, height_pix, width_pix, viewing_distance_m):
"""
computer pixels per degree given display parameters and viewing distance
This is a convenience function that can be used to provide angular
resolution of input images for the HDR-VDP-2.
Note th... | c448df9bc921ac88ef1fabe6cb0978a54821cf41 | 645,640 |
def extract_request_body(requests_text: str):
"""
Parse change requests, a text of RPSL objects along with metadata like
passwords or deletion requests.
Returns a dict suitable as a JSON HTTP POST payload.
"""
passwords = []
overrides = []
rpsl_texts = []
delete_reason = ""
requ... | a14d9b016294c7b2b777f872a6b45394f58e76c4 | 645,643 |
def from_ms(time: int) -> str:
"""
Convert millisconds into a string in format mm:ss.ms
"""
minute = time // 60_000
second = time // 1000 - minute * 60
millisecond = time - minute * 60_000 - second * 1000
if second < 10:
second = "0" + str(second)
else:
second = str(se... | 83e5ac96a1aa2502636f6e375339b9bdd06b08a8 | 645,644 |
def output_file(out):
"""Convert file path to writeable file object."""
try:
return open(out, 'w')
except IOError as exc:
print('Error opening output file at path: {}.\n\n{}'.format(out, exc))
exit(1) | 854db5dc754e88aee2d76d9e06d636f00058a33b | 645,645 |
from typing import Optional
from typing import List
def get_class_selector(config_name: str) -> Optional[List[str]]:
"""Determines the class selector, based on the config name. This enables support for configs,
which train a model only on a subset of classes.
:param config_name: Name of the config used f... | 883d629f76cdbf8a9fd7e2433c7541dc136d9844 | 645,646 |
def import_m(module):
"""Will simply import a module into a var
Usage : pygame = import_m("pygame")"""
return __import__(module) | 78c417ba3a3bff2a45a1c09d52743a46e952c74c | 645,647 |
def checksum16(payload):
"""
Calculates checksum of packet.
:param payload: Bytearray, data to which the checksum is going
to be applied.
:return: Int, checksum result given as a number.
"""
chk_32b = 0 # accumulates short integers to calculate checksum
j = 1 # iterates through p... | 5a3e68cbb2310cdb872c22eba1424bef99a4136e | 645,651 |
def cir_RsC_fit(params, w):
"""
Fit Function: -Rs-C-
"""
Rs = params["Rs"]
C = params["C"]
return Rs + 1 / (C * (w * 1j)) | da444240d9b2956e8814c626f32e020feb7c380b | 645,653 |
def read_from_8bit_eeprom(bus, address, count, bs=16):
"""
Reads from an 8-bit EEPROM. Only supports starting from 0x00, for now.
(to add other start addresses, you'll want to improve the address counting mechanism)
Default read block size is 16 bytes per read.
"""
data = [] # We'll add our read... | 782dbc4f17144881fcd66e5f5fb51126070dc634 | 645,654 |
import pathlib
import lzma
import tempfile
def extract_lzma(path):
"""Extract an lzma file and return the temporary file name"""
tlfile = pathlib.Path(path)
# open lzma file
with tlfile.open("rb") as td:
data = lzma.decompress(td.read())
# write temporary tar file
fd, tmpname = tempfil... | 9444eca8456e113a70841427444e3fd305a88862 | 645,656 |
def is_iterable(x):
"""Checks if an object x is iterable.
It checks only for the presence of __iter__, which must exist for
container objects.
Note: we do not consider non-containers such as string and unicode as
`iterable'; this behavior is intended.
"""
return hasattr(x, "__iter__") | a848ebe577a0ead3eb55262bff7b63e2720e0473 | 645,658 |
from typing import Dict
from typing import Any
def slider_handle_label(is_numerical: bool, is_ten_pow: bool = False) -> Dict[str, Any]:
"""Get the slider handle label dict."""
if is_numerical:
label = "BINS"
if is_ten_pow:
label = "SMART BINS"
else:
label = "CATEGORIES"... | e841509cf5c4077b6977aedc8abbcdbb2338985f | 645,662 |
def get_integer(prompt):
"""
Get an integer from Standard Input (stdin).
The function will continue looping, and prompting
the user, until a valid `int` is entered.
:param prompt: The String that the user will see, when
they're prompted to enter the value
:return: The integer that the... | 42f246e54a1fa6ef48c28d796d84010c0d5fd9e3 | 645,664 |
def is_tuple(obj):
"""Helper method to see if the object is a Python tuple.
>>> is_tuple((1,))
True
"""
return type(obj) is tuple | 79dc59e5166e88d9dda627b6bf36682cbd75b169 | 645,665 |
def escape_register(register):
"""Escape register names suitable rust module and variable names."""
return register.replace("[", "").replace("]", "") | 81d6fb55a69e6054ed71483f0935453180b88d31 | 645,667 |
import math
def pts2bins(pts, prec=0.25):
"""
:param pts: List of 2d points
:param prec: Width of each bin
:return: A dictionary of bin centers and points in the bin
"""
# for pt in pts:
# def val2bin_int(val):
# return math.ceil(val / prec) if val > 0 else math.floor(pt[1]... | 731e894d85b9546cc8b1f8b622ade7402bf33b7a | 645,668 |
def serial_listen_ports(migrate_data):
"""Returns ports serial from a LibvirtLiveMigrateData"""
ports = []
if migrate_data.obj_attr_is_set('serial_listen_ports'):
ports = migrate_data.serial_listen_ports
return ports | 2d28f32f8afbd4082d811de909a361f93bc1e379 | 645,669 |
from typing import List
def splitStrToList(
string: str,
separator: str = ',',
ignores: str = '\\'
) -> List[str]:
"""Split the given string into a list, using a separator
@type string: str
@param string: The string to be splited
@type separator: str
@param separator: A separator to s... | d9fc4ca5d2a680a4fde32897250a80883ff47a90 | 645,670 |
import base64
import struct
def _decode_linear_biases(linear_string, nodelist):
"""Inverse of _serialize_linear_biases.
Args:
linear_string (str): base 64 encoded string of little endian
8 byte floats, one for each of the nodes in nodelist.
nodelist (list): list of the form [node1... | 823c4759d90d28fb0c2b3cdaf2a6f0d1de96d4f5 | 645,675 |
def validate_list_of_numbers_from_csv(data):
"""
Converts a comma separated string of numeric values to a list of sorted unique integers.
The values that do not match are skipped.
:param (str, iterable) data: - str | iterable
:return: - list(int)
"""
if isinstance(data, str):
... | e1c49eae266d074bda44a2699c1ccddd578a77ae | 645,676 |
def sizeof_fmt(num, suffix='B'):
"""Returns human-readable file size
Supports:
* all currently known binary prefixes
* negative and positive numbers
* numbers larger than 1000 Yobibytes
* arbitrary units (maybe you like to count in Gibibits!)
Example:
--------
>>> sizeof_fmt(16... | ba1b6cc8b7121a87ccee00bc333d77e4b251dd61 | 645,680 |
def compute_reduced_cost(column, duals):
"""Compute and return the reduced cost of 'column'."""
return (column.objective_coefficient -
sum(duals[index] * coef
for index, coef in zip(column.row_indices,
column.row_coefficients))) | 14b02864f9a9ca10584b3436f1e33e14ffd90fc9 | 645,684 |
def extract_array(line):
"""
Return the array on the RHS of the line
>>> extract_array("toto = ['one', 'two']\n")
['one', 'two']
>>> extract_array('toto = ["one", 0.2]\n')
['one', 0.2]
"""
# Recover RHS of the equal sign, and remove surrounding spaces
rhs = line.split('=')[-1].stri... | 9156cab7e4a12df858da9189b90fab355f5a97ed | 645,687 |
def get_bs_dims(bands_array):
"""
Get the dimensions from the bands array of a BandsData node.
:param numpy.array bands_array:
an array with bands as stored in an array.bands data node
:return: a tuple containing num_bands, num_kp, num_spins.
if the array is only 2d, num_spins = 0
:... | c7e92d6f90d45d5cfdf7ef50285c88fc57d55ca6 | 645,691 |
from typing import Optional
def comment(c: str, inner: str, units: Optional[str] = None):
"""Add 'Begin c' and 'End c' comments around an inner block.
Optionally add another 'units' comment before the inner block.
"""
units_str = "" if units is None else f"# {units}\n"
return units_str + f"# Beg... | 385f4566f9aa6f20fc3fa8b4d77fd7f8a0a9a580 | 645,692 |
def parse_position(string):
"""
>>> parse_position('3,000,000')
3000000
>>> parse_position('3M')
3000000
>>> parse_position('3kk')
3000000
"""
units = ''
for index, char in enumerate(string):
if char.lower() in ['k', 'm']:
units = string[index:]
st... | 893aef37ab347bcab81f1ced2019ce29f5d29bd4 | 645,695 |
import re
def validate_replication_tags(replication_tags):
"""
Returns validated replication tags or raises an error.
- 'replication_tags' should be a list of 'tag's.
- a 'tag' should be dictionary with Keys 'Key' and 'Value'
- the 'Key' Values should be a string with length between 0 and 127
... | 5a665fe2c9eaa4ab8fbfd1dda64b2d0ead65b953 | 645,698 |
from typing import Dict
from typing import Any
def abi_input_signature(input_abi: Dict[str, Any]) -> str:
"""
Stringifies a function ABI input object according to the ABI specification:
https://docs.soliditylang.org/en/v0.5.3/abi-spec.html
"""
input_type = input_abi["type"]
if input_type.start... | e2ed8b9587066b1edcbd3563c8c45ceb64dc1442 | 645,699 |
import importlib
def get_class_from_qualname(name):
"""
Resolve a fully qualified class name to a class, attempting any imports
that need to be done along the way.
:raises: ImportError or AttributeError if we can't figure out how to import it
"""
tokens = name.split(".")
module_name = ".".... | 5ee7ff2113ce9bcd6951b7f6a6906879b42444c2 | 645,702 |
import boto
from typing import Optional
def get_aws_zone_from_boto() -> Optional[str]:
"""
Get the AWS zone from the Boto config file, if it is configured and the
boto module is available.
"""
try:
zone = boto.config.get('Boto', 'ec2_region_name')
if zone is not None:
z... | eebbe2bb15f9c95def8e1e68f95c08c5a7a29137 | 645,705 |
def restrict_to_setting(df, setting, run='eval'):
"""Restrict an experiment dataframe to one hyperparameter setting."""
setting_df = df[df['run'] == run]
for k, v in setting.items():
if k in df.columns.values:
setting_df = setting_df[setting_df[k] == v]
return setting_df | 820f0eae187d872e231c5e688575ef05d500b607 | 645,708 |
import functools
def synchronized(lock):
"""
Synchronizes a function call access on the given lock object. `lock` must have an `acquire()` and a `release()`
method. Function call cannot proceed until the lock is acquired. Deadlocks are possible be careful
Args:
lock: the lock upon which to syn... | 14ded2891347a72bbbc51e2fcf74410ddf616dc4 | 645,714 |
import struct
def gatt_dec_svc_attr(data):
"""Decodes Service Attribute data from Discovery Response data.
BTP Single Service Attribute
0 16 32 40
+--------------+------------+-------------+------+
| Start Handle | End Handle | UUID Length | UUID |
+----------... | 868e46ae7cc4e8fdd492919d1930b46ff86eeb26 | 645,720 |
import logging
def get_log_level(name="cleverhans"):
"""
Gets the current threshold for the cleverhans logger
:param name: the name used for the cleverhans logger
"""
return logging.getLogger(name).getEffectiveLevel() | 8d95cf9b3b2d6a8663e3aab8efada09b548569c2 | 645,721 |
def calc_labor_restriction(x_0,l_0,l_t):
"""
A function to compute sector output with the available labor force.
Parameters
----------
x_0 : np.array
sector output under business-as-usual (in M€/d)
l_0 : np.array
number of employees per sector under business-as-usual
l_t : n... | 9d28b9125d254dfb6f66dd857388c9924b7a04d4 | 645,724 |
def hash_object(x):
"""Given a variable or object x, returns an object suitable for
hashing. Equivalent variables should return equivalent objects."""
if hasattr(x, 'hash_object'):
return x.hash_object()
else:
return x | b3a0a8c2accbfcd0e17839345e4e3c4e9d620810 | 645,726 |
def interpolate(v1, v2, delta):
"""Interpolates between 2 arrays of vectors (shape = N,3)
by the specified delta (0.0 <= delta <= 1.0).
:param numpy.array v1: an Nd array with the final dimension
being size 3. (a vector)
:param numpy.array v2: an Nd array with the final dimension
being ... | fcc0f18e9231c829f56162ce4f5c49565cfd5505 | 645,729 |
def convert_spaces(file_name):
"""Return file_name with all spaces replaced with "-"."""
return file_name.replace(" ", "-") | 78253cb1167b0f350b136fb62f665839dad7cc0e | 645,730 |
def allowed_file(file_name_list: list) -> bool:
"""Return True if file extension of all passed file names is allowed"""
allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'}
for file_name in file_name_list:
if not file_name:
return False
if file_name.split('.')[-1].lower() not in al... | c517a9b33f4a35f3a19c341b90233b5091951e37 | 645,732 |
def parkes_error_zone_detailed(act, pred, diabetes_type):
"""
This function outputs the Parkes Error Grid region (encoded as integer)
for a combination of actual and predicted value
for type 1 and type 2 diabetic patients
Based on the article 'Technical Aspects of the Parkes Error Grid':
https:... | 081e40ff960f02f0cd977b31cabbc8fadaa56bdb | 645,733 |
def get_project(directory):
"""
Get the project in the given directory.
Figure out the project name, and return a dictionary with the project name,
the readable project path, the absolute project path, and a unique ID.
"""
namefile = directory.expanduser() / '.idea' / '.name'
try:
n... | b98914dd06eb69026d2e238a4d03fc4830350fea | 645,737 |
from typing import Union
from typing import Iterable
import torch
from typing import Tuple
def recursive_to_device(
iterable: Union[Iterable, torch.Tensor],
device: Union[str, torch.device],
) -> Iterable:
"""Recursively puts an Iterable of (Iterable of (...)) tensors on the given device
:param iter... | f64bd8d4976308215ce4a0eb3842db4e39abddea | 645,738 |
def _get_actor_name(message):
"""Returns actor name by parsing incoming message.
"""
return str(message).split('(')[0] | 55615e7593a14f8ab50f8ddbaabe659f0095a900 | 645,739 |
def format_timedelta(td):
"""
Format a timedelta
Args:
td (datetime.timedelta): A timedelta
Returns:
str: A string which represents the timedelta
Examples:
>>> import datetime
>>> td = datetime.timedelta(days=3)
>>> format_timedelta(td)
'3 days'
... | c8bb60b05f4264966f51d347722599abe5bd3134 | 645,740 |
def combine_status_info(obj, status_info, attrs, separator='\n= {attr} ='):
"""
Combine status information from the given attributes.
Parameters
----------
obj : OphydObj
The parent ophyd object.
status_info : dict
The status information dictionary.
attrs : sequence of str... | efc333e5f7083ed034db8bdb4b295ac99d84a849 | 645,746 |
def get_saturation(rgb):
"""Returns the saturation (hsl format) of a given rgb color
:param rgb: rgb tuple or list
:return: saturation
"""
c_max = max(rgb) / 255
c_min = min(rgb) / 255
d = c_max - c_min
return 0 if d == 0 else d / (1 - abs(c_max + c_min - 1)) | a5784ae01316a0d9d924f2144f22d842c6fbb229 | 645,747 |
def _get_segmentation_strategy(segmentation):
"""Get the baci string for a geometry pair strategy."""
if segmentation:
return 'segmentation'
else:
return 'gauss_point_projection_without_boundary_segmentation' | 267a10a7237b2d42f1988ad9e35eddc7febbe789 | 645,748 |
def selection_sort(array):
"""
Selection sort algorithm for sorting an array of ints.
Returns sorted array.
Running time = O(n2) to O(n2)
"""
A = array.copy()
n = len(array)
# Loop over the first to penultimate elements in array
for i in range(0, n - 1):
# Find smallest eleme... | a4ec5f4d3b073c6175db57ff23dc6a2fa413a1e4 | 645,749 |
import math
def generalized_logistic_curve(t, a, k, b, eta, q, c=1):
"""See https://en.wikipedia.org/wiki/Generalised_logistic_function."""
return a + (k - a) / math.pow((c + q * math.exp(-b * t)), 1.0 / eta) | a01606ab053077a16072e0a6ed93613bb3f8d8c7 | 645,751 |
def sort_by_inclusion(array: list) -> list:
"""
Сортировка простым включением.
Суть: массив делится на две части - отсортированную и неотсортированную.
На каждом шаге берется очередной элемент из неотсортированной части и "включается" в отсортированную часть массива.
Максимальная временная сложност... | 296a222d0a24b3fc85d1b6da6aec3e42358dc912 | 645,754 |
def quadFit(x, a, b, c):
""" Quadratic fit function. """
return a*x*x + b*x +c | d7a14fe1fad30b5fa7782bbc6b96592979afac95 | 645,755 |
from datetime import datetime
def to_timestamp(ts):
""" Return a date/time in UTC from a timestamp """
return datetime.utcfromtimestamp(ts/1000.0) | e8c6c6b262d6d8b05dc936e3cdc1adab1ba4ccc7 | 645,756 |
def get_line_data(line, separator=None):
"""Converts a line scraped from a web page into a list.
Parameters:
- line, a line scraped (read) from a web page. The type is <class 'bytes'>.
- separator (optional, default value None). If set, becomes the optional
separator argument to th... | 0b49108042e270ee3d0bda60cc75507dbfc8f60e | 645,757 |
from typing import Optional
def cognito_user_id(event: dict) -> Optional[str]:
"""
Returns the User ID (sub) from cognito or None
"""
try:
return event["requestContext"]["authorizer"]["claims"]["sub"]
except (TypeError, KeyError):
return None | 4e1216ea0cfa4e21be03a8e95da14ce6c13888a9 | 645,759 |
def nsec_to_usec_round(DatetimeNanos) -> int:
"""Round nanoseconds to microseconds
Timestamp in zipkin spans is int of microseconds.
See: https://zipkin.io/pages/instrumenting.html
"""
inttimestamp = DatetimeNanos.timestamp() * 1e9
return int((inttimestamp + 500) // 10 ** 3) | 054fb56d733988a90ac8945e9bf1b733fb1a0572 | 645,762 |
def describe_selection(selection):
"""Create a human-readable description of the given selection
Parameters
----------
selection: FileSelectionFile
Returns
-------
str
"""
return (
f"Selection containing {len(selection.selected_paths)} files:\n"
f"Description: {se... | 25c5ddc34d5f4d530022932b2940af420f385d40 | 645,765 |
def check_complexity(check_bytes: bytes, complexity: int) -> bool:
"""Check the complexity of a bystream to see if it has the proper amount of leading 0 bits
Args:
bytes: byte stream to check for complexity bits
complexity: number of leading bits that must be 0 in order to pass complexity
Re... | 79d227a59c288cd2b8c39c73f568bd3e5c430038 | 645,768 |
def remove_new_lines_in_paragraph(article):
"""When we publish articles to dev.to sometimes the paragraphs don't look very good.
So we will remove all new lines from paragraphs before we publish them. This means we
don't have to have very long lines in the document making it easier to edit.
Some elemen... | 6f2123bebe966b4e3b03a0c4473628985b883f3f | 645,770 |
def delta_percent(decimals=1):
"""A delta formatter to display the delta as a float with a given number of decimals.
Args:
decimals: The number of decimals to display.
Returns:
A delta formatter function (f(a,b)) returning (b-a)/a displayed as a percentage.
"""
return (lambda a, b... | a8c04264ab6f6289fce8642822254afb8155054a | 645,771 |
def key_values_to_tags(dicts):
"""
Converts the list of key:value strings (example ["mykey:myValue", ...])
into a list of AWS tag dicts (example: [{'Key': 'mykey', 'Value': 'myValue'}, ...]
"""
return [{'Key': tag_key_value[0], 'Value': tag_key_value[1]}
for tag_key_value in [key_value_o... | 795f1b40ebfb5d7eb2aae14d52509ebed52a9650 | 645,772 |
def fixed(b1, b2):
"""
XORs two given sets of bytes, of equal length, together.
"""
# Ensure that byte arrays are of equal length.
if len(b1) != len(b2):
raise Exception('Byte arrays are not of equal length.')
# XOR byte arrays together and return.
return bytearray([x ^ y for x, y i... | 60860b055f0db8c4c4bfe34afd75ddaf319dcd59 | 645,774 |
def assert_(condition, message=None, *args, val=None): # pylint: disable=keyword-arg-before-vararg
"""
Return `value` if the `condition` is satisfied and raise an `AssertionError` with the specified
`message` and `args` if not.
"""
if message:
assert condition, message % args
else:
... | e3a24b51c5cce487610786739d16c88ccb1da1e3 | 645,775 |
def coerce_to_list(data, key):
"""
Returns the value of the ``key`` key in the ``data`` mapping. If the value is a string, wraps it in an array.
"""
item = data.get(key, [])
if isinstance(item, str):
return [item]
return item | 00cf50d81f7a7513deb4593d3a236639353079af | 645,779 |
import struct
def writeRegisterRequestValue(data):
"""Return the value to be written in a writeRegisterRequest Packet."""
packet = struct.unpack('>H', data[10:])
return packet[0] | f21cc8bd9407aa758d18fd1a095c619a7030fd1f | 645,780 |
def dict_to_r_vec(d):
"""Convert a skylark dict to a named character vector for R."""
return ", ".join([k + "=" + v for k, v in d.items()]) | 59458064faa2341411b4fdd9168752a326e9c66b | 645,783 |
def find_any(words, case_sens = False):
"""Tests if any of the given words occurs in the given string.
This filter is case INsensitive by default.
"""
if not case_sens:
used_words = [w.lower() for w in words]
else:
used_words = words
def apply_to(s):
if not case... | f94b168fcfe025ce961de59ef03151ee05bb8921 | 645,785 |
def is_iterable(obj):
""" Check if the object is iterable. """
has_iter = hasattr(obj, "__iter__")
has_get_item = hasattr(obj, "__getitem__")
return has_iter or has_get_item | 92a8c6c4203f00b0ed535bb6a4688d07d33e5f8b | 645,787 |
def _decode_ctrl(key):
"""
Convert control codes ("\x01" - "\x1A") into ascii representation C-x
"""
assert len(key) == 1
if key == '\n':
return 'RET'
code = ord(key)
if not 0 < code <= 0x1A:
# Not control code
return key
letter = code + ord('a') - 1
return ("... | cd30c728903dae557f1eeef30bd73caae2da718a | 645,789 |
def start_gamma2_imp(model, lval: str, rval: str):
"""
Calculate starting value for parameter in data given data in model.
For Imputer -- just copies values from original model.
Parameters
----------
model : Model
Imputer instance.
lval : str
L-value name.
rval : str
... | 80c1949be96498437708b544ed87c6f31c142070 | 645,790 |
def get_yes_no_input(question_text):
""" :return True/False as answer to the passed yes-no question"""
confirm = ""
while confirm.lower() not in ["y", "n"]:
confirm = input(f"{question_text} [y/n]: ")
return confirm.lower() == 'y' | a56ff8f98f8072fbc5ccb25673e940df8fb2b548 | 645,791 |
def usage(progname):
""" print program usage """
print(("Usage: %s /path/to/tables "
"/path/to/generated output[_amalgamation.cpp]") % progname)
return 1 | 1da5da77c98f8d0a1b84961caec1de7041e0cf5d | 645,792 |
def agent_portrayal(agent):
"""
Properties of the agent visualization.
"""
portrayal = {"Shape": "circle",
"Color": f"rgb({140-(agent.speed*3.6)},{50+(agent.speed*3.6)},0)",
"Filled": "true",
"r": 4}
return portrayal | 0053c055266f632a56b414b30d098d5c4396d246 | 645,795 |
from pathlib import Path
from typing import Dict
from typing import Any
import json
def read_json_file(json_file: Path) -> Dict[Any, Any]:
"""Parse the application JSON file into native dict
:param json_file (Path): JSON file to parse"""
with open(json_file, 'r') as f:
return json.load(f) | cae03c07969adca8329afe55cc7940ba8d959ec3 | 645,803 |
from enum import Enum
from typing import Dict
from typing import Any
def enum_to_dict_fn(e: Enum) -> Dict[str, Any]:
"""
Converts an ``Enum`` to a ``dict``.
"""
return {
'name': e.name
} | 13205618bedfb25a5912ec5bb29aacb0e12a53f5 | 645,804 |
def blksLeftStakeWindow(height, netParams):
"""
Return the number of blocks until the next stake difficulty change.
Args:
height (int): Block height to find remaining blocks from.
netParams (module): The network parameters.
Returns:
int: The number of blocks left in the current... | b0dcfc6747aec4a7c9e580a24dda80a32b9e5f03 | 645,807 |
def _normalize_columns(columns: list[str]) -> list[str]:
"""Normalize column names."""
new_columns = [
"".join([substr.capitalize() for substr in col.split("_")])
for col in columns
]
return new_columns | 26e2f7922612d883de51a9164c819a31161eba81 | 645,808 |
import json
def _parse_callout_ffdc(version: int, data: memoryview) -> str:
"""
Parser for callout list FFDC.
"""
# The data in this section is simply a string representation of JSON data.
# When the JSON data is written to the section, it will include a null
# character at the end because it... | 6d69caff37cd28b6da596670503924dcb85adb18 | 645,809 |
import torch
def numpy2tensor(x):
"""Transter type numpy.ndarray to type torch.Tensor and change the precision to float
Write in function so that can be used in functional programming
:param x: The numpy data to be transformed
:type x: numpy.ndarray
:return: The torch data after transformatio... | 38212f1f124f73fd1a26030d31348ae714824e9f | 645,810 |
from typing import Counter
def sort(sequence, values):
"""
Sort using the counting sort algorithm.
sequence -- the sequence to sort
values -- all the possible values of elements in the sequence
(values must be in sorted order)
Returns a list with the given sequence's elemen... | 611dd6339751b0969a6e42c3c5521d0b17d9a64f | 645,812 |
def always(_):
"""Predicate function that returns ``True`` always.
:param _:
Argument
:returns:
``True``.
"""
return True | 2754168d1ae203864d457552dd1aa4eab5dca51b | 645,814 |
def sanitize_page_number(page):
"""A helper function for cleanup a ``page`` argument. Cast a string to
integer and check that the final value is positive.
If the value is not valid returns 1.
"""
if isinstance(page, str) and page.isdigit():
page = int(page)
if isinstance(page, int) and (... | 9dd98ce4461cd3e2883c93f5f6bb9469cbff4678 | 645,815 |
import re
def read_and_prep_file(filename):
"""Read contents of a file,remove html tags
Args: filename(str): a filename with full path to be loaded
Returns: text(str): a string containing all words
We read in all lines in a file, join into one long string, remove all html, turn any character that isnt... | c8ae164c6dbea04c5d056f76b8bc71bce3d12fed | 645,816 |
def key_sort(data):
"""
sort by dict key and return sorted list
:param data: dict to sort
:type data: dict
:return: sorted list of k,v tuple
:rtype: list
"""
return [(k, data[k]) for k in sorted(data.keys())] | cfcab10805dcd7d8a69115ef3fbe51225f0c4d28 | 645,818 |
def sort_words_case_insensitively(words):
"""Sort the provided word list ignoring case,
one twist: numbers have to appear after letters!"""
char = [c for c in words if not c[0].isnumeric()]
num = [n for n in words if n[0].isnumeric()]
sorted_words = sorted(char, key = lambda word: word.lower()) +... | d1cea948f3b00149f24cd569c7018791a2071511 | 645,820 |
def extract_line(text_list, keyword, vname, col):
"""Takes a list of text and for every line containing the keyword,
creates a dictionary where vname is key and the word at col is the value.
Used for extracting one value from output file.
"""
dictionary = {}
for line in text_list:
if keyword in line:
diction... | dccb2c94f5b24d555d317e62e4b362e66fe5cc5c | 645,823 |
def update_event_visibility(review):
"""
Update event's `is_published` flag according to review
:param review: EventReview object
:return: event review updated object
"""
review.event.is_published = False
if review.is_approved:
review.event.is_published = True
review.event.save... | 42c38cfed7c62b1ac7cbfc9d526139265bf856ea | 645,828 |
def hierarchical_merge(dicts):
"""Merge a list of dictionaries.
Parameters
----------
dicts: List[Dict]
Dicts are given in order of precedence from lowest to highest. I.e if
dicts[0] and dicts[1] have a shared key, the output dict
will contain the value from dicts[1].
Retur... | f708b72667ad7495d8bcb9282028e4ea18c4720b | 645,834 |
def check_if_all_tss_are_bad(tss):
""" Check if all time series in a list are not good.
'Not good' means that a time series is None or all np.nan
"""
def bad(ts):
return True if ts is None else ts.isnull().all()
return all([bad(ts) for ts in tss]) | a8113b13f08b6df1273213d3a938d7b687443576 | 645,838 |
import pickle
def load_meta(fname, data_id=''):
"""Load a metadata file.
Parameters
----------
fname : str
Path to TFRecord folder
Returns
-------
meta : dict
Metadata file
"""
with open(fname+data_id+'_meta.pkl', 'rb') as f:
meta = pickle.load(f)
ret... | 2f63d0f2fc1c25fbab59b3c667458e2daf397526 | 645,841 |
def composite_identity(f, g):
"""
Return a function with one parameter x that returns True if f(g(x)) is
equal to g(f(x)). You can assume the result of g(x) is a valid input for f
and vice versa.
>>> add_one = lambda x: x + 1 # adds one to x
>>> square = lambda x: x**2
>>> b1 = compo... | df89773a3a01bf7d8b3ba5e33ec4866a0f365026 | 645,843 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.