content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def walk_links_for_node(node, callback, direction, obj=None):
"""
Walks the each link from the given node. Raising a StopIteration will terminate the
traversal.
:type node: treestruct.Node
:type callback: (treestruct.Node, treestruct.Node, object) -> ()
:type direction: int
:type obj: Any
... | a92cb831945a537c55ff4c014eedcb17b26ddd96 | 702,873 |
import configparser
def get_config_parser(filepath):
"""Create parser for config file.
:param filepath: Config file path
:type filepath: str
:return: configparser.ConfigParser instance
"""
config_parser = configparser.ConfigParser(interpolation=None)
# use read_file() instead of read() to... | 224f524c60161bc45b1324b26eeb6d4715c43054 | 702,874 |
def load_id_map(id_file):
""" Load a ids file in to a barcode -> coordinate dictionary.
"""
id_map = {}
with open(id_file, "r") as fh:
for line in fh:
bc, x, y = line.split("\t")
id_map[bc] = (int(x), int(y))
return id_map | cd2c0635496209c3e19597fa45ae4f486779ceac | 702,875 |
from typing import Set
from typing import Mapping
from typing import Sequence
def expand_related_tasks(tasks: Set[str],
expand_map: Mapping[str, Sequence[str]]) -> Set[str]:
"""The inverse of `collapse_related_tasks`.
Args:
tasks: a list of tasks to expand.
expand_map: map from a... | 16abd2160dc972e89ade3e5cb2b40e8451a932a7 | 702,876 |
import sympy
def antal_h_coefficient(index, game_matrix):
"""
Returns the H_index coefficient, according to Antal et al. (2009), as given by equation 2.
H_k = \frac{1}{n^2} \sum_{i=1}^{n} \sum_{j=1}^{n} (a_{kj}-a_{jj})
Parameters
----------
index: int
game_matrix: sympy.Matrix
Ret... | 0e05a6a622ef24ff63b18b9c8b80348b860a16c3 | 702,877 |
import hashlib
def getcertpubhash(certobj):
"""
Method 1: Hash from public key
:param certobj:
:return:
"""
if certobj:
pubkey = certobj.get_pubkey().as_der()
pubkeyhash = hashlib.sha256(pubkey).hexdigest()
return pubkeyhash
else:
return None | 3002a8ddba6522acf7de0c1cfa225e68a1e3f141 | 702,878 |
from typing import List
from typing import Dict
def _cx_to_dict(list_of_dicts: List[Dict], key_tag: str = "k", value_tag: str = "v") -> Dict:
"""Convert a CX list of dictionaries to a flat dictionary."""
return {d[key_tag]: d[value_tag] for d in list_of_dicts} | ea80e9a50ea04536c2ed068d19220b56a9bdf3ed | 702,879 |
import typing
import pathlib
import itertools
def find_pyfiles() -> typing.Iterator[pathlib.Path]:
"""Return an iterator of the files to format."""
return itertools.chain(
pathlib.Path("../gdbmongo").rglob("*.py"),
pathlib.Path("../gdbmongo").rglob("*.pyi"),
pathlib.Path("../stubs").rg... | 74b0c11771799fba6090569595d24e70ec68899d | 702,880 |
def merge_args(args, cloud_args):
"""merge_args"""
args_dict = vars(args)
if isinstance(cloud_args, dict):
for key in cloud_args.keys():
val = cloud_args[key]
if key in args_dict and val:
arg_type = type(args_dict[key])
if arg_type is not type(... | 06f84376e23535e9d291eb9bc9514fa27582faa2 | 702,881 |
def visibility_define(config):
"""Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string)."""
hide = '__attribute__((visibility("hidden")))'
if config.check_gcc_function_attribute(hide, 'hideme'):
return hide
else:
return '' | b08e8515440c4bf1ebec51c4100e55fe9f14b17d | 702,882 |
def calculate_num_points_in_solution(solution):
"""Calculates the number of data points in the given solution."""
return sum(len(points) for points in solution.values()) | c75f7cb7d9c8c2731e4698040954c559b6b5d4ec | 702,883 |
import re
def get_polygon_speed(polygon_name):
"""Returns speed unit within a polygon."""
result = re.search(r"\(([0-9.]+)\)", polygon_name)
return float(result.group(1)) if result else None | 2d2cc99f30153c4fbc9ac358ad3debc15fc3227e | 702,884 |
def pt_in_ploy(poly, x, y):
""" 判断 点(x,y) 是否 在 poly 最大和最小坐标之外,粗略 判断点是否在图形之内 """
n = len(poly)
if n < 3:
return False
xmax = xmin = poly[0]['x']
ymax = ymin = poly[0]['y']
for i in range(1, n):
if poly[i]['x'] > xmax:
xmax = poly[i]['x']
elif poly[i]['x'] < x... | 2e07429edd6929a7e5747e6ba113f4186413dab8 | 702,885 |
def random_node_presence(t_windows, rep, plac, dur):
"""
Generate the occurrence and the presence of a node given occurrence_law(occurrence_param)
and presence_law(presence_param).
:param t_windows: Time window of the Stream Graph
:param rep: Number of segmented nodes
:param plac: Emplacement o... | 416ea50c4cdd1280dde90816ec735b8eff6f81f1 | 702,886 |
import pdb
import torch
def batch_hard_triplet_loss(labels, embeddings, k, margin=0, margin_type='soft'):
"""Build the triplet loss over a batch of embeddings.
For each anchor, we get the hardest positive and hardest negative to form a triplet.
Args:
labels: labels of the batch, of size (batch_s... | 2853124d06688eaca4f7da2a5bc19819490656c9 | 702,887 |
import sys
from pathlib import Path
import os
def resource_path(relative_path):
""" Return absolute path for provided relative item based on location
of program.
"""
# If compiled with pyinstaller then sys._MEIPASS points to the location
# of the bundle. Otherwise path of python script is used.
... | 303418a0d61ae2107d7ac4f8e3503c71bac090bf | 702,888 |
def _set_default_voltage_ratio(
voltage_ratio: float, subcategory_id: int, type_id: int
) -> float:
"""Set the default voltage ratio for semiconductors.
:param voltage_ratio: the current voltage ratio.
:param subcategory_id: the subcategory ID of the semiconductor with missing
defaults.
:pa... | d084f157c4d105193693af722e72028129e17821 | 702,889 |
import copy
def random_reset_mutation(random, candidate, args):
"""Return the mutants produced by randomly choosing new values.
This function performs random-reset mutation. It assumes that
candidate solutions are composed of discrete values. This function
makes use of the bounder function as specif... | c357237e22e34b7496f8cc17f4ad0efa2bd4621d | 702,891 |
def is_same_data(data1, data2, precision=10**-5):
"""
Compare two data to be the same.
:param data1: given data1
:type data1: list
:param data2: given data2
:type data2: list
:param precision: comparing precision
:type precision: float
:return: True if they are the same
"""
... | 16e786a552d9190eebb44721ab75ddd45d7086cf | 702,892 |
import re
def normalise_name(raw_name):
"""
Normalise the name to be used in python package allowable names.
conforms to PEP-423 package naming conventions
:param raw_name: raw string
:return: normalised string
"""
return re.sub(r"[-_. ]+", "_", raw_name).lower() | 2c9aea4a3e83fdb52f952d2308de29d8948f6917 | 702,893 |
def timestr_mod24(timestr):
"""
Given a GTFS HH:MM:SS time string, return a timestring in the same
format but with the hours taken modulo 24.
"""
try:
hours, mins, seconds = [int(x) for x in timestr.split(":")]
hours %= 24
result = "{:02d}:{:02d}:{:02d}".format(hours, mins, s... | ea049f4b31861de56b04dba6f4356ed46930af44 | 702,894 |
def set_ext_api(file_path):
"""Smart Function to set Extension."""
ext = file_path.split('.')[-1]
if ext == 'plist':
return 'plist'
elif ext == 'xml':
return 'xml'
elif ext in ['sqlitedb', 'db', 'sqlite']:
return 'db'
elif ext == 'm':
return 'm'
else:
... | 816a7f33c659ff3e0089502530fb916a40982d79 | 702,895 |
def animations():
"""animations() -> tuple
Returns a list of animatable things the user wants to work on.
If this is a command being executed from a menu item in a curve editor, a list of the names of all selected curves is returned. If this list is empty a "No curves selected" error is produced.
If this is a comm... | a30923e499824739c8a0429bdb6a8f10f42928ba | 702,896 |
def add_solution(
respy_obj,
periods_rewards_systematic,
states_number_period,
mapping_state_idx,
periods_emax,
states_all,
*args,
):
"""Add solution to class instance."""
respy_obj.unlock()
respy_obj.set_attr("periods_rewards_systematic", periods_rewards_systematic)
respy_ob... | ea0660fe5956bf5e8f6706a12e766a0cc5e2f2db | 702,897 |
def mod(source):
"""Create kernel module shared among multiple tests."""
return source.get_module_for_symbol("snd_request_card") | 484afb203021497614ee18c7ac99200e4cb39a12 | 702,898 |
from functools import reduce
def constant_time_compare(x, y):
"""
Compares two byte strings in a way such that execution time is constant
regardless of how much alike the input values are, provided that they
are of the same length.
Comparisons between user input and secret data such as calculated... | fe7fc348d367907eee2c9df3b7d0fbe232072714 | 702,900 |
def _str2bool(string):
"""Converts either 'true' or 'false' (not case-sensitively) into a boolean."""
if string is None:
return False
else:
string = string.lower()
if string == 'true':
return True
elif string == 'false':
return False
else:
raise ValueError(
'String should either... | 97755d1901a836bb1e3ce062afdbffc8b5b92de1 | 702,901 |
import math
def _get_alpha_bar_from_time(t):
"""
Noise scheduling method proposed by Nichol et. al to avoid too noisy image especially for smaller resolution.
This strategy creates beta as follows:
alpha_bar(t) = f(t) / f(0)
f(t) = cos((t / T + s) / (1 + s) * PI / 2) ** 2
beta(t) ... | ecb79239e2181d6e17db0b30885ec68d48b0a2d3 | 702,902 |
def decrementAny(tup):
""" the closest tuples to tup: decrementing by 1 along any dimension.
Never go into negatives though. """
res = []
for i, x in enumerate(tup):
if x > 0:
res.append(tuple(list(tup[:i]) + [x - 1] + list(tup[i + 1:])))
return res | 44d5c968231cfb761c641892883a85c6a168c338 | 702,903 |
def ExtractModuleIdIfValidBreakpad(file_path):
"""Extracts breakpad file's module id if the file is valid.
A breakpad file is valid for extracting its module id if it
has a valid MODULE record, formatted like so:
MODULE operatingsystem architecture id name
For example:
MODULE mac x86_64 1240DF90E9AC39038E... | e846cf05976c2c1622160d1a2a639d605e072417 | 702,904 |
from datetime import datetime
import pytz
def _timestamp_to_iso_str(timestamp):
"""
Converts the timestamp value into a iso str
Args:
timestamp(float): the timestamp to convert
Returns:
str: converted timestamp
"""
return datetime.fromtimestamp(timestamp).replace(tzinfo=pytz.... | 89257c74a96c5335bc25ef617e41c0eeeb31021e | 702,905 |
def subtract_mean_vector(frame):
"""
Re-center the vectors in a DataFrame by subtracting the mean vector from
each row.
"""
return frame.sub(frame.mean(axis='rows'), axis='columns') | 4a6207889b958aebd608c349ad889e109ab3f4a9 | 702,906 |
def reduce_level(ast):
"""
The function removes from the abstract syntax tree a declaration current level (pointer or array). For instance it
makes from AST of 'int *a' it makes AST for 'int a'.
:param ast: Current abstract syntax tree.
:return: Abstract syntax tree for the pointer or an array elem... | 6d7e61265555106efe9f0733ec5f40b51bdaedf8 | 702,907 |
def to_location(maiden: str, center: bool = False) -> tuple[float, float]:
"""
convert Maidenhead grid to latitude, longitude
Parameters
----------
maiden : str
Maidenhead grid locator of length 2 to 8
center : bool
If true, return the center of provided maidenhead grid square... | fddcbdab4f3e0f812dd7fac3509e66bc63f8fb84 | 702,908 |
def flipDP(directionPointer: int) -> int:
"""
Cycles the directionpointer 0 -> 1, 1 -> 2, 2 -> 3, 3 -> 0
:param directionPointer: unflipped directionPointer
:return: new DirectionPointer
"""
if directionPointer != 3:
return directionPointer + 1
return 0 | 928347a5c1934c822c77434ca9a91d913ef7f3b5 | 702,909 |
def get_datatype(data):
"""
rules defining the sidtype, based on the data dict of the sid.
The keys are always given.
The values can be empty.
:param data:
:return:
"""
subtype = "project"
if "entity" in data.keys():
subtype = "entity"
if data.get("type"):
subt... | a7677db6d6aa9a9ccdcbdd9f6fd9d87032fcd18f | 702,911 |
import os
import subprocess
def build(env_meta_path):
"""
Builds the package for `env_meta_path`.
Parameters
----------
env_meta_path : str
path pointing to a 'meta.yaml' file.
Returns
-------
success : the path to the build package
failure : None
"""
if not os.... | b4802347c3e22ff7b6ae0e8b77ebd31815ebcc7b | 702,912 |
def process_link(link):
"""
Get text and link from an anchor
"""
return link.text_content(), link.get('href') | 34429289076c8518b076fdf0f228eb6948109c6c | 702,913 |
from numpy import interp
def linear(x, y, xref):
"""
Linear interpolation.
:param x:
:param y:
:param xref:
:return:
"""
return interp(xref, x, y, left=None, right=None, period=None) | 16ffc3dd0d73b8bdb395a067bb1962e70d9a255b | 702,914 |
def merge_unique(list1, list2):
"""
Merge two list and keep unique values
"""
for item in list2:
if item not in list1:
list1.append(item)
return list1 | ecfd32178541dcb5956d4c1c74dc9cea2ab1fa45 | 702,916 |
def increment(number: int) -> int:
"""Increment a number.
Args:
number (int): The number to increment.
Returns:
int: The incremented number.
"""
return number + 1 | 27f4becd9afb747b22de991ab4cf030b14d3dac5 | 702,917 |
def CPP(record):
""" "Channel Process if Passive": a CP input link will be treated as
a channel access link and if the linking record is passive,
the linking passive record will be processed any time the linked record
is updated.
Example (Python source)
-----------------------
`my_record.IN... | 047f19b90e3eb89c8b6f298e1d4ecbf9b035040a | 702,918 |
import re
def normalize_name(name: str) -> str:
"""Replace hyphen (-) and slash (/) with underscore (_) to generate valid
C++ and Python symbols.
"""
name = name.replace('+', '_PLUS_')
return re.sub('[^a-zA-Z0-9_]', '_', name) | 46624c7180b1303e715d73aefe75cdd8e49b4a22 | 702,919 |
def sample(f1, f2, f3, f4):
"""
@see: field 1
@note : is it a field? has space before colon
@param f1: field 3 with an arg
@type f1: integer
@param f2 : is it a field? has space before colon
@return: some value
@param f3: another one
"""
return 1 | 20326992b0a03916b37360edc2a306df706075b3 | 702,920 |
def test_preprocessor_visit_one_children(patch, magic, preprocessor):
"""
Check that a single inline_expression is found
"""
tree = magic()
c1 = magic()
replace = magic()
c1.children = [magic()]
tree.children = [c1]
def is_inline(n):
return n == c1
preprocessor.visit(tre... | 4e450c7dbeff77069281fb63d495f0e4770f5fd3 | 702,922 |
def ris_defaultValue_get(fieldsTuple):
"""
params: fieldsTuple, ()
return: fieldVaule_dict, {}
"""
#
ris_element = fieldsTuple[0]
if len(fieldsTuple[1]) != 0:
default_value = fieldsTuple[1][0]
else:
default_value = []
fieldValue_dict = {}
fieldValue_dict[ris_eleme... | 0551462066eb984c796ef7ee08d640e9bc4373e5 | 702,923 |
import torch
def project_to_2d(X, camera_params):
"""
Project 3D points to 2D using the Human3.6M camera projection function.
This is a differentiable and batched reimplementation of the original MATLAB script.
Arguments:
X -- 3D points in *camera space* to transform (N, *, 3)
camera_para... | 0727efaeecfa48540590461f7d9222c8e6071f6d | 702,924 |
def n_coeffs_to_degree(n_coeffs):
"""what is degree if 2d polynomial has n_coeffs coefficients"""
delta_sqrt = int((8 * n_coeffs + 1.)**.5 + 0.5)
if delta_sqrt**2 != (8*n_coeffs+1.):
raise ValueError('Wrong input in n_coeffs_to_degree(): {:}'.format(n_coeffs))
return int((delta_sqrt - 3.) / 2. +... | 29a767668579d7a9d7c9c871cdb3168c7db3c6c1 | 702,926 |
import hashlib
def checksum_md5(filename, blocksize=8192):
"""Calculate md5sum.
Parameters
----------
filename : str or pathlib.Path
input filename.
blocksize : int
MD5 has 128-byte digest blocks (default: 8192 is 128x64).
Returns
-------
md5 : str
calculated ... | 759c0c5cbc37ebe0cc85eb8156127308eff354bc | 702,927 |
def normalize_volume_and_number(volume, number):
"""
Padroniza os valores de `volume` e `number`
Args:
volume (None or str): volume se aplicável
number (None or str): número se aplicável
Notas:
- se `number` é igual a `ahead`, equivale a `None`
- se `00`, equivale a ... | 1ec42912b942f6c1b7e22d2e64c4d842af100877 | 702,928 |
from typing import List
from typing import Tuple
def style_close(style: List[Tuple[str, str]]) -> str:
"""
HTML tags to close a style.
>>> style = [
... ("font", 'color="red" size="32"'),
... ("b", ""),
... ("i", ""),
... ("u", ""),
... ]
>>> style_close(style)
... | 2043803e50230f139a6a60599b40c53461ed6ed8 | 702,929 |
def get_theta_hat_bw_imd_cm1(theta_star_bw_std):
"""制御モードcmの中間条件におけるM1スタンダードモード沸き上げ温度(℃)(27b-1)
Args:
theta_star_bw_std(float): 標準条件の沸き上げ温度(
Returns:
float: 制御モードcmの中間条件におけるM1スタンダードモード沸き上げ温度(
"""
# 制御モードがファーストモードの場合
return theta_star_bw_std | caf43cc7c9e17417e3b0096fe89e4a02d41dc0e6 | 702,930 |
import re
def CreateKwargHandler(endpoints, f):
"""
Create methods which contains kwargs
and return the remaining endpoints to handle
"""
index = 0
# endpoints = ["/v2/users", "/v2/users/:id"]
remainEndpoints = []
while index < len(endpoints) - 1:
firstMatches = re.fi... | a805b8c2b1c1593e973fa0ac781fa780fa4a6d1a | 702,931 |
def pow_many(power, *args):
"""
Функция складывает любое количество цифр и возводит результат в степень power (примеры использования ниже)
:param power: степень
:param args: любое количество цифр
:return: результат вычисления # True -> (1 + 2)**1
"""
rs = 0
for v in args:
rs +=... | da0404f24045f5818ffb2219153fccd9b864965b | 702,933 |
import shutil
def gunzip_merge(outfile, list_files):
"""
Merge gunzip files into final file
:param outfile: String for output file
:param list_files: List of files to merge
:type outfile: string
:type list_files: list
"""
list_files = list(list_files)
list_files.sort()
print ("\tMerging files into: "... | ae37753cc1f16d9fc4cb4cf50587e99ef045a938 | 702,934 |
import subprocess
def _doSysExec(command: str, errorAsOut: bool = True) -> tuple[int, str]:
"""Execute a command and check for errors.
Args:
command (str): commands as a string
errorAsOut (bool, optional): redirect errors to stdout
Raises:
RuntimeWarning: throw a warning should there be a non exit code
R... | 4f6ae92628090c1f00be3268599dcef07c3818ac | 702,935 |
def get_media_pool_clip_list_and_clip_name_list(project):
"""
Parametes
---------
project : Project
a Project instance
Returns
-------
clip_return_list : list
clip list
clip_name_list : list
clip name list
Examples
--------
>>> resolve, project_manag... | f69a67d1ae29e714bf8c153519b515238a93875d | 702,936 |
def get_payment_request_with_payment_method(business_identifier: str = 'CP0001234', payment_method: str = 'CC'):
"""Return a payment request object."""
return {
'paymentInfo': {
'methodOfPayment': payment_method
},
'businessInfo': {
'businessIdentifier': business_... | c506f2750e0ffe5d1852116eab241e7e022d3b84 | 702,937 |
import os
def _coffea_fn_as_file_wrapper(tmpdir):
""" Writes a wrapper script to run dilled python functions and arguments.
The wrapper takes as arguments the name of three files: function, argument, and output.
The files function and argument have the dilled function and argument, respectively.
The f... | d8beac710f818bdc01cd794c586c0f101ea26b9b | 702,939 |
def process_categories(cat_path):
""" Returns the mapping between the identifier of a category in
Places365 and its corresponding name
Args:
cat_path: Path containing the information about the Places365
categories
"""
result = {}
with open(cat_path) as f:
lines = f.re... | f87741b990ee9ab9c8216112df73c7aa5bab8d49 | 702,940 |
import struct
def fread(f,byteLocation,structFormat=None,nBytes=1):
"""
Given an already-open (rb mode) file object, return a certain number of bytes at a specific location.
If a struct format is given, calculate the number of bytes required and return the object it represents.
"""
f.seek(byteLoca... | ae86bb1f3bc839053ca34c8bf2b4beb0af04aaee | 702,942 |
def _cast_types(args):
"""
This method performs casting to all types of inputs passed via cmd.
:param args: argparse.ArgumentParser object.
:return: argparse.ArgumentParser object.
"""
args.x_val = int(args.x_val) if args.x_val != 'None' else None
args.test_size = float(args.test_size)
# criterion (string)
# s... | 61438940cdc572b08ebd7ee0efe56cae65c1ddd7 | 702,943 |
def _get_year(obj):
"""
Get the year of the entry.
:param obj: year string object
:return: entry year or none if not valid value
"""
year = obj[0:4]
try:
year = int(year)
except ValueError:
year = None
return year | 6d3cbcc8759096ec3e798e90dc3a307b4a34b6ae | 702,945 |
import argparse
def _parse_arguments():
"""Return a parser context result."""
parser = argparse.ArgumentParser(description="CMake AST Dumper")
parser.add_argument("filename", nargs=1, metavar=("FILE"),
help="read FILE")
return parser.parse_args() | a811308be0fdb28294f8a0a0af80bf3a2cceae51 | 702,946 |
def epochPoints(abf):
"""Return a list of time points where each epoch starts and ends."""
if abf.abfVersion["major"] == 1:
return []
position = int(abf.sweepPointCount/64)
epochPoints = [position]
for epochNumber, epochType in enumerate(abf._epochPerDacSection.nEpochType):
pointCoun... | 1eafc6a6cd7a3e68a5136ef6b92a4e7defae0648 | 702,948 |
import math
def lat_meters(lat: float) -> float:
"""
Transform latitude degree to meters.
Parameters
----------
lat : float
This represent latitude value.
Returns
-------
float
Represents the corresponding latitude value in meters.
Examples
--------
Latit... | c31025552778b0039079d33e134e0b19077b83d4 | 702,949 |
def getFilteredLexicon(lexicondict, allwords):
""" Returns a lexicon with just the necessary words.
Assumes all wanted keys exist in the given lexicon """
return { word: lexicondict[word] for word in allwords } | db3c58b71df848ef5b1d49ebdd4670a552481c64 | 702,951 |
import unittest
def filter_suite(condition, suite):
"""Return tests for which ``condition`` is True in ``suite``.
:param condition: A callable receiving a test and returning True if the
test should be kept.
:param suite: A test suite that can be iterated. It contains either tests
or suit... | 9131d49d3f87a117d2b9625d521e932db2666860 | 702,952 |
import torch
def collate_fn(batch):
"""Creates mini-batch tensors from the list of tuples (images,
triplets_local_indexes, triplets_global_indexes).
triplets_local_indexes are the indexes referring to each triplet within images.
triplets_global_indexes are the global indexes of each image... | c7267579e6e7f4fa54cca951b5cad15e4ce5283a | 702,953 |
def bytes_to_long(in_bytes):
"""Converts a byte string into a long"""
hexstr = ''.join(["%0.2x" % ord(byte) for byte in in_bytes])
return int(hexstr, 16) | 89d82a72226457c3a1ac1438cab1071d3cbcd62d | 702,955 |
def func():
"""Return a new matrix of given shape and type, without initializing entries.
Parameters
----------
shape : int or tuple of int
Shape of the empty matrix.
dtype : data-type, optional
Desired output data-type.
order : {'C', 'F'}, optional
Whether to store multi... | c48914045c296b25fbfef0f1e409b7bc40b1a677 | 702,956 |
def cli(ctx, library_id, access_in="", modify_in="", add_in="", manage_in=""):
"""Set the permissions for a library. Note: it will override all security for this library even if you leave out a permission type.
Output:
General information about the library
"""
return ctx.gi.libraries.set_library_permi... | 833f828b5405b29d577a8859da8a895791da22bc | 702,958 |
def get_users():
"""Retrieve information about users"""
return "get users" | 40e2c1e8046beaa6d1b6f7875c2a3e3f7bad8e69 | 702,959 |
import grp
def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn):
"""Upgrade a SAM group.
:param samldb: SAM database.
:param gid: Group GID
:param sid_name_use: SID name use
:param nt_name: NT Group Name
:param comment: NT Group Comment
:param domaindn: Dom... | 05c005c01131684bad78fd45af0b82d4b1b2fedc | 702,960 |
def get_postgres_curie_prefix(curie):
"""The representation in postgres moves things to lowercase, and replaces . with _"""
if ':' not in curie:
raise ValueError(f'Curies ought to contain a colon: {curie}')
prefix = curie.lower().split(':')
prefix = '_'.join(prefix[0].split('.'))
return pref... | 314d59205fffd7e3dcdfb3a5ca7a81a12baffa76 | 702,961 |
import json
def parse_stations(html):
"""
Strips JS code, loads JSON
"""
html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '')
html = json.loads(html)
return html['suggestions'] | f9fb64d21c0b206b4c034e0f8a5c560eccb9b9e4 | 702,962 |
import json
def json_to_str(json_obj):
"""JSONをstr型へ変換"""
return json.dumps(json_obj, separators=(",", ":"), ensure_ascii=False) | 1ef38962b264991287f5b468489b20bd85be30ff | 702,963 |
def get_color(orig_label=None,
gt_label=None,
target_label=None,
adv_label=None,
targeted_attack=False):
"""Get color according to different possible correctness combinations."""
if ((gt_label is None or orig_label == gt_label) and
(adv_label is None or ... | 8a05dde4c60582bc2559f182423e795d2ecc1c1d | 702,964 |
import re
def read_cpr(path):
"""Read and parse a CPR file. Return masks, which are (id, RLE data).
Note: Python 3.6.4 docs say its XML module is not secure, se we use regexp.
"""
# Example: <Mask id="123">[12 34 56]</Mask>
mask_pattern = r'<Mask\s.*?id="(.*?)".*?>.*?\[(.*?)\].*?</Mask>'
text... | b5781607c150d0521d816c9027660e2b5e4b0fe0 | 702,965 |
import math
def schaffer6(phenome):
"""The bare-bones Schaffer function 6."""
sum_of_squares = phenome[0] ** 2 + phenome[1] ** 2
result = math.sin(math.sqrt(sum_of_squares)) ** 2 - 0.5
result /= (1.0 + 0.001 * sum_of_squares) ** 2
result += 0.5
return result | 80f19b28ebf4511a0670dfa622ffd3c55e8ec670 | 702,966 |
def take_before_exclusive(iterable, predicate):
"""Yield items up to but excluding including the first match.
If no matching item is present, the result is empty.
Args:
iterable: An iterable series of items.
predicate: A function of one argument used to select the last item.
Returns:... | 3f62a1575541dfcd071424fca4b290f3f50cc518 | 702,967 |
def build_filters(tbinfogolden):
"""
Build for each tb in tbinfo a filter
"""
filter_return = []
"""Each assembler string"""
for tb in tbinfogolden["assembler"]:
tb_filter = []
"""remove first split, as it is empty"""
split = tb.split("[ ")
"""For each line"""
... | fdbf2c0b64c9582a00acb38c8395d249dfeb6f56 | 702,968 |
from pathlib import Path
def data_root_directory():
"""Get a path to the top level data directory. Checks whether you have created the local store of data at the expected
location and returns that as default if found, otherwise returns the location on the shared folder
Returns:
(pathlib Path): A ... | f687ffcf05aa74c521624467c3be7ec108de6a46 | 702,969 |
import re
import socket
def get_host_name() -> str:
"""Get the host name.
:return: A string value.
"""
return re.sub(r"\.(?:local|lan)", "", socket.gethostname()) | 225889a0bf40943ef962903551bde85fd2729ac8 | 702,970 |
def fix_hyphen_commands(raw_cli_arguments):
"""Update options to match their module names with underscores."""
for i in ['gen-sample', 'run-python', 'run-stacker']:
raw_cli_arguments[i.replace('-', '_')] = raw_cli_arguments[i]
raw_cli_arguments.pop(i)
return raw_cli_arguments | cbc420547f1d3a04787d059aa09eb0199df82dba | 702,971 |
def get_data_types(nb_sensors):
"""
What should be the data type for each sensor (1 - integer, 2 - float)
Input
nb_sensors -> how many sensors (int)
Output
data_type_per_sensor -> list of data types for each sensor
"""
print("Choose data type for each sensor: 1-integer / 2-floa... | f3133d415f1d6c8448fec57a1f14fb88d697107d | 702,972 |
def read_line_offset(file, offset):
""" Seek to offset in file, read a line and return the line and new offset """
fp = open(file, "r")
fp.seek(offset, 0)
line = fp.readline()
offset = fp.tell()
fp.close()
return (line, offset) | 429d592cf44e1f287eea5a67302a78473eb2362f | 702,973 |
def calculate_bmi(weight, height):
"""
Calculates BMI given the weight and height as float
"""
bmi = (weight / (height * height)) * 703.0
return bmi | 8495b11598e50516dca80965d5063df92aa78f40 | 702,974 |
import re
def get_task_factor(task_name, overrides, override_type, factor):
"""Check for task override and return factor."""
for task_override in overrides.get(override_type, []):
if re.compile(task_override["task"]).match(task_name):
return task_override["factor"]
return factor | eb58f291c5a21a9974b9f7d4bce739bdc99d5f89 | 702,975 |
def argstr(arg): # pragma: no cover
"""
Return string representation of a function argument.
:param object arg: Argument object. Differs between Python versions.
:return: String name of argument.
"""
if isinstance(arg, str):
return arg
if 'id' in arg._fields:
return arg.id
... | 565349fc4a1fb9b28e8333a44893925cea9e72d9 | 702,976 |
def getDistance(sensor):
"""Return the distance of an obstacle for a sensor."""
# Special case, when the sensor doesn't detect anything, we use an
# infinite distance.
if sensor.getValue() == 0:
return float("inf")
return 5.0 * (1.0 - sensor.getValue() / 1024.0) | 68ff9e0c8c4dd7687e328d3b9c4634677cfe25cd | 702,978 |
def test_path_and_query_parameters(
arg1,
arg2,
):
"""
Use same arg name as the one in path for receiving path args
For those args which names not matched path arg names, will be parsed as query parameter
```python
from django_mini_fastapi import Path
@api.get('/test_path_and_query_par... | 72823f5fa66065171c36329f6b05e61a710fa065 | 702,979 |
import re
def GENERIC_MAX(segment_pattern, lenv=None, renv=None):
"""Takes the regex pattern for segments being examined for
deletion, and a pair of lists indicating their deletion environment,,
and returns a function that will count how many times a segment
of that class is deleted from an input to a... | d729cb96850397a36b687d2b43c487b3670f7c56 | 702,980 |
import logging
import time
def check_subs(client):
""" Checks that all Subscriptions have been received"""
wcount = 0
while wcount < 10:
for t in client.topic_ack:
wcount += 1
if t[2] == 0:
logging.info("subscription to " + str(t[0]) + " not acknowledged")
... | 95892066b9da2a530a28f06a7e5804fdee7e65d0 | 702,982 |
def Get_Items(filename):
"""Convert plain text to class string"""
L = []
with open(filename, 'r') as file:
items = file.readlines()
for line in items:
L.append(line[:-1])
return L | 8b579dcfb8df21de68a05a8dad4d7aff06951f64 | 702,983 |
import math
def circles_intersection(x_a, y_a, r_a, x_b, y_b, r_b):
"""
Returns the point of intersection of two circkes
:param x_a: x coordinate of the center of first circle
:param y_a: y coordinate of the center of first circle
:param r_a: radius of first circle
:param x_b: x coordinate of ... | dc504bbe970c83bf1caf7727613ecaa44c1c818e | 702,985 |
def get_grade_map():
"""
Defines a mapping of Fontainebleau grades to integer values
"""
grade_map = {
'6B': 0, # V4
'6B+': 0, # V4
'6C': 1, # V5
'6C+': 1, # V5
'7A': 2, # V6
'7A+': 3, # V7
'7B': 4, # V8
'7B+': 4, # V8
'7C': 5, ... | 1137d7c21b18556ce69db635314c968024b3394b | 702,986 |
import os
def which(cmd):
"""
Returns full path to a executable.
Args:
cmd (str): Executable command to search for.
Returns:
(str) Full path to command. None if it is not found.
Example::
full_path_to_python = which("python")
"""
def is_exe(fp):
return ... | db7d9f79d0a7d7f9673d181fb4fb1f0d00aa6fab | 702,987 |
def get_class_mapping(super_mode: str):
"""
Mapping mode into integer
:param super_mode: before, after & both
:return:
"""
class_mapping = ['none', 'replace']
if super_mode == 'both':
class_mapping.extend(['before', 'after'])
else:
class_mapping.append(super_mode)
ret... | 33e1f40c600f68b6ea760ec9340d04555ecae463 | 702,989 |
import socket
def get_banner():
"""Get the ``banner`` that will be signed in :meth:`adb_shell.adb_device.AdbDevice.connect` / :meth:`adb_shell.adb_device_async.AdbDeviceAsync.connect`.
Returns
-------
bytearray
The hostname, or "unknown" if it could not be determined
"""
try:
... | 9babf7db8d4177b427f46c0785b899c79ba2691c | 702,990 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.