content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_bin_number(bins, val):
"""
Gets the bin number of a value in a binspace
Parameters
==========
bins :: list
The bin edges
val :: real number
The value to get the bin number for
Returns
=======
The bin number of the test value. -1 if it is not within the binspace
"""
for i in range(l... | 76175c23e3da6697e2cbfb80d3fa7fe85a8abed3 | 671,893 |
def first_vs_rest(first_func, rest_func=lambda w: w):
"""Supply one or two transformer functions for the first and rest of
words respectively.
Leave second argument out if you want all but the first word to be passed
through unchanged.
Set first argument to None if you want the first word to be pas... | 9bcf193e300a3838ecd4a3551fce24341431bb20 | 671,895 |
def make_event_cname(ev_spec) -> str:
"""Create a transition connector name based on an event name and an optional signature"""
if not ev_spec.signature:
return ev_spec.name
else:
return ev_spec.name + '( ' + ', '.join( [f'{p.name}:{p.type}' for p in ev_spec.signature]) + ' )' | ca291484d972b9cda4d1f40db3045e3c9075e7a4 | 671,896 |
def happy_color(health):
"""Return pyplot color for health percentage."""
if health > 0.8:
return 'g'
if health > 0.6:
return 'y'
return 'r' | 8abb43423f9baa91790bfa69be8d4b850108c112 | 671,899 |
def remaining_evals(cur_step, epoch, train_steps_per_epoch, evals_per_epoch):
"""Helper function to calculate remaining evaluations for a trainer.
Args:
cur_step: current step of the supervised trainer
epoch: current epoch of the RL trainer
train_steps_per_epoch: supervised trainer steps per RL epoch
... | b897af4f78e9a6946326f28392834d2d9e085471 | 671,900 |
import click
def serror(message, *args, **kwargs):
"""Print a styled error message."""
if args or kwargs:
message = message.format(*args, **kwargs)
return click.secho(message, fg='white', bg='red', bold=True) | e0ea22165a86345b019987b5d4a196b11e8c4b01 | 671,904 |
def check_script(script):
""" Checks if a given string is a script (hash160) (or at least if it is formatted as if it is).
:param script: Script to be checked.
:type script: hex str
:return: True if the signatures matches the format, raise exception otherwise.
:rtype: bool
"""
if not isins... | e7d8f5227a9e9d399b591736d7c3f04a371d02ed | 671,906 |
def unquote_option_value(value):
"""Remove quotes from a string."""
if len(value) > 1 and value[0] in ('"', "'") and value[0] == value[-1]:
return value[1:-1]
return value | 089e8ca9006004703e649684af6f0bd1a1cc74ca | 671,908 |
def bisect_find(n, f, *args, **kw):
"""
Find largest `k` for which `f(k)` is true.
The k is integer in range 1 <= k <= n. If there is no `k` for which
`f(k)` is true, then return `0`.
:param n: Range for `k`, so :math:`1 <= k <= n`.
:param f: Invariant function accepting `k`.
:param *args... | 7279788d8e4edb8f4e4f49becd26652cd477fa24 | 671,911 |
import re
def lineMatching(regexStr, lines):
""" Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified regex string, or None if no match was found
Note: if you have a pre-compiled regex pattern, use lineMatchingPattern() ins... | 5587f06878abc663fd44908630d97450e6dc1243 | 671,912 |
import smtplib
def connect(smtp_server, smtp_port, email, password):
"""
Connect to the SMTP server to send emails.
:param smtp_server: Hostname or IP Address of the SMTP server
:param smtp_port: Port number of the SMTP server.
:param email: Valid email address for authentication.
:param pass... | 34ac16b58b86f0e99709e80829114c6753fbc1d3 | 671,913 |
def rgb_hex_to_rgb_list(hex_string):
"""Return an RGB color value list from a hex color string."""
return [int(hex_string[i:i + len(hex_string) // 3], 16)
for i in range(0,
len(hex_string),
len(hex_string) // 3)] | 310bf3de778d6557729132f89e7888296d21da18 | 671,914 |
import re
def get_latest_hub_per_task(hub_module_paths):
"""Get latest hub module for each task.
The hub module path should match format ".*/hub/[0-9]*/module/.*".
Example usage:
get_latest_hub_per_task(expand_glob(["/cns/el-d/home/dune/representation/"
"xzhai/1899361/*... | 17d5f763ca3837dd6cf1fe1dff5b265a64dfa976 | 671,915 |
import time
def search_updated_intrusion_prevention_rules(api, configuration, api_version, api_exception, num_days):
""" Searches for Intrusion Prevention rules that have been updated within a specific number of days.
:param api: The Deep Security API modules.
:param configuration: Configuration object t... | ee29d5e0fd59b9dfa188fdbcbbc2955f522950e2 | 671,917 |
def sexp(self, labr="", lab1="", lab2="", exp1="", exp2="", **kwargs):
"""Forms an element table item by exponentiating and multiplying.
APDL Command: SEXP
Parameters
----------
labr
Label assigned to results. If same as existing label, the existing
values will be overwritten by t... | 6825e5a553a0866f509e3a1023ce571a0f64ff03 | 671,918 |
import random
def get_random_integer(number):
"""
This function takes in a number and returns a random integer between 0 and that number
"""
return random.randint(0, number) | e5456480530f01f013428f9c5827421b7aaa12f0 | 671,921 |
def vectors_from_indices(bm, raw_vert_indices):
"""Return List of vectors from input Vertex Indices.
Args:
bm: Object Bmesh
raw_vert_indices: List of Chosen Vertex Indices
Returns:
List of Vertex coordinates.
"""
return [bm.verts[i].co for i in raw_vert_indices] | bbbdb246a5d3f434f13d0ee00301957a331ae569 | 671,923 |
def _has_matched_brackets(text: str) -> bool:
"""
Evaluate whether every opening bracket '[' in the 'text' has a matching closing bracket ']'.
:param text: the text.
:return: Boolean result, and associated message.
"""
open_bracket_stack = []
for index, _ in enumerate(text):
if text... | 4c8b0e30654a3f5ad72da173233b7a64110042a4 | 671,930 |
def get_aliases(cur, cp):
"""get all aliases of a codepoint"""
cur.execute("SELECT alias FROM codepoint_alias WHERE cp = %s", (cp,))
return map(lambda s: s['alias'], cur.fetchall()) | bd1e541a4d7b4f56955cd98b496c290a562c3ef6 | 671,933 |
def select_matching_record(dataframe, linked_row, matching_col):
"""Return dataframe row based on matching column name"""
return dataframe[
dataframe[matching_col] == linked_row[matching_col]
].compute() | 09ff9ec683d1199e8736d8cb8c673b514ba4609f | 671,934 |
import six
def column_info(df):
"""Returns a list of columns and their datatypes
Args:
df (`pandas.DataFrame`): The dataframe to get info for
Returns:
:type:`list` of :type:`dict`: A list of dicts containing column ids and their
Dtypes
"""
column_info = []
for co... | ea1652133b976d529e6440cdcb2f397c1b3109bc | 671,936 |
import requests
import tempfile
import gzip
def get_cif(code, mmol_number, outfile=None):
"""
Parameters
----------
code : str
PDB code.
mmol_number : int
mmol number (biological assembly number) of file to download. Numbers from PDBe.
If None, defaults to the preferred bio... | b76ff7bfddaf64df862cff1773cdf82deee99ea1 | 671,938 |
import re
def read_data_table(filename: "str") -> "dict":
"""
Reads in a CSV file containing columnwise data for various elements, and returns a dictionary containing the data.
Lines beginning with "#" are ignored
:param filename: A valid filename for a csv file
:type filename: str
:return: A... | 44a8407153867016ec8b7f62505da11a8ebcffee | 671,941 |
def last_column_type(column_types):
"""Return the max order in the order types."""
return max([v['order'] for v in column_types.values()], default=0) | 98ff619ae143e6e62efc2baa01f1e6b50081db50 | 671,943 |
def le16(data, start=0):
"""
Read value from byte array as a long integer
:param bytearray data: Array of bytes to read from
:param int start: Offset to start reading at
:return int: An integer, read from the first two bytes at the offset.
"""
raw = bytearray(data)
return raw[start] ... | 2e085120a9dc129dfdf8b03ce2490ad1e4fbf5ea | 671,944 |
import re
def svgparselength(lengthstr):
"""
Parse an SVG length string into a float and a units
string, if any.
:param lengthstr: SVG length string.
:return: Number and units pair.
:rtype: tuple(float, str|None)
"""
integer_re_str = r'[+-]?[0-9]+'
number... | 483b6431981f0d13f8c1d4987a3dfb5cbf67b923 | 671,948 |
def _parse_preamble(path):
"""
Parse preamble at path.
"""
with open(path, "r") as f:
preamble = f.read().split('\n')
return preamble | f551f29e015854079abd112406b5629971570a41 | 671,951 |
import requests
from bs4 import BeautifulSoup
def get_soup(url):
"""Given a url, returns a BeautifulSoup object of that page's html"""
web_page = requests.get(url)
return BeautifulSoup(web_page.text, "html.parser") | eedabb426d409f63f0eaf71105f1f329ad7ee1e5 | 671,956 |
def index_to_position(index, strides):
"""
Converts a multidimensional tensor `index` into a single-dimensional position in
storage based on strides.
Args:
index (array-like): index tuple of ints
strides (array-like): tensor strides
Return:
int : position in storage
"""
... | 87999cabc9c465a5a787988a90ad29fdf07e3804 | 671,957 |
from typing import List
from typing import Union
def ls_strip_elements(ls_elements: List[str], chars: Union[None, str] = None) -> List[str]:
"""
>>> ls_strip_elements([' a','bbb',' '])
['a', 'bbb', '']
>>> ls_strip_elements([])
[]
"""
if (not ls_elements) or (ls_elements is None):
... | 830691f26e934d025b96e0d1c3d89d0bb634ed4d | 671,958 |
def create_intersected_loops_row(loop_coords, loop_id_1, loop_id_2):
"""
Create intersected loops row.
"""
row = [
loop_coords[loop_id_1]['chrom'],
loop_coords[loop_id_1]['start'],
loop_coords[loop_id_1]['end'],
loop_id_1,
'0',
'+',
loop_coords[loo... | 5c7b677d437c4da52bde799196134b57853383a1 | 671,960 |
from typing import Optional
def get_scheduler_state(code: int) -> Optional[str]:
"""Translate an schduler state code to a human-readable state.
Official mapping is available
`here <https://github.com/BOINC/boinc/blob/master/py/Boinc/boinc_db.py>`.
Args:
code:
The code of scheduler stat... | 36ae5e82ddb2cee058101e286bd1e04eedcc8956 | 671,962 |
def _clean_join(content):
"""
Joins a list of values together and cleans (removes newlines)
:param content: A str or list of str to process
:return: The joined/cleaned str
"""
if not isinstance(content, str):
content = ''.join(content) if content else ''
return content.replace('\n', ... | 6f47fe51b1fced76fe45b91ed5a83368090062ea | 671,964 |
from typing import Any
def py_is_none(x: Any) -> bool:
"""Check if x is None."""
return x is None | de9ea258cbefdf4547194c559b70aeebb19e8a2d | 671,966 |
def format_odometer(raw: list) -> dict:
"""Formats odometer information from a list to a dict."""
instruments: dict = {}
for instrument in raw:
instruments[instrument["type"]] = instrument["value"]
if "unit" in instrument:
instruments[instrument["type"] + "_unit"] = instrument["u... | 06f75f5682dcbd7c36ce112bfb0e24279376c91c | 671,967 |
def try_parse_ticket_ids(title):
"""Get ticket id from PR title.
Assumptions:
- ticket id or special prefix before PR title
- no whitespace before ticket id
- whitespace between ticket id and PR title
Transformations (for the worst case):
"ggrc-1234/1235: Do something" -> ["GGRC-1234", "GGRC-123... | 080350d8af1d070a18c461bb95fdf5e2680064ea | 671,968 |
import json
def string_to_dict(value):
"""str to dict, replace '' with None"""
if not value:
return None
values = json.loads(value)
for key in values:
if values[key] == "":
values[key] = None
return values | d9d11241f32dd2d3cddbd89c604da60c3e9a18b7 | 671,974 |
def make_readable(res):
"""
Eliminates the namespace from each element in the results of a
SPARQL query.
"""
return [[uri.split("#")[-1] for uri in row] for row in res] | 877568d3d0e0a10d01b68d8cce2b71f08b56ecc2 | 671,978 |
from datetime import datetime
def strf_timestamp(timestamp, form):
"""
Helper function to safely create string date time from a timestamp value
:return: string - date time in the specified form
"""
try:
return datetime.utcfromtimestamp(timestamp).strftime(form)
except Exception: # py... | 0d9866c6bf73f084d723acb7e2a7b820c34a1105 | 671,979 |
import csv
def close_history(args):
"""close the history file and print the best record in the history file"""
args.hist_file.close()
args.hist_file = open(args.results_dir+'/history.csv', 'r', newline='')
reader = csv.DictReader(args.hist_file)
best_epoch = 0
best = {}
for epoch, record i... | ec033b6feb34343d15287a1df6f4056304187379 | 671,980 |
def reduce_by_ident(retain_data, reduce_data, idents, cutoff=0.3):
"""
Remove the proteins from a list of ids which are sequence similar to the ids in another list of ids.
Args:
retain_data: List of ids which should be retained.
reduce_data: List of ids which should be reduced according to ... | f50f13e792e14194c696bf8b0ac5e3bc071a3e1d | 671,989 |
import hashlib
def get_hash(dict_obj):
"""
Return hash of a dict of strings
"""
rec = []
for k, v in dict_obj.items():
if isinstance(v, str):
rec.append(k + ":" + v)
elif isinstance(v, list):
rec.append(k + "".join(v))
# Update, use sorted so the origin... | 36ffeb0ba74cf8efebcdc38d400ad2d940588c0f | 671,991 |
def dup_factions(factions, num_winners):
"""Expand a list of factions by a factor of num_winners into a list of candidates
>>> dup_factions(['A', 'B'], 3)
['A1', 'A2', 'A3', 'B1', 'B2', 'B3']
"""
return [f'{f}{n}' for f in factions for n in range(1, num_winners+1)] | 7b691a7d8bf163ac55b4c75fba2864c4df72e81c | 671,993 |
from typing import List
from typing import Tuple
from typing import Optional
def _get_homos_lumos(
moenergies: List[List[float]], homo_indices: List[int]
) -> Tuple[List[float], Optional[List[float]], Optional[List[float]]]:
"""
Calculate the HOMO, LUMO, and HOMO-LUMO gap energies in eV.
Parameters
... | 356be753670b3d2503fae8db8f0ba363baab2316 | 671,994 |
def is_oneliner(txt) -> bool:
"""Checks if the given string contains no newlines."""
assert isinstance(txt, str)
return len(txt.splitlines()) == 1 | cd612c5818b9458e7a048907cdcc9aba32f41973 | 671,995 |
import pathlib
import pkg_resources
def get_requirements(source):
"""Get the requirements from the given ``source``
Parameters
----------
source: str
The filename containing the requirements
"""
with pathlib.Path(source).open() as requirements_txt:
install_requires = [
... | 68aab8795c42348b88853ea3bf9376c290c45df9 | 671,996 |
def agestr2years(age_str: str) -> int:
"""Convert an Age String into a int where the age unit is
in years. Expected formats are: nnnD, nnnW, nnnM, nnnY.
Notes
-----
The return value may not yield precise results as the following
assumptions are made: there are 365 days in a year, there are 52
... | 76a3b579aed95de608e529e2a8009f897763ecaa | 671,998 |
def format_label(fld, skip_last=False):
"""return a label consisting of subfields in a Field, properly formatted"""
subfields = fld.get_subfields('a','b','n','d','c')
if len(subfields) > 0:
if skip_last:
subfields = subfields[:-1]
return ' '.join(subfields)
else:
return None | fc4d6517b78b5b9f4077642609bb99564c7dec50 | 671,999 |
def to_intpmf(values, counts, simplify=True):
""" Convert an integer probability mass function to a stochastic expression. """
if len(counts) != len(values):
raise ValueError("Mismatching number of values and counts.")
if len(values) == 0:
raise ValueError("Cannot construct distribution fro... | 8b360e6256410efabbcbee90bf441b8e2d084458 | 672,003 |
def isPathExcluded(curPath,excludePath):
""" Returns True if excludePath is part of parameter curPath, otherwise False. """
try:
curPath.relative_to(excludePath)
return True
except ValueError:
return False | d888302bc1a8976bed4e9d2d9dc6d12929fe968f | 672,010 |
from typing import List
def head_commit_query(user: str, repo: str, branches: List[str]) -> str:
"""
Fetch the head commit for a list of branches
"""
def branch_part(branch: str, num: int) -> str:
return f"""
r{num}: repository(name: "{repo}", owner: "{user}") {{
ref(quali... | b8dd69fef321fe882d046e9be7399abafc1386ce | 672,011 |
def holling_type_0(X,idx_A,coefficient):
""" linear response with respect to *destination/predator* compartment
For examples see:
`Examples <https://gist.github.com/465b/cce390f58d64d70613a593c8038d4dc6>`_
Parameters
----------
X : np.array
containing the current state of the conta... | 354b3a8b041bec0c287764daf0dcd919f76531d8 | 672,012 |
def parse_intf_status(lines):
"""
@summary: Parse the output of command "show interface description".
@param lines: The output lines of command "show interface description".
@return: Return a dictionary like:
{
"Ethernet0": {
"oper": "up",
"admin": "up... | dfc4590f0659fea16daac31e01c9beeae98d590f | 672,017 |
def distanc(*args):
"""Calcs squared euclidean distance between two points represented by n dimensional vector
:param tuple args: points to calc distance from
:return: euclidean distance of points in *args
"""
if len(args) == 1:
raise Exception('Not enough input arguments (expected two)')
... | c1e52723970c243876e89a9dbdb91c5d5580a49d | 672,018 |
from typing import Dict
def role_playing_hubs() -> Dict[str, str]:
"""Build role playing hubs definition."""
return {"h_customer_role_playing": "h_customer"} | 6aff38d2704ae960874bf3c7449ce97acddec79c | 672,028 |
def _is_nested_type(field_type: type) -> bool:
"""Determine whether a typing class is nested (e.g. Union[str, int])."""
return type(field_type._subs_tree()) is tuple | 09bcda59ae59ca243baa45f5b7ba02ae87d5cbba | 672,029 |
def calc_formation_enthalpy(ergs_react,erg_prod,coeffs):
"""
Calculate the formation enthalpy using energies and coefficients of reactants,
and energy of product.
"""
if len(ergs_react) != len(coeffs):
raise ValueError('len(ergs_react) != len(coeffs)')
dH = erg_prod
for i in range(le... | 8e3b3573a145b2d5d1ba24ece2e2c4a8279bafbc | 672,034 |
def format_all_sides(value):
"""Convert a single value (padding or border) to a dict
with keys 'top', 'bottom', 'left' and 'right'"""
all = {}
for pos in ('top', 'bottom', 'left', 'right'):
all[pos] = value
return all | 33a86122b2cbe24be79c4cc25b43cba59f781792 | 672,036 |
def remember_umbrella(weather_arg: str) -> bool:
"""Remember umbrella
Checks current weather data text from :meth:`get_weather` for keywords indicating rain.
Args:
weather_arg: String containing current weather text of specified city.
Returns:
True if any of the rain keywords are foun... | a912b75f1e4a32c7088120e09843609a08fe20f3 | 672,037 |
import colorsys
def color_RGB_to_hsv(iR: float, iG: float, iB: float) -> tuple[float, float, float]:
"""Convert an rgb color to its hsv representation.
Hue is scaled 0-360
Sat is scaled 0-100
Val is scaled 0-100
"""
fHSV = colorsys.rgb_to_hsv(iR / 255.0, iG / 255.0, iB / 255.0)
return rou... | 87e0a45cae0c9577bd2a51689422dd49dec79e01 | 672,038 |
def make_bool(s):
""" Convert string to bool """
return True if s.lower() == 'true' else False | d9c0d0d0a7e14cb5f520aacd11717de7b4a4ef94 | 672,040 |
def dict_item(d, k):
"""Returns the given key from a dictionary."""
return d[k] | 57ba01362a9051c97f12e166e1f9c33e03a70615 | 672,042 |
def extract_tests(api_response, defined_tests):
"""
Create and return a dict of test name to test data.
If api_response is None, return a dict with an empty dict.
api_response: the JSON response from the Proctor API in Python object form.
defined_tests: an iterable of test name strings defining th... | d81e621cd26605fe9d8469a0fab2e7983416c0b6 | 672,045 |
import math
def calc_distance(pos1, pos2):
"""
Calculate euclidean distance between two positions
"""
return round(math.sqrt((pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2), 3) | 429f36effa3103db1843e38016a61eaba06c35df | 672,046 |
def get_account_id_from_arn(trail_arn):
"""Gets the account ID portion of an ARN"""
return trail_arn.split(':')[4] | d13f72357e9932459a44f76cfb28462b38a92f46 | 672,047 |
import json
def load_model_config(filename):
"""
Load model configuration from json file and return it
"""
with open(filename, 'r') as fp:
data = json.load(fp)
return data | f03473aea608fe4efdce4144e17068d8e47b973a | 672,048 |
def tensor2numpy(tensor):
"""Convert tensor to ndarray
"""
return tensor.cpu().detach().numpy() | 805c54c3915d5d685dab295cac7e0afb5673e955 | 672,051 |
def _get_normalized_vm_statuses(vm_iv):
"""Iterate over a list of virtual machine statuses and normalize them.
Arguments:
vm_iv (dict): Raw virtual machine instance view record.
Returns:
dict: Normalized virtual machine statuses
"""
normalized_statuses = {}
for s in vm_iv.get(... | b8fc8a14ccda4574fbe6838716bc944196a09c2e | 672,053 |
def extension_without_gz(path):
"""Get the file extension ignoring .gz if present"""
suffixes = path.suffixes
last = len(suffixes)
if suffixes[last] == ".gz":
extension = suffixes[last - 1]
else:
extension = suffixes[last]
return extension | 211ed82b7a853dfcd42258ef8f2e7f7184f781fa | 672,054 |
def _dol_to_lod(dol):
"""Convert a dict of lists to a list of dicts."""
return [{key: dol[key][ii] for key in dol.keys()}
for ii in range(len(dol[list(dol.keys())[0]]))] | 1e85cdebf64bdb6910545dc2a832a268a9b69add | 672,056 |
def create_mapping(dico):
"""
Create a mapping (item to ID / ID to item) from a dictionary.
Items are ordered by decreasing frequency.
"""
sorted_items = sorted(dico.items(), key=lambda x: (-x[1], x[0]))
id_to_item = {i: v[0] for i, v in enumerate(sorted_items)}
item_to_id = {v: k for k, v i... | 226b0c3bf35fdf2736ca1df90616c2ad97de9588 | 672,058 |
import torch
def add_id(df):
"""
Add the identity to a tensor with the shape of the Jacobian
Args:
df (torch.tensor): batched `(n,m,m)` tensor
Returns:
torch.tensor: :code:`df` plus a batched identity of the right shape
"""
return df + torch.eye(df.shape[1], device=df.devi... | 475e46185c95becc5680109e6cd72f04aa7030bd | 672,059 |
def list_users(iam_conn, path_prefix):
"""List IAM users."""
users = []
marker = None
while True:
if marker:
response = iam_conn.list_users(PathPrefix=path_prefix,
Marker=marker)
else:
response = iam_conn.list_users(Pat... | 1d849e928177d13cc6c300c138dc6bed01651ab0 | 672,064 |
def _get_max_size(x, y, map_info):
"""
Get the size of the biggest square matrix in the map
with first point: (x, y)
Arguments:
x -- column index
y -- line index
map_info -- a dict of the map and its information
Returns:
size -- biggest square matrix size
"""
x_max ... | 5180fdd9894ef368fba36b50939f5661418147d2 | 672,066 |
import requests
def pulsar_list(addr, auth):
"""
Return a list of the all the pulars in the database.
Args:
addr: hostname or ip address of database server.
auth: tuple of username and password.
"""
path = '{0}/{1}/'.format(addr, 'pulsar_list')
r = requests.get(url=path, ... | 61dd51ae1cb1a83753735a66695ff4f7a2653385 | 672,069 |
from pathlib import Path
def get_product_name_from_path(path):
"""
Extract S2 product name from the path.
"""
parents = list(Path(path).parents)
if len(parents) > 1:
first_dir = Path(parents[len(parents) - 2])
if first_dir.suffix == '.SAFE':
return first_dir.stem | 35c608afd98ecbf071244167855e22cae728463f | 672,072 |
def isPrime(x):
"""
Checks whether the given
number x is prime or not
"""
if x == 2:
return True
if x % 2 == 0:
return False
for i in range(3, int(x ** 0.5) + 1, 2):
if x % i == 0:
return False
return True | 5c1e3614a67263d57eed6bf6f60d5ff5572f4026 | 672,076 |
def genwhctrs(anchor):
"""Return width, height, x center, and y center for an anchor (window).
"""
base_w = anchor[2] - anchor[0] + 1 # 15 + 1
base_h = anchor[3] - anchor[1] + 1
x_ctr = anchor[0] + 0.5 * (base_w - 1)
y_ctr = anchor[1] + 0.5 * (base_h - 1)
return base_w, base_h, x_ctr, y_ctr | 99aebcabe18ccd68aefa4f404cf8028ce0f21fcf | 672,077 |
def _get_coordinator(hostname, port=9001):
""" Generates the coordinator section of a Myria deployment file """
return '[master]\n' \
'0 = {}:{}\n\n'.format(hostname, port) | dba81eac4d18219833e17aa52d8271ee19f25f6e | 672,079 |
def look_and_say(seq, times):
""" Recursively play look-and-say on the sequence """
if times == 0:
return seq
newseq = ''
currentc = ''
count = 1
for c in seq:
if c == currentc:
count += 1
else:
if currentc != '':
newseq += str(coun... | 6471c4234761da8f4727051f49b71ac5c446c2f1 | 672,082 |
def mocked_system(mocker):
"""Mocking `plaform.system`"""
return mocker.patch("platform.system") | 3c0b52c2a8fa0a5ff84431fb0c7c067ed33a8381 | 672,087 |
def test_triangle(dim):
"""
Tests if dimensions can come from a triangle.
dim is a list of the three dimensions (integers)
"""
dim = [int(x) for x in dim]
dim.sort()
if dim[0] + dim[1] > dim[2]:
return True
else:
return False | bd36868a680c1114585baf19aa8ecf6eee33e481 | 672,088 |
def asymptotic_relation_radial(enn,numax,param):
"""
Compute the asymptotic frequency for a radial mode.
Parameters
----------
enn : int
The radial order of the mode.
numax : float
The frequency of maximum oscillation power
param : array_like
Collection of the asypm... | 8575c62b3ff5a54fa831b033d1578dfa40cf018e | 672,089 |
def cipher(text, shift, encrypt=True):
"""
Encrypt or Decrypt a string based on Caesar cipher.Each letter is replaced by a letter some fixed number of position down the alphabet.
Parameters
----------
text : string
A string you wish to encrypt or decrypt.
shift : integer
A in... | aad52df5a2750b04dd8e1dfb8cafef42c087277e | 672,091 |
def minimise_xyz(xyz):
"""Minimise an (x, y, z) coordinate."""
x, y, z = xyz
m = max(min(x, y), min(max(x, y), z))
return (x-m, y-m, z-m) | 78005610682605beec77a4bc2e7a84de876d7e8f | 672,092 |
def transpose(data):
"""
Utility function for transposing a 2D array of data.
"""
return zip(*data) | 5fae54f27d7eb46904a5c269c02cafc0936a3b58 | 672,093 |
import torch
def to(input, dtype):
"""Convert input to dtype."""
if dtype == 'long':
dtype = torch.long
elif dtype == 'uint8':
dtype = torch.uint8
elif dtype == 'float32':
dtype = torch.float32
return input.to(dtype) | a71ecbfc0b5b22af8d57813dfd81fad02fb0a065 | 672,096 |
import re
def clean_column(s):
""" utils function that clean a string to be a cleaner name of column
Parameter
---------
s : string
the string to clean
Return
------
cleaned string
"""
if s is None:
return None
r = s.strip().lower()
r = ... | dfb26fa641738729d4d4c3dc3d1d16e32f575fc3 | 672,098 |
def count_increase(list_int):
"""
This function calculates the number of times a measurement increases.
This is the answer to the first puzzle.
Parameters:
list_int (list): list of measurements(integers)
Returns:
n (int): number of times a measurement inctreases.
"""
n = 0... | 63e63a8399209aa51cb22ef94c2cbd1f22d9fefc | 672,099 |
from typing import Dict
import json
def load_data(file_path: str) -> Dict[str, list]:
""" Loads the json file in as a Python dictionary.
Parameters
----------
file_path : str
Absolute file path to the Frew model.
Returns
-------
json_data : Dict[str, list]
A Python dictio... | cb86a9ff5f5c73b7bd246497d3a33d4d4939a87c | 672,100 |
def _s3_glob(s3_filepath, my_bucket):
""" Searches a directory in an S3 bucket and returns keys matching the wildcard
Parameters
----------
s3_filepath : str
the S3 filepath (with wildcard) to be searched for matches
my_bucket : boto3 bucket object
the S3 bucket object containing th... | 69549ae41e7af13c192ddde8331433a24a1a9997 | 672,101 |
def v2_to_internal(menu):
"""Convert a v2 menu object to an internal menu object"""
if not menu['open']:
return {'open': False}
def soup_to_soup(soup):
return {
'price': soup['price'],
'name': soup['name']
}
def other_to_other(other):
return {
... | 2f262fc66a3af35494f886aa107b2e97af222ea5 | 672,102 |
import re
import random
def scramble(word):
"""For words over 3 characters, shuffle the letters in the middle"""
if len(word) > 3 and re.match(r'\w+', word):
middle = list(word[1:-1])
random.shuffle(middle)
word = word[0] + ''.join(middle) + word[-1]
return word | af0a638544a860515c1f3a062941a99b9ea2a370 | 672,103 |
def max_bitrate_ext(val):
"""
Given ESM value, return extended maximum bit rate (Kbps).
Please refer to 10.5.6.5, TS24.008 for more details.
:param val: the value encoded in the ESM NAS message
"""
if val <= 74:
return 8600 + val * 100
elif val <= 186:
return 16000 + (val - ... | ee8c139ad28d836d01b43f1b24d795550844f695 | 672,106 |
import torch
def ConstantTensor(value, *size, dtype=torch.float, device='cuda:0'):
"""
Returns a Tensor containing only value
Parameters
----------
value : int or float
the value of every item in the Tensor
*size : int...
the shape of the tensor
dtype : type (optional)
... | b89484afebd0311b5c66cd3ac66d22de9a46bc29 | 672,107 |
def get_figsize(columnwidth=241.14749, wf=1.0, hf=(5. ** 0.5 - 1.0) / 2.0, b_fixed_height=False):
"""Parameters:
- wf [float]: width fraction in columnwidth units
- hf [float]: height fraction in columnwidth units.
Set by default to golden ratio.
- columnwidth [float]: width... | d0d7ed41bc14e5f4d5ec21837f8d899aa57e9c34 | 672,108 |
def isKanji(char):
""" return true if char is a kanji or false if not """
code = ord(char)
return 0x4E00 <= code <= 0x9FFF | 1c83d77b0296590dc892ef29691fde27966bcfd0 | 672,109 |
def is_track_in_tracks(song_uri, tracks):
"""
Checks whether song is within a list of songs
:param song_uri: ID of target song
:param tracks: Page object of track or playlist track objects
:return: Whether or a not a song is within a list of tracks
"""
for track in tracks['items']:
t... | d035c9c2515cdaa2f7fc89c12a5a754259815eec | 672,112 |
import re
import json
import collections
def LoadJSON(filename):
"""
Read `filename`, strip its comments and load as JSON.
"""
with open(filename, "r") as f:
match_cpp_comments = re.compile("//.*\n")
# The order in which structures are described in JSON matters as we use them
# as a seed. Computin... | 9e0f3375a76048ef64502908833c25bc33a8c92f | 672,113 |
def update_speed_limit(intersection, new_speed):
"""
Updates the speed limit of the intersection
:param intersection: intersection
:param new_speed: new speed value
:type intersection: Intersection
:type new_speed: int
:return: updated intersection
"""
return intersection.update_spee... | a531ff9152611299499d347cb0639faba559d153 | 672,116 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.