content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def extract_tty_phone(service_center):
""" Extract a TTY phone number if one exists from the service_center
entry in the YAML. """
tty_phones = [p for p in service_center['phone'] if 'TTY' in p]
if len(tty_phones) > 0:
return tty_phones[0] | 9c4d349e0c75b1d75f69cb7758a3aac7dca5b5a5 | 702,311 |
from pathlib import Path
def get_data_dir() -> str:
"""Get a filepath to the drem data directory.
Returns:
str: Filepath to the drem data directory
"""
cwd = Path(__file__)
base_dir = cwd.resolve().parents[3]
data_dir = base_dir / "data"
return str(data_dir) | 16e1bf3d8eab4c4f58ec90f832fd15809bdbbbca | 702,312 |
import shutil
def get_unshare_path():
"""Find the path to the unshare utility."""
return shutil.which('unshare') | 5ca2f1a9bdd8cc107c00be137c6dc3ca0a6f0db7 | 702,313 |
def l3_interface_group_id(ne_id):
"""
L3 Interface Group Id
"""
return 0x50000000 + (ne_id & 0x0fffffff) | 00576c8c33fc965d759abc2aa00aa8f46b930a07 | 702,314 |
def make_tag_list(tag_dict):
""" make list from tag dictionary """
tag_list = tag_dict.keys()
# needless because keys doesn't overlap.
# tag_list = list(set(tag_list))
# but, in python3, type of tag_list is not list, it is dict_key.
tag_list = list(tag_list)
tag_list.sort()
return tag_li... | 3dc825c1ac9cf9b6a1d2df5d4b46f2755b267381 | 702,315 |
def sentinel(name):
"""Create a unique, one-off object with a useful repr"""
def __repr__(_):
return f'<{name}>'
return type(name, (), {'__repr__': __repr__})() | 6abe44a5b72bf7d5685c3d7ca97caf0b9c2ee49b | 702,316 |
def datestr(datetime_inst):
""" make iso time string from datetime instance
"""
return datetime_inst.isoformat("T") | 027dbaa0c3223261f4afd4e2f3aab45611eab265 | 702,317 |
import math
import torch
def wrap_phi_to_2pi_torch(x):
"""Shift input angle x to the range of [-pi, pi]
"""
pi = math.pi
x = torch.fmod(2 * pi + torch.fmod(x + pi, 2 * pi), 2 * pi) - pi
return x | 0905134f4cce5aae13f91e9e7900dd053a5861aa | 702,318 |
def FixAbsolutePathInLine(line, relative_paths):
"""Fix absolute paths present in |line| to relative paths."""
absolute_path = line.split(':')[0]
relative_path = relative_paths.get(absolute_path, absolute_path)
if absolute_path == relative_path:
return line
return relative_path + line[len(absolute_path):] | e0db0d2f3a0973b4db5f3e551f164481861c0b56 | 702,319 |
def loss(_sender_input, _message, _receiver_input, receiver_output, labels, _aux_input):
"""
Accuracy loss - non-differetiable hence cannot be used with GS
"""
acc = (labels == receiver_output).float()
return -acc, {"acc": acc} | 85c7d614e004c6c5349c4f42eb99155b7c7aee48 | 702,320 |
def lazyprop(func):
"""Wraps a property so it is lazily evaluated.
Args:
func: The property to wrap.
Returns:
A property that only does computation the first time it is called.
"""
attr_name = '_lazy_' + func.__name__
@property
def _lazyprop(self):
"""A lazily evalu... | b14f82b196177be207923744dda695d6aa70248f | 702,321 |
def extract_range(s):
""" Extract range from string"""
ranges = s.split(',')
if len(ranges) > 1:
return (int(ranges[0]), int(ranges[1]))
else:
return (int(ranges[0]), None) | 2a0fea0bdbd40a9fc998fa0b1e2af97be1cbd980 | 702,322 |
import os
def create_output_path(filename, outdir=None):
"""
Given a filename for keypoints and descriptors, create an output
directory with _kps.h5 appended.
Parameters
----------
filename : str
The filename or full path
outdir : str
An optional output path
... | 102efd0ee8a523ac5050bcec5d6a1a41670d5203 | 702,323 |
import sys
def _get_python_executable() -> str:
"""Returns Python executable.
Returns:
Python executable to use for setuptools packaging.
Raises:
EnvironmentError: If Python executable is not found.
"""
python_executable = sys.executable
if not python_executable:
rai... | 90bcc7a8c4f57d092aca81720f68f005a1974f60 | 702,324 |
def simpleCollision(spriteOne, spriteTwo):
"""
Simple bounding box collision detection.
"""
widthSpriteOne, heightSpriteOne = spriteOne.image.get_size()
rectSpriteOne = spriteOne.image.get_rect().move(
spriteOne.pos.x - widthSpriteOne / 2,
spriteOne.pos.y - heightSpriteOne / 2)
... | b6084ad260e084effb11701a6b859e0a58c9d19b | 702,325 |
def gen_path(base, code):
"""
Generate a path for give base path and code used in data generation
"""
#return os.path.join(base, code[:2], code[:3])
return base | e05790a740b7ab0f83ba5db020598c20d0f89520 | 702,326 |
import numbers
import json
import base64
def encode(d):
"""Encode an object in a way that can be transported via Mesos attributes: first to
JSON, then to base64url. The JSON string is padded with spaces so that the base64
string has no = pad characters, which are outside the legal set for Mesos.
"""
... | b1018b9eba2f136f9281dcb936d0903290abd505 | 702,327 |
def a2str(a):
"""
formatting for 1 or 2 dimensional numpy arrays of booleans
"""
if len(a.shape) == 1:
return "".join(map(str, a))
elif len(a.shape) == 2:
return "\n".join(map(lambda row: "".join(map(str, row)), a)) | 589cbc72bc1c3379f74a924f14b304d91a517157 | 702,328 |
def __read_dataset_item(path):
"""Reads data set from path returns a movie dict.
Parameters
----------
path : str
Absolute path of the MovieLens data set(u.data).
Returns
-------
rating_dict : dict
Returns a dict of users, movies and ratings.... | a87baecc5b0c28675bc715aab646bf41e4b40f96 | 702,329 |
def get_manifest_indexes(manifest, channel, column):
"""Get the indices for channel and column in the manifest"""
channel_index = -1
for x in range(len(manifest["channels"])):
if manifest["channels"][x]["channel"] == channel:
channel_index = x
break
if channel_index == -1... | 63d82417b1e106d408866933bce776c272b2e77d | 702,330 |
import torch
def query_ball_point(radius, nsample, xyz, new_xyz):
"""
Input:
radius: local region radius
nsample: max sample number in local region
xyz: all points, [B, N, 3]
new_xyz: query points, [B, S, 3]
Return:
group_idx: grouped points index, [B, S, nsample]
... | e74992747103d11b6618ecf7daf035c4f83e9911 | 702,331 |
def is_bounded(coord, shape):
"""
Checks if a coord (x,y) is within bounds.
"""
x, y = coord
g, h = shape
lesser = x < 0 or y < 0
greater = x >= g or y >= h
if lesser or greater:
return False
return True | 0a0b6921fcdf285c89b5021d113585ff38255013 | 702,332 |
from typing import Optional
def bool_to_int(bool_value: Optional[bool]) -> Optional[int]:
"""Cast bool to int value.
:param bool_value: some bool value
:return: int represenation
"""
if bool_value is None:
return bool_value
return int(bool_value) | fde6cda3dc8909638bb315451a09938224f2f306 | 702,333 |
from typing import Any
def arghash(args: Any, kwargs: Any) -> int:
"""Simple argument hash with kwargs sorted."""
sorted_args = tuple(
x if hasattr(x, "__repr__") else x for x in [*args, *sorted(kwargs.items())]
)
return hash(sorted_args) | c3e95c63831c958bb2a52cabad9f2ce576a4fed8 | 702,334 |
import os
import re
def _applyReplacements(cfile, replacements):
"""Applies custom replacements.
Argument cfile is string.
Argument replacements is a list of dicts, with keys "match",
"replacement", and (optional) "is_regex"
"""
for rep in replacements:
if not rep.get('with_extension... | 647e541eee027de21e171be570a2abc60c889cf2 | 702,335 |
def _get_pcluster_version_from_stack(stack):
"""
Get the version of the stack if tagged.
:param stack: stack object
:return: version or empty string
"""
return next((tag.get("Value") for tag in stack.get("Tags") if tag.get("Key") == "Version"), "") | 86106e52ea6ef8780c8aa8f514e0708dd53fb8e3 | 702,336 |
import json
def extract(spark, source):
"""Return an RDD[String]."""
rdd = spark.sparkContext.textFile(source)
return rdd.map(lambda x: json.loads(x)) | fef96d6cae65551a6879396ea699acfd2e4cda4b | 702,337 |
def _remove_leading_zeroes_in_field(string):
"""If blank-separated fields are integer, remove the leading zero."""
split = string.split(" ")
for i, field in enumerate(split):
if field.isdigit():
split[i] = f"{int(field)}"
return " ".join(split) | 48ba659b25809f19a0c3ed722d6201ffef73c409 | 702,338 |
def kmp(pattern, text):
"""Knuth-Morris-Pratt substring matching"""
pattern_length = len(pattern)
matched, subpattern = 0, [0] * pattern_length
for i, glyph in enumerate(pattern):
if i:
while matched and (pattern[matched] != glyph):
matched = subpattern[matched - 1]
... | 4f2a30a7a92d2e5890d9c257626c37201b281fec | 702,339 |
def istext(obj):
"""
Deprecated. Use::
>>> isinstance(obj, str)
after this import:
>>> from future.builtins import str
"""
return isinstance(obj, type(u'')) | 60f3d751f22ad4d120ce7624dd9a07d2c841e206 | 702,340 |
def crc16(string, value=0):
"""CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1
@param string: Data over which to calculate crc.
@param value: Initial CRC value.
"""
crc16_table = []
for byte in range(256):
crc = 0
for _ in range(8):
if (byte ^ crc) & 1:
... | e31ddafc6216b682d9cd0ac24a9fb634f1be1fb8 | 702,341 |
def chunks(seq, size):
"""Breaks a sequence of bytes into chunks of provided size
:param seq: sequence of bytes
:param size: chunk size
:return: generator that yields tuples of sequence chunk and boolean that indicates if chunk is
the last one
"""
length = len(seq)
return ((seq... | 25abe8afdb032af0e2b10dbd3c03b369d862813f | 702,342 |
def secondYAxis(requestContext, seriesList):
"""
Graph the series on the secondary Y axis.
"""
for series in seriesList:
series.options['secondYAxis'] = True
series.name= 'secondYAxis(%s)' % series.name
return seriesList | d1c34f16da1f2142021c845afffb63b595e2ce69 | 702,344 |
def evaluate(bounds, func):
"""
Evaluates simpsons rules on an array of values and a function pointer.
.. math::
\int_{a}^{b} = \sum_i ...
Parameters
----------
bounds: array_like
An array with a dimension of two that contains the starting and
ending points for the int... | af5102d37c1943420a0ff3fff980342ee8c9dad9 | 702,345 |
import hashlib
def get_dataset_id(settings):
""" Creates and returns an unique ID (for practical purposes), given the data parameters.
The main use of this ID is to make sure we are using the correct data source,
and that the data parameters weren't changed halfway through the simulation sequence.
"""... | a696f0f85c8ee9c3cab975838db520cc061dfaf4 | 702,346 |
import torch
def instance_masks_to_semseg_mask(instance_masks, category_labels):
"""
Converts a tensor containing instance masks to a semantic segmentation mask.
:param instance_masks: tensor(N, T, H, W) (N = number of instances)
:param category_labels: tensor(N) containing semantic category label fo... | 127c9b9ff3d1044b1c5e1e8650ed493f8a4bc6de | 702,347 |
import time
def fix_end_now(json):
"""Set end time to the time now if no end time is give"""
if 'end' not in json or json['end'] is None:
json['end'] = int(time.time())
return json | 2c126e00ac293c6a511cb86457d60536f1d690ef | 702,348 |
def topics_to_calldata(topics, bytes_per_topic=3):
"""Converts a list of topics to calldata.
Args:
topics (bytes[]): List of topics.
bytes_per_topic (int): Byte length of each topic.
Returns:
bytes: Topics combined into a single string.
"""
return b''.join(topic.to_bytes(b... | 2d500016963934fdbc60b388632b817624d5ad8d | 702,349 |
def remove_basic_block_assembly(pydot_cfg):
"""
Remove assembly text from the CFG's basic blocks
"""
# Avoid graph and edge nodes, which are the 1st and 2nd nodes
nodes = pydot_cfg.get_nodes()[2:]
for n in nodes:
n.set_label("")
return pydot_cfg | 3ca5d7fcd46dc96bff92aea67b47afbe53accc40 | 702,350 |
def construct_array(nums):
"""
:param nums: array
:return: mul array
"""
l = len(nums)
ans = [1 for _ in range(l)]
p = q = 1
for i in range(l):
ans[i] *= q
ans[-i - 1] *= p
q *= nums[i]
p *= nums[-i - 1]
return ans | 5327945cbb83290af94efcce07e4ae391fb3da45 | 702,351 |
import argparse
import os
import json
import shutil
def main():
""" Use pw_module_tests.testinfo.json files to find and copy fuzzers. """
parser = argparse.ArgumentParser()
parser.add_argument('--buildroot')
parser.add_argument('--out')
args = parser.parse_args()
print(' buildroot: ' + args.buildroot)
... | bcbbda75629e9186d37387ccad02b5560ad4342c | 702,352 |
def return_point(m, n, p):
"""
m is the index number of the Hammersley point to calculate
n is the maximun number of points
p is the order of the Hammersley point, 1,2,3,4,... etc
l is the power of x to go out to and is hard coded to 10 in this example
:return type double
"""
if p == 1:... | 73b1c75d6b4ebdc6a0616d9a7b2d6207a4728316 | 702,353 |
def OverscanTrim(d,ds):
"""
Overscan correct and Trim a refurbished HIRES image
"""
ds = ds.split(',')
dsy = ds[0][1:]
dsx = ds[1][:-1]
dsy = dsy.split(':')
dsx = dsx.split(':')
x0 = int(dsx[0])-1
x1 = int(dsx[1])
y0 = int(dsy[0])-1
y1 = int(dsy[1])
newdata = d[x0:x1]... | ceb434ca75f458c43137b73b89c0f0242bfe7e93 | 702,354 |
import re
def __tokenize(syntax) -> list:
"""
Validate and tokenize the syntax.
Valid syntax: snake_case_words, integers, plus, minus.
"""
if not re.match(r"^[\w\d\s\+-]+$", syntax):
raise SyntaxError("Invalid syntax.")
syntax = re.sub(r"\s*([+-])\s*", r" \g<1> ", syntax)
return ... | 68e79222987771d964ac0d39e38c425d710d3765 | 702,355 |
def indent(yaml: str):
"""Add indents to yaml"""
lines = yaml.split("\n")
def prefix(line):
return " " if line.strip() else ""
lines = [prefix(line) + line for line in lines]
return "\n".join(lines) | 815babb29378f1cfac6ada8258322df92235fc9e | 702,356 |
def get_rbac_role_assigned(self) -> dict:
"""Get list of accessible menus based on the current session
permissions
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - rbacRole
- GET
- /rbac/role/menuAssigned
.. no... | 91d0dcbded36b857a0dc0ddfeaa2815516d162f6 | 702,357 |
def _has_sectors(tax_name: str, ignore_sectors: bool) -> bool:
"""Determine whether we are doing a sector-based forecast."""
return tax_name in ["birt", "sales", "wage", "rtt"] and not ignore_sectors | 5725693c514937988b4e668c699606cb3ab46d10 | 702,359 |
import os
import pathlib
def getFile(path):
"""
Retrieve the path to one of the reference or example files
Relies on the environment variable ``SERPENT_TOOLS_DATA``
to find the data files.
Parameters
----------
path : str
The name of the file without any additional directory
... | 09fba05e5be7fbb6bb6c8d40acafa71d2018cf29 | 702,361 |
def numPointsInSpans(spans):
"""
ARC112B
>>> numPointsInSpans([(1, 3)])
3
>>> numPointsInSpans([(1, 3), (5, 7)])
6
>>> numPointsInSpans([(1, 3), (3, 5)])
5
>>> numPointsInSpans([(1, 3), (2, 5)])
5
"""
timeline = []
for start, end in spans:
assert start <= end
... | e1ffecb3a1d4147f4b15256278f398c5213df200 | 702,363 |
def merge_import_policies(value, order=""):
"""
Merges and returns policy list for import.
If duplicates are found, only the most specific one will be kept.
"""
if not hasattr(value, "merged_import_policies"):
raise AttributeError("{value} has not merged import policies")
return value.... | adaaf5626e09022b36b69b332fb85788665c114e | 702,364 |
def disqus_dev(context):
"""
No longer supported by Disqus
"""
return {} | 9d823582b4ddc4e3bed992ef203642641ef83486 | 702,365 |
def min_sentence_set():
""" minimum query """
return {'hello', 'world'} | 6ec3b76f47c9596422c473b4401ce4124806ec1c | 702,366 |
def _sort_student(name: str) -> str:
"""
Return the given student name in a sortable format.
Students are sorted by last name (i.e., last space-split chunk).
"""
return name.lower().split()[-1] | 92747346e0e6ded9715761b8907ccb8ab33da742 | 702,367 |
import re
def is_gcd_file(filename: str) -> bool:
"""Checks whether `filename` is a GCD file."""
if re.search('(gcd|geo)', filename.lower()):
return True
return False | 3022bd165683cde609d1f866c3ce655e84561dc4 | 702,368 |
from pathlib import Path
def _test_path(fn):
"""Leads to files saved in the data folder
Parameters
----------
fn: str
The whole filename.
Returns
-------
The path of the file in the current working system.
"""
return Path(__file__).parent / "data" / fn | 2f6d7e6b952c40e8fe8cefd1c0c8f0c000e02fdd | 702,369 |
def yes_or_no(msg, *params, yes=True, certain=False, third_choice=False):
"""Query yes, no or display with message.
Args:
msg (str): Message to be printed out.
yes (bool): Indicates whether the default answer is yes or no.
"""
choices = " [Y/n]?" if yes else " [yes/N]" if certain else ... | 42058dd0ed2fb606444233e13551d6d5f11a90a7 | 702,370 |
def _magni_test_var_in_globals_func(*args, **kwargs):
"""Test function used in some tests."""
return 'magni_test_var' in globals() | c4209abbc865e65644df919678dd11ddbad24e7e | 702,371 |
def overlap(layer, interval):
"""
calculate the thickness for a layer that overlapping with an interval
:param layer: (from_depth, to_depth)
:param interval: (from_depth, to_depth)
:return: the overlapping thickness
"""
res = 0
if layer[0] >= interval[0] and layer[1] <= interval[1]: # c... | f77fdc433f79cf7990416a97cc9edfcbcc860585 | 702,372 |
import zipfile
def _extract_info(archive, info):
"""
Extracts the contents of an archive info object
;param archive:
An archive from _open_archive()
:param info:
An info object from _list_archive_members()
:return:
None, or a byte string of the file contents
"""
... | 3014a9e85077f33522aaf466c9bef3bd020d252b | 702,373 |
def _space_all_but_first(s: str, n_spaces: int) -> str:
"""Pad all lines except the first with n_spaces spaces"""
lines = s.splitlines()
for i in range(1, len(lines)):
lines[i] = " " * n_spaces + lines[i]
return "\n".join(lines) | 36da5eb15a9ab5fa473831b5440ffa88495f6cac | 702,374 |
import argparse
import sys
def parse_args():
""" Parse command-line arguments."""
parser = argparse.ArgumentParser(description='''Identify family distribution with unmasked Ensembl ID''')
parser.add_argument(
'-i','--input', nargs='?', type=argparse.FileType('r'),
default=sys.stdin, help='... | 54de56cab2708bb82c32808e7961295f3e427ba4 | 702,375 |
def fix_brackets(placeholder: str) -> str:
"""Fix the imbalanced brackets in placeholder.
When ptype is not null, regex matching might grab a placeholder with }
missing. This function fix the missing bracket.
Args:
placeholder: string placeholder of RuntimeParameter
Returns:
Placeholder with re-bal... | 5fa4a83eeca676c58c33038add62a0c5bed7fe8b | 702,376 |
def ParseRangeHeader(range_header):
"""Parse HTTP Range header.
Args:
range_header: A str representing the value of a range header as retrived
from Range or X-AppEngine-BlobRange.
Returns:
Tuple (start, end):
start: Start index of blob to retrieve. May be negative index.
end: None or ... | ad37fd1532edd9519073c93aa73402b3c7d0a404 | 702,377 |
from typing import Any
from typing import List
def init_args(
cls: Any,
) -> List[str]:
""" Return the __init__ args (minus 'self') for @cls
Args:
cls: class, instance or callable
Returns:
The arguments minus 'self'
"""
# This looks insanely goofy, but seems to literally be th... | 2d867049f3c1f4937d0d8a7042315644cef219ae | 702,378 |
import re
def create_url(url):
"""
modifying the given url so that it returns JSON data when
we do a GET requests later in this script
"""
# extract the branch name from the given url (e.g master)
branch = re.findall(r"\/tree\/(.*?)\/", url)[0]
api_url = url.replace("https://github.com", "https://api.githu... | 682343d1e7462ef224865b659357716e55cd22cd | 702,379 |
import secrets
def generate_token_urlsafe(unique=False, nbytes=32):
"""Generate an URL-safe random token."""
return secrets.token_urlsafe(nbytes=nbytes) | 5bdab6879f241a7459653e5ec363110263f0c171 | 702,380 |
import re
def parse_multiline(element, poe_implicit_split = False):
""" Get data from a row & regroup tag-separated
string (<br/>) in a list
poe_implicit_split: <number>( to )<number>
for Implicit Mods extraction (optional)
"""
res = []
for data in element:
content = []
for x in data.strings:
... | ef59fe17a3b221086276baa67448d0870b838f71 | 702,381 |
def score_sig_1D_base(true_signatures, pred_signatures):
"""
percent of mutations with the right signature
Parameters
----------
true_signatures: iterable
array-like of length N (number of mutations), with the
true signature for each mutation
pred_signat... | cd04cef1c7eecea8da804fe631fedc18c33b4d11 | 702,383 |
def compute_apparent_power(f, j, seconds_per_file, values):
"""
Apparent power is the product of the voltage RMS and the current RMS.
"""
cs = [n for n in list(f) if 'current' in n]
apparent_power = dict()
for cs_i, _ in enumerate(cs):
if 'voltage' in list(f):
voltage_name ... | 76f7b903bce2f340d0494524f3d0d2ad40e6422e | 702,384 |
import decimal
def _dict_decimal_to_float(my_dict):
"""If any values in dictionary are of dtype 'Decimal', cast
to float so can be JSONified.
"""
for key, val in my_dict.items():
if isinstance(val, decimal.Decimal):
my_dict[key] = float(val)
return my_dict | 7d1741322782c49b9b8a6a7369344797439ff00b | 702,385 |
def string2cycles(string):
"""
Convert string from user input to permutation in cycle notation as list
:param string: Permutation as string
:type string: string
:return: Returns permutation in cycle notation as list
:rtype: list
"""
groups = string.split(')(')
items = []
for i... | 5a10f270fb934a1b22f61e84e61f679f2cad5f79 | 702,386 |
def from_args(it, key, lo, hi, prefix, reverse, max_, include, max_phys):
"""This function is a stand-in until the core.py API is refurbished."""
if key:
it.set_exact(key)
return it.forward()
elif prefix:
it.set_prefix(prefix)
else:
if lo:
it.set_lo(lo)
... | 859e716e5eb32be10806de400b97fdf0e4770ed4 | 702,388 |
def bump_version(version_array, level):
"""
Perform ++1 action on the array [x, y, z] cell,
Input values are assumed to be validated
:param version_array: int array of [x, y, z] validated array
:param level: string represents major|minor|patch
:return: int array with new value
"""
if typ... | 8a26db1694cf777915cc8c170355fd77ea4e9e66 | 702,389 |
def _get_timestep_lookup_function(control_loop_period, memory_loc, rtf_key):
"""
Creates a customized timestep lookup function for a SynchronizedTimedLoop
:param control_loop_period: duration in [s] of each timed loop
:param memory_loc: location in shared memory to get() data from
:param rtf_key: ke... | 500e61c0cbb38012bbce18dfc6f648c78a4b3f36 | 702,390 |
def daemonize(func):
"""
A function wrapper that checks daemon flags. This wrapper as it is assumes
that the calling class has a daemon attribute.
"""
def _wrapper(self, *args, d_init=False, **kwargs):
if d_init:
self.daemon.d_init.append((func, self, args, kwargs))
retur... | 3f7b52c319be0a570e8c4843d061e1d0387982af | 702,391 |
def get_cursor(connection):
"""
Gets a cursor from a given connection.
:type MySQLdb.connections.Connection
:param connection: A mysql connection
:rtype MySQLdb.cursors.SSDictCursor
:return A mysql cursor
"""
return connection.cursor() | dc1e9b99bff6b43eb324161026196358d318f59c | 702,392 |
def _popup_footer(view, details):
"""
Generate a footer for the package popup that indicates how the package is
installed.
"""
return """
{shipped} <span class="status">Ships with Sublime</span>
{installed} <span class="status">In Installed Packages Folder</span> ... | 8f159f75990e87c8d431bb2dd1d01e648079ac96 | 702,393 |
def trycast(new_type, value, default=None):
"""
Attempt to cast `value` as `new_type` or `default` if conversion fails
"""
try:
default = new_type(value)
finally:
return default | d670f545fb1853dfd95da1de961e44ee5a477c5f | 702,394 |
def _generate_wireless_settings_data(settings):
"""Generates a wireless settings data array to push to the
router from the given wireless settings."""
settings.ensure_valid()
data = {'ssid1': settings.ssid, 'channel': settings.channel, 'Save': 'Save'}
if settings.is_enabled:
data['ap'] = 1... | d41d13f56ecd813d01d2c9223db0b69ad26af5ae | 702,395 |
def dummy_house():
"""
Sample dataset that will be used to alter and make prediction on
"""
return {
"Id": 34,
"MSSubClass": 20, # Identifies the type of dwelling involved in the sale.
"LotFrontage": 70.0, # Linear feet of street connected to property
"LotArea": 10552, ... | d1360a8709712746f07f92df85a8d704bccd797c | 702,396 |
def construct_description(prefix: str, suffix: str, items: list):
"""Construction of complete description with prefix and suffixx.
Args:
prefix (str): prefix
suffix (str): suffix
items (list): itesm
Returns:
str: complete description string
"""
item_str = ','.join(... | 61eec7c2f40bf3b4857cdd682e52aabac1f2ec76 | 702,398 |
def read_cookies_file(filename):
"""read cookie txt file
:param filename: (str) cookies file path
:return: (dict) cookies
"""
with open(filename, 'r') as fp:
cookies = fp.read()
return cookies | 79ce16fabdec49a7b7b60b4d8bd5346798f03edf | 702,399 |
from typing import Union
def kind_div(x, y) -> Union[int, float]:
"""Tries integer division of x/y before resorting to float. If integer
division gives no remainder, returns this result otherwise it returns the
float result. From https://stackoverflow.com/a/36637240."""
# Integer division is tried fi... | 97343b68051291acc5a614d086d09f59f9b9abfd | 702,400 |
from itertools import chain
import os
def parse_feedstock_file(feedstock_fpath):
"""
Takes a file with space-separated feedstocks on each line and comments
after hashmarks, and returns a list of feedstocks
:param str feedstock_fpath:
:return: `list` -- list of feedstocks
"""
if not (isins... | 0c6bd403c07c97256db9fd310ceaf2476b2b78f3 | 702,401 |
def get_first_node_of_tree(root_node):
"""root_node's rhythm is #4"""
return root_node.sons[0].sons[0].sons[0].sons[0].sons[0] | 3dc2d8cb4a2ea006c35cc3fcfdf5efde5c21bb78 | 702,402 |
def rat_fun(x, poles):
"""
Computes the value of a rational function with poles in poles and roots in
-poles; see Definition 8.29 from the doctoral thesis "Model Order Reduction
for Fractional Diffusion Problems" for a precise definition.
Parameters
----------
x : float
The argument... | 48e14764595f1242e65908d8008ada2ac64a4a90 | 702,403 |
def createCode(videoNameList, fileUrlList, videoIdList, codeFile):
"""
参数:文件名称列表,文件链接列表,文件id列表,代码文件
功能:将已有数据批量写入代码并形成列表
返回值:代码列表
"""
codeList = []
for i in range(len(videoNameList)):
codeF = open(codeFile, "r", encoding = "utf-8")
code = codeF.read()
codeF.close()
... | 6c6bc86e971975a1c9524a201c74c2fcfec7c1fc | 702,404 |
def _optargs_to_kwargs(args):
"""Convert --bar-baz=quux --xyzzy --no-squiz to kwargs-compatible pairs.
E.g., [('bar_baz', 'quux'), ('xyzzy', True), ('squiz', False)]
"""
kwargs = []
for arg in args:
if not arg.startswith('--'):
raise RuntimeError("Unknown option %r" % arg)
... | f0523442f3de88d123c0d968a770f817084149df | 702,405 |
import csv
def _get_reader(file):
"""Get CSV reader and skip header rows."""
reader = csv.reader(file)
# Skip first 3 rows because they're all headers.
for _ in range(3):
next(reader)
return reader | 588328d9ccb5af32abad0c0d8fe8c4489d306c12 | 702,406 |
from typing import Counter
def add_intersection_delay(G, intersection_delay=7, time_col = 'time', highway_col='highway', filter=['projected_footway','motorway']):
"""
Find node intersections. For all intersection nodes, if directed edge is going into the intersection then add delay to the edge.
If the hig... | 536ac0d22fcccf9426140e7b4de6367a029c41a6 | 702,407 |
def left_justify_string(keyword, value):
"""Returns a string with dotted separation.
"""
return '%s' % keyword .ljust(40, ".") + ": " + '%s\n' % value | dc9c59224ee2c62e2c55093792f352f80df5c4b2 | 702,408 |
import pathlib
def write_text(path: str, data: str, encoding=None, append=False):
"""write text `data` to path `path` with encoding
e.g
j.sals.fs.write_text(path="/home/rafy/testing_text.txt",data="hello world") -> 11
Args:
path (str): path to write to
data (str): ascii content
... | 1d64c9494ee87c3ce0f0ad33466e260c1d7e43bd | 702,409 |
def get_first_index_greater_than_benchmark(arr, benchmark, reverse=False):
"""
获取在数组 arr 中第一个大于基准值的索引。reverse 控制反向查找或正向查找
Args:
arr(list):
benchmark():
reverse(bool):
Returns:
"""
if reverse:
start = len(arr) - 1
stop = -1
step = -1
else:
start = 0
stop = len(arr)
ste... | 8bc6fd64e07428af68da4dd39e1f44db856e55d8 | 702,410 |
import argparse
def local_args():
""" Create an argparse namespace to create a local dask cluster.
"""
args = argparse.Namespace()
args.num_procs = 1
args.num_threads_per_proc = 1
args.cluster_location = "LOCAL"
args.client_restart = False
return args | 2c9d9d260a1994bfa794d356babe101af9722521 | 702,411 |
def fixture_packages_with_trailing_spaces():
"""
A packages dictionary with trailing spaces on some items
"""
packages = {
"basic": ["package-one ", "package-two"],
"complex": ["package-three", "package-four", "package-five"],
}
return packages | cdf80f2f45ad339aeb8da40c175ad26b10e1e1c6 | 702,413 |
def dice(a, b):
"""
"Entity-based" measure in CoNLL; #4 in CEAF paper
"""
if a and b:
return (2 * len(a & b)) / (len(a) + len(b))
return 0. | ef650786ad86e0e60a3b80c99445bc95b2b5187d | 702,414 |
def traverseFilter(node,filterCallback):
"""Traverse every node and return a list of the nodes that matched the given expression
For example:
expr='a+3+map("test",f())'
ast=SeExprPy.AST(expr)
allCalls=SeExprPy.traverseFilter(ast.root(),lambda node,children: node.type==SeExprPy.ASTType.C... | 751810f0eb54b4aa08cf020f34649780bd208d81 | 702,415 |
def int2bin(n,digits=8):
""" integer to binary string"""
return "".join([str((n >> y) & 1) for y in range(digits-1, -1, -1)]) | 13e8ad69a1f8523c647376473605f581369488d9 | 702,416 |
def replace_digits(p, digits):
"""If p contains more than one of the same digit, replace them will all
other possible digits."""
if 0 in digits:
other_digits = [str(d) for d in list(range(1, 10))
if str(d) != str(p)[digits[0]]]
else:
other_digits = [str(d)... | e29c2e95d043f07aefb538c71f57bbe7d857b086 | 702,417 |
def active_piece(piece):
"""
Validate piece as active.
"""
return piece & 1 and piece & 0xE | bb9740b3eabfade4fa6f2a810243965e03c64d2e | 702,418 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.