content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def __pydonicli_declare_args__(var_dict):
"""
Limit a dictionary, usually `locals()` to exclude modules and functions and thus contain
only key:value pairs of variables.
"""
vars_only = {}
for k, v in var_dict.items():
dtype = v.__class__.__name__
if dtype not in ['module', 'fun... | 0b38f0df8eb72993ee895a9a85c8abdc92e426cb | 665,982 |
def always_hold(state):
"""Always hold strategy."""
return 'hold' | 892d418d6a0eb729780b3b9412dbdd5903035d28 | 665,984 |
def normalize(X):
""" Normalizes the input between -0.5 and 0.5 """
return X / 255. - 0.5 | acff24b3548cfb5a7219e0620d3bb7e04010c4f2 | 665,985 |
def list_diff(listEE1, listEE2):
""" Difference between two earth engine lists
:param listEE1: one list
:param listEE2: the other list
:return: list with the values of the difference
:rtype: ee.List
"""
return listEE1.removeAll(listEE2).add(listEE2.removeAll(listEE1)).flatten() | 24ca014f66163c02c47f8bd67cf0e09f4ed6534e | 665,988 |
def iteration(printer, ast):
"""Prints "for (name : type) {body}"."""
name_str = ast["name"]
type_str = printer.ast_to_string(ast["type"])
body_str = printer.ast_to_string(ast["body"])
return f'for ({name_str} : {type_str}) {body_str}' | 27390871e7b39424b1fd763ded31b12578352c07 | 665,993 |
from pathlib import Path
def yaml_path_to_html_path(yaml_path):
"""Converts a yaml filepath to the corresponding html filepath.
For instance: converts 'newsletters/yaml/week_032.yml' to:
'newsletters/html/week_032.html'.
Args:
yaml_path (pathlib.Path): the yaml path to ... | 1c32811b363effa339c5f5a443972bca74db8bec | 665,994 |
import time
import math
def run_time(t1, name="", is_print=True):
"""Performance test function, test run time.
:param t1: Set the time of the breakpoint
:param name: Set the name of the print
:param is_print: True, Whether to print
:return: Printed string content
>>> t1 = time.time()
# t... | 5a25cfb969a09ca66273f960e8dae8583ef29da2 | 665,996 |
import math
def factors(n):
""" Returns the list of n's factors
--param
n : int
--return
list
"""
if n < 1:
return []
elif n in {1,2,3}:
temp = set()
temp.add(1)
temp.add(n)
return list(temp)
else:
temp = set()
temp.add(1)
... | 47d8fce4c7d736badb769c94455fe5df8e021bf3 | 665,999 |
import json
def _schema(**vals):
"""Default schema."""
data = dict(
id='a-b-c-d-e',
date="2016-08-23 15:03:49.178000",
layout="grid",
name="testlayout",
modules=[],
)
data.update(**vals)
return json.dumps(data) | 7f3c768f95a3a32cf803d2621f112951eebc98b2 | 666,001 |
def temp_cache_pos_file(temp_folder, temp_cache_pos_filename):
"""Create a file path to for the cached part-of-speech (POS) file."""
return temp_folder.join(temp_cache_pos_filename) | 29672c9d7bf84cfcf76f15ff719ae197ee9d9d71 | 666,003 |
import requests
def get_interlanguage_links(page_title, endpoint='en.wikipedia.org/w/api.php', redirects=1):
"""The function accepts a page_title and returns a dictionary containing
the title of the page in its other languages
page_title - a string with the title of the page on Wikipedia
endp... | cd96b0a0962a8edf4f28958a4f7b850bbb2e0f74 | 666,006 |
def in_seconds(days=0, hours=0, minutes=0, seconds=0):
"""
Tiny helper that is similar to the timedelta API that turns the keyword arguments into
seconds. Most useful for calculating the number of seconds relative to an epoch.
>>> in_seconds()
0
>>> in_seconds(hours=1.5)
5400
>>> in_sec... | cdd9878ff99448717ea8eb36452ed1536d64fe44 | 666,008 |
from typing import List
from typing import Optional
def response_detect_blocking_messages(
text: str, blocking_messages: List[str]
) -> Optional[str]:
"""Method to check whether any of blocking messages appears in the response text.
:param text: response text
:param blocking_messages: list of pot... | dd8c1b5fc7761fcfee066671da1415d7bb4aeab0 | 666,016 |
import time
def TimeoutExpired(epoch, timeout, _time_fn=time.time):
"""Checks whether a timeout has expired.
"""
return _time_fn() > (epoch + timeout) | 8d667b9cbf31adefba826d0a59359bdb17211eb9 | 666,019 |
def get_bool(value: str) -> bool:
"""Get boolean from string."""
if value.upper() in ["1", "T", "TRUE"]:
return True
if value.upper() in ["0", "F", "FALSE"]:
return False
raise ValueError(f"Unable to convert {value} to boolean.") | 35d6cbe90f04a5fd9942a51c8ea3c412b38250eb | 666,020 |
def linne() -> list:
"""
Returns the linnean Taxonomy:
species,
genus,
family,
order,
class,
phylum,
kingdom
"""
return ['species',
'genus',
'family',
'order',
'class',
'phylum',
'kingdom'] | def4cf538af94a73cd6e369eb7921988e7a91ff6 | 666,026 |
def initialize_hyper_parameters(layer_acts, learning_rate):
"""
Initialize parameters for different levels of the network
Arguments:
layer_acts -- python array (list) containing the activation functions of each layer in the network
learning_rate -- float value used as constant for gradient descent
... | 110e6cf603e241028e291fa8cb4552e124f4a1e5 | 666,034 |
import requests
def get_token(username: str,
pw: str,
filehost: str = "securefileshare.wales.nhs.uk") -> dict:
"""
Fetch Bearer token for securefileshare
Parameters
----------
username: str
pw: str
filehost: str
Returns
-------
dict
Diction... | 98593425daaa606c938e63d488ebcd72a314d57d | 666,036 |
def resolve_locations(ctx, strategy, d):
"""Resolve $(location) references in the values of a dictionary.
Args:
ctx: the 'ctx' argument of the rule implementation function
strategy: a struct with an 'as_path(string) -> string' function
d: {string: string} dictionary; values may contain $(loca... | ff0f4c83b44e0a6b7430b6bea39ee60e959e1fe8 | 666,041 |
def avg(lst: list) -> float:
"""return the average of a list.
Preconditions:
- all items in lst are ins or floats.
"""
return sum(lst) / len(lst) | a413a71e47301095615f05d629f273e00e1fbc1b | 666,042 |
def _Boolean(value):
"""Returns a string indication whether a value is true ("truthy").
Args:
value: Any value.
Returns:
String indicating whether the value is true.
"""
return '*' if value else '-' | 32fc213e9ecb13f55576522037ea85c65e863a5d | 666,044 |
def _intsqrt(v):
"""Compute int squareroot floor"""
c = 0
while c**2 <= v:
c += 1
return c - 1 | 5368eac7afe25fa6743fd78b999d9dcfe4b63432 | 666,045 |
def and_join(strings):
"""Join the given ``strings`` by commas with last `' and '` conjuction.
>>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])
'Korea, Japan, China, and Taiwan'
:param strings: a list of words to join
:type string: :class:`collections.abc.Sequence`
:returns: a joined string... | 4b9a411738a662897095a055cd9037ca1a3a0c98 | 666,052 |
def get_file_name(file_name: str, at: int = -1, split: str = '/') -> str:
"""
Extracts fileName from a file.
Example:
get_file_name('/a/b/file_dir/my_file.csv') -> 'my_file'
get_file_name('/a/b/file_dir/my_file.csv',at=-2) -> 'file_dir'
:param file_name:
:param at: fetch name after... | cfca089f4a652fa922c85e662bbde2238a995f32 | 666,057 |
def limit_issues(issues, limit_len=100000):
"""Limit the number of issues saved in our DB."""
sorted_issues = sorted(issues, key=lambda x: x['updated_at'], reverse=True)
return sorted_issues[:limit_len] | 1dcd4461e9ca78605bf03e7a0fd1635a49bdd69a | 666,058 |
import glob
def expand_file_pattern(pattern):
"""
use glob to find all files matching the pattern
Parameters
----------
pattern : str
unix bash shell like search pattern
Returns
-------
list
list of file names matching the pattern
"""
assert pattern is... | c4e70527163f2167265693b9497deb238a39ea85 | 666,059 |
import itertools
def all_neighbors(graph, node):
""" Returns all of the neighbors of a node in the graph.
If the graph is directed returns predecessors as well as successors.
Parameters
----------
graph : NetworkX graph
Graph to find neighbors.
node : node
The node whose nei... | fed95fed1771194df42bae7387dcb318ba7aea31 | 666,061 |
def dashes(i=1, max_n=12, width=1):
"""
Dashes for matplotlib.
Parameters
----------
i : int, optional
Number of dots. The default is 1.
max_n : int, optional
Maximal Number of dots. The default is 12.
width : float, optional
Linewidth. The default is 1.
Returns... | 2cffaa4448d7d3d4765dfb83f644fcf2ed6344e5 | 666,062 |
def timeseries_train_test_split(X, y, test_size):
"""
Perform train-test split with respect to time series structure
"""
# get the index after which test set starts
test_index = int(len(X)*(1-test_size))
X_train = X.iloc[:test_index]
y_train = y.iloc[:test_index]
X_test = X... | f066cde3fc58de00b6d592d406b94e98beb0cbeb | 666,063 |
def fontawesome(icon_name, size=""):
"""
Generate fontawesome syntax for HTML.
Usage:
{% fontawesome "iconname" %}
{% fontawesome "iconname" "size" %}
Size values are: lg, 2x, 3x, 4x, 5x
"""
if len(size) > 0:
size = "fa-%s" % size
return '<i class="fa fa-%s %s"></i... | af0ab4c5264a2e6117ca3b94d096862f5e401876 | 666,065 |
def ask_confirmation(message, yes = 'y', no = 'n', default = False):
"""
Ask user to confirm something. Ask again if answer other than expected.
Arguments:
- message (string): message to print (e.g. "Are you sure?")
- yes (string): expected value if user confirms
- no (s... | bd66b526f1efe8f648b3d204e7c791a74b4324b7 | 666,066 |
def match_substructures(mol, substructures):
"""
This function checks if a molecule contains any of the provided substructures.
Parameters
----------
mol : Chem.rdchem.Mol
An RDKit molecule.
substructures: list
List of substructures as RDKit molecules.
Returns
-------
... | 070a3d1dfdce75f910329ecfde1bedc898c1be65 | 666,068 |
def _to_time(integ, frac, n=32):
"""Return a timestamp from an integral and fractional part.
Parameters:
integ -- integral part
frac -- fractional part
n -- number of bits of the fractional part
Retuns:
timestamp
"""
return integ + float(frac)/2**n | b558806f174f5305bf1c1b0c20c2a5fab8331037 | 666,071 |
import math
def negative_binomial(x, k, p):
"""
Evaluate the negative binomial distribution b*(x; k, p) as defined in the textbook.
Equivalent to finding the probability of coin flip x to be the k-th head when the
probability of getting a head on any one coin flip is p.
Found with the equation (... | c4b2d923cafdb95142cafe40c1f4248278f06323 | 666,073 |
import hashlib
def sha224hash(text):
"""Takes in text and returns the sha224 hash"""
hash = hashlib.sha224()
hash.update(text.encode("utf-8"))
return hash.hexdigest() | 7667a4ff9571505c53015f89d392f88819dc6e73 | 666,079 |
def get_alias_names(meta_data):
"""Returns the list of configured alias names."""
if len(meta_data) <= 0 or 'alias' not in meta_data:
return None
aliases = meta_data['alias']
if isinstance(aliases, list):
# If the alias meta data is a list, ensure that they're strings
return list... | b00ba31d9c60c001f950a2a3c4d7a0d8e863d7f9 | 666,081 |
def simplify(seq, drop_zero):
"""
Combine coefficients of terms with the same variable and optionally drop
zero weights and sum up terms without a variable.
"""
elements = []
seen = {}
rhs = 0
for co, var in seq:
if co == 0:
continue
if var is None:
... | da5a4aef7e483b31996cfb9d5381f1e056b4b130 | 666,082 |
import json
def read_json(filename: str):
"""Read a json file and return data as a dict object"""
print('Reading json file ' + filename + '...')
f = open(filename, 'r')
Instance = json.load(f)
f.close()
print('Done')
return Instance | d5327b4a34e9c5635fd51ad5d45c47a0d4ab2f46 | 666,086 |
def Porcentagem(p, v):
"""
Retorna a porcentagem de um valor
p: porcento
v: valor
"""
return p * v / 100 | f7bc1ffd866c1bcdf3143a4d640fb2cde21c20d5 | 666,088 |
def ImportModule(moduleName):
"""
A convenience method for importing the given module name.
@param moduleName: the name of the module to attempt to import
@type moduleName: C{str}
@return: A reference to the module object that can be queried, introspected,
or instantiated.
@rtype: C{module}... | 37c2ee934e5220bc74bfac67843afc7c76e84e04 | 666,093 |
from typing import Optional
from typing import List
from typing import Tuple
def is_valid_atom_index(index: int,
coordinates: Optional[dict] = None,
existing_indices: Optional[List[int]] = None,
) -> Tuple[bool, str]:
"""
Check whether an... | 311b106f00994f617b953d6b630f8f3515f8dd8b | 666,099 |
from operator import add
def top_five_urls(rdd):
"""
Return a rdd only with the top 5 url's
with more requests by descending order.
return type: pyspark.rdd.PipelinedRDD
"""
urls_rdd = rdd.map(lambda line: line.split('"')[1].split(' ')[1])
count_rdd = urls_rdd.map(lambda url... | d0a8826e47dc16026acd9568b91038fe11023749 | 666,100 |
def str_bool(s: str) -> bool:
"""Converts string ('0' or '1') to boolean"""
return s == '1' | 740299a29eca3f851ad3aec5f836c3db5c98a2c5 | 666,101 |
def encode(self, inputs, label):
""" Encodes the input into the latent space."""
return self.sess.run(self.z_mean, feed_dict={self.x: inputs, self.y: label}) | ab51527090212251a803e7a0406c790ad2224a4a | 666,107 |
import torch
from typing import Tuple
def get_pair_embedding(
pair_info: torch.Tensor,
embedding: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
We are working with N pairs, the k'th pair is (a_k,b_k).
Args:
- pair_info: (N,6) array representing (bi,hi,wi, bj,hj,wj)
... | dc0af39d581980b73b3dc46cf881e8a1439063fa | 666,112 |
def TabSpacer(number_spaces, string):
"""Configuration indentation utility function."""
blank_space = ' '
return (blank_space * number_spaces) + string | d85e013daa7da875bfe2ca9805dacd13fe1169d0 | 666,116 |
def iroot(a, b):
"""Function to calculate a-th integer root from b. Example: iroot(2, 4) == 2
Parameters:
a: int
Root power
b: int
Number to calculate root from
Returns:
result: int
Integer a-th root of b
"""
if b < 2:
... | 6704b7d0b663008c5a4e9d235d90aabcc9ca063d | 666,120 |
def get_values_matching_key(doc, key):
"""
Returns iterator of values in 'doc' with the matching 'key'.
"""
def _get_values(doc, key):
if doc is not None:
if key in doc:
yield doc[key]
for z in doc.items():
v = z[1]
if isi... | da7beea651f2e8ffa461c9f60d577628815d323d | 666,121 |
import ast
def redis_hgetall(duthost, db_id, key):
"""
Get all field name and values for a given key in given redis dataabse
:param duthost: DUT host object
:param db_id: ID of redis database
:param key: Redis Key
:return: A dictionary, key is field name, value is field value
"""
cmd =... | a083912cfa5b635a4a96fe23ac6b0f7df49cd9a0 | 666,124 |
def angle2NDE(angle):
""" Converts an angle in degrees from an East due North coordinate system to a North due East coordinate system
Calling this function again will convert it back, since: x = angle2NDE(angle2NDE(x))
Arguments:
angle: [float] angle to be converted in degrees.
Returns:
... | 9618279d98bd21c3a4b7caf159048c18b1946d80 | 666,125 |
def get_hostlist_by_range(hoststring, prefix='', width=0):
"""Convert string with host IDs into list of hosts.
Example: Cobalt RM would have host template as 'nid%05d'
get_hostlist_by_range('1-3,5', prefix='nid', width=5) =>
['nid00001', 'nid00002', 'nid00003', 'nid00005']
"... | 53b6e0464acc635a3cb76962ec3ff71bd566ac1e | 666,126 |
def fib(n):
"""
Finding the Fibonacci sequence with seeds of 0 and 1
The sequence is 0,1,1,2,3,5,8,13,..., where
the recursive relation is fib(n) = fib(n-1) + fib(n-2)
:param n: the index, starting from 0
:return: the sequence
"""
n = n//1 if n>=1 else 0 # ensure n is non-negative integer
if n>1:
... | e54a8103994d25ff404d2f1b43c3d1134af8375a | 666,127 |
def delta_encode_values(df, total, scale=100):
"""Convert a dataframe from acres to delta-encoded integer scalar values,
where original values are first scaled.
This can be used to express percent where scale = 100.
Values are packed into a caret-delimited string with 0 values omitted, e.g.,
'<bas... | 2e44253e0aadad4f6525a5578f40c855d61cde22 | 666,128 |
def celsius2kelvin(celsius):
"""
Convert temperature in degrees Celsius to degrees Kelvin.
:param celsius: Degrees Celsius
:return: Degrees Kelvin
:rtype: float
"""
return celsius + 273.15 | 4826bbdee8e50356649a1adb7294ec12824186d3 | 666,129 |
def create_variable(df, name, label, label_map, default_value=0):
"""
Create a new variable (column) in the specified dataframe. The label of
this variable will be appended the global label map.
Parameters
----------
df : pandas DataFrame
dataframe to add variable/column to
name... | e64bb8f8393b75a1c981b4db7d026691c924212f | 666,133 |
from typing import List
def parse_dns(dns: bytes) -> List[bytes]:
"""Parse the output of grab_dns, returning a list of parsed values that we would like to search.
:param dns: Output of grab_dns
:type dns: bytes
:return: A list of parsed values (Record Name, CNAME, A (HOST))
:rtype: List[bytes]
... | 35808143534d210013e4dec5f52917dcc6ca2ad5 | 666,134 |
import re
def normalise(s):
"""
Tokenize on parenthesis, punctuation, spaces and American units followed by a slash.
We sometimes give American units and metric units for baking recipes. For example:
* 2 tablespoons/30 mililiters milk or cream
* 2 1/2 cups/300 grams all-purpose flour
... | 4d91af491dda8a08523ad4b8c467a15c07248cd6 | 666,137 |
import re
def fix_empty_methods(source):
"""
Appends 'pass' to empty methods/functions (i.e. where there was nothing but
a docstring before we removed it =).
Example:
.. code-block:: python
# Note: This triple-single-quote inside a triple-double-quote is also a
# pyminifier self... | d49181f65e76bda84ffd9b71187944a728d0f2f2 | 666,138 |
import collections
def _sort_almost_sorted(almost_sorted_deque, key):
"""
Sort a deque like that where only the first element is potentially unsorted and should probably be last and the rest
of the deque is sorted in descending order.
:param collections.deque almost_sorted_deque: The deque of size n... | 93d282f6cc0fd4df16480b0ebbc33d132bd3cc0e | 666,140 |
def poi_vs_all(true_pep_iz, prep_result):
"""
true_pep_iz refers to the full set of all peptides.
This function returns remapped values of true_pep_iz such that
each peptide that is from a POI keeps its true_pep_i
whereas all other peptides are remapped to class 0, ie "OTHER"
"""
df = prep... | 50a979f8f6304d0869eaec1bfe19f5f4d0e2f2ef | 666,146 |
import json
def dumps( data ):
"""Serializes the incoming object as a json string"""
return json.dumps( data ) | 9f0e96cc80387909918a9aca97f5ca3bb3b41b6d | 666,153 |
def load(fl, normalise=False):
"""
load airfoil
args:
fl (str): filename
kwargs:
normalise (bool): flag determining whether the airfoil is normalised to
unit length
returns:
[(x,y),...] airfoil point coordinates
"""
d = []
print("loading airfoil %s" % ... | 4032a703a66465799aadfa08dd7888682b0a767d | 666,156 |
def list_uniq(seq, key=None):
"""
Removes duplicate elements from a list while preserving the order of the rest.
>>> uniq([9,0,2,1,0])
[9, 0, 2, 1]
The value of the optional `key` parameter should be a function that
takes a single argument and returns a key to test the uniqueness.
... | d9385dad029663fb2c8dce0d5c9b488a6f39ae5f | 666,165 |
def neighbor_equality(w1, w2):
"""
Test if the neighbor sets are equal between two weights objects
Parameters
----------
w1 : W
instance of spatial weights class W
w2 : W
instance of spatial weights class W
Returns
-------
Boolean
Notes
-----
Only se... | 6465f06151d8bf3505cc6f9fe1e9e3b7319e7878 | 666,166 |
def svg_from_file(pathname):
""" Read SVG string from a file """
f = open(pathname, 'r')
svg = f.read()
f.close()
return(svg) | 136b560af57f2d4b0f533cbfb18b7160c678f103 | 666,177 |
def atom_to_csv(self):
"""Return Atom as a comma-separated string of its properties."""
return f"{self.chain},{self.atomid},{self.resid},{self.icode},{self.name}" | 89af5589412eae124a1b1191c8934482d7cfc989 | 666,179 |
def drag_force(c_d,A,rho,v):
"""
Calculate drag force given c_d,A,rho,v:
rho -> density of fluid
A -> Frontal area
c_d -> Drag coefficient
v -> Velocity of bicycle
"""
return 0.5*c_d*rho*A*v**2 | f31caac5b43ad0387ededb225effa31b6f06b86c | 666,181 |
import time
def try_until(func, count=1, sleep=0.5):
"""
Tries to execute the specified function a number of times.
@param func callable to execute
@param count number of times to try (default 1)
@param sleep seconds to sleep after failed attempts, if any
(defaul... | 823cdddc6fed72ae4a63dd77b7eca1ace597f927 | 666,182 |
def docker_mem_used(container_id):
"""
Bytes of memory used from the docker container.
Note: If you have problems with this command you have to enable memory control group.
For this you have to add the following kernel parameters: `cgroup_enable=memory swapaccount=1`.
See: https://docs.docker.com/e... | a58bde5871894d5f52bd230ad070fa0396df6d34 | 666,183 |
import six
def create_mashup_dict(image_meta):
"""
Returns a dictionary-like mashup of the image core properties
and the image custom properties from given image metadata.
:param image_meta: metadata of image with core and custom properties
"""
def get_items():
for key, value in six.... | 976e1f92d1dcac4a8bdc2b03c799d76fbd9c146f | 666,184 |
def get_wind_degrees(value):
"""
Returns the wind direction in degrees from a dict containing degrees and direction
"""
try:
new_value = float(value['degrees'])
except (TypeError, KeyError):
return value
return new_value | 07db665a7ed31c7dcf6a5c91558ab7dd966f03f5 | 666,189 |
def strip_hash_bookmark_from_url(url):
"""Strip the hash bookmark from a string url"""
return (url or '').split('#')[0] | c31f569b147d4e9bd74e932856b1a2e168e05bb3 | 666,194 |
def get_adjacents(i, j, matrix):
"""given a matrix and a couple of indices finds indexes of points
adjacent to given input
Args:
i ([int]): [index of row]
j ([int]): [index of column]
matrix ([numpy array]): [matrix of measurements]
Returns:
[list]: [list of adjacent in... | 4223d55397d4a4697f4ed08b55674279dfb2dfaa | 666,196 |
from typing import Optional
def get_fullname(namespace: Optional[str], name: str) -> str:
"""
Constructs a fullname from a namespace and a name.
"""
if namespace:
return namespace + "." + name
else:
return name | 5bc82836186089368eeeea66c206d8f09b006ba6 | 666,198 |
def to_sense_key(syn):
"""
Returns the sense key for the given synset.
@param syn - Synset
@return Corresponding sense key as string
"""
return syn.lemmas()[0].key() | 06b34bef01c72122dc4e24261d57da5a32de9490 | 666,200 |
def generate_exploit() -> str:
"""This function returns the payload that will print `hacked`.
Our payload should cause `run.py` to print out `hacked`.
Warnings:
1. `run.py` should print `hacked`, and the testing will be case *sensitive*
2. This time, `run.py` must NOT crash
Returns:
... | 2ae39c8aeac5f113f0c69082539a83acc3c5b35c | 666,201 |
import re
def parse_logs(response):
""" Parses the travis log.
:params response: text from the ci log
:return: dict that contains error information
"""
start = "FAILURE: Build failed with an exception."
end = "BUILD FAILED"
# capture the substring between two strings
capture_error ... | 4f3ac8561401d14bce51600d20adc6130479bb3a | 666,206 |
def can_import(name):
"""Attempt to __import__ the specified package/module, returning
True when succeeding, otherwise False"""
try:
__import__(name)
return True
except ImportError:
return False | 7b02767184e73935c92b9e0e15769bb73ac24d95 | 666,209 |
def _find(root: dict, word: str) -> dict:
"""Find the node after following the path in a trie given by {word}.
:arg root: Root of the trie.
:arg word: A word.
:returns: The node if found, {} otherwise.
"""
node = root
for char in word:
if char not in node:
return {}
... | c8fc53ab5ef855822086a1db258521e4c351768a | 666,212 |
import re
def all_matches(iterable, pattern):
"""
Get all of the items that match a pattern.
Args:
iterable (Iterable[str])
pattern (str or regular expression)
Returns:
List[str]
"""
result = []
for string in iterable:
match = re.search(pattern, string)
... | a30bde68c282d1a47d7a76615eb722b50ac398b9 | 666,213 |
def diff(a1, a2, shift):
"""
Compute the diff after shifting array a2 by shift
"""
if len(a1) != len(a2):
raise ValueError("Diff, input arrays must be same length, got {} and {}".format(len(a1), len(a2)))
return a1[:(-shift)] - a2[shift:] | 2fd47e43e6b41c9f606378d370f04308e8db3883 | 666,217 |
from typing import Optional
import random
def make_monster_name(is_titan: Optional[bool] = False) -> str:
"""
Generate a normal boss's name
Parameters
----------
is_titan : bool
If the boss is a titan
Returns
-------
str
The name of the boss
"""
# Boss is a t... | 9faf5b2835cc73523c840f610490e65f73363a93 | 666,218 |
def string_concatenator(string1, string2):
"""Combines strings together by adding them and returning the combination as an output.
Parameters
----------
string1 : string
String that will be added to another string.
string2 : string
String that will be added to anot... | a721b3bcad25d4b602fbf4ec10d2bc49a07fe533 | 666,222 |
def first_choice_counts(A,P):
"""
Return list giving first-choice counts, in decreasing order by count
"""
count = { }
for a in A:
count[a] = 0
for ballot in P:
if len(ballot)>0:
a = ballot[0]
count[a] += P[ballot]
L = [ (count[a],a) for a in A ]
L... | 986c501fc9ebc57125ae355e679a0244adb4c4cf | 666,223 |
import itertools
def flatten(param_groups):
""" Flattens out a pair of list of lists representing a param_group into
a single list
:param param_groups: The group to flatten
:return: The flattened list
"""
return itertools.chain(*param_groups) | 90c6eb3858a6de266dee80c3eea1221652e2fab5 | 666,226 |
from typing import Tuple
def split_markdown_front_matter(text: str) -> Tuple[str, str]:
"""
Return a tuple of (front matter, markdown body) strings split from a
``text`` string. Each can be an empty string. This is used when security
advisories are provided in this format.
"""
lines = text.spl... | 9a3260368509bde504aed43d42ccd1c2fb390acf | 666,228 |
def check_input(s):
"""
This function checks the input is in correct format or not
:param s: The input string of each row
:return: (bool) If the input format is correct
"""
for i in range(len(s)):
if i % 2 == 1 and s[i] != ' ':
return True
elif len(s) != 7:
return True
elif i % 2 == 0 and s[i].isalpha... | d03ee2e88e2a1db0abbc3e05387f2532ab260245 | 666,230 |
def season(month_number):
"""
Возвращает название сезона по номеру месяца.
:param month_number: номер месяца.
:return: строка с названием сезона.
"""
if month_number in [1, 2, 12]:
return 'Winter'
elif 3 <= month_number <= 5:
return 'Spring'
elif 6 <= month_number <= 8:
... | e629a5c816b424a1ee0daa63102ca54089276f09 | 666,235 |
def decimal_to_string(fnum, no_dec=0):
"""
Convert a decimal to a string with no_dec decimal places
"""
res = ''
if no_dec == 0:
res = str(int(fnum))
else:
res = str(round(fnum, no_dec))
return res | 720708e81c1893beef997db7ec6ff710fd1a4f4a | 666,238 |
import six
def str2list(s):
"""Returns the string `s` as a list of lines, split by \n"""
return s.strip().split('\n') if isinstance(s, six.string_types) else s | 8bfae807d3c220c4cf71e39340205936454fd4ed | 666,240 |
def default_mutation_stength(param):
"""
Returns the default mutation strength for a parameter.
Based on http://www.iue.tuwien.ac.at/phd/heitzinger/node27.html.
"""
return (param.upper_bound - param.lower_bound) / 10 | d3288ae975a4803ae09ffb3f17439c56b6cf2230 | 666,242 |
def parse_bucket_blob_from_gs_link(path):
"""Utility to split a google storage path into bucket + blob name.
Args:
path (str): A string of google cloud storage path (must have gs:// prefix)
Returns:
(str, str): A tuple of (bucket name, blob name)
"""
if not path.startswith('gs://')... | 72a4ab2ce199fc754fd5e485a3fe149f312d4e04 | 666,243 |
from pathlib import Path
import pickle
def my_piclke_dump(var, file_name):
"""
This function saves 'var' in a pickle file with the name 'file_name'.
We use the folder 'Pickles' to save all the pickles.
Example:
file_name = "test"
x = 4
var = x
my_piclke_dump(var, file_name)
:para... | 26c8715dc92b963aac54f09ee15d7f77d1dc49a5 | 666,244 |
def cumret(ts):
"""Calculate cumulative returns for input time series
:ts: Time series
:returns: Cumulative returns
"""
return ((ts + 1).cumprod() - 1) * 100 | a7105ff05af17b101324e1dc3fd67ec63d170d9b | 666,248 |
def get_input_nodes(node):
"""
Get input nodes of node.
Args:
node (NodeGraphQt.BaseNode).
Returns:
list[NodeGraphQt.BaseNode].
"""
nodes = {}
for p in node.input_ports():
for cp in p.connected_ports():
n = cp.node()
nodes[n.id] = n
retur... | 42855ff941851f1b18bf025bb5b2005a0e0516f3 | 666,249 |
def cut_to_pages(h, pgsz):
"""Cut each data block to pages.
Args:
h (list): response from `asaloader.ihex.padding_space`.
pgsz (int): page size, e.g. 256, 512.
Returns:
list: data pages
"""
res = []
for sect in h:
sect_addr = sect['address']
sect... | 73ac1000784f814f3ed70ad53f38359ffa65d150 | 666,250 |
def rankine2celcius(R):
"""
Convert Rankine Temperature to Celcius
:param R: Temperature in Rankine
:return: Temperature in Celcius
"""
return (R - 491.67) * 5.0 / 9 | 59ffd05620dd5781bb8f5d53dc67936ae7bdb37c | 666,253 |
def apply_diagnostic_inflation(cov_pop_burden_df, param_df, index):
"""Inflates the target_pop in df
Inputs:
cov_pop_burden_df - a df with the column 'target_pop'
param_df - a df of parameters, must contain the columns 'inflation_factor'
index - a string that is one of the i... | 0ae01d78b7c8d7747b80cdf9ec6fa731769e0b84 | 666,258 |
def get_argnames(func):
"""Get the argument names from a function."""
# Get all positional arguments in __init__, including named
# and named optional arguments. `co_varnames` stores all argument
# names (including local variable names) in order, starting with
# function arguments, so only grab `co... | 1b1e030f85d29d724c25f4770e4214f9f17cb9fc | 666,259 |
def convert_listlike_cols_to_str(df, list_cols, convert_nan=False, nanreplacement = "[]"):
""" Convert listlike values in pandas DataFrame to stringlists.
Writing a DataFrame to excel and csv raises errors due to presence of listlike or arraylike data.
Here, all listlike and arraylike data is converted to ... | c932ec05038d9942cefeda85de51f6359fe67e97 | 666,260 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.