content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def cf_ni_ratio(cf_df, financials_df):
"""Checks if the latest reported Operating CF (Cashflow) is larger than the latest reported NI (Net Income).
cf_df = Cashflow Statement of the specified company
financials_df = Financial Statement of the specified company
"""
cf = cf_df.iloc[cf_df.index.ge... | f0997b38950e4fadcd2a9bb8d1da7e648c970bc9 | 49,330 |
def retrieve_files(s3, short_name, date_str):
"""Retrieve a list of files from S3 bucket.
Parameters
----------
s3: S3FileSystem
reference to S3 bucket to retrieve data from
short_name:
string short name of collection
date_str: str
string date and time to search for
... | e362b1be22f56dae4c17280038eb2f5ff1315ae4 | 49,334 |
from typing import List
from typing import Dict
def get_readme_download_url(files: List[Dict[str, str]]) -> str:
"""
Takes in a response from the github api that lists the files in a repo and
returns the url that can be used to download the repo's README file.
"""
for file in files:
if fil... | 5c394d247b0ab06099b3d3a540fa2f5101b385e6 | 49,338 |
import threading
def _start_thread(target, *args, **kwargs) -> threading.Thread:
"""Helper to simplify starting a thread."""
thread = threading.Thread(target=target, args=args, kwargs=kwargs)
thread.start()
return thread | a5d9e1feb1b02ee9b1ec3aaa46758cd3d27e1880 | 49,340 |
def count_trees(data, route):
"""
>>> count_trees([
... [False, False, True, True, False, False, False, False, False, False, False],
... [True, False, False, False, True, False, False, False, True, False, False],
... [False, True, False, False, False, False, True, False, False, True, Fal... | 1a81a8ccb3b7dd87f04b7713d08370297cb7b5fa | 49,342 |
def combination_of_two_lists(lst1, lst2):
"""
["f", "m"] and ["wb", "go", "re"] => ["f_wb", "f_go", "f_re", "m_wb", "m_go", "m_re"]
"""
return [e1 + "_" + e2 for e1 in lst1 for e2 in lst2] | 3f966ff5bb535d95c232162f76705b2b9f6311c6 | 49,344 |
def letter_for(label):
"""Return the letter for a given label."""
return "ABCDEFGHIJ"[label] | 6c0692f7451db6fd45141339f702665ba3ac2bb4 | 49,352 |
def read_coverages(input_file):
"""Return coverage values."""
coverages = []
with open(input_file, 'r') as input_handle:
for line in input_handle:
coverages.append(float(line.rstrip()))
return coverages | 6820da83d0ecb24cdad1169b0521505d59d3dcbf | 49,353 |
def bgr01(r, g, b):
"""Rescales BGR to a 0-1 scale."""
return (b / 255.0, g / 255.0, r / 255.0) | c7d9d5cecfec3311ad8f5d3b2baf619b5bbe83cf | 49,357 |
def to_world_canvas(world_point, canvas_extents, world_extents):
"""Transforms a point from world coord system to world canvas coord system."""
x = int(world_point[0] / world_extents[0] * canvas_extents[0])
y = int(canvas_extents[1] - 1 - world_point[1] / world_extents[1] * canvas_extents[1])
return (x,... | 5dec7f87fae35542b5798f88b0353c9b593e88fb | 49,369 |
import struct
def py_int2byte(val):
"""
Converts Python int value to byte.
"""
return struct.pack('B', val) | d6ab7467c615a23ccb416db2d1150a3909d9f1ff | 49,372 |
def flatten_dict(dd, separator='.', prefix=''):
"""Recursive subroutine to flatten nested dictionaries down into a single-layer dictionary.
Borrowed from https://www.geeksforgeeks.org/python-convert-nested-dictionary-into-flattened-dictionary/
Parameters
----------
dd : dict
dictionary to f... | f0b356aa0c516b88e83d8c8820fc53f4db69623d | 49,376 |
def known_mismatch(hashes1, hashes2):
"""Returns a string if this is a known mismatch."""
def frame_0_dup_(h1, h2): # asymmetric version
return ((h1[0] == h2[0]) and
(h1[2:] == h2[2:]) and
(h1[1] != h2[1] and h2[1] == h1[0]))
def frame_0_dup(h1, h2):
return fram... | dfd3985a26e53147147b2485203964863db8600c | 49,377 |
def to_unicode(s):
"""Return the parameter as type which supports unicode, possibly decoding
it.
In Python2, this is the unicode type. In Python3 it's the str type.
"""
if isinstance(s, bytes):
# In Python2, this branch is taken for both 'str' and 'bytes'.
# In Python3, this branch... | 34353f67dedad93220cf1b567c739dccba610ecf | 49,384 |
def time_check(message):
"""
check if the duration for the quick search preference is a valid input
"""
time = 0
try:
time = int(message)
except Exception as e:
return False
if time < 1 or time > 8:
return False
return True | 745bcc45986d2b149b062d4864ae9cf8eb060901 | 49,387 |
def _same_side(pos, p, q, a, b):
"""Indicates whether the points a and b are at the same side of segment p-q"""
dx = pos[p][0] - pos[q][0]
dy = pos[p][1] - pos[q][1]
dxa = pos[a][0] - pos[p][0]
dya = pos[a][1] - pos[p][1]
dxb = pos[b][0] - pos[p][0]
dyb = pos[b][1] - pos[p][1]
return (dy... | e8635b29322a53d6928677fb9379a04440ef6e0e | 49,389 |
def apply_opcode4(code_list, opcode_loc, parameter_mode_dict):
"""When you've determined that the opcode is 4 - which means to return a
value in the location of its only parameter as an output - you can use this
function to adjust code_list.
Parameters
----------
code_list : list
The op... | 52b9e57185f7eb6fc01266b91d1cfea86f048a43 | 49,390 |
def sz_to_ind(sz, charge, nsingle):
"""
Converts :math:`S_{z}` to a list index.
Parameters
----------
sz : int
Value :math:`S_{z}` of a spin projection in the z direction.
charge : int
Value of the charge.
nsingle : int
Number of single particle states.
Returns
... | c6016a5f21f4a4e9904046260b94b1f4d6d397ba | 49,391 |
def map_activity_model(raw_activity):
""" Maps request data to the fields defined for the Activity model """
return {
'activity_id': raw_activity['key'],
'description': raw_activity['activity'],
'activity_type': raw_activity['type'],
'participants': raw_activity['participants']... | 080370bc0ddbc3c7487e0c6789612c7bc5298258 | 49,392 |
import math
def wrap_to_pi(angle):
"""
Wrap the given angle to pi: -pi <= angle <= pi.
:param angle: float, Angle to wrap in rads
:return: float, Wrapped angle
"""
while angle > math.pi:
angle -= 2 * math.pi
while angle < -math.pi:
angle += 2 * math.pi
return angle | 613c81b3404ece1326e19639bc8684cafdd4a990 | 49,394 |
def check_module( mymodule, indent='' ):
"""
Returns a string describing the version number, import path and
other administrative information contained in a given module.
:Parameters:
mymodule: Python module
The module to be checked. It must already have been imported.
... | d86b87d1b031bed13610605c1b82920b28f31c23 | 49,397 |
def get_bytes_used(current_time, process_durations):
"""
Return bytes used at given time.
>>> get_bytes_used(12, [2, 3, 4])
13
>>> get_bytes_used(14, [2, 3, 4])
14
:type current_time: int
:param current_time: Array index
:type process_durations: list
:param process_durations: ... | b87e4bc1f7050904a58ef6124beded518fda3094 | 49,400 |
def solutionClosed(n: int, p: float) -> float:
"""
A closed-form solution to solutionRecursive's recurrence relation.
Derivation:
Let q = (-2p + 1).
h[0] = 1,
h[n] = q h[n-1] + p.
By iterating,
h[1] = q + p,
h[2] = q (q + p) + p = q^2 + pq + p,
h[3] = q (q^2 + pq + p) + p = q^3 + pq^2 + pq + p,
h[n] = ... | 2f3bac0cd6981989dac4570180a215e20966dc11 | 49,407 |
def has_lower_letters(password):
"""Return True if password has at least one lower letter."""
return any(char.islower() for char in password) | d55a37e994e289886efdce6e815a430777572b97 | 49,410 |
import yaml
def load(file: str = "lang/en_US.yaml") -> dict:
"""Loads the language file and returns it"""
global lang
with open(file, encoding="utf-8") as f:
lang = yaml.safe_load(f)
return lang | a34cb9d9561b2edf1597f542a07d50b683a8fbff | 49,411 |
def extract_property_from_uri(uri: str) -> str:
"""
从property uri中提取出property name
:param uri: 如 <http://www.kg.com/kg/ontoligies/ifa#createTime>
:return: 如 'createTime'
"""
separator_idx = uri.rfind('#')
if separator_idx == -1:
raise ValueError
return uri[separator_idx + 1:] | 6c0902a954a247c7c843f15be6e3d98bf3a3721f | 49,416 |
def is_supported_value_type(value):
"""
checks if the given value type is supported.
Supported Types:
- strings
- bytes
- numbers
- tuples
- lists
- dicts
- sets
- booleans
- None
"""
if (
isinstance(value, (str, bytes... | fa9d8ae96dcde739e73d8108cfeefef8bd88451b | 49,419 |
import six
def _is_possible_token(token, token_length=6):
"""Determines if given value is acceptable as a token. Used when validating
tokens.
Currently allows only numeric tokens no longer than 6 chars.
:param token: token value to be checked
:type token: int or str
:param token_length: allo... | 186447c08cb64178e1f99fabc5523f2a92762ca5 | 49,420 |
def add_releaseyear(dataframe):
"""extract release year from release date"""
dataframe['release_year'] = dataframe['release_date'].apply(lambda x: str(x)[:4])
return dataframe | b679361ec35d99611ca64207afd24b542868f179 | 49,422 |
def interpolate_grids(data2, interpolation_scheme):
""" Interpolate all variables in data to a different grid.
Possible interpolations are:
T -> U; T -> V; U -> V; V -> U.
Parameter
---------
data : xarray.Dataset
Dataset containing 4D ('time_counter','x','y','z') and
3D... | 11d340e701a74fcd74d898501a57a192aca3ccb4 | 49,423 |
import unicodedata
def maketrans_remove(accents=("COMBINING ACUTE ACCENT", "COMBINING GRAVE ACCENT")):
""" Makes a translation for removing accents from a string. """
return str.maketrans("", "", "".join([unicodedata.lookup(a) for a in accents])) | 516114526f6d7d36b2b454cd07e40302bd7a83f7 | 49,424 |
import struct
def unpackbyte(b):
"""
Given a one-byte long byte string, returns an integer. Equivalent
to struct.unpack("B", b)
"""
(ret,) = struct.unpack("B", b)
return ret | 8d4a79bda22554604637e1ca934a85b3a6f71cdb | 49,426 |
import math
def slurm_format_memory(n):
"""Format memory in bytes for use with slurm."""
if n >= 10 * (1024 ** 3):
return "%dG" % math.ceil(n / (1024 ** 3))
if n >= 10 * (1024 ** 2):
return "%dM" % math.ceil(n / (1024 ** 2))
if n >= 10 * 1024:
return "%dK" % math.ceil(n / 1024)... | 7a454fee5754503ad30d3b0cb8e8261adac7d19f | 49,427 |
import time
from datetime import datetime
def base_record() -> dict:
"""
Return a basic record with the audit flags we use in all records.
Args:
None
Returns:
(dict): dict with audit fields populated.
"""
return {"time": time.time(), "time_str": datetime.utcnow().strftime("%Y... | 49a16ac37947ccff482a1400c054f87abfb2553b | 49,431 |
from typing import List
def reverse(data: List[int]) -> List[int]:
"""Given a list of integers, returns the same list in reverse
order.
Initialize empty List Reversed
While there are Numbers in Data:
Remove last Number in Data
Append Number to Reversed
Return Reversed
"""
... | 595a6815c1823141875d7cac7e5cdb5a2bb8b934 | 49,432 |
def get_non_hidden_fields(form):
"""
Returns all the visible fields of the form.
"""
return form.visible_fields() | a7003b12f1ca89414db299114a06bd819b3f4932 | 49,435 |
def is_namedtuple_cls(cls):
"""Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple"""
try:
if issubclass(cls, tuple):
bases = getattr(cls, "__bases__", []) or [None]
module = getattr(cls, "__module__", None)
return module == "torch.return_type... | 73698f8836b902405241df045aa01800173414c8 | 49,437 |
def sort_rat(name_list: list, ratings: list, reverse: bool = True):
"""
Sort ratings associated with names. The sort is stable.
:param name_list: The list of names to be associated with the ratings respectively
:param ratings: The list of ratings to sort
:param reverse: Descending by default. False... | cfb944d067c41f45c4e558fdeb55905de0ec01b4 | 49,438 |
def sigmoid(x):
"""
Sigmoid(x) = 1 / (1+e^-x)
"""
return 1 / (1 + (-x).exp()) | 1d60e8061e239b4de471ae4a38eb337365f498b5 | 49,441 |
def copy_df(df):
"""
DESCRIPTION
-----------
Deep copy a pandas dataframe.
PARAMETERS
----------
df : pd.DataFrame
A pandas dataframe instance
RETURNS
-------
A deep copy of a given pandas dataframe
MODIFICATIONS
-------------
Created : 4/26/19
"""
... | a130830820a9aef0c2419580a2493bb1f14111df | 49,447 |
def strip_locals(data):
"""Returns a dictionary with all keys that begin with local_ removed.
If data is a dictionary, recurses through cleaning the keys of that as well.
If data is a list, any dictionaries it contains are cleaned. Any lists it
contains are recursively handled in the same way.
"""... | 92fb36a2f3bb618b7b706dd33a3347666d0fa07e | 49,448 |
def budget_equalities(sequence:str, price_vars:list, budget_vars:list)->list:
"""
Given a picking-sequence, create symbolic equalities determining that the
total price of each agent's bundle equals the agent's budget.
Currently works only for 2 agents.
:param sequence: a string determining the pic... | ead48548766afc53e7583b65d88bfc8a10906382 | 49,450 |
def get_recipes_in_node(node):
"""Gets the name of all recipes present in the run_list of a node"""
recipes = []
for elem in node.get('run_list'):
if elem.startswith("recipe"):
recipe = elem.split('[')[1].split(']')[0]
recipes.append(recipe)
return recipes | 9d2cc0aac4b819428a5984e3852035650afeedf4 | 49,453 |
from pathlib import Path
from typing import Tuple
from datetime import datetime
def parse_dates_from_filename(file: Path) -> Tuple[datetime, datetime]:
"""
Extracts the start and end time from an existing file.
:param file:
:return: tuple of start and end time
"""
split_names = file.stem.spl... | a03212ed2df9826cc631cda9e63157d6675f82a8 | 49,456 |
def weekend_init(M, i, t):
"""
Determines days to treat as weekend using midnight threshold parameters
:param M: Model
:param i: period
:param t: tour type
:return: list of ints; either [1, 7] or [6, 7]
"""
result = []
lens = [M.lengths[k] for k in M.tt_length_x[t]]
max_len = ma... | 59e049e4d22f03e042aafa1799fe9f4e199babb4 | 49,457 |
import json
def canonical_json(o):
"""
Dumps an object as canonical JSON string.
Canonical JSON does not contain an space (except in strings) and
have all the keys sorted.
Args:
o: The object to dump.
Return:
The canonical JSON string.
"""
return json.dumps(o, sort_k... | 74a6e880987cc1aaccd19a3d68f63ecf0d9835d3 | 49,458 |
def _count_trailing_zeros(mask: int) -> int:
"""count the trailing zeros of a bit mask. Used for shifting.
Args:
mask (int): bit mask, eg 0b00111000
Returns:
int: number of trailing zeros
"""
if mask == 0:
raise ValueError("mask is all zeros")
count = 0
for i in ran... | 3f8ce2c9a5a5143715e2fe52aabdeed3ae692f17 | 49,465 |
def relative_x(xarr, yarr, *args):
"""First value in xarr is subtracted from each x
"""
return (xarr - xarr[0], yarr) + args | 8c8310b41b6de8a3d9a1846bda2e23a3d67474c8 | 49,473 |
def get_state(person):
"""Feed a person dict return the state only"""
return person['state'] | b670382b80ccd5f14d6ff2b6cd98ef28330f3c76 | 49,478 |
def kwargsGet(kwargs, key, replacement):
"""As kwargs.get but uses replacement if the value is None."""
if key not in kwargs:
return replacement
elif key in kwargs and kwargs[key] is None:
return replacement
else:
return kwargs[key] | bcb5da19757f685d6ba5b7669c474e5cbc9a13f0 | 49,479 |
def set_creo_version(client, version):
"""Set the version of Creo you are running.
This function only needs to be called once per creoson session.
This function must be called if you are doing certain functions
in Creo 7 due to deprecated config options.
Needed for functions:
familytable_r... | ddedcbb614f9fd545538804ba306b375f26bb1c8 | 49,483 |
def rank_items(items):
""" Get a rank for each item that is computed by price/weight """
for item in items:
item['rank'] = (item['price'] * 1.0) / (item['weight'] * 1.0) # I use 1.0 to get floats
return items | 2237664c7822afc76ddb6b32923e5fd98630b885 | 49,485 |
from typing import List
from typing import Dict
def get_entities_fields(entity_title: str, entities: List[str]) -> List[Dict]:
"""
Builds an entity from given entity title and entities list
Args:
entity_title (str): Title of the entity.
entities (List[str]): List of the entities.
Retu... | 201702971b3bb58285f3adf10e492a6b83f62d27 | 49,486 |
def ZhangJohnson(tokens, index, history):
"""
These features were taken from Zhang and Johnson (2003). They correspond
to the combination B+D+E+F in their paper.
Feature 'C' was not included, since
CRFsuite cannot handle 2nd order CRFS (which can use the i-1 and (i-2)th
labels) or features of t... | f63f22692a8198bba05091b8fdd62cd22f714159 | 49,488 |
import json
import requests
def download_rail_route(rr_file, verbose=False):
"""
Downloads rail route data from railrouter.sg repo.
Source: https://github.com/cheeaun/railrouter-sg
params
------
rr_file (str): filename in the data directory in the repo
verbose (bool): print downloaded rou... | 93d5d16a5b7ba1afb11fc26c3d8a9df4a301dafa | 49,490 |
import re
def valid_uniprot_ac_pattern(uniprot_ac):
"""
Checks whether Uniprot AC is formally correct according to
https://www.uniprot.org/help/accession_numbers
This is no check whether it actually exists.
:param uniprot_ac: Accession code to be checked
"""
ac_pat = "[OPQ][0-9][A-Z0-9... | 8478f998d1b8ff2b7f8343317056a9c2c0b36021 | 49,504 |
def AIC(params, log_likelihood_fun, data):
"""Calculates the AIC (akaike criterion)
Parameters
_________
params : tuple
MLE parameters for distribution
log_likelihood_fun : function
calculates the log likelihood for the desired distribution
data : array
empirical dataset to calcula... | 48f812b68fa44320f83032ec927c4d900ae44620 | 49,507 |
def five_options_around(page):
""" Create five page numbers around current page for discovery pagination. """
if page.number <= 3:
return list(range(1, min(5, page.paginator.num_pages) + 1))
elif page.number >= (page.paginator.num_pages - 2):
return list(range(max((page.paginator.num_pages -... | b65b635df3fe0abd4c5674b5b8c41b47a5630f79 | 49,515 |
import base64
def parse_authorization_header(auth_header):
""" Parse auth header and return (login, password) """
auth_str = auth_header.split(' ')[1] # Remove 'Basic ' part
auth_str = base64.b64decode(auth_str).decode() # Decode from base64
auth_str = auth_str.split(':')
return auth_str[0], aut... | cc2db762ddf7b4ce0669a81f24bce9517785350a | 49,516 |
def calc_kcorrected_properties(frequency, redshift, time):
"""
Perform k-correction
:param frequency: observer frame frequency
:param redshift: source redshift
:param time: observer frame time
:return: k-corrected frequency and source frame time
"""
time = time / (1 + redshift)
frequ... | 3a7c151a6777a0e11022e38e73ded45fc7a6706c | 49,518 |
def tokenize_options(options_from_db, option_name, option_value):
"""
This function will tokenize the string stored in database
e.g. database store the value as below
key1=value1, key2=value2, key3=value3, ....
This function will extract key and value from above string
Args:
options_fro... | 88127c5e693064ef0c3c087b18bbf213c8a6184f | 49,521 |
def check_int(num):
"""Check if arguement is integer.
Arg:
num (int): The only arguement.
Returns:
bool: The return value. True if num is indeed an integer, False otherwise.
"""
if num is not None:
try:
int(num)
return True
except ValueError:... | 556bc91dbdece439bd66f7f8fa2182d2f9683c67 | 49,522 |
def find_min_max(shape):
"""Finds min/max coordinates for a given shape and returns a tuple
of the form (minx, maxx, miny, maxy)
shape: list with points"""
minx = miny = 1000
maxx = maxy = -1000
for x, y in shape:
if x < minx:
minx = x
if x > maxx:
maxx = ... | 133bc42b9193a950869a784a5cf74b960e79eda1 | 49,523 |
def create_dict(breadcrumbs, value=None):
"""
Created a dict out of the breadcrumbs in a recursive manner.
each entry in the breadcrumb should be a valid dictionary key.
If value is None, the last string within' the breadcrumbs becomes the
final value.
:param breadcrumbs:
:param value:
:... | f2f4d2be32aa96b31703cc548edff3999bd42bd3 | 49,525 |
from typing import Dict
from typing import Any
from typing import List
async def get_sorted_agenda_items(
agenda_items: Dict[int, Dict[str, Any]]
) -> List[Dict[str, Any]]:
"""
Returns all sorted agenda items by id first and then weight, resulting in
ordered items, if some have the same weight.
""... | d661488d7e508e86a974d98ec558856f5810a3e4 | 49,527 |
def _melt_keep_index(df, value_name="value"):
""" Fully melt a dataframe keeping index, setting new index as all but `value` """
id_vars = df.index.names
return (
df.reset_index()
.melt(id_vars=id_vars, value_name=value_name)
.set_index([*id_vars, df.columns.name])
) | 94bfc7f663d62db2c36f15bc9f09a078cc978174 | 49,529 |
def findall_text(node, path):
"""Find all n.text elements from a path.
"""
return [n.text for n in node.findall(path)] | 2a40b2442e50e58a64320539153e27acfde15a8f | 49,533 |
import struct
def add(text: str) -> str:
"""
Add surrogate pairs to characters in the text. This makes the indices match how most platforms
calculate string length when formatting texts using offset-based entities.
Args:
text: The text to add surrogate pairs to.
Returns:
The text... | ffcaa7216686d2da09fae65719ed1a244a755f94 | 49,534 |
import torch
def tsn_sample(num_tokens, num_samples, training):
""" num_tokens >= num_samples
args:
num_tokens: int, num of total tokens
num_samples: int, num of sampled tokens
training: bool
returns:
indexes: tensor, sampled indexes of frames
"""
if num_samples... | 8821aa111e17c231a8ffc61afd43c9fd71e3efcc | 49,535 |
def getCacheThumbName(path):
"""
Returns a thumb cache filename.
:param path: string or unicode -- path to file
Example::
thumb = xbmc.getCacheThumbName('f:\videos\movie.avi')
"""
return str() | f3b467d542842ab011bbbf22cee86399cf80d1e6 | 49,537 |
import torch
def mae(predictions, actuals):
"""
computes mean absolute error
- predictions: predictions computed from call to model.forward(...) (Tensor)
- actuals: actual values (labels) (Tensor)
@returns:
computed mae = sum(abs(predictions - actuals)) / actual... | 00cb15d83a06427947bcabb85e48ef4ffa0d2677 | 49,539 |
def split_path(path):
"""//foo/bar/baz -> ['foo', 'bar', 'baz']"""
return [x for x in path.split('/') if x != ''] | 13376639f9597d598c2b69a844e232a7c059fc3a | 49,540 |
def s2b(s):
"""portable way to convert string to bytes. In 3.x socket.send and recv require bytes"""
return s.encode() | 92a2b6301858c80d856d80e1200f00b17e2e2327 | 49,542 |
from typing import Optional
def distribute_about_center(index: int, size: int,
max_loc: float = 1.0,
max_size: Optional[int] = None):
"""
Get the coordinate from between 0 and 1 of an item given its index in a
collection.
:param index: The 0-bas... | 4dfae63fc3b7639c08f37ece62e8afad352f8d23 | 49,543 |
import fnmatch
def _matches(file, glob):
""" check if file matches a glob"""
return fnmatch.fnmatch(file, glob) | 5a104720f76910bcb280350c440d4bea8d156b81 | 49,548 |
from datetime import datetime
import re
def get_date_from_string(date_string):
"""Transforms the specified date string into a proper datetime object. """
format_string = '%Y-%m-%dT%H:%M:%S%z'
regexp = r"(\+\d{1,2})(:)(\d{1,2})"
data = datetime \
.strptime(re.sub(regexp, r"\1\3", date_string)... | f6e6d713cecef451b226e57ddae550fccc91cae8 | 49,553 |
def shieldsio_markdown_badge_generator(badge_label=None,
badge_hover=None,
badge_link=None,
metric='count',
badge_color=None,
... | 2401eb53f0725b3594274b4b258e3dfe2c04b2d5 | 49,555 |
def convert_twos_compliment(bin_str):
""" Converts a string of binary numbers to their two's compliment integer representation """
length = len(bin_str)
if(bin_str[0] == '0'):
return int(bin_str, 2)
else:
return int(bin_str, 2) - (1 << length) | b5b62eb0f74aecd35de880d11470855e189fd713 | 49,567 |
import re
def clean_text(text):
"""去掉文本的空白字符、标点符号"""
return re.sub(r'[? 、;!,。“”?.~…,$\r\n《》——]|(<.*>)', '', text.strip()) | b5da8949a30ccf1216508b94b1088c0a3dd8f547 | 49,568 |
import random
def random_choice(bucket):
"""Safely get a random choice from a list.
If the list is zero-length, this just returns an empty string rather than
raise an exception.
Parameters:
bucket (list): A list to randomly choose from.
Returns:
str: The random choice. Blank str... | 2b781ede8fff9c2f455eebab9bf64cdf01717bee | 49,572 |
import torch
def mul(input, other, *args, **kwargs):
"""
Multiplies each element of the input ``input`` with the scalar ``other`` and
returns a new resulting tensor.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.mul(
... ttorch.tenso... | 027789f0ef85cb68e374994065a4eb19f815eb52 | 49,573 |
def add_entry_list_strings(list_string, entry):
"""
add a new entry to a list of strings, including some newlines
"""
list_string.append(entry)
list_string.append('\n')
return list_string | 49e5beafa3748adfae397c8f44d5ef6abcdaef78 | 49,574 |
def interval_intersection_width(a, b, c, d):
"""returns the width of the intersection of intervals [a,b] and [c,d]
(thinking of these as intervals on the real number line)"""
return max(0, min(b, d) - max(a, c)) | fc913c1d2510e9141ab40f4d56f4ce952f3d7d04 | 49,577 |
def filter_dict(data, keys):
"""Filter dict :data by given :keys"""
result = {}
for key in keys:
if key in data:
result[key] = data[key]
return result | 80cc8a7226c8b7929588191a48a5d3f1ce07bbbd | 49,584 |
def format_schema_errors(e):
"""Format FlaskJsonSchema validation errors"""
return {
"error": e.message,
"errors": [validation_err.message for validation_err in e.errors],
} | 9197f83adc03d031681ed097dbc96206dbdd8ac9 | 49,586 |
import hashlib
def _make_stmt_name(func):
"""
Create the prepared query name which is a string up-to 63 characters made up of
- an underscore
- the md5 hash of the <module.function> name
- an underscore
- up-to 29 characters of the function name
"""
m = hashlib.md5()
func_name = fu... | bad6f2530b7dbae2a814ab6eba030e6f0040a58f | 49,592 |
def extract_headers(response):
"""Extract relevant headers from a response into a dictionary."""
result = {}
for key in response.headers.keys():
if isinstance(key, bytes):
key = key.decode('utf-8')
value = response.headers.get(key)
if isinstance(value, bytes):
... | fde2f4d9c4e449f95c57fcc20dae3d003ec6bc9b | 49,596 |
from typing import Any
from typing import Union
def issubclass_(
cls: Any,
types: Union[type[Any], tuple[type[Any], ...]],
) -> bool:
"""Like `issubclass`, but do not raise error if value is not `type`."""
return isinstance(cls, type) and issubclass(cls, types) | f300d79f12a74ac549b6e7d66e1d865449b0eca9 | 49,599 |
def find_difference_sum_of_squares_and_square_of_sum(num: int) -> int:
"""Find the difference between sum of squares and square of sum for the first
`num` natural numbers.
Args:
num (int): First natural numbers.
Returns:
int: Difference.
"""
sum_of_squares = sum(x ** 2 for x in... | 3f0d5fbc75451f8c883d0aedc3b5a91cbffb1a77 | 49,606 |
def hello(name):
"""
Function that returns a greeting for whatever name you enter.
Usage:
>>> hello('Emiel')
'Hello, Emiel!'
"""
return ''.join(["Hello, ", name, '!']) | ffbdf2ee0869b3fd20f0cb85eff8eae748e30d28 | 49,609 |
def merge(source, destination):
"""
Merges 2 dicts recursively.
If leaves are lists, they are extended.
If leaves are ints, floats, strs, they are concatenated
into a string, if the leaves are not the same.
"""
for key, value in source.items():
if isinstance(value, dict):
... | 7f771e83c5f89fa641fa79f863f4382ac5cc0ead | 49,610 |
import re
def filter_content(content):
"""Filter content to make sure it can be built into json object
"""
filtered_content = re.sub(r'[^\x00-\x7f]', r' ', content.strip("'").
replace("\n", "\\n").
replace("\r", "").
... | 267be82061ddc3614e8eb340a0eab065dd2a7b23 | 49,615 |
def cost_req_met(card, opponent_cost):
"""Check if a card meets cost requirements"""
if card.intrigue:
if (opponent_cost - card.cost) > 0:
if (opponent_cost - card.cost) % card.intrigue == 0:
return True
else:
if card.cost == opponent_cost:
return Tr... | 8a6dfc891b338a4dadcc412b08ad1b16fdc14dce | 49,621 |
import torch
from typing import Optional
def squash(inputs: torch.Tensor, dim: Optional[int] = -1) -> torch.Tensor:
"""
Apply `squash` non-linearity to inputs
Args:
inputs (T): input tensor which is to be applied squashing
dim (int, optional): dimension to be applied squashing. Defaul... | 91ee55ecedf0a8fac4098c37d9352775db85cc3c | 49,625 |
def build_id(Z: int, A: int, state: str = "") -> int:
"""
Builds a canonical nuclide id from atomic number, atomic mass, and
and energy state.
Parameters
----------
Z : int
Atomic number.
A : int
Atomic mass.
state : str
energy state.
Returns
-------
... | 6686ac4841e6272ff7a683b4d2b267f95e1615be | 49,626 |
def read_expected_result(filename):
"""
Get the expected result from the given file. The expected outcome is the % message following after
%Expected outcome:
:param filename: The name of the file
:return: The expected result.strip().
:rtype: str
"""
result = ""
with open(filename) as... | 98522127ecfeb9a32b9bf429eab35fccd90cc849 | 49,631 |
def make_field(name, _values, **kwargs):
"""
specialization of make_parameters for parameters that define fields
(aka color inputs). In this case the values is a list of name, type pairs
where types must be one of 'rgb', 'lut', 'depth', 'value', or 'luminance'
May also be given an set of valueRanges... | f5eb045d17b75e4fb315a43c1b5611a82827fda9 | 49,642 |
import logging
def str_to_float(value: str) -> float:
"""
Return float from string or raise/log error.
:param value: The string value.
:return: The float value.
"""
try:
int_val = float(value)
return int_val
except ValueError as e:
logging.error(f"Cannot convert st... | 152be429a66cbf4062ef9b288e0d71d89b2f7352 | 49,658 |
def empty_cells(state):
"""
Each empty cell will be added into cells' list
:param state: the state of the current board
:return: a list of empty cells
"""
cells = []
for x, row in enumerate(state):
for y, cell in enumerate(row):
if cell == 0:
cells.append... | b3e3944d9dd3c699ff2bfbffbd66407e1bda7d4a | 49,659 |
def compute_best_test_losses(data, k, total_queries):
"""
Given full data from a completed nas algorithm,
output the test error of the best architecture
after every multiple of k
"""
results = []
for query in range(k, total_queries + k, k):
test_losses = [d[-1] for d in data[:query]... | 024dc22fa93c6577193da484d6de499be4ecbf00 | 49,662 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.