content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def SmvHistoricalValidators(*validators):
"""Decorator to specify set of validators to apply to an SmvDataSet.
Each validator should specify the standard `metadata` and `validateMetadata`
methods. In addition, each validator will have a unique key defined that
will determine how it is stor... | f7eabfcf75de960323d07f897d74fa637969b6ad | 659,048 |
def get_end_index_of_a_paragraph_from_string(text, start=0):
"""
:param text: a string
:param start: the index of the start position
:return: the index of the new line character or the last character
"""
return min(len(text) - 1, text.find('\n', start)) | 25d0918749477029b2103b560be3d2556a9bb2ac | 659,049 |
def assign_labels_colors(labels, colors):
"""
Takes a list of labels and colors and assigns a unique label to each color. Returns a color_list of length(labels).
The colors will loop around if the number of unique labels are more than the number of unique colors
:param labels:
:param colors:
:re... | 79984b3de57a7c5782282f30a87564dd139a346f | 659,051 |
from typing import Union
from pathlib import Path
def path_resolver(f: Union[str, Path], *, touch: bool = True) -> Path:
"""Resolve a path.
Parameters
----------
f : Union[str, Path]
File whose path needs to be resolved.
touch : bool
Create file is not already existent. Default: T... | df3caefaec5ded71658f0f99686008e2a1a27272 | 659,052 |
import subprocess
def expand_target_path_on_host(target, target_path):
"""Attempts to expand target path on remote host.
This is incase ~ is used.
"""
completed_process = subprocess.run(
[
"ssh",
target,
f'python3 -c "import os; print(os.path.join(... | 38a8cd995aa95d900e778bc23d0450c96430add6 | 659,053 |
def format_timedelta(timedelta):
"""
convenience function to convert timedelta object into %HH%MM%SS string, since strftime isn't defined for timedelta objects
"""
seconds = timedelta.seconds % 60
minutes = (timedelta.seconds % 3600) // 60
hours = timedelta.days*24 + timedelta.seconds // 3600
... | 721005b2844a0ca9eaebeab0c2fc76a20305400b | 659,054 |
def format_timestamp(time_stamp):
"""Create a consistent datetime string representation based on ISO 8601 format.
YYYY-MM-DDTHH:MM:SS.mmmmmm for unaware datetime objects.
YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM for aware datetime objects
:param time_stamp: value to convert
:type time_stamp: datet... | eec7386c898da42bfee9e22d19f015ba1ce398b3 | 659,055 |
def g5halves(x):
"""g5halves(x), equal to -g_{5/2}(-e^x)"""
if (x<1e-4):
return x
else:
return 0.999856*x + 0.179586*x**2 + 0.0296957*x**3 + 0.328735*x**4 -1.90262*x**5 + 9.61982*x**6 - 38.0899*x**7 + 121.384*x**8 - 313.11*x**9 +655.703*x**10 - 1112.32*x**11 + 1517.67*x**12 - 1643.55*x**13 ... | 82204e7ff9872e1bb52babd1f98949b8c8514121 | 659,056 |
def validate_slice_int(the_int: int, bound: int, include=True):
"""
Ensure that the given integer makes sense as a slice entry, and move to
a normalized form.
Parameters
----------
the_int : int
bound : int
include : bool
Returns
-------
int
"""
if not isinstance(b... | 1bc20d825e41c1f8cf2283fed9a1ee607101f0c2 | 659,057 |
import sys
def argument_reader():
"""Reads the 7 arguments in from the command line and checks if they're of the correct format"""
arguments = sys.argv[1:]
Csin = int(arguments[0])
Csout = int(arguments[1])
Crin = int(arguments[2])
Crout = int(arguments[3])
Sin = int(arguments[4])
Rin... | f20a85dc6b654ddcebd5b568f4db167f6775b328 | 659,058 |
import hashlib
def get_sha1_hash(password):
"""For a given password string, utf-8 encode it and hash it with SHA1."""
encoded = password.encode('utf8')
hashed = hashlib.sha1(encoded).hexdigest()
return hashed | a7155cd1da31930fbc2f7a24875b75f3b444354c | 659,059 |
import json
def read_lane_stats( lane_file ):
"""
Read RUN001_Lxxx.stats.json file created in bbi-sciatac-demux pipeline run.
These files are in the demux_out/fastqs_barcode directory. The run is always
RUN001 and the Lxxx denotes the results for each lane; that is, L001, ...
"""
lane_stats = json.load( l... | be161f2c64f87a22092b6528928053f89b0d8f93 | 659,062 |
import math
import numpy
def extrude2d(x, y, limits, n=None, ds=None, force=False):
"""Extrude the two-dimensional section along the third direction (z).
Parameters
----------
x : numpy.ndarray
x-coordinates of the section.
y : numpy.ndarray
y-coordinates of the section.
limit... | f438ab12f1988273021a1f6f64f48234bab61d7b | 659,063 |
import sys
import os
def locate_spy_file(file_name):
"""Tries to find shellpy file on filesystem. Given a filename without extension it tries to locate it with .spy
extension in pythonpath
:param file_name: Filename without extension
:return: Path to shellpy file or None if not found
"""
for ... | 300622ded5ead0449c9e71b7c45520b24006e4c9 | 659,064 |
def mysql_old_passwd(password, uppercase=True): # prior to version '4.1'
"""
Reference(s):
http://www.sfr-fresh.com/unix/privat/tpop3d-1.5.5.tar.gz:a/tpop3d-1.5.5/password.c
http://voidnetwork.org/5ynL0rd/darkc0de/python_script/darkMySQLi.html
>>> mysql_old_passwd(password='testpass', uppe... | bdc589d119193ec03f3152d6e65b0ec241528eca | 659,065 |
def key(name):
"""Extracts the filename key."""
dot = name.rfind(".")
if -1 != dot:
return name[0:dot]
return "" | 22e52edec1e3ea4a021881da1085f8d812ab59bf | 659,066 |
def is_a_reverse_shallow_copy_list(x, y):
"""
Return :bool:`True` if 'y' is a reversed copy of 'x' and :bool:`False` otherwise.
"""
return x == list(reversed(y)) | 46cca39ed238eec27be65c638bbef331a0a85353 | 659,068 |
import sys
import argparse
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object:
parser = argparse.ArgumentParser(
... | fd4a940eb17c35a258f0fead00e19fc314247993 | 659,071 |
from typing import Dict
from typing import Any
def _process_replacement(line: str, parameters: Dict[str, Any]) -> str:
"""Appropriately replace a single <replace> statement."""
new_line = line.format(**parameters)
if None in parameters.values():
raise ValueError("Found a parameter with no specifie... | 162d008feda8b84820afb244b8f6a458d5014f5e | 659,072 |
def _swap(bytestring: str) -> str:
"""Swap characters pairwise in a string.
This corresponds to a "byte swap".
Args:
* bytestring (str): input. The length should be an even number.
Return the string with characters swapped.
"""
length = len(bytestring)
if length % 2:
rais... | 45f72840c6aa3f3b3eae11e35c41e587abc05b22 | 659,073 |
from pathlib import Path
def req_exists(r):
""" Checks whether a dependency exists on a drive. """
if type(r) is str:
if not Path(r).is_file() and not Path(r).is_symlink() and not Path(r).is_dir():
return False
elif type(r) is list:
return not (False in map(req_exists, r))
... | 97ced7dea3e0e617ef11ad0261113d93f02b01b8 | 659,076 |
def syncFn1(n):
"""sync fucntion"""
print(f"start:fn({n})")
print(f"finish:fn{n}")
return f"finish:fn{n}" | 52faa79ee79c075cb7e3072f089b739c0c1a7a69 | 659,077 |
def seat_number(seat):
"""Return the consecutive seat number (8 seats per row)."""
rows, columns = list(range(128)), list(range(8))
for character in seat:
if character == 'F':
rows = rows[:len(rows) // 2]
elif character == 'B':
rows = rows[len(rows) // 2:]
eli... | 3a2ce437a0658f19c87bc3262e2a54a98f224eab | 659,078 |
def points(games: list) -> int:
""" This function counts the points of our team in the championship. """
score = 0
for item in range(len(games)):
x = games[item][0]
y = games[item][2]
if x > y:
score += 3
elif x == y:
score += 1
return score | dd61eaed8b0718b4c996453cc4c06da9a1e45a9f | 659,080 |
def galaxy_attrib():
""" List of properties expected to be stored for CASBAH galaxies
"""
attrib = [ (str('RA'), float), # RA (J2000)
(str('DEC'), float), # DEC (J2000)
(str('Z'), float), # Redshift
(str('Z_ERR'), ... | eeefad62745dcc92bacd76743b83ef9d5ce19084 | 659,081 |
def inject_participant(team, participant, team_size, rnd) -> bool:
""" For a given team and participant, return True if a participant should be injected. """
# Don't add more than team_size members.
if team.member_count() >= team_size:
return False
# Allow two Indians in first, owing to their... | 03516878bd97f57ebf06f6702812c38f460c6f83 | 659,082 |
def test_names_list(test_suite):
"""Build a list containing all the test names of a test suite."""
test_names = []
for test in test_suite.test_cases():
test_names.append(test.description)
return test_names | 3418cf021cb9c1de1ef0f2b007de4ee6efbd9d8f | 659,083 |
def get_action():
""" Find out what the player wants to do next. """
print()
print("What do you want to do next?")
print(" m) move")
print(" a) fire an arrow")
action = input("> ")
if action == "m" or action == "a":
return action
else:
print()
print(action + "?")
... | 5c3332650ce6fba913db2dda049e1e12262bb283 | 659,084 |
def process_names(raw_names):
""" Processes the names to be used as inputs for the model. Spaces are
changed by 0, hyphens by 1 and end of names are delimited by 2 """
names = []
for name in raw_names:
name = name.lower()
if ' ' in name:
name = '0'.join(name.split())
... | b5db06aaf169aa8069e83a3b5f6c25784a827b7a | 659,086 |
def _getGeoTransform(xyData, xres, yres):
"""Adpated to accomodate the orientation expected by geotiffs. """
xmin, ymin, xmax, ymax = [xyData[:, 0].min(), xyData[:, 1].min(),
xyData[:, 0].max(), xyData[:, 1].max()]
ncols = round(((xmax - xmin) / xres) + 1)
nrows = round(((... | e799a3e6dec48edc40090eb9a22007fb3deedde7 | 659,087 |
def model_device(model):
"""Determine the device the model is allocated on."""
# Source: https://discuss.pytorch.org/t/how-to-check-if-model-is-on-cuda/180
if next(model.parameters()).is_cuda:
return 'cuda'
return 'cpu' | a827a48a5f71bf0a6a3f264de6016248f0a1f0ce | 659,089 |
import imp
def get_curved_roads(source_file):
"""
Given a source file, get the dict of curved roads.
"""
data_module = imp.load_source('local_data', source_file)
return data_module.curved_roads | 8f08658cd1cb1e07d4b10e89b683a8c3818b44fe | 659,090 |
import math
def binomial_coefficient(n: int, k: int) -> int:
"""Calculate Binomial coefficient"""
n_fac = math.factorial(n)
k_fac = math.factorial(k)
n_minus_k_fac = math.factorial(n - k)
return round(n_fac/(k_fac*n_minus_k_fac)) | b15da267b67d09df0fd93ac65d088ee739a0d9c0 | 659,091 |
import string
import random
def randstr(nchars=10):
"""Creates a random string identifier with the given number of chars"""
chars = string.ascii_letters + string.digits
ret = ''.join([random.choice(chars) for i in range(nchars)])
return ret | 7576805a9f3474758ae1237c6efea14ef90bfff8 | 659,092 |
import random
def key(_):
"""Функция"""
return random.random() | eae0b0fc364aabd54bd48d5817dd3df39dbf552f | 659,093 |
from datetime import datetime
def string_to_time(time: str):
"""
:param time:
:return:
"""
return datetime.strptime(time, "%H:%M:%S") | 85649fd445f3d2c8257a6dacd48af5ee9247b6f2 | 659,094 |
def gen_array(fen):
"""" Generate array from FEN """
slash_index = [pos for pos, char in enumerate(fen) if char == '/']
arr = []
i = 0
for el_ in slash_index:
if slash_index[-1] == el_:
arr.append(fen[i:el_])
arr.append(fen[el_+1:])
else:
arr.appe... | fb984d210760ad9f4c5254c8c2a37bad8e49d2c6 | 659,095 |
def tag_simplify(tag):
"""转化为单标签"""
temp = [0 for i in range(len(tag))]
max = float('-inf')
id = 0
for i in range(len(tag)):
if tag[i] > max:
max = tag[i]
id = i
temp[id] = 1
return temp | d6df425d2c3b1ce84f40e0d3cc0cf09ee334fb6c | 659,096 |
def dbTables():
"""
db tables to init
"""
return [
{
'name': 'bot',
'schemas': [
{
'name': 'id',
'type': 'string',
'primary': True
},
{
'name': 'token',
'type': 'json'
},
{
'name': 'data',
... | 25202a2aa705a973ce9db46462472152db54af1b | 659,099 |
def _format_function(func_name):
"""Provide better context for a "function" of the caller.
"""
if func_name is None:
return ""
elif func_name == "<module>":
return " (top level stmt)"
else:
return " in " + func_name | c4699a2e2e49f461f469a85f1af85fffc408d104 | 659,100 |
def reformat_tract_code(tract: str, state_code: str, county_code: str) -> str:
"""Helper function to return GEOIDs compatible with those in deep-dive data files.
Parameters
----------
tract : A string
An unformatted tract code, e.g. '53.38'
state_code : A string
The FIPS code for th... | 4b96694b47e91f3d400f7987ee690b7af0fb9573 | 659,101 |
def nil():
""" -> list[alpha] """
return [] | 1dc0ff780c6502e888fc8c6d771b4f6c7521841f | 659,102 |
def xunicode(s):
"""If ``s`` is None return empty string
.. deprecated::
Use :func:`xstr` instead.
:param s: string
:return: s or an empty string if s in None
:rtype: str
"""
return '' if s is None else str(s) | b45f6197e9a3631cba6da6ef8248c8238d544cc2 | 659,103 |
def same_level_stars(prev, curr):
"""Two stars in a row can exist on the same level if the previous is
inline"""
two_stars = prev.is_stars() and curr.is_stars()
return two_stars and prev.depth == curr.depth and prev.is_inline_stars() | 1b6db251338f38520af655c97a25363fc1e78be7 | 659,104 |
def _safe_mesos_dns_taskname(task_name):
"""Converts a potentially slash-delimited task name to one that works for '.mesos' task names
Mesos DNS task names handle folders like this: /path/to/myservice => myservice-to-path"""
elems = task_name.strip("/").split("/")
elems.reverse()
return "-".join(ele... | 71189da614287f835448be4709c9e120ba16e725 | 659,105 |
def get_list_of_subsets(subset_task):
"""
Get the subsets to process for this analysis
Parameters:
-----------
subset_task: string
string which specifies which subsets to use
Results:
--------
list of subset tasks
"""
# prefix for data and images
if subset_task =... | c4d2e632bf4c70ef3232505694d86b1c48a9a0de | 659,106 |
def mean_of_number_list(numbers, delim="_"):
"""Report arithmetic mean of a string of integers that are separated by a
common delimiter. Used here to get mean of IES lengths reported in MILRAA
output GFF attribute.
Parameters
----------
numbers : str
List of numbers separated by a commo... | 2b1c04ba67ed0dac279fbc9ca6dd8458575f5f69 | 659,107 |
def branch_population(merged_population):
"""
create an unmerged population representation
"""
feasible_pop = []
infeasible_pop = []
for instance in merged_population:
if instance.feasibility:
feasible_pop.append(instance)
else:
infeasible_pop.append(ins... | 842049e6201d8d3d8dd4f220bdaaccb790cf1bce | 659,108 |
def odd_elements(array):
"""
"""
odd = set()
for item in array:
if item in odd:
odd.remove(item)
else:
odd.add(item)
return odd | 79c99b88a282c3db817825062e8f17854a5b8c8f | 659,109 |
def loadLowFreqLabels(labelFilePath):
"""
Return dictionary of channel labels.
:param labelFilePath: path to the data. The path should end with the folder containing all data for a specific house.
:type labelFilePath: str
:rparam: keys=channels_x - appliance name
:rtype: dict
"""
... | 241ef9b58d01c24e36d28e855563af3b91e145f0 | 659,110 |
def unpack_arch(architecture):
"""
:param architecture: dict. containing num. of units in every layer (2-layer FC network)
:return: input_size, hidden_size, output_size of NN
"""
input_size = architecture["state_dim"]
hidden_size = architecture["hidden_units"]
output_size = architecture["nu... | ac84f930b4c73b20e27c938288277028793d34c0 | 659,111 |
def rmpHomozygousWithTheta(theta, pu):
"""
Notation from Baldings and Nichols (1994)
taken from Buckleton FSI Gen (23) 2016; 91-100
https://doi.org/10.1016/j.fsigen.2016.03.004
"""
# 2theta + (1-theta)*pu
numerator1 = (theta+theta) + (1-theta)*pu
# 3theta + (1-theta)*pu == theta + numerator1
numerator... | 4d51059c75bc357d96397165fe7df3b4b9eeee32 | 659,112 |
def find_root(array, value):
"""
Find the root and balance
Complexity: O(logN)
"""
if array[value] != value:
array[value] = find_root(array, array[value])
return array[value] | f0c2d0e1e2af9cc200e201a4b67696e5920b5241 | 659,113 |
import random
def step_i__get_dxdydz(r, log, eps=1.e-7):
"""
Generation of shifts from screw rotations.
"""
dx0, dy0, dz0 = 0, 0, 0
if(abs(r.dx)>eps): dx0 = random.normalvariate(0,r.dx)
if(abs(r.dy)>eps): dy0 = random.normalvariate(0,r.dy)
if(abs(r.dz)>eps): dz0 = random.normalvariate(0,r.dz)
return d... | a99a3d4a59eb8e587ff26a24275ecf53a3ff094a | 659,114 |
def bytes_to_gb(number: float) -> float:
"""
Convert bytes to gigabytes.
Parameters
----------
number : float
A ``float`` in bytes.
Returns
-------
float
Returns a ``float`` of the number in gigabytes.
"""
return round(number * 1e-9, 3) | d97ac89429c7ebc321e44fe3d8b33c1a0f1288c7 | 659,115 |
import re
def default_output_mixer_channel(discovery_props, output_channel=0):
"""Return an instrument's default output mixer channel based on the specified
`devicetype` and `options` discovery properties and the hardware output
channel.
This utility function is used by the ziPython examples and retu... | 5e927a8e2ff3596ea08d55b723b9d664531ca271 | 659,116 |
import click
def burst_limit_option(func):
"""Add a burst limit option."""
return click.option('--burst-limit', help='Number of simultaneous file changes to allow.',
default=0, type=click.INT)(func) | 20bc959c2bc5ae93107a2503f36550801e35013f | 659,117 |
def empty_list ():
"""
Creates a new empty list.
:return: A frest list
:rtype: dict
"""
return { "head" : None, "tail" : None } | f1b5e1252b6da513e83acf04108ac0eeca10c1c2 | 659,118 |
import torch
def root_sum_of_squares(x, dim=0):
"""
Compute the root sum-of-squares (RSS) transform along a given dimension of
a complex-valued tensor.
"""
assert x.size(-1) == 2
return torch.sqrt((x**2).sum(dim=-1).sum(dim)) | e446eba20b70453630122a5543ae0f70b6063b5d | 659,119 |
import random
def getQuote():
"""Returns an awesome randomized quotation."""
libraryFile=open('static/quotes.txt','r')
library=libraryFile.readlines()
return (random.choice(library)).split(';') | 26781d964ab1045950641b00e8501c3e66ea0dab | 659,121 |
def build_links(tld, region_code, states):
"""
This will build start_urls, It needs to be available before the ChipotleSpider creation
:param tld: 3rd level domain name to use for building the links e.g .co.uk
:param region_code: region is an important url param required for the search
:param state... | d42291356a149b3a8e411a0bfe715d522c03da4a | 659,122 |
import os
def find_libxml2_include():
"""Find lxml2 libraries to include in the extension"""
include_dirs = []
for d in ['/usr/include/libxml2', '/usr/local/include/libxml2']:
if os.path.exists(os.path.join(d, 'libxml/tree.h')):
include_dirs.append(d)
return include_dirs | cac5944f1f017d194b15019c633c728817a30f0e | 659,123 |
import six
def _reset_cached_subgraph(func):
"""Resets cached subgraph after execution, in case it was affected."""
@six.wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
self._subgraph = None
return result
return wrapper | 5cb500767cbed39ebdad3fede63b551e52c1747f | 659,124 |
def dt_writer(obj):
"""Check to ensure conformance to dt_writer protocol.
:returns: ``True`` if the object implements the required methods
"""
return hasattr(obj, "__dt_type__") and hasattr(obj, "__dt_write__") | fdb601d53bfe77b5732cbd0c5fe1108f20269841 | 659,125 |
def upstairs(n):
"""
第n个台阶的走法有F(n) = F(n-2) + F(n-1)这两种,存一次类推,那么边界的话就是,如果0个台阶,那就有0种走法
如果第一个台阶,那就有1种走法,而第2个台阶,就有2种走法。
"""
if n == 0:
return 1
elif n == 1:
return 1
elif n == 2:
return 2
else:
return upstairs(n - 1) + upstairs(n - 2) | 1856c6afdd1d27063de15388d17fcf3531e7ccfd | 659,126 |
def index():
"""
Initial view or endpoint when visiting localhost:8000/
:rtype: Welcome and instruction for walkthrough via readme or localhost:8000/docs
"""
return {
"👋 Hello": "Please refer to the readme\
documentation for more or visit http://localhost:8000/docs"
} | b53ef0e1668af8d931a9c003d6ce00909d5f5e20 | 659,128 |
def _aggregate_at_state(joint_policies, state, player):
"""Returns {action: prob} for `player` in `state` for all joint policies.
Args:
joint_policies: List of joint policies.
state: Openspiel State
player: Current Player
Returns:
{action: prob} for `player` in `state` for all joint policies.
... | b2bed9b7b2b48a4a73989fe9a3bd9b241c4a40ad | 659,129 |
from typing import Tuple
import torch
from typing import List
def cross_entropy_loss(batch: Tuple, model: torch.nn.Module) -> Tuple[float, Tuple[torch.Tensor, List]]:
"""
Calculate cross entropy loss for a batch and a model.
Args:
batch: batch of groundtruth data
model: torch model
R... | 158f08353fe83125c20ba34313611f0023338326 | 659,130 |
from pathlib import Path
import platform
def get_py_prefix(venv_path: Path) -> Path:
"""Return the appropriate prefix for the virtual environment's Python.
>>> # If platform.system() is 'Windows'
>>> get_py_prefix(Path.cwd()/'.venv')
Path('.venv/Scripts/python.exe')
>>> # If platform.system() is... | a81a185d24f6d7fac52aa9e68512e193811b3407 | 659,131 |
import json
def load_json(filename):
"""Returns students as a list of dicts from JSON file."""
with open(filename) as f:
students = json.load(f)
return students | 9730ae02f2409518f594b3014702915cdda5ad03 | 659,133 |
import os
def get_experiment_paths(path: str
) -> tuple:
""" Walk through path recursively and find experiment log files.
Note:
In a directory must exist a config.json and metrics.json file, such
that path is detected.
Parameters
----------
pa... | 2e639e9f04cf16b4a548a46c1188908d332afd19 | 659,134 |
import typing
def flatten_list(list_of_lists: typing.List[typing.List[typing.Any]]) -> typing.List[typing.Any]:
"""flatten a 2 level deep nested list into a single list
Parameters
----------
list_of_lists: typing.List[typing.List[typing.Any]]
2 level nested list
Returns
-------
... | eab91121f66cefc1ab7e43f5644544360f1e678c | 659,135 |
import os
def listdirfiles(dir):
"""
read spec or data directory
:param dir: directory name
:return: list of files in the given directory
"""
return os.listdir(dir) | 273d5bba48d12093688c62183d0454de9a2b6a68 | 659,136 |
import os
import json
def load_metrics(exp_dir, filename='metrics.json'):
"""
Load metrics from the given exp directory..
Parameters
----------
exp_dir : ``str``
Folder to load metrics from
filename : ``str``, optional (default: 'metrics.json')
Name of metrics file
Return... | bbf1600b00bf48598ab7499331bf1082404d3d80 | 659,137 |
def sqliteRowsToDicts(sqliteRows):
"""
Unpacks sqlite rows as returned by fetchall
into an array of simple dicts.
:param sqliteRows: array of rows returned from fetchall DB call
:return: array of dicts, keyed by the column names.
"""
return map(lambda r: dict(zip(r.keys(), r)), sqliteRows) | 93f897ca07db4edd14a303bef00e233b0a06a6e3 | 659,138 |
import linecache
import inspect
def _getCallerDict(callerDict=None, depth=2):
"""This is IT!!!!"""
if callerDict is None:
linecache.checkcache()
frame = inspect.stack()[depth][0]
try:
return frame.f_globals
finally:
del frame
return callerDict | 9bf797e15508ba1a12d3534688a54bfd0f60ef35 | 659,139 |
import json
def retrieve_exec_resp_fixture():
"""Load execution response test fixture data."""
j = json.load(open("./tests/fixtures/execution_resp_obj.json"))
return j | 910c4dfc07bb025ce222a35592ffcaa174a0f088 | 659,140 |
def class_name(self):
"""
Return the name of this class without qualification.
eg. If the class name is "x.y.class" return only "class"
"""
return self.__class__.__name__.split('.')[-1] | 562c956cbdc8e724eea2733697c479a82a0f936b | 659,141 |
import os
import pprint
def _get_dataset_files(dataset_info, mode, root, file_range):
"""Generates lists of files for a given dataset version."""
basepath = dataset_info.basepath
base = os.path.join(root, basepath, mode)
files = [
(int(f.split('-')[0]), os.path.join(base, f))
for f in ... | ee4197432b75050dcec16aef252625976c202275 | 659,142 |
import copy
def rect_smooth(spectrum, m):
"""Rectangular smoothing function.
Parameters
----------
spectrum: str
a spectrum object
m : int
the smoothing width, must be an odd integer more than 3
Returns
-------
smooth_spect: a spectrum object
"""
if m < 3:
... | e9f7ca5aea7f5ad27960738b4a86779cb21516c9 | 659,143 |
import re
def parse_ivar_line(line):
"""
Description:
Parse ivar line to get needed variables for vcf format.
input:
line - ivar tsv line
return:
CHROM, POS, ID, REF, ALT, QUAL, INFO, FORMAT, REF_CODON, ALT_CODON, pass_test, var_type
"""
line = re.split("\t", line)
... | ece2729ee76806b7601c05bfd13777e9b545dc32 | 659,144 |
def add_season_steps(df, season_length):
"""
Adds a column to the DataFrame containing the season step depending on the given season_length.
The season step determines the position of each column within a season. It ranges from 0 to season_length - 1.
:param df: pandas DataFrame with a DateTime index a... | d24c6dfc49821d5fb849d298834f988355afe359 | 659,146 |
def J(x, alpha):
"""
Calculates J as in eq (22)
"""
return 4. * x**(11./2. - alpha) / (1. + x**(3.-alpha))**(7./2.) | 5621397bbd0dd3f0851160141a442c89dd533e67 | 659,147 |
def normalize(J):
"""Normalize a vector."""
# alpha = ellipse_azimuth(J)
# gamma = phase(J)
return J | 5fdefea67287420c86284a836bffd00e089590eb | 659,149 |
def _byte_string(s):
"""Cast a string or byte string to an ASCII byte string."""
return s.encode('ASCII') | db048e47ebbb964ee6d14d2c32a8d4dcd3b45ad4 | 659,150 |
def is_threaded_build(root):
"""
Check whether the tk build in use supports threading.
:param root: the tk widget to be used as reference
:return: ``1`` if threading is supported ``0`` otherwise
"""
return int(root.tk.eval("set tcl_platform(threaded)")) | 554d92e51fabff650bf809662a16ca44f190c994 | 659,151 |
def bezierPoint(a, b, c, d, t):
"""Given the x or y coordinate of Bézier control points a,b,c,d and
the value of the t parameter, return the corresponding
coordinate of the point."""
u = 1.0 - t
return a * u * u * u + b * 3 * u * u * t + c * 3 * t * t * u + d * t * t * t | 1da9a9f0756b47c04ecd6f91f611d7c7d2f22760 | 659,152 |
import requests
def current_location():
""" Get ISS Current location data
"""
url = "http://api.open-notify.org/iss-now.json"
response = requests.get(url)
return response.json() | 22f3f1cd3d12d875dc2cc8364972b80a743e1c34 | 659,153 |
import json
def read_categories_dict():
"""
读取code与名称的dict
:return: dict
"""
file_name = "library_a_dict.json"
file_object = open(file_name)
json_object = json.load(file_object)
return json_object | 65918180f70f50b35dd74ebfca9f67196e03e885 | 659,154 |
def get_decoding_route_length(molecular_graph):
""" Returns the number of subgraphs in the `molecular_graph`s decoding route,
which is how many subgraphs would be formed in the process of deleting the
last atom/bond in the molecule stepwise until only a single atom is left.
Note that this is simply the ... | 7e55e4d1a243a9bbb8352b95cd22066006e7060a | 659,155 |
def _remove_extrem_holes(z_lst, end_z, start_z=0):
"""Remove extrem holes from the list of holes so that we will not interpolate on the extrem slices."""
if start_z in z_lst:
while start_z in z_lst:
z_lst = z_lst[1:]
start_z += 1
if len(z_lst):
z_lst.pop(0)
... | fce804c0517dffbb4820b5799ef3aa30e22432d0 | 659,156 |
def get_texture_declaration(texture):
"""Return the GLSL texture declaration."""
declaration = "uniform sampler%dD %s;\n" % (texture["ndim"], texture["name"])
return declaration | 625dbc7e84949b9bf8bbda6ca86244c681187825 | 659,157 |
def bin_coef_efficient(n: int, k: int) -> int:
"""
C(n, k) = C(n, n-k) # fact
therefore, if k > n-k, change k for n-k (for easier calculation)
i.e. C(n, k) = n! / (k! * (n-k)!) = [(n) * (n-1) * ... (n-k+1) / k!]
=> k terms above and k terms below
Time Complexity: O(k)
Space Complexity: O(... | 09508012cc6f35320d5c8b27168f76f65e71a4a6 | 659,158 |
def ec2_inst_is_vpc(inst):
""" Is this EC2 instance a VPC instance? """
return (inst.vpc_id is not None) | a7c53f0aea53e78ebcebba5023a85aeed0a56afb | 659,159 |
def read_number_of_agents(dpomdp_file):
"""Returns the number of agents in a Dec-POMDP problem
Keyword arguments:
dpomdp_file -- path to problem file in the .dpomdp format
"""
with open(dpomdp_file) as file:
for line in file:
if line.startswith('agents:'):
return int(line.split(':')[1])
raise V... | 13f91b6f00b290783898928f287bcccb0e2f4b69 | 659,160 |
import io
def _has_fileno(stream):
"""Returns whether the stream object seems to have a working fileno()
Tells whether _redirect_stderr is likely to work.
Parameters
----------
stream : IO stream object
Returns
-------
has_fileno : bool
True if stream.fileno() exists and doe... | a725119eb2cce135e33adab11854f9da5e8af64d | 659,161 |
import subprocess
import sys
def run_bash(cmd, raise_on_err=True, raise_on_warning=False, versbose=True, return_exist_code=False, err_ind_by_exitcode=False):
""" This function takes Bash commands and return their stdout
Returns: string (stdout)
:type cmd: string
"""
p = subprocess.Popen(cmd, shell... | 1c13cfdec764ee5864a0cb9ba6604e03f447715f | 659,162 |
import re
import argparse
def valid_url(url):
"""Validate url.
:rtype: str
:return: url
:param str url: package homepage url.
"""
regex = re.compile(
r'^(?:http)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?))'
r'(... | 14878702a1cce4ca00aa9934a2fd73a8ff843255 | 659,163 |
import logging
def loggingDecorator(func):
"""记录日志的装饰器"""
def wrapperLogging(*args, **kwargs):
logging.info("开始执行 %s()... " % func.__name__)
func(*args, **kwargs)
logging.info("%s() 执行完成... " % func.__name__)
return wrapperLogging | bfdfbaa3f29ad4b9a5bdb193070685231729f62d | 659,164 |
import re
def extract_keybinds(contents):
"""extract each commented keybind block to an array
Args:
contents (string): contents of the i3 config
Returns:
array: array of tuples containing the matched commented keybind block
"""
return re.findall(r'((#(((?!bindsym)(?!exec).)*?)\n)... | c4251ba802c194abc422bc83acf7759aa921610b | 659,166 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.