content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_rb_data_attribute(xmldict, attr):
"""Get Attribute `attr` from dict `xmldict`
Parameters
----------
xmldict : dict
Blob Description Dictionary
attr : str
Attribute key
Returns
-------
sattr : int
Attribute Values
"""
try:
sattr = int(xml... | dfc48ad47f67b2303874154ce4a164a176c1f4bf | 707,786 |
def tls_params(mqtt_config):
"""Return the TLS configuration parameters from a :class:`.MQTTConfig`
object.
Args:
mqtt_config (:class:`.MQTTConfig`): The MQTT connection settings.
Returns:
dict: A dict {'ca_certs': ca_certs, 'certfile': certfile,
'keyfile': keyfile} with the TL... | 4b5d214a50fea60f5cb325fc7a0c93dfa9cb3c02 | 707,787 |
def segment_range_to_fragment_range(segment_start, segment_end, segment_size,
fragment_size):
"""
Takes a byterange spanning some segments and converts that into a
byterange spanning the corresponding fragments within their fragment
archives.
Handles prefix, suff... | e20c9bb55d9d3e90beb20bed7a170d1066611ba9 | 707,788 |
def test_function_decorators():
"""Function Decorators."""
# Function decorators are simply wrappers to existing functions. Putting the ideas mentioned
# above together, we can build a decorator. In this example let's consider a function that
# wraps the string output of another function by p tags.
... | 03b3ba299ceb7a75b0de1674fabe892243abd8b3 | 707,789 |
import os
import sys
def exists_case_sensitive(path: str) -> bool:
"""Returns if the given path exists and also matches the case on Windows.
When finding files that can be imported, it is important for the cases to match because while
file os.path.exists("module.py") and os.path.exists("MODULE.py") both ... | a879f950bcfb6739db3bfe620a75591de92a7a35 | 707,790 |
def generate_parallelogrammatic_board(width=5, height=5):
"""
Creates a board with a shape of a parallelogram.
Width and height specify the size (in fields) of the board.
"""
return [[1] * height for _ in range(width)] | 1c9bd6e6e26f6693b434d44e6dbe4085ba9236b8 | 707,791 |
import torch
def where(condition, x, y):
"""Wrapper of `torch.where`.
Parameters
----------
condition : DTensor of bool
Where True, yield x, otherwise yield y.
x : DTensor
The first tensor.
y : DTensor
The second tensor.
"""
return torch.where(condition, x, y) | 0ec419e19ab24500f1be6c511eb472d1d929fe2c | 707,792 |
def _xyz_atom_coords(atom_group):
"""Use this method if you need to identify if CB is present in atom_group and if not return CA"""
tmp_dict = {}
for atom in atom_group.atoms():
if atom.name.strip() in {"CA", "CB"}:
tmp_dict[atom.name.strip()] = atom.xyz
if 'CB' in tmp_dict:
... | fd7ef43b1935f8722b692ad28a7e8b309033b720 | 707,793 |
from typing import get_origin
from typing import Tuple
def is_tuple(typ) -> bool:
"""
Test if the type is `typing.Tuple`.
"""
try:
return issubclass(get_origin(typ), tuple)
except TypeError:
return typ in (Tuple, tuple) | c8c75f4b1523971b20bbe8c716ced53199150b95 | 707,794 |
import functools
import unittest
def _skip_if(cond, reason):
"""Skip test if cond(self) is True"""
def decorator(impl):
@functools.wraps(impl)
def wrapper(self, *args, **kwargs):
if cond(self):
raise unittest.SkipTest(reason)
else:
impl(s... | 4141cc1f99c84633bdf2e92941d9abf2010c11f6 | 707,795 |
import ctypes
def destructor(cfunc):
"""
Make a C function a destructor.
Destructors accept pointers to void pointers as argument. They are also wrapped as a staticmethod for usage in
classes.
:param cfunc: The C function as imported by ctypes.
:return: The configured destructor.
"""
... | 05abd181649a2178d4dce704ef93f61eb5418092 | 707,796 |
def update_file_info_in_job(job, file_infos):
"""
Update the 'setup.package.fileInformations' data in the JSON to append new file information.
"""
for file_info in file_infos:
try:
job['setup']['package']['fileInformations'].append(file_info)
except (KeyError, TypeError, Attr... | 9902173548d72fcd35c8f80bb44b59aac27d9401 | 707,797 |
import math
def distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Finds distance between two given points
Parameters:
x1, y1 : The x and y coordinates of first point
x2, y2 : The x and y coordinates of second point
Returns:
... | 63f103f46b52aae146b52f385e15bc3441f042e5 | 707,798 |
def _str_trim_left(x):
"""
Remove leading whitespace.
"""
return x.str.replace(r"^\s*", "") | 2718086073706411929b45edf80a1d464dfaeff6 | 707,799 |
def print_formula(elements):
"""
The input dictionary, atoms and their amount, is processed to produce
the chemical formula as a string
Parameters
----------
elements : dict
The elements that form the metabolite and their corresponding amount
Returns
-------
formula : str
... | a3c404ef0d18c417e44aee21106917f4ee203065 | 707,801 |
import unicodedata
def is_chinese_char(cc):
"""
Check if the character is Chinese
args:
cc: char
output:
boolean
"""
return unicodedata.category(cc) == 'Lo' | d376e6097e628ac2f3a7934ba42ee2772177f857 | 707,802 |
def is_quant_contam(contam_model):
"""Get the flag for quantitative contamination"""
# the list of quantitative models
quant_models = ['GAUSS', 'FLUXCUBE']
# set the default value
isquantcont = True
# check whether the contamination is not quantitative
if not contam_model.upper() in quant_... | 8a88609857ac8eb61bfddfa8d8227ffa237d2641 | 707,803 |
def format_component_descriptor(name, version):
"""
Return a properly formatted component 'descriptor' in the format
<name>-<version>
"""
return '{0}-{1}'.format(name, version) | 2edb92f20179ae587614cc3c9ca8198c9a4c240e | 707,804 |
import sqlite3
def dbconn():
"""
Initializing db connection
"""
sqlite_db_file = '/tmp/test_qbo.db'
return sqlite3.connect(sqlite_db_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) | b0c6dd235490cee93ada20f060d681a319b120f0 | 707,805 |
def get_r(x, y, x1, y1):
"""
Get r vector following Xu et al. (2006) Eq. 4.2
x, y = arrays; x1, y1 = single points; or vice-versa
"""
return ((x-x1)**2 + (y-y1)**2)**0.5 | 424408f86e6e3301ee6eca72e2da7da5bf1f8140 | 707,807 |
import re
def replace_empty_bracket(tokens):
"""
Remove empty bracket
:param tokens: List of tokens
:return: Fixed sequence
"""
merged = "".join(tokens)
find = re.search(r"\{\}", merged)
while find:
merged = re.sub(r"\{\}", "", merged)
find = re.search(r"\{\}", merged)
... | fd2c9f2f1c2e199056e89dbdba65f92e4d5834eb | 707,808 |
def extra_credit(grades,students,bonus):
"""
Returns a copy of grades with extra credit assigned
The dictionary returned adds a bonus to the grade of
every student whose netid is in the list students.
Parameter grades: The dictionary of student grades
Precondition: grades has netids as keys, i... | 334a9edb3d1d045832009e20c6cba7f24e5c181d | 707,809 |
def get_rectangle(origin, end):
"""Return all points of rectangle contained by origin and end."""
size_x = abs(origin[0]-end[0])+1
size_y = abs(origin[1]-end[1])+1
rectangle = []
for x in range(size_x):
for y in range(size_y):
rectangle.append((origin[0]+x, origin[1]+y))
retu... | 36badfd8aefaaeda806215b02ed6e92fce6509a3 | 707,810 |
def policy(Q):
"""Hard max over prescriptions
Params:
-------
* Q: dictionary of dictionaries
Nested dictionary representing a table
Returns:
-------
* policy: dictonary of states to policies
"""
pol = {}
for s in Q:
pol[s] = max(Q[s].items(), key=lambda... | e69f66fba94b025034e03428a5e93ba1b95918e8 | 707,811 |
def user_directory_path(instance, filename):
"""Sets path to user uploads to: MEDIA_ROOT/user_<id>/<filename>"""
return f"user_{instance.user.id}/{filename}" | 84be5fe74fa5059c023d746b2a0ff6e32c14c10d | 707,812 |
def pa11y_counts(results):
"""
Given a list of pa11y results, return three integers:
number of errors, number of warnings, and number of notices.
"""
num_error = 0
num_warning = 0
num_notice = 0
for result in results:
if result['type'] == 'error':
num_error += 1
... | 346c1efe0cae5934e623a8643b0f23f85300181d | 707,813 |
import requests
def http_request(method, url, headers, data=None):
"""
Request util
:param method: GET or POST or PUT
:param url: url
:param headers: headers
:param data: optional data (needed for POST)
:return: response text
"""
response = requests.request(method, url, headers=hea... | 6d0453be79b3ae0f7ed60b5a8759b9295365dd6c | 707,814 |
def parse_title(line):
"""if this is title, return Tuple[level, content],
@type line: str
@return: Optional[Tuple[level, content]]
"""
line = line.strip()
if not line.startswith('#'):
return None
sharp_count = 0
for c in line:
if c == '#':
sharp_count += 1
... | 7c170f417755c878d225b780b8475a379501c19f | 707,815 |
def postprocess(backpointers, best_tag_id):
"""Do postprocess."""
best_tag_id = best_tag_id.asnumpy()
batch_size = len(best_tag_id)
best_path = []
for i in range(batch_size):
best_path.append([])
best_local_id = best_tag_id[i]
best_path[-1].append(best_local_id)
for b... | 5be856610a3c81453c11c584507dcb4ad0e4cf61 | 707,816 |
def f(p, x):
"""
Parameters
----------
p : list
A that has a length of at least 2.
x : int or float
Scaling factor for the first variable in p.
Returns
-------
int or float
Returns the first value in p scaled by x, aded by the second value in p.
Examples
... | 3a5e464e7599b6233086e3dddb623d88c6e5ccb6 | 707,817 |
import requests
def pairs_of_response(request):
"""pairwise testing for content-type, headers in responses for all urls """
response = requests.get(request.param[0], headers=request.param[1])
print(request.param[0])
print(request.param[1])
return response | f3a67b1cbf41e2c2e2aa5edb441a449fdff0d8ae | 707,818 |
import itertools
import functools
def next_count(start: int = 0, step: int = 1):
"""Return a callable returning descending ints.
>>> nxt = next_count(1)
>>> nxt()
1
>>> nxt()
2
"""
count = itertools.count(start, step)
return functools.partial(next, count) | 299d457b2b449607ab02877eb108c076cb6c3e16 | 707,819 |
import json
def make_img_id(label, name):
""" Creates the image ID for an image.
Args:
label: The image label.
name: The name of the image within the label.
Returns:
The image ID. """
return json.dumps([label, name]) | 4ddcbf9f29d8e50b0271c6ee6260036b8654b90f | 707,820 |
def CalculatePercentIdentity(pair, gap_char="-"):
"""return number of idential and transitions/transversions substitutions
in the alignment.
"""
transitions = ("AG", "GA", "CT", "TC")
transversions = ("AT", "TA", "GT", "TG", "GC", "CG", "AC", "CA")
nidentical = 0
naligned = 0
ndifferent... | 84d67754d9f63eaee5a172425ffb8397c3b5a7ff | 707,821 |
def scale(pix, pixMax, floatMin, floatMax):
""" scale takes in
pix, the CURRENT pixel column (or row)
pixMax, the total # of pixel columns
floatMin, the min floating-point value
floatMax, the max floating-point value
scale returns the floating-point value that
corresp... | 455d0233cbeeafd53c30baa4584dbdac8502ef94 | 707,822 |
def make_set(value):
"""
Takes a value and turns it into a set
!!!! This is important because set(string) will parse a string to
individual characters vs. adding the string as an element of
the set i.e.
x = 'setvalue'
set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'}
make_set(x) ... | c811729ea83dc1fbff7c76c8b596e26153aa68ee | 707,823 |
def dt642epoch(dt64):
"""
Convert numpy.datetime64 array to epoch time
(seconds since 1/1/1970 00:00:00)
Parameters
----------
dt64 : numpy.datetime64
Single or array of datetime64 object(s)
Returns
-------
time : float
Epoch time (seconds since 1/1/1970 00:00:00)
... | f7cdaf44312cb0564bf57393a5fde727bc24e566 | 707,824 |
import math
def calc_val_resize_value(input_image_size=(224, 224),
resize_inv_factor=0.875):
"""
Calculate image resize value for validation subset.
Parameters:
----------
input_image_size : tuple of 2 int
Main script arguments.
resize_inv_factor : float
... | 5a8bcb77d849e62ef5ecfad74f5a3470ab4cfe59 | 707,825 |
from typing import Optional
def unformat_number(new_str: str, old_str: Optional[str], type_: str) -> str:
"""Undoes some of the locale formatting to ensure float(x) works."""
ret_ = new_str
if old_str is not None:
if type_ in ("int", "uint"):
new_str = new_str.replace(",", "")
... | 419698cf46c1f6d3620dbb8c6178f0ba387ef360 | 707,826 |
import os
def mkdirs(path, raise_path_exits=False):
"""Create a dir leaf"""
if not os.path.exists(path):
os.makedirs(path)
else:
if raise_path_exits:
raise ValueError('Path %s has exitsted.' % path)
return path | d2491589f2ee9d9aa9b9ceeb5ae8d0f678fc5473 | 707,827 |
def cli(ctx, comment, metadata=""):
"""Add a canned comment
Output:
A dictionnary containing canned comment description
"""
return ctx.gi.cannedcomments.add_comment(comment, metadata=metadata) | bacfab650aac1a1785a61756a7cbf84aab7df77a | 707,828 |
def PyException_GetCause(space, w_exc):
"""Return the cause (another exception instance set by raise ... from ...)
associated with the exception as a new reference, as accessible from Python
through __cause__. If there is no cause associated, this returns
NULL."""
w_cause = space.getattr(w_exc, spa... | dce5c1df12af7074ce25387e493ccac1aaac27ec | 707,829 |
def splitclass(classofdevice):
"""
Splits the given class of device to return a 3-item tuple with the
major service class, major device class and minor device class values.
These values indicate the device's major services and the type of the
device (e.g. mobile phone, laptop, etc.). If you google ... | 37c19ab17293b4fd0c46cff24c30e349459f7bd0 | 707,830 |
def get_positive(data_frame, column_name):
"""
Query given data frame for positive values, including zero
:param data_frame: Pandas data frame to query
:param column_name: column name to filter values by
:return: DataFrame view
"""
return data_frame.query(f'{column_name} >= 0') | 2aec7f611a1b181132f55f2f3ca73bf5025f2474 | 707,831 |
import argparse
def _get_server_argparser():
"""
Create a :class:`argparse.ArgumentParser` with standard configuration
options that cli subcommands which communicate with a server require, e.g.,
hostname and credential information.
:return: the argparser
:rtype: argparse.ArgumentParser
""... | 0e9300600640e622cd26ba76145f33ca682e6e4c | 707,832 |
def is_internet_file(url):
"""Return if url starts with http://, https://, or ftp://.
Args:
url (str): URL of the link
"""
return (
url.startswith("http://")
or url.startswith("https://")
or url.startswith("ftp://")
) | 00f9d90d580da3fe8f6cbc3604be61153b17a154 | 707,833 |
from typing import List
def get_groups(records_data: dict, default_group: str) -> List:
"""
Returns the specified groups in the
SQS Message
"""
groups = records_data["Groups"]
try:
if len(groups) > 0:
return groups
else:
return [default_group]
except... | 29ffe05da86816750b59bab03041d8bf43ca8961 | 707,834 |
import os
import stat
import pickle
def dump_obj(obj, path):
"""Dump object to file."""
file_name = hex(id(obj))
file_path = path + file_name
with open(file_path, 'wb') as f:
os.chmod(file_path, stat.S_IWUSR | stat.S_IRUSR)
pickle.dump(obj, f)
return file_name | d392ffa14e5eb8965ba84e353427358219c9eacc | 707,835 |
import time
def count_time(start):
"""
:param start:
:return: return the time in seconds
"""
end = time.time()
return end-start | 1945f6e6972b47d7bbdb6941ee7d80b8a6eedd9a | 707,836 |
def split_by_state(xs, ys, states):
"""
Splits the results get_frame_per_second into a list of continuos line segments,
divided by state. This is to plot multiple line segments with different color for
each segment.
"""
res = []
last_state = None
for x, y, s in zip(xs, ys, states):
... | 0a872617bd935f7c52ee0d10e759674969a19c4e | 707,837 |
def pwr_y(x, a, b, e):
"""
Calculate the Power Law relation with a deviation term.
Parameters
----------
x : numeric
Input to Power Law relation.
a : numeric
Constant.
b : numeric
Exponent.
e : numeric
Deviation term.
Returns
-------
nume... | e736d9bb2e4305ef0dc0a360143a611b805f7612 | 707,838 |
def mimicry(span):
"""Enrich the match."""
data = {'mimicry': span.lower_}
sexes = set()
for token in span:
if token.ent_type_ in {'female', 'male'}:
if token.lower_ in sexes:
return {}
sexes.add(token.lower_)
return data | 724d09156e97961049cb29d9f3c1f02ab5af48b0 | 707,839 |
def LeftBinarySearch(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums)
while low < high:
mid = (low + high) // 2
if nums[mid] < target:
low = mid + 1
else:
high = mid
assert l... | d08f72e1563ee91e9ca6c9cf95db4c794312aa59 | 707,840 |
def parse_char(char, invert=False):
"""Return symbols depending on the binary input
Keyword arguments:
char -- binary integer streamed into the function
invert -- boolean to invert returned symbols
"""
if invert == False:
if char == 0:
return '.'
elif char == 1... | 38c0d1c150a1c8e8f7d2f3d1bde08ec3e5ceb65b | 707,841 |
def list_datasets(service, project_id):
"""Lists BigQuery datasets.
Args:
service: BigQuery service object that is authenticated. Example: service = build('bigquery','v2', http=http)
project_id: string, Name of Google project
Returns:
List containing dataset names
"""
data... | 2712e6a99427ce3b141e7948bba36e8e724f82bc | 707,842 |
def make_postdict_to_fetch_token(token_endpoint: str, grant_type: str,
code: str, client_id: str,
client_secret: str,
redirect_uri: str) -> dict:
"""POST dictionary is the API of the requests library"""
return {'u... | f366fc140c70d094ff99b28a369ac96b4c2a8b49 | 707,844 |
def spread_match_network(expr_df_in, node_names_in):
"""
Matches S (spreadsheet of gene expressions) and N (network)
The function returns expr_df_out which is formed by reshuffling columns of
expr_df_in. Also, node_names_out is formed by reshuffling node_names_in. The
intersection of node_names_out ... | c0b78263a341d3b7682922eb9a948c21ab2e7e45 | 707,845 |
from typing import List
from typing import Tuple
import bisect
def line_col(lbreaks: List[int], pos: int) -> Tuple[int, int]:
"""
Returns the position within a text as (line, column)-tuple based
on a list of all line breaks, including -1 and EOF.
"""
if not lbreaks and pos >= 0:
return 0, ... | 6b99e3b19ed1a490e4a9cc284f99e875085f819a | 707,846 |
import random
def get_word():
"""Returns random word."""
words = ['Charlie', 'Woodstock', 'Snoopy', 'Lucy', 'Linus',
'Schroeder', 'Patty', 'Sally', 'Marcie']
return random.choice(words).upper() | c4437edc3a1e91cd90c342eda40cfd779364d9c1 | 707,847 |
from datetime import datetime
def parsed_json_to_dict(parsed):
"""
Convert parsed dict into dict with python built-in type
param:
parsed parsed dict by json decoder
"""
new_bangumi = {}
new_bangumi['name'] = parsed['name']
new_bangumi['start_date'] = datetime.strptime(
pa... | e3bb8306e19a16c9e82d5f6e96c9b4a3707c0446 | 707,848 |
from datetime import datetime
from shutil import copyfile
def backup_file(file):
"""Create timestamp'd backup of a file
Args:
file (str): filepath
Returns:
backupfile(str)
"""
current_time = datetime.now()
time_stamp = current_time.strftime("%b-%d-%y-%H.%M.%S")
backupf... | 1c1b33028aab01b4e41ed3ef944202ecc53415df | 707,849 |
def _rle_decode(data):
"""
Decodes run-length-encoded `data`.
"""
if not data:
return data
new = b''
last = b''
for cur in data:
if last == b'\0':
new += last * cur
last = b''
else:
new += last
last = bytes([cur])
... | 8463ff6a20b3a39df7b67013d47fe81ed6d53477 | 707,850 |
def scale_log2lin(value):
"""
Scale value from log10 to linear scale: 10**(value/10)
Parameters
----------
value : float or array-like
Value or array to be scaled
Returns
-------
float or array-like
Scaled value
"""
return 10**(value/10) | 04f15a8b5a86a6e94dd6a0f657d7311d38da5dc0 | 707,851 |
def _error_to_level(error):
"""Convert a boolean error field to 'Error' or 'Info' """
if error:
return 'Error'
else:
return 'Info' | b43e029a4bb14b10de4056758acecebc85546a95 | 707,852 |
def add_review(status):
"""
Adds the flags on the tracker document.
Input: tracker document.
Output: sum of the switches.
"""
cluster = status['cluster_switch']
classify = status['classify_switch']
replace = status['replace_switch']
final = status['final_switch']
finished = statu... | 8f2ba4cd8b6bd4e500e868f13733146579edd7ce | 707,853 |
import math
import operator
from typing import Counter
def vertical_log_binning(p, data):
"""Create vertical log_binning. Used for peak sale."""
index, value = zip(*sorted(data.items(), key=operator.itemgetter(1)))
bin_result = []
value = list(value)
bin_edge = [min(value)]
i = 1
while len... | bf536250bc32a9bda54c8359589b10aa5936e902 | 707,854 |
from datetime import datetime
def generateDateTime(s):
"""生成时间"""
dt = datetime.fromtimestamp(float(s)/1e3)
time = dt.strftime("%H:%M:%S.%f")
date = dt.strftime("%Y%m%d")
return date, time | 8d566412230b5bb779baa395670ba06457c2074f | 707,855 |
def prep_ciphertext(ciphertext):
"""Remove whitespace."""
message = "".join(ciphertext.split())
print("\nciphertext = {}".format(ciphertext))
return message | a5cd130ed3296addf6a21460cc384d8a0582f862 | 707,856 |
from typing import List
from typing import Tuple
from typing import Union
def normalize_boxes(boxes: List[Tuple], img_shape: Union[Tuple, List]) -> List[Tuple]:
"""
Transform bounding boxes back to yolo format
"""
img_height = img_shape[1]
img_width = img_shape[2]
boxes_ = []
for i in ran... | 086e0b069d06a4718e8ffd37189cf3d08c41d19f | 707,857 |
import copy
def _make_reference_filters(filters, ref_dimension, offset_func):
"""
Copies and replaces the reference dimension's definition in all of the filters applied to a dataset query.
This is used to shift the dimension filters to fit the reference window.
:param filters:
:param ref_dimensi... | eeeeb74bb3618c87f3540de5b44970e197885dc6 | 707,858 |
import os
def detect():
"""
Detects the shell the user is currently using. The logic is picked from
Docker Machine
https://github.com/docker/machine/blob/master/libmachine/shell/shell.go#L13
"""
shell = os.getenv("SHELL")
if not shell:
return None
if os.getenv("__fish_bin_dir")... | 4c6db387f21b1e4abef17efebbdc45b45c5b7fe7 | 707,859 |
def _destupidize_dict(mylist):
"""The opposite of _stupidize_dict()"""
output = {}
for item in mylist:
output[item['key']] = item['value']
return output | f688e25a9d308e39f47390fef493ab80d303ea15 | 707,860 |
def filter_pdf_files(filepaths):
""" Returns a filtered list with strings that end with '.pdf'
Keyword arguments:
filepaths -- List of filepath strings
"""
return [x for x in filepaths if x.endswith('.pdf')] | 3f44b3af9859069de866cec3fac33a9e9de5439d | 707,861 |
import os
def alter_subprocess_kwargs_by_platform(**kwargs):
"""
Given a dict, populate kwargs to create a generally
useful default setup for running subprocess processes
on different platforms. For example, `close_fds` is
set on posix and creation of a new console window is
disabled on Window... | 93ada5c681c535b45fc5c321ab4b27b49587a106 | 707,862 |
def _format_program_counter_relative(state):
"""Program Counter Relative"""
program_counter = state.program_counter
operand = state.current_operand
if operand & 0x80 == 0x00:
near_addr = (program_counter + operand) & 0xFFFF
else:
near_addr = (program_counter - (0x100 - operand)) & ... | 74f13e9230a6c116413b373b92e36bd884a906e7 | 707,863 |
def justify_to_box(
boxstart: float,
boxsize: float,
itemsize: float,
just: float = 0.0) -> float:
"""
Justifies, similarly, but within a box.
"""
return boxstart + (boxsize - itemsize) * just | a644d5a7a6ff88009e66ffa35498d9720b24222c | 707,864 |
def istype(klass, object):
"""Return whether an object is a member of a given class."""
try: raise object
except klass: return 1
except: return 0 | bceb83914a9a346c59d90984730dddb808bf0e78 | 707,865 |
import numpy
def scale_quadrature(quad_func, order, lower, upper, **kwargs):
"""
Scale quadrature rule designed for unit interval to an arbitrary interval.
Args:
quad_func (Callable):
Function that creates quadrature abscissas and weights on the unit
interval.
orde... | f3854cee12a482bc9c92fe2809a0388dddb422e0 | 707,866 |
import re
def text_cleanup(text: str) -> str:
"""
A simple text cleanup function that strips all new line characters and
substitutes consecutive white space characters by a single one.
:param text: Input text to be cleaned.
:return: The cleaned version of the text
"""
text.replace('\n', ''... | 84b9752f261f94164e2e83b944a2c12cee2ae5d8 | 707,867 |
import os
def get_files_under_dir(directory, ext='', case_sensitive=False):
"""
Perform recursive search in directory to match files with one of the
extensions provided
:param directory: path to directory you want to perform search in.
:param ext: list of extensions of simple extension for files t... | 3ba3428d88c164fce850a29419b6eab46aa8b646 | 707,868 |
def boolean(func):
"""
Sets 'boolean' attribute (this attribute is used by list_display).
"""
func.boolean=True
return func | 9bbf731d72e53aa9814caacaa30446207af036bd | 707,869 |
from typing import OrderedDict
from typing import Counter
def profile_nominal(pairs, **options):
"""Return stats for the nominal field
Arguments:
:param pairs: list with pairs (row, value)
:return: dictionary with stats
"""
result = OrderedDict()
values = [r[1] for r in pairs]
c = Cou... | 00ef211e8f665a02f152e764c409668481c748cc | 707,870 |
import os
def getJsonPath(name, moduleFile):
"""
获取JSON配置文件的路径:
1. 优先从当前工作目录查找JSON文件
2. 若无法找到则前往模块所在目录查找
"""
currentFolder = os.getcwd()
currentJsonPath = os.path.join(currentFolder, name)
if os.path.isfile(currentJsonPath):
return currentJsonPath
else:
moduleFolder... | 5f0dca485794dead91ecce70b4040809886186c3 | 707,871 |
def enable_pause_data_button(n, interval_disabled):
"""
Enable the play button when data has been loaded and data *is* currently streaming
"""
if n and n[0] < 1: return True
if interval_disabled:
return True
return False | 4257a2deb9b8be87fe64a54129ae869623c323e8 | 707,872 |
import sys
def _score_match(matchinfo: bytes, form, query) -> float:
""" Score how well the matches form matches the query
0.5: half of the terms match (using normalized forms)
1: all terms match (using normalized forms)
2: all terms are identical
3: all terms are identical, including case
... | ef8c223b6c972f7b43fe46788ac894c5454e3f18 | 707,873 |
def thread_loop(run):
"""decorator to make the function run in a loop if it is a thread"""
def fct(self, *args, **kwargs):
if self.use_thread:
while True:
run(*args, **kwargs)
else:
run(*args, **kwargs)
return fct | a68eee708bc0a1fe0a3da01e68ec84b6a43d9210 | 707,874 |
def get_price_for_market_stateless(result):
"""Returns the price for the symbols that the API doesnt follow the market state (ETF, Index)"""
## It seems that for ETF symbols it uses REGULAR market fields
return {
"current": result['regularMarketPrice']['fmt'],
"previous": result['regularMark... | 6afb9d443f246bd0db5c320a41c8341953f5dd7a | 707,875 |
def jump(current_command):
"""Return Jump Mnemonic of current C-Command"""
#jump exists after ; if ; in string. Always the last part of the command
if ";" in current_command:
command_list = current_command.split(";")
return command_list[-1]
else:
return "" | 2530ae99fcc4864c5e529d783b687bfc00d58156 | 707,877 |
def compute( op , x , y ):
"""Compute the value of expression 'x op y', where -x and y
are two integers and op is an operator in '+','-','*','/'"""
if (op=='+'):
return x+y
elif op=='-':
return x-y
elif op=='*':
return x*y
elif op=='/':
return x/y
else:
r... | dbdf73a91bdb7092d2a18b6245ce6b8d75b5ab33 | 707,878 |
def get_indentation(line_):
"""
returns the number of preceding spaces
"""
return len(line_) - len(line_.lstrip()) | 23a65ba620afa3268d4ab364f64713257824340d | 707,880 |
import argparse
def node_parameter_parser(s):
"""Expects arguments as (address,range,probability)"""
try:
vals = s.split(",")
address = int(vals[0])
range = float(vals[1])
probability = float(vals[2])
return address, range, probability
except:
raise argparse... | a1d378d5f71b53fb187a920f71d7fc3373e775df | 707,881 |
from typing import List
from typing import Any
from typing import Optional
def jinja_calc_buffer(fields: List[Any], category: Optional[str] = None) -> int:
"""calculate buffer for list of fields based on their length"""
if category:
fields = [f for f in fields if f.category == category]
return max... | c1f619acd8f68a9485026b344ece0c162c6f0fb0 | 707,882 |
def get_delete_op(op_name):
""" Determine if we are dealing with a deletion operation.
Normally we just do the logic in the last return. However, we may want
special behavior for some types.
:param op_name: ctx.operation.name.split('.')[-1].
:return: bool
"""
return 'delete' == op_name | 508a9aad3ac6f4d58f5890c1abc138326747ee51 | 707,883 |
def warmUp():
"""
Warm up the machine in AppEngine a few minutes before the daily standup
"""
return "ok" | f7c83939d224b06db26570ab8ccc8f04bd69c1d6 | 707,884 |
def _mysql_int_length(subtype):
"""Determine smallest field that can hold data with given length."""
try:
length = int(subtype)
except ValueError:
raise ValueError(
'Invalid subtype for Integer column: {}'.format(subtype)
)
if length < 3:
kind = 'TINYINT'
... | 3a0e84a3ac602bb018ae7056f4ad06fe0dcab53b | 707,885 |
def regularity(sequence):
"""
Compute the regularity of a sequence.
The regularity basically measures what percentage of a user's
visits are to a previously visited place.
Parameters
----------
sequence : list
A list of symbols.
Returns
-------
float
1 minus th... | e03d38cc3882ea5d0828b1f8942039865a90d49d | 707,886 |
def contains_whitespace(s : str):
"""
Returns True if any whitespace chars in input string.
"""
return " " in s or "\t" in s | c5dc974988efcfa4fe0ec83d115dfa7508cef798 | 707,887 |
import math
def divide_list(l, n):
"""Divides list l into n successive chunks."""
length = len(l)
chunk_size = int(math.ceil(length/n))
expected_length = n * chunk_size
chunks = []
for i in range(0, expected_length, chunk_size):
chunks.append(l[i:i+chunk_size])
for i in range(le... | bad7c118988baebd5712cd496bb087cd8788abb7 | 707,888 |
from typing import List
import os
def get_output_file_path(file_path: str) -> str:
"""
get the output file's path
:param file_path: the file path
:return: the output file's path
"""
split_file_path: List[str] = list(os.path.splitext(file_path))
return f'{split_file_path[0]}_sorted{split_fi... | baf014ab2587c2b8b3248284e4993a76c502983a | 707,890 |
def binarySearch(arr, val):
"""
array values must be sorted
"""
left = 0
right = len(arr) - 1
half = (left + right) // 2
while arr[half] != val:
if val < arr[half]:
right = half - 1
else:
left = half + 1
half = (left + right) // 2
if arr[ha... | 2457e01dee0f3e3dd988471ca708883d2a612066 | 707,891 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.