content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def soft_equals(a, b):
"""Implements the '==' operator, which does type JS-style coertion."""
if isinstance(a, str) or isinstance(b, str):
return str(a) == str(b)
if isinstance(a, bool) or isinstance(b, bool):
return bool(a) is bool(b)
return a == b | 2813936f29090c2ba7d61f1f7f337773effb2160 | 109,172 |
def resource_to_type_name(resource):
"""Creates a type/name format from a resource dbo.
Args:
resource (object): the resource to get the the type_name
Returns:
str: type_name of the resource
"""
return resource.type_name | a837aac94a493a2201f470670862eb7b22e70941 | 109,173 |
def addColorbar(ax, mappable, norm, cbarLabel=None):
"""
Quick utility to add a colorbar to an axes object
Parameters
----------
mappable: iterable
Collection of meshes, patches, or values that are used to construct
the colorbar.
norm: None or :class:`matplotlib.colors.Normalize` subclass
Normalizer for this plot
cbarLabel: None or str
If given, place this as the y-label for the colorbar
Returns
-------
:class:`matplotlib.colorbar.Colorbar`
The colorbar that was added
"""
cbar = ax.figure.colorbar(mappable, norm=norm)
if cbarLabel is not None:
cbar.ax.set_ylabel(cbarLabel)
return cbar | b53905f7e213e254442250ab8288810ad2d70fac | 109,174 |
def getDataType(p_type, p_size):
"""Given the input type and size, returns the corresponding
Python character for that data type"""
# How many bits in a single value?
if p_type == 'float':
if p_size == 32:
return 'f'
elif p_size == 64:
return 'd'
else: # Anything else is an error.
assert True, "Error: Cannot have floats and pixel size of " + str(p_size)
elif p_type == 'signed fixed':
if p_size == 8:
return 'b'
elif p_size == 16:
return 'h'
elif p_size == 32:
return 'i'
else: # PIXSIZE of 64
return 'q'
else: # TYPE of unsigend
if p_size == 8:
return 'B'
elif p_size == 16:
return 'H'
elif p_size == 32:
return 'I'
else: # PIXSIZE of 64
return 'Q' | 3fad77e48c7a40ff908b5066cd353a83649425b6 | 109,176 |
import hashlib
def hashDictionary(dictionary):
"""
Hash a dictionary. Sort the dictionary according
to the keys beforehand.
"""
chain = ""
for key,value in sorted(dictionary.items()):
chain += key+","+value+";"
return hashlib.md5(chain.encode()).hexdigest() | 20c078737e836a4a1002f8948f344ddadc6cdb4b | 109,188 |
def index_to_sq(ix):
"""Convert an index to a column and rank"""
return (ix % 8, ix // 8) | 65e9a7859dc8f5e4b96b400b396e3bb3d4fa3495 | 109,197 |
def xcp_created (db):
"""Return number of XCP created thus far."""
cursor = db.cursor()
cursor.execute('''SELECT SUM(earned) AS total FROM burns \
WHERE (status = ?)''', ('valid',))
total = list(cursor)[0]['total'] or 0
cursor.close()
return total | 2f298fca557e6df89b5a84880516302497518fc5 | 109,199 |
def get_required(question):
"""
Returns True if metaschema question is required.
"""
required = question.get('required', False)
if not required:
properties = question.get('properties', False)
if properties and isinstance(properties, list):
for item, property in enumerate(properties):
if isinstance(property, dict) and property.get('required', False):
required = True
break
return required | f116f616dd07bfcfef6fec554da897342ab2b493 | 109,201 |
def _run_dict(session, run_dict, feed_dict=None):
"""Convenience function to run a session on each item in a dict of tensors.
Args:
session: The session to evaluate.
run_dict: A dict of tensors to be run in the session.
feed_dict: Feed dict to be used in running the session.
Returns:
A dict containing the result of evaluating the tensors.
Raises:
ValueError: if `run_dict` is missing or empty.
"""
if run_dict is None:
raise ValueError('Invalid run_dict %s.', run_dict)
keys = run_dict.keys()
values = session.run([run_dict[key] for key in keys], feed_dict=feed_dict)
return dict(zip(keys, values)) | c0f2edc8ded0932ab5aae2fbacb2ef79071f65e9 | 109,203 |
import inspect
def _get_plugin_methods(plugin_klass):
"""
Return a list of names of all the methods in the provided class.
Note: Abstract methods which are not implemented are excluded from the
list.
:rtype: ``list`` of ``str``
"""
methods = inspect.getmembers(plugin_klass, inspect.ismethod)
# Exclude inherited abstract methods from the parent class
method_names = []
for name, method in methods:
method_properties = method.__dict__
is_abstract = method_properties.get('__isabstractmethod__', False)
if is_abstract:
continue
method_names.append(name)
return method_names | 154c3d081bdf6c7129414affa4d85325308c61ff | 109,212 |
from typing import Dict
def DictOf(name, *fields):
"""
This function creates a dict type with the specified name and fields.
>>> from pyws.functions.args import DictOf, Field
>>> dct = DictOf(
... 'HelloWorldDict', Field('hello', str), Field('hello', int))
>>> issubclass(dct, Dict)
True
>>> dct.__name__
'HelloWorldDict'
>>> len(dct.fields)
2
"""
ret = type(name, (Dict,), {'fields': []})
#noinspection PyUnresolvedReferences
ret.add_fields(*fields)
return ret | a97e63a0d5c6a0c6abcab260a372a267210fdb42 | 109,214 |
from datetime import datetime
def datetime_string_to_naive(datetime_string):
"""
This function converts ISO 8601 time string without timezone info to a naive datetime object.
Main usage is for date of birth and other places where timezon is not required.
"""
try:
dt = datetime.strptime(datetime_string, '%Y-%m-%dT%H:%M:%S')
return dt
except ValueError:
return None | d3b61f2bfc28e0eebaeda607fc3dd4b2f7d288ff | 109,217 |
def get_hook_environment_value(application):
"""From an Application that has been mangled with the "complete" hook, get the value
of the token and the URL that were added to it.
Args:
application (Application): the Application augmented with the elements of the
"complete" hook.
Returns:
(str, str): a tuple of two elements: the token generated by the "complete" hook
and the URL of the Krake API, as inserted by the hook.
"""
deployment = application.status.last_observed_manifest[0]
token = None
url = None
for container in deployment["spec"]["template"]["spec"]["containers"][:-1]:
for env in container["env"][:-1]:
if env["name"] == "KRAKE_TOKEN":
token = env["value"]
if env["name"] == "KRAKE_COMPLETE_URL":
url = env["value"]
if token is None or url is None:
raise ValueError("The token and the url must be in the environment")
return token, url | 46a6e8314e776d5ff4f494b919d106b768b47e04 | 109,218 |
def delogify_mass(logmass=0.0, **extras):
"""Simple function that takes an argument list including a `logmass`
parameter and returns the corresponding linear mass.
Parameters
----------
logmass : float
The log10(mass)
Returns
-------
mass : float
The mass in linear units
"""
return 10**logmass | ac525e951106074f6aaf2276dc0fa8a3967e37b5 | 109,220 |
import itertools
def xnat_children(obj):
"""
Returns the XNAT objects contained in the given parent object.
:param obj: the XNAT parent object
:return: the child objects
:rtype: list
"""
# pyxnat children() is oddly the child collection attributes
# rather than objects.
child_attrs = obj.children()
# The children generators for each child type.
nested = (getattr(obj, attr)() for attr in child_attrs)
flattened = itertools.chain(*nested)
return list(flattened) | ffd225fe0c2ca869c60e1cc88a675fa6d8241b9d | 109,225 |
from typing import Union
from typing import Callable
def format_fully_qualified_type_name(
type_object: Union[Callable, type]) -> str:
"""Formats a fully qualified name of any type."""
module: str = type_object.__module__
type_name: str = type_object.__qualname__
if module is None or module == object.__module__:
return type_name
return f'{module}.{type_name}' | 339f56f649f35aac293dbd42ffb856cdafc80ddc | 109,226 |
def only_sig(row):
"""Returns only significant events"""
if row[-1] == 'yes':
return row | 12ff2d7b5cea4a01f3ecbba81dc1f4f982f7bd5a | 109,229 |
def build_geometry(self):
"""Compute the curve (Line) needed to plot the Slot.
The ending point of a curve is the starting point of the next curve in
the list
Parameters
----------
self : SlotCirc
A SlotCirc object
Returns
-------
curve_list: list
A list of one Arc
"""
line_dict = self._comp_line_dict()
curve_list = [
line_dict["1-M"],
line_dict["M-2"],
]
return [line for line in curve_list if line is not None] | 5368f8eb53ff3cf5fe37df0e44cb7aba6c4169f9 | 109,236 |
def get_path(data, question_name, path_list):
"""
A recursive function that returns the xpath of a media file
:param json data: JSON representation of xform
:param string question_name: Name of media file being searched for
:param list path_list: Contains the names that make up the xpath
:return: an xpath which is a string or None if name cannot be found
:rtype: string or None
"""
name = data.get('name')
if name == question_name:
return '/'.join(path_list)
elif data.get('children') is not None:
for node in data.get('children'):
path_list.append(node.get('name'))
path = get_path(node, question_name, path_list)
if path is not None:
return path
else:
del path_list[len(path_list) - 1]
return None | d7b31854aa741e8bc088439b01cc36e6c3417868 | 109,238 |
import base64
def encode(message):
"""
Encodes the message in base64
Args:
message (str/list): message to encode
Returns:
str: encoded message in base64
"""
message_bytes = message.encode("ascii")
encoded_base64_bytes = base64.b64encode(message_bytes)
encoded_message = encoded_base64_bytes.decode("ascii")
return encoded_message | 2de0557421d030c548d84909756817c3c2df2646 | 109,239 |
from typing import Dict
from typing import Set
def filter_least_used_disks(disk_to_copy_processes_count: Dict[str, int]) -> Set[str]:
"""Filters for the least used disk
Parameters
----------
disk_to_lockfile_count : Dict[str, int]
Dictionary of disks with lockfile count
Returns
-------
available_dirs : Set[str]
Available directories with minimal lockfile count. In case of
equal lockfile count then the disks are given randomly.
"""
minimum_number_of_lockfiles = min(disk_to_copy_processes_count.values())
available_target_dirpaths = {
dirpath
for dirpath in disk_to_copy_processes_count
if disk_to_copy_processes_count[dirpath] == minimum_number_of_lockfiles
}
return available_target_dirpaths | c52e55837cd0cbd8216441e0b2d9e14e7d0862b8 | 109,245 |
def load_image_set(imageSets_file):
"""
Get image identifiers from ImageSets dir's file for train or test. like ['set00_V000_I00000','set00_V000_I00001'...]
"""
with open(imageSets_file, 'r') as f:
lines = f.readlines()
image_identifiers = [x.strip() for x in lines]
return image_identifiers | 5d0ac0f37f3debe1ec2aef81424055dc7df60758 | 109,246 |
import itertools
def findsubsets(S, m):
"""
Find all subsets of S containing m elements.
Parameters
----------
S: list
List of objects.
m: int
Number of elements per subset.
Returns
-------
subset_list: list
List of subsets.
"""
subset = list(itertools.combinations(S, m))
subset_list = [list(x) for x in subset]
return subset_list | 096b00d378a2b631736934fb250faf417d89b6d2 | 109,252 |
import six
def get_macros(macro_maker, build_xml, build_system):
"""Generate build system ("Macros" file) output from config_compilers XML.
Arguments:
macro_maker - The underlying Build object.
build_xml - A string containing the XML to operate on.
build_system - Either "Makefile" or "CMake", depending on desired output.
The return value is a string containing the build system output.
"""
# Build.write_macros expects file-like objects as input, so
# we need to wrap the strings in StringIO objects.
xml = six.StringIO(str(build_xml))
output = six.StringIO()
output_format = None
if build_system == "Makefile":
output_format = "make"
elif build_system == "CMake":
output_format = "cmake"
else:
output_format = build_system
macro_maker.write_macros_file(macros_file=output,
output_format=output_format, xml=xml)
return str(output.getvalue()) | 0cf10822e133d13603b2100e3dd994760aafcc7e | 109,263 |
def leading_spaces(line: str) -> int:
"""
Calculates the number of leading spaces in a string.
Parameters
----------
line
Returns
-------
int
"""
return len(line) - len(line.lstrip()) | ab973694fa45b8dded10a046329638d9f65e0d02 | 109,268 |
def complement(chromosome, point1, point2):
"""
Flip chromosome bits between point1 and point2.
"""
new_chromosome = ""
for i in range(len(chromosome)):
if i >= point1 and i <= point2:
if chromosome[i] == '0':
new_chromosome += '1'
else:
new_chromosome += '0'
else:
new_chromosome += chromosome[i]
return new_chromosome | ebe0a0c35873592f031e94f67cbf31589dd25cf3 | 109,269 |
def terminate_execution() -> dict:
"""Terminate current or next JavaScript execution.
Will cancel the termination when the outer-most script execution ends.
**Experimental**
"""
return {"method": "Runtime.terminateExecution", "params": {}} | 63a4b776b68498cdaa938a0591456f30a64f122e | 109,271 |
def read_converged(content):
"""Check if program terminated normally"""
return True | aa5158fb32e16f98ceb0b64b568f7f2c0f8847a1 | 109,273 |
def output_list(str_num):
"""
Outputs a list from a string of numbers that is meant to represent a sudoku game
board. For example, the following...
530070000600195000098000060800060003400803001700020006060000280000419005000080079
will turn into...
[[5 3 0 0 7 0 0 0 0]
[6 0 0 1 9 5 0 0 0]
[0 9 8 0 0 0 0 6 0]
[8 0 0 0 6 0 0 0 3]
[4 0 0 8 0 3 0 0 1]
[7 0 0 0 2 0 0 0 6]
[0 6 0 0 0 0 2 8 0]
[0 0 0 4 1 9 0 0 5]
[0 0 0 0 8 0 0 7 9]]
"""
i = 0
sudoku_list = [[], [], [], [], [], [], [], [], []]
for list in sudoku_list:
for num in str_num[i:i+9]:
if len(list) < 10:
list.append(int(num))
i += 9
return sudoku_list | 745adf06f9af5966bb7bd9046d6f039264698e52 | 109,278 |
import re
def normalize_mac(mac):
"""
Given a Mac, strip periods, colons, or dashes form string and return result in lower case
This works but for a more production ready script look at the netaddr module
:param mac:
:return: lowercase mac without any special characters
"""
return re.sub(r'(\.|:|\-)', '', mac).lower() | f2d7a99984fb1690c0eebd5246fe1288f6648910 | 109,279 |
def testsuites_dict(class_testplan):
""" Pytest fixture to call add_testcase function of
Testsuite class and return the dictionary of testsuites"""
class_testplan.SAMPLE_FILENAME = 'test_sample_app.yaml'
class_testplan.TESTSUITE_FILENAME = 'test_data.yaml'
class_testplan.add_testsuites()
return class_testplan.testsuites | bdd7c875b2af9b8e61f9dab0326554f7d7f068f3 | 109,280 |
def convert_string_to_float(s):
"""
Attempt to convert a string to a float.
Parameters
---------
s : str
The string to convert
Returns
-------
: float / str
If successful, the converted value, else the argument is passed back
out.
"""
try:
return float(s)
except TypeError:
return s | aa5f2423e50addd39626bc37d086733fd1fa5032 | 109,283 |
def cal_msg(tick:dict) -> str:
"""
根据tick信息计算成交性质
:param tick: 当前tick
:return: string 成交性质
"""
msg = ''
if tick['oi_diff'] > 0 and tick['oi_diff'] == tick['vol_diff']:
msg = '双开'
elif tick['oi_diff'] < 0 and tick['oi_diff'] + tick['vol_diff'] == 0:
msg = '双平'
else:
if tick['pc'] == 0:
msg = '换手'
else:
msg = ('多' if tick['pc'] > 0 else '空') + ('开' if tick['oi_diff'] > 0 else '平' if tick['oi_diff'] < 0 else '换')
return msg | 89fc7167be63e95bedde5031c4ecb96b9a2296bc | 109,289 |
def time_left_str(since_time):
"""Return a string with how much time is left until
the 1 hour cooldown is over."""
until_available = (60 * 60) - since_time
minute, second = divmod(until_available, 60)
hour, minute = divmod(minute, 60)
return "{:d}:{:02d}:{:02d}".format(hour, minute, second) | 071be855a35daf5b64623784b8015ffe2893e875 | 109,292 |
def split_path(path):
"""
Get the parent path and basename.
>>> split_path('/')
['', '']
>>> split_path('')
['', '']
>>> split_path('foo')
['', 'foo']
>>> split_path('/foo')
['', 'foo']
>>> split_path('/foo/bar')
['/foo', 'bar']
>>> split_path('foo/bar')
['/foo', 'bar']
"""
if not path.startswith('/'): path = '/' + path
return path.rsplit('/', 1) | 44ca28d0877e1f24d62ed5cf246ea007e71aa27e | 109,295 |
def read_spectrum(spectrum, index):
"""Read a single spectrum
Parameters
----------
spectrum : mzML spectrum
The mzML spectrum to parse.
Returns
-------
out : list of tuples
List of values associated with each peak in the spectrum.
"""
polarity = 'MS:1000130' in spectrum
ms_level = spectrum['ms level']
rt, units = spectrum['MS:1000016']
if units != 'minute':
rt /= 60
collision_energy = spectrum.get('MS:1000045', 0)
precursor_intensity = spectrum.get('MS:1000042', 0)
precursor_mz = spectrum.get('MS:1000744', 0)
min_mz = spectrum.get('lowest m/z value', 0)
max_mz = spectrum.get('highest m/z value', 0)
if ms_level == 1:
data = [(mz, i, rt, polarity) for (mz, i) in spectrum.peaks]
else:
data = [(mz, i, rt, polarity, precursor_mz, precursor_intensity,
collision_energy) for (mz, i) in spectrum.peaks]
return data, ms_level, polarity | b3d05c4af829377bcea0e077cd92ceffaca375e5 | 109,299 |
def get_broken_limbs(life):
"""Returns list of broken limbs."""
_broken = []
for limb in life['body']:
if life['body'][limb]['broken']:
_broken.append(limb)
return _broken | 5de9d33885d90ba27a7be90c201d7b61598ec328 | 109,305 |
import re
def strip_prefix(string, strip):
"""
Strips a prefix from a string, if the string starts with the prefix.
:param string: String that should have its prefix removed
:param strip: Prefix to be removed
:return: string with the prefix removed if it has the prefix, or else it
just returns the original string
"""
strip_esc = re.escape(strip)
if re.match(strip_esc, string):
return string[len(strip):]
else:
return string | aff70bfc19206ad7f7123b2be4fdb40c6d9c3828 | 109,308 |
import importlib
def get_module_class(d, c):
"""Load module m in directory d with the class name c."""
m = importlib.import_module('.'.join([d, c]))
return getattr(m, c) | ada580a602a23781923e8fe38b081de5299aa51b | 109,310 |
def set_axes_vis(p, xlabel, ylabel):
""" Set the visibility of axes"""
if not xlabel: p.xaxis.visible = False
if not ylabel: p.yaxis.visible = False
return p | 2a2632b1c041b4957bf08280eeffea9bbc2977f0 | 109,317 |
def get_res_str4WOA18(input):
"""
Convert WOA folder resolution str into filename's resolution str.
"""
d = {
'0.25': '04',
'1.00': '01',
'5deg': '5d',
}
return d[input] | fac2b1471205d876584338f99fb8908ef1139cd6 | 109,319 |
def binary_search_recursive(array, item, left=None, right=None):
"""Return index of item in sorted array or none if item not found."""
# BASE CASE: left and right point to same index
if left == right and left is not None:
# not in array
if left == len(array):
return None
# check if index is item
if array[left] == item:
return left
else:
return None
# if left and right are none set to length arr
if left is None:
left = 0
if right is None:
right = len(array)
# set the middle index
mid = (left + right) // 2
# check if mid index is item
if array[mid] == item:
return mid
# check if index's item is greater
elif array[mid] > item:
# nothing left to search
if left == mid:
return None
# change right to middle index - 1
return binary_search_recursive(array, item, left, mid - 1)
# check if item at index less than
elif array[mid] < item:
# nothing left to search
if right == mid:
return None
# change left to middle index + 1
return binary_search_recursive(array, item, mid + 1, right) | 39fa4f85e789333d35dfcfcf817f4887ea4df9d0 | 109,320 |
import time
def time_solve(sokoban):
""" Time how long it takes to solve a Sokoban game """
t0 = time.time()
result = sokoban.solve()
return (time.time() - t0, result) | d3f2366e2a6d550152dfb3439ac81c36acdf0096 | 109,322 |
def getLnrm(arg, pattern):
"""Normalizes the given arg by stripping it of diacritics, lowercasing, and
removing all non-alphanumeric characters.
"""
arg = pattern.sub('', arg)
arg = arg.lower()
return arg | 4e85bcc315f5f7f14b943cb5f48763e68e826253 | 109,324 |
from pathlib import Path
def fixture_snp_path(fixtures_path: Path) -> Path:
"""Return the path to a file with snp definitions"""
return fixtures_path / "snps.grch37.txt" | 44cb3bfb7d197485668b9cfe84074e61bba1d6aa | 109,325 |
def get_energy(output_parameters):
"""
Given the output parameters of the pw calculation,
return the energy (eV).
"""
E = output_parameters.dict.energy
return (E) | 38a03577ef8b937de2ceae1ac1a943c224095e94 | 109,332 |
import re
def was_replied(df):
"""Looks to see if something like Re or RE: is in the subject. Uses regular expressions
"""
return df['subject'].str.contains('re?\:?\s', flags=re.IGNORECASE).values | 6a4ef72bef1049e8e4c6c707f6c6f7978e1663a2 | 109,335 |
def read_sh(path: str):
"""
read a sh file. skip comment, shebang and qsub params.
Args:
path (str): path to the sh file
Returns:
list: list of lines of the sh file without comment, shebang and qsub params.
"""
lines = []
with open(path) as f:
for line in f:
if line.startswith("#"):
continue
lines.append(line.rstrip("\n"))
return lines | 1ab6f3841cf0870afbbbb8b6349897149bb3697a | 109,337 |
def encrypt(plaintext, rails):
"""
Rail fence cipher. Encrypts plaintext by given number of rails.
:param plaintext: plaintext to encrypt.
:param rails: number of rails to use to encrypt.
:returns: encrypted plaintext (ciphertext).
See https://en.wikipedia.org/wiki/Rail_fence_cipher
Example:
>>> encrypt("DANGEROUS", 2)
'DNEOS AGRU'
>>> encrypt("DANGEROUS", 3)
'DGO AEU NRS'
"""
data = [""] * rails
for index, character in enumerate(plaintext):
data[index % rails] += character
return " ".join(data) | 57b4cf3b71d8ef33f041326d90032beda4da48a9 | 109,339 |
def _sorted_by_type(fields):
"""Sorts params so that strings are placed before files.
That makes a request more readable, as generally files are bigger.
It also provides deterministic order of fields what is easier for testing.
"""
def key(p):
key, val = p
if isinstance(val, (bytes, str)):
return (0, key)
else:
return (1, key)
return sorted(fields, key=key) | 8f08d89a55eeeb3a7b32e4a232134a467905231f | 109,341 |
def owner_id_to_string_array(owner_id):
"""
Converts a snowflake owner id to an array of strings.
Parameters
----------
owner_id : `int`
Snowflake value.
Returns
-------
owner_id_array : `list` of `str`
"""
return [str(owner_id)] | 2083eecc50090ef94631199755f61043f66bd664 | 109,347 |
import json
def read_jobs_statuses(filename):
"""Deserialize statuses for all jobs from the JSON file."""
with open(filename) as fin:
return json.load(fin)["jobs"] | dc05789f342d333e8ee0179ac359b1637a624763 | 109,349 |
def play_episode(env, policy, render_option, min_steps):
"""
Play an episode with the given policy.
:param min_steps: the minimum steps the game should be played
:param env: the OpenAI gym environment
:param policy: the policy that should be used to generate actions
:param render_option: how the game play should be rendered
:return: episode reward
"""
state = env.reset()
done = False
episode_reward = 0.0
step_cnt = 0
while not done or step_cnt < min_steps:
if render_option == 'collect':
env.render()
action = policy(state)
next_state, reward, done, _ = env.step(action)
episode_reward += reward
state = next_state
step_cnt += 1
print('episode finished with reward {0}'.format(episode_reward))
return episode_reward | 4644d80df0dcbfc1ca6172ec949235ea9b2b1f0e | 109,355 |
def read_string(puzzle_string: str):
"""
Read string describing puzzle,
converting it into a form the solver can understand.
puzzle_string: string specifying puzzle
return: array of numbers and operations for each row and column
"""
puzzle = [
part.split(' ')
for part
in puzzle_string.split('\n')
]
puzzle = [
row[:2] + [float(row[2])]
for row
in puzzle
if len(row) == 3
]
return puzzle | 1e6e25b6a58aa16b7a9d23bcc632fc0622b2800a | 109,368 |
def inverse(a, n):
"""Find the multiplicative inverse of one number over a given range.
Adapted from Wikipedia: Extended Euclidian Algorithm -
http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
Returns the multiplicative inverse of a over the finite range n. The result
is a number which, when multiplied by a, will return 1 over range n.
Keyword arguments:
a -- The integer whose multiplicative inverse should be found.
n -- A positive integer defining the numeric range to evaluate.
"""
t = 0
newt = 1
r = n
newr = a
while newr != 0:
quotient = r // newr
t, newt = newt, t - quotient * newt
r, newr = newr, r - quotient * newr
if r > 1: return None
if t < 0: t = t + n
return t | d1c8d624c912e51d01f9da2e63bea50794b0f48f | 109,370 |
def fib_from_pascal(m):
"""Return the mth fibonacci number using Pascal's triangle."""
def fib_pascal(n, fib_pos):
if n == 1:
line = [1]
fib_sum = 1 if fib_pos == 0 else 0
else:
line = [1]
prev, fib_sum = fib_pascal(n - 1, fib_pos + 1)
line.extend(prev[i] + prev[i + 1] for i in range(len(prev) - 1))
line.append(1)
if fib_pos < len(line):
fib_sum += line[fib_pos]
return line, fib_sum
return fib_pascal(m, 0)[1] | 658ed4ef2142b6e13805a9e57687190167e788b4 | 109,374 |
def file_extension(filename):
"""
Return the extension of a file (if any)
"""
parts = filename.split(".")
if len(parts) >= 2:
return parts[-1]
else:
return "" | fa230dce3b05ca16c27470140ad6a32e8f497068 | 109,376 |
def stopw_removal(inp, stop):
"""
Stopwords removal in line of text.
Input:
- inp: str,
string of the text input
- stop: list,
list of stop-words to be removed
"""
# Final string to be returned
final = ''
for w in inp.lower().split():
if w not in stop:
final += w + ' '
# Remove last whitespace that was added ' '
final = final[:-1]
return final | ec7f386cc66b8673ee00f18d9f6a3e62eb06731e | 109,378 |
def _select_points(a, list_like):
"""
returns one above a, one below a, and the third
closest point to a sorted in ascending order
for quadratic interpolation. Assumes that points
above and below a exist.
"""
foo = [x for x in list(list_like) if x-a <= 0]
z = [min(foo, key=lambda x : abs(x-a))]
foo = [x for x in list(list_like) if x-a > 0]
z.append(min(foo, key=lambda x : abs(x-a)))
foo = [x for x in list(list_like) if x not in z]
z.append(min(foo, key=lambda x : abs(x-a)))
return sorted(z) | 4487336f10a2d08561bf38ee095be9f21f05d078 | 109,380 |
def mid_point(start_x, start_y, end_x, end_y):
"""
returns the mid point of two points
"""
mid_x = (start_x + end_x) / 2
mid_y = (start_y + end_y) / 2
return mid_x, mid_y | f445dcea7827bb57d4f96690ef2eae9578278660 | 109,383 |
def _field_path_to_elasticsearch_field_name(field_path):
"""Take a field_path tuple - for example: ("va", "info", "AC"), and converts it to an
elasicsearch field name.
"""
# drop the 'v', 'va' root from elastic search field names
return "_".join(field_path[1:] if field_path and field_path[0] in ("v", "va") else field_path) | d215378cb40d2d4bd8c6a99c1c655c5a2e5aa905 | 109,384 |
from typing import Callable
def locate_resource(name: str) -> Callable:
""" Locate a resource (module, func, etc) within the module's namespace """
resource = globals()[name]
return resource | 392d6b4daac711cb9a33907e3ce8f439a0022a61 | 109,385 |
def pattern_from_multiline(multiline, pattern):
"""Return only lines that contain the pattern
Parameters
----------
multiline - multiline str
pattern - str
Returns
-------
multiline str containing pattern
"""
return "\n".join([line for line in multiline.splitlines() if pattern in line]) | d8be4e97fa53fccb3869a59a0725fbc88f2f2ba9 | 109,386 |
def get_sourced_from(entry):
"""Get a list of values from the source_from attribute"""
sourced_from = 'http://worldmodelers.com/DataProvenance#sourced_from'
if sourced_from in entry:
values = entry[sourced_from]
values = [i['@id'] for i in values]
return values | a4b7751eae4c5c49938cee0765b80828d14f2854 | 109,387 |
def fast_mean_variance_update(new_sample, old_mean, old_variance, k):
"""
Return the new mean and variance if one new sample is added.
"""
new_mean = (k * old_mean + new_sample)/(k+1)
new_variance = (k-1) * old_variance / k + (new_sample - old_mean)**2/(k+1)
return new_mean, new_variance | 12097acde4eecdf5df222c1af8f83d27f2f6b46f | 109,388 |
def to_code(cells):
"""
Turns the cells into Python code.
:param cells: the cells to iterate
:type cells: list
:return: the generated code
:rtype: list
"""
result = []
for cell in cells:
if ("cell_type" in cell):
if (cell["cell_type"] == "code") and ("source" in cell):
for line in cell["source"]:
if ("%" in line) and ("pip " in line):
result.append("# " + line.rstrip())
else:
result.append(line.rstrip())
elif (cell["cell_type"] == "markdown") and ("source" in cell):
for line in cell["source"]:
result.append("# " + line.rstrip())
result.append("")
return result | 38c21ba513fd27ea41fd226607bdc230f26c7bb8 | 109,391 |
def get_hostname_to_data_dict(fio_data):
"""Create dictionary mapping hostname to its fio data.
Returns:
Dict[str, List[dict]] - hostname to its fio data
"""
hostname_data_dict = {}
for jb in fio_data['client_stats']:
if jb['jobname'] == 'All clients':
continue
hostname = jb['hostname']
if hostname not in hostname_data_dict:
hostname_data_dict[hostname] = [jb]
else:
hostname_data_dict[hostname].append(jb)
return hostname_data_dict | 15c3b2b2159332634648a62f7ca31bc4d660e498 | 109,392 |
def vect3_subtract(v1, v2):
"""
Subtracts one 3d vector from another.
v1, v2 (3-tuple): 3d vectors
return (3-tuple): 3d vector
"""
return (v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2]) | b5710e04d80340f731db55b472e690fdfcba9f7a | 109,397 |
def add_base_class_to_instance(instance, base_class=None, new_name=None):
"""
Generic utility for adding a base class to an instance.
This function returns a copy of the given instance which
will then include the new base_class in its ``__mro__``.
The way that is done internally is it creates a brand new
class with correct bases. Then the newly created class is
instantiated. Since ``__init__`` could be expensive operation
in any of the base classes of the original instance mro,
nto make it cheap, we temporarily switch __init__ with
super simple implementation which does nothing but only
instantiates class. Once instantiated, then we copy all of the
instance attributes to the newly created instance.
Finally, then we pop our mock ``__init__`` implementation.
Args:
instance (object): Instance of any object
base_class (type): Any class which will be added as first class
in the newly copied instance mro.
Returns:
Shallow copy of ``instance`` which will also inherit ``base_class``.
"""
# overwrite __init__ since that is mainly responsible for setting
# instance state but since we explicitly copy it, we can
# make __init__ a noop method
def __init__(self, *args, **kwargs):
pass
if base_class is not None and base_class not in instance.__class__.mro():
base_classes = (base_class, instance.__class__)
else:
base_classes = (instance.__class__,)
new_field_class = type(
str(new_name or instance.__class__.__name__),
base_classes,
{'__init__': __init__}
)
new_instance = new_field_class()
new_instance.__dict__.update(instance.__dict__)
# we added __init__ just for faster instantiation
# since then we dont have to copy all the parameters
# when creating new instance and then update its state
# however after we instantiated the class, we want to
# pop our silly __init__ implementation so that if somebody
# wants to instantiate instance.__class__(), it will
# use the original __init__ method
del new_field_class.__init__
return new_instance | 4c4f07922d5b79cf72d5ab10e7634e96688199b3 | 109,399 |
def calc_completeness(req_tags, tags):
"""Takes in a list of required tags and
tags found. Returns a string status of
completion depending if all required tags
were found."""
status = "Incomplete"
result = all(k in tags for k in req_tags)
if result:
status = "Complete"
return status | ca2213ef144e4a59621fd48eb48553399b67a8b6 | 109,401 |
def heuristic(node, goal)->int:
"""
Heuristic function that estimates the cost of the cheapest path from node to the goal.
In our case it is simple manhatan distance.
:param node:
:param goal:
:return: Manhatan distance of nodes
"""
# expand nodes
x1, y1 = node.get_pos()
x2, y2 = goal.get_pos()
# compute
return abs(x1 - x2) + abs(y1 - y2) | b625872a0eef65e860a41f768975f724b9f8cbb6 | 109,402 |
def max_divisible(a, b):
"""
Keep dividing(a/b) till it's divisible(a % b == 0)
e.g.
Input: a = 300; b = 2
Output: 75
:param a:
:param b:
:return:
"""
while a % b == 0:
a = a / b
return a | 66c4df2e935db614c40a509569ceaa46a7141f3b | 109,403 |
def textwrap(text, width=80, indent=0):
"""Wrap a string with 80 characters
:param text: input text
:param width: (defaults to 80 characters)
:param indent: possible indentation (0 by default)
"""
if indent == 0:
indent = ""
else:
indent = " " * indent
data = [indent + text[i*width:(i+1)*width:] for i in range(len(text)//width + 1)]
return "\n".join(data) | e963d0a0f72205816fa5f4b74471873189521392 | 109,412 |
def calc_check_digit(number):
"""Calculate the check digit.
The number passed should not have the check digit included.
"""
primary_weights = (3, 2, 7, 6, 5, 4, 3, 2)
secondary_weights = (7, 4, 3, 2, 5, 2, 7, 6)
# pad with leading zeros
number = (8 - len(number)) * '0' + number
s = -sum(w * int(n) for w, n in zip(primary_weights, number)) % 11
if s != 10:
return str(s)
s = -sum(w * int(n) for w, n in zip(secondary_weights, number)) % 11
return str(s) | 253159db05c0796f744acc027fca0687d69efc61 | 109,413 |
def env_str_to_bool(varname, val):
"""Convert the boolean environment value string `val` to a Python bool
on behalf of environment variable `varname`.
"""
if val in ["False", "false", "FALSE", "F", "f", "0", False, 0]:
rval = False
elif val in ["True", "true", "TRUE", "T", "t", "1", True, 1]:
rval = True
else:
raise ValueError("Invalid value " + repr(val) +
" for boolean env var " + repr(varname))
return rval | 6572a4368f492510b6287a49ef38be2ef614dca0 | 109,414 |
def wrapseq(seq, size=60):#{{{
"""
wrap the sequence in to a list of fixed length
"""
return [seq[i:i+size] for i in range(0, len(seq), size)] | 1932bd6caef677337de12a88495fb64917446518 | 109,415 |
import functools
def wrap(before=None, after=None, condition=lambda *args, **kwargs: True):
"""
A helper for creating decorators.
Runs a "before" function before the decorated function, and an "after"
function afterwards. The condition check is performed once before
the decorated function.
"""
def decorator(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
yes = condition(*args, **kwargs)
if yes and before:
before()
result = func(*args, **kwargs)
if yes and after:
after()
return result
return wrapped
return decorator | ca9e6c4a41f93ca2902fe7e7c9fbbb2a96826064 | 109,418 |
from typing import Dict
from typing import Any
def default_style() -> Dict[str, Any]:
"""Define default values of the pulse stylesheet."""
return {
'formatter.general.fig_size': [8, 6],
'formatter.general.dpi': 150,
'formatter.color.fill_waveform_d': ['#648fff', '#002999'],
'formatter.color.fill_waveform_u': ['#ffb000', '#994A00'],
'formatter.color.fill_waveform_m': ['#dc267f', '#760019'],
'formatter.color.fill_waveform_a': ['#dc267f', '#760019'],
'formatter.color.baseline': '#000000',
'formatter.color.barrier': '#222222',
'formatter.color.background': 'f2f3f4',
'formatter.color.annotate': '#222222',
'formatter.color.frame_change': '#000000',
'formatter.color.snapshot': '#000000',
'formatter.color.axis_label': '#000000',
'formatter.alpha.fill_waveform': 1.0,
'formatter.alpha.baseline': 1.0,
'formatter.alpha.barrier': 0.7,
'formatter.layer.fill_waveform': 2,
'formatter.layer.baseline': 1,
'formatter.layer.barrier': 1,
'formatter.layer.annotate': 4,
'formatter.layer.axis_label': 4,
'formatter.layer.frame_change': 3,
'formatter.layer.snapshot': 3,
'formatter.margin.top': 0.2,
'formatter.margin.bottom': 0.2,
'formatter.margin.left': 0.05,
'formatter.margin.right': 0.05,
'formatter.margin.between_channel': 0.1,
'formatter.label_offset.pulse_name': -0.1,
'formatter.label_offset.scale_factor': -0.1,
'formatter.label_offset.frame_change': 0.1,
'formatter.label_offset.snapshot': 0.1,
'formatter.text_size.axis_label': 15,
'formatter.text_size.annotate': 12,
'formatter.text_size.frame_change': 20,
'formatter.text_size.snapshot': 20,
'formatter.text_size.fig_title': 15,
'formatter.line_width.fill_waveform': 0,
'formatter.line_width.baseline': 1,
'formatter.line_width.barrier': 1,
'formatter.line_style.fill_waveform': '-',
'formatter.line_style.baseline': '-',
'formatter.line_style.barrier': ':',
'formatter.control.apply_phase_modulation': True,
'formatter.control.show_snapshot_channel': True,
'formatter.control.show_acquire_channel': True,
'formatter.control.show_empty_channel': True,
'formatter.unicode_symbol.frame_change': u'\u21BA',
'formatter.unicode_symbol.snapshot': u'\u21AF',
'formatter.latex_symbol.frame_change': r'\circlearrowleft',
'formatter.latex_symbol.snapshot': '',
'generator.waveform': [],
'generator.frame': [],
'generator.channel': [],
'generator.snapshot': [],
'generator.barrier': []} | a516ad47fa4f90cca3533c6c7bc643ce874329b5 | 109,421 |
import torch
def diff(x: torch.Tensor, dim: int) -> torch.Tensor:
"""Take the finite difference of a tensor along an axis.
Arguments:
x (torch.Tensor):
Input tensor of any dimension.
axis (int):
Axis on which to take the finite difference.
Returns:
d (torch.Tensor):
Tensor with size less than x by 1 along the difference dimension.
Raises:
ValueError: Axis out of range for tensor.
"""
length = x.shape[dim]
return x.narrow(dim, 1, length-1) - x.narrow(dim, 0, length-1) | d705b586b7cec135474d616ce2edca748d1fa15f | 109,429 |
def has_spdx_licenses(resource):
"""
Return True if a Resource licenses are all known SPDX licenses.
"""
if resource.scan_errors:
return False
for detected_license in resource.licenses:
if not detected_license.get('spdx_license_key'):
return False
return True | 06048d6806c4d056ef8df581aa7b860e8469a88c | 109,430 |
def get_number_from_string(s, number_type, default):
"""Returns a numeric value of number_type created from the given string or default if the cast is not possible."""
try:
return number_type(s.replace(",", "."))
except ValueError:
return default | f4905debb35daefb1b9490142009f7827c345a1e | 109,432 |
def _get_factory_attr(factory, attr):
"""
Try getting a meta attribute 'attr' from a factory.
The attribute is looked up as '_attr' on the factory, then, if the factory
and its model class names match, as 'attr' on the model's meta. The
factory's own meta cannot define custom attributes and is skipped.
If the attribute is not found in either place, an AttributeError is raised.
"""
try:
return getattr(factory, "_" + attr)
except AttributeError:
# pylint:disable=protected-access
if factory.__name__ == factory._meta.model.__name__ + "Factory":
return getattr(factory._meta.model._meta, attr)
else:
raise | 29f8a87fdf573b0fae3864f2fa00ba0ef263ffac | 109,435 |
def _get_spm_arch(swift_cpu):
"""Maps the Bazel architeture value to a suitable SPM architecture value.
Args:
bzl_arch: A `string` representing the Bazel architecture value.
Returns:
A `string` representing the SPM architecture value.
"""
# No mapping at this time.
return swift_cpu | d44dc3bcccbe44dfd9203a3aea21920e8e907e74 | 109,442 |
import math
def truncate(x:float)->int:
"""
Float to int truncating for possitive and negative values.
x - float to be truncated.
return truncated int.
"""
return math.floor(x) if x<0 else math.ceil(x) | b163a11cc00d679d4f94886780672236cc12f8ef | 109,444 |
def cleanup_watch(watch):
"""Given a dictionary of a watch record, return a new dictionary for output
as JSON."""
watch_data = watch
watch_data["id"] = str(watch["_id"])
watch_data["author"] = str(watch["author"])
watch_data["watched"] = str(watch["watched"])
del watch_data["_id"]
return watch_data | e464764c2360486fc8ba3008b77f508ff950a882 | 109,448 |
import io
def export_sass(palette):
"""
Return a string of Sass variable for every colors.
Arguments:
palette (dict): Dictionnary of named colors (as dumped in JSON from
``colors`` command)
Returns:
string: Sass variables.
"""
# Sass color palette variable
sass_palette = io.StringIO()
for original_code, values in sorted(palette.items(), key=lambda x:x[1]):
name, from_color = values
sass_palette.write('${}: {};\n'.format(name, original_code))
output = sass_palette.getvalue()
sass_palette.close()
return output | c6c6f870d60fb9b5e71bb7697f2218a2ff2904fc | 109,449 |
def is_removable(queue_url) -> bool:
"""
Returns True if the queue url does not end with staging or production
:param str queue_url: The queue url
:return bool:
"""
if str(queue_url).endswith("staging") == True \
or str(queue_url).endswith("production") == True:
return False
return True | 04e822f9571b9ee5c181e23e2c79b3a3d72610e9 | 109,450 |
from typing import Tuple
def _pad_strides(strides: int, axis: int) -> Tuple[int, int, int, int]:
"""Converts int to len 4 strides (`tf.nn.avg_pool` uses length 4)."""
if axis == 1:
return (1, 1, strides, strides)
else:
return (1, strides, strides, 1) | 8cd91ea7e04b2c032505d51d68a6d4ad088d5934 | 109,452 |
def nucl_count(sequence):
"""determine counts of each letter in a sequence,
return dictionary with counts"""
nucl = {'A': 0, 'C': 0, 'G': 0, 'T': 0, 'N': 0}
for letter in sequence:
if letter not in nucl:
print(f'unexpected nucleotide found: "{letter}"')
nucl[letter] = 0
nucl[letter] += 1
return nucl | 4082ef833cb857dab64fdb897a4be3495d67c482 | 109,453 |
def bhp2watts(bhp):
"""convert brake horsepower (bhp) to watts"""
return bhp * 745.7 | 8a1ffdf59104431d0e78353b7ba9f52408c5ebc4 | 109,462 |
import inspect
def nargs(fun):
"""Get the number of arguments of a function"""
return len(inspect.signature(fun).parameters) | ccf278bda20f9e8c49bcf141f21e1654c30b599f | 109,465 |
def camelcased_to_uppercased_spaced(camelcased: str) -> str:
"""Util function to transform a camelCase string to a UPPERCASED SPACED string
e.g: dockerImageName -> DOCKER IMAGE NAME
Args:
camelcased (str): The camel cased string to convert.
Returns:
(str): The converted UPPERCASED SPACED string
"""
return "".join(map(lambda x: x if x.islower() else " " + x, camelcased)).upper() | e9a01ee1fdbc6ea626ed509d68ec3ae799c2a007 | 109,470 |
def ordinalStr(n) :
"""
Given the positive integer n, return the corresponding ordinal number string
"""
assert(n>0)
def getSuffix(n) :
def getOrdKey(n) :
if n < 14 : return n
else : return (n % 10)
i = getOrdKey(n)
if i == 1: return 'st'
elif i == 2: return 'nd'
elif i == 3: return 'rd'
else : return 'th'
return str(n) + getSuffix(n) | 9736abc3cce2611fb3ce60a6903a7f77ed026998 | 109,472 |
def configure_proxy_settings(ip, port, username=None, password=None):
"""
Configuring proxies to pass to request
:param ip: The IP address of the proxy you want to connect to ie 127.0.0.1
:param port: The port number of the prxy server you are connecting to
:param username: The username if requred authentication, need to be accompanied with a `password`.
Will default to None to None if not provided
:param password: The password if required for authentication. Needs to be accompanied by a `username`
Will default to None if not provided
:return: A dictionary of proxy settings
"""
proxies = None
credentials = ''
# If no IP address or port information is passed, in the proxy information will remain `None`
# If no proxy information is set, the default settings for the machine will be used
if ip is not None and port is not None:
# Username and password not necessary
if username is not None and password is not None:
credentials = '{}:{}@'.format(username, password)
proxies = {'http': 'http://{credentials}{ip}:{port}'.format(credentials=credentials, ip=ip, port=port),
'https': 'https://{credentials}{ip}:{port}'.format(credentials=credentials, ip=ip, port=port)
}
return proxies | 1e24d07f1039c8538033561a41c9cc01dc74b17f | 109,477 |
def _summary_name(node):
"""
Generate summary label for node based on its package, type, and name
"""
if node.name:
return "%s (%s/%s)"%(node.name, node.package, node.type)
else:
return "%s/%s"%(node.package, node.type) | b5633207dd78d0dedd68c96ef6e7e14bfb1760cd | 109,480 |
import requests
from bs4 import BeautifulSoup
import re
import itertools
def translate(word: str) -> list:
"""Translate word
Arguments:
word {str} -- the word to be translated
Returns:
[list] -- list of translations
"""
req = requests.get(f"https://www.diki.pl/slownik-angielskiego?q={word}")
page = BeautifulSoup(req.text, "html.parser")
find_li = page.find_all("li", re.compile("meaning*"))
find_a = [x.find_all("a", "plainLink") for x in find_li]
flatten = itertools.chain().from_iterable(find_a)
translated: list = [x.text for x in flatten]
return translated | 37281a50c9c8d787cdc643eb6945de6d118f85b8 | 109,485 |
def min_max_denorm(data, min_, max_):
"""
Denormalize the data using that was normalized using min-max normalization
:param data: 1d array of power consumption
:param min: the min of the power consumption
:param max: the max of the power consumption
:return: denormalized power consumption
"""
return data * (max_ - min_) + min_ | e88346945aff245566bb21b1a50e828ff79115f8 | 109,492 |
def get_covid_ids(projs):
"""Returns covid-related ids in cordis data"""
d_ids = set(
projs.loc[
(projs["covid_level"] != "non_covid") | (projs["has_covid_term"] == True)
]["project_id"]
)
return d_ids | f57391338744d6357396dd81c6702d310801a820 | 109,493 |
def d2arcs(d):
"""Convert degrees into arcseconds."""
return d * 3600.0 | 87c897170dce450764fb6dbd2b12795969f7e64c | 109,495 |
import re
def _matching_ints(strings, regex):
"""Uses regular expression to select and then extract an integer from
strings.
Parameters
----------
strings : list of strings
regex : string
Regular Expression. Including one group. This group is used to
extract the integer from each string.
Returns
-------
list of ints
"""
ints = []
p = re.compile(regex)
for string in strings:
m = p.match(string)
if m:
integer = int(m.group(1))
ints.append(integer)
ints.sort()
return ints | 0b13031c5ede9b5af04ed8bd9d40e9c0895e5ce5 | 109,500 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.