content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def getRuleCount( lstRules, policy_name ):
"""
This function return the rule count for a given policy
indicated by policy_name
Parameters:
- IN : 1. List containing all the rules
2. Name of the policy
- Out: # of rules in the policy.
"""
count = 0
for x in lstRules:
if x.split(',')[0] == poli... | b4956b0a5af91f1834ee4d463414df2cc02c8796 | 701,858 |
def send_format(catfact):
"""
Format's the catfact into a the message to send content string
"""
return """
Thank you for subscribing to CatFacts™
Did you know:
```
{}```
Type "UNSUBSCRIBE" to unsubscribe from future catfacts.
""".format(catfact) | 208605f35db4505bb0037cae23088c89e6b1475f | 701,859 |
def effect_from_model(model, ref, ref_rc, alt, alt_rc, methods, mutation_positions, out_annotation_all_outputs,
extra_args=None, **argv):
"""Convenience function to execute multiple effect predictions in one call
# Arguments
model: Keras model
ref: Input sequence with the ... | 27c528da568d257d129ae219f504ecf4f23b93f2 | 701,860 |
def get_pronoun(pronoun, gender='MALE', sep='_'):
""" Gets the correct gender pronoun
Arguments:
pronoun {str} -- HE_SHE pronoun that needs to be converted
Keyword Arguments:
gender {str} -- [description] (default: {'MALE'})
sep {str} -- [description] (default: {'_'})
... | a9f3d7aa3f09af305ac110e1cc8c9ac977051d8b | 701,861 |
def is_fill_compute_el(obj):
"""Object contains executable methods 'fill' and 'compute'."""
return hasattr(obj, 'fill') and hasattr(obj, 'compute') \
and callable(obj.fill) and callable(obj.compute) | 18f1825947852f6dd307e0a2ab07c8d95f213151 | 701,862 |
def addstr(str1, str2):
"""Concatenate strings str1 & str2"""
return str(str1) + str(str2) | 209c932bca262a458013afcafd6899e6cf02b3b6 | 701,863 |
import difflib
def get_name_similarities(name_pairs):
"""Get char LCS similarity for each signature pair."""
return [difflib.SequenceMatcher(None, sig1, sig2).ratio() for sig1, sig2 in name_pairs] | a124e36387d4a72968985967fde0c48dc4d3b21d | 701,864 |
import subprocess
def run_cmd(cmd_args, cwd=None, shell=False):
"""Runs a command and returns output as a string."""
process = subprocess.Popen(
cmd_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
cwd=cwd)
output = process.communicat... | 792d966bffac12aada63e5c36795cd7043ead4ec | 701,865 |
import sys
def extract_ut_args():
"""Extract unittest specific arguments from sys.argv"""
# -h -v -q -f -c -b
# --locals
# anything not starting with a -
newargs = []
for i in range(1, len(sys.argv)): # must ignore progname in argv[0]
arg = sys.argv[i]
if arg in ["-h", "-v", "... | a899dee319466e9e91c727f00be6f7a130127c8f | 701,866 |
def parse_predictions_dict(predictions, num_growths):
"""Parses predictions dictionary to remove graph generated suffixes.
Args:
predictions: dict, predictions dictionary directly from SavedModel
inference call.
num_growths: int, number of model growths contained in export.
Ret... | fbb1789cf317e7c4d0015271bf8690ea4bddf0ef | 701,867 |
import os
def create_idx_to_path(lfw_dir):
"""
Create a dictionary where the key is the image index and the value is the
path to the image.
"""
labels = sorted(os.listdir(lfw_dir))
idx = 0
idx_to_path = {}
for label in labels:
for img in sorted(os.listdir(os.path.join(lfw_dir, ... | 7e9e475a04c04637902103f7ba4e7cc181d8ab88 | 701,868 |
import subprocess
def create_movie(name, folder):
"""
Creates the movie with all the images present in the given directory
:param name:
:param folder:
:return: result of subprocess
"""
cmd = ["ffmpeg", "-framerate", "1", "-i", folder + "/pic%04d.png", "-c:v",
"libx264", "-r", "3... | 392f5b88d1da63ad241402e313ab8f601ebe997c | 701,869 |
def get_word_pattern(word: str) -> str:
""" Get word pattern.
This pattern is useful to break substitution cipher.
:param word: Word to get pattern for.
:return: Word pattern.
"""
# There is no ordered set type in Python, but we can get that behaviour using
# dict keys because since python... | ce81624bd3690c2037c5b570e19ba2340907a24a | 701,871 |
def _run_op_1(task):
"""Test function using the function decorator."""
return task.run() | b2d3b220dcd1371f9140859b4ffe025f8231b4da | 701,872 |
def create_df(dass_words, dfcp_words):
"""
this function creates a dictionary, that keeps track of each occurance of a word in a 'dass' context and 'dfcp' context
it returns this dictionary
"""
dass = {}
dfcp = {}
data = [dass, dfcp]
for listed_values in dass_words: # access single lis... | 43e5715808247d726a353e7841a5dbc2aa117740 | 701,873 |
def q_in_valid_range(q):
"""
Asserts that q is either 1, 2 or 3.
For other values, the formulas have not been implemented.
"""
assert 1 <= q <= 3, "Please enter q in {1,2,3}"
return True | 6ef79efde7376f0743bc840fe394707a8f9b213f | 701,874 |
import hashlib
def sha512_first_half(message: bytes) -> bytes:
"""
Returns the first 32 bytes of SHA-512 hash of message.
Args:
message: Bytes input to hash.
Returns:
The first 32 bytes of SHA-512 hash of message.
"""
return hashlib.sha512(message).digest()[:32] | 591a0096e643af32326ae051f9a993db82a758c5 | 701,875 |
def median(arr: list):
"""
Returns the median and its index in the array.
"""
indices = []
list_size = len(arr)
median = 0
if list_size % 2 == 0:
indices.append(int(list_size / 2) - 1) # -1 because index starts from 0
indices.append(int(list_size / 2))
median = (arr... | 639a6d4efbc91457520ef1411ef7b935fb477b82 | 701,876 |
import os
def get_abs_path(in_path):
"""
Given a relative or absolute path, return the absolute path.
:param in_path:
:return:
"""
if os.path.isabs(in_path):
return in_path
else:
return os.path.abspath(in_path) | 6d732d563bef61dbde058110addc5fa91fea4a5d | 701,877 |
def is_(a: object, b: object) -> bool:
"""
Return `a is b`, for _a_ and _b_.
Example:
>>> is_(object())(object())
False
Args:
a: left element of is expression
b: right element of is expression
Return:
`True` if `a is b`, `False` otherwise
"""
return... | 6edda9af046f6a45f37578c073ed0e21e3320778 | 701,878 |
import logging
import os
import sys
def get_logger(name, path, fname):
"""create a logger and return
"""
logger = logging.getLogger(name)
file_log_handler = logging.FileHandler(os.path.join(path, fname))
stderr_log_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(file_log_handler... | 4f2b99074944b73e4d4f43620f2f0d933a845dbf | 701,879 |
def _set_default_contact_rating(contact_rating_id: int, type_id: int) -> int:
"""Set the default contact rating for mechanical relays.
:param contact_form_id: the current contact rating ID.
:param type_id: the type ID of the relay with missing defaults.
:return: _contact_rating_id
:rtype: int
"... | e39f5f9701d4314cd19109ce08c599b3737cd064 | 701,880 |
import json
def _read_color_map(path, object_hook=None):
"""
Read a color map as json.
:param path (str): The path to read the map from.
:param object_hook (func): A Function to manipulate the json.
:return: A dictionary of color map.
"""
with open(path) as f:
return json.load(f, o... | 34c627443cd418d84b19bd54b3e79427d8168b1e | 701,881 |
def convertd2b(amount, x_pow, y_pow):
"""Apply the equation to get the result. Decimal to binary."""
res = amount * (10 ** x_pow / 2 ** y_pow)
return res | 8a6c7ca98a351b9a6f6c499954f7d8a533559122 | 701,882 |
def task_3_list_customers_in_germany(cur) -> list:
"""
List the customers in Germany
Args:
cur: psycopg cursor
Returns: 11 records
"""
cur.execute("""SELECT * FROM Customers WHERE country='Germany'""")
return cur.fetchall() | bf6465cc590cfe7d45817eff02e0dbaacb02e195 | 701,883 |
def find_page(pages, limit, value):
"""
Function to calculate and return the current page of a paginated result.
:param pages:
:param limit:
:param value:
:return:
"""
page_range = [limit * page for page in range(1, pages + 1)]
for index, my_range in enumerate(page_range):
if... | d1b97fb0c6c54c85b748922fb6df3d96121ea3c7 | 701,884 |
def dict_to_str(d):
"""Represent dictionary as string.
Represents a dictionary as a string. This is useful when
a representation for a filename is desired. The function
will unroll all keys and join their parameters with '_',
yielding a single string for the dictionary.
Parameters
--------... | 4279cbc08dde9ef4e513cd562c66f63f09c866fa | 701,885 |
def compare(guess, answer):
"""
Compare guess and answer
Arguments:
guess -- a 4-digital number string of the guess.
answer -- a 4-digital number string of right answer.
Returns:
cow -- a number of the user guessed correctly in the correct place.
bull -- a number of the user gu... | f615f4ebd555c0c4119d0fcbf9ae581146fe7816 | 701,886 |
def _get_parent_node_by_pred(node, pred, search_current=False):
"""Find the first parent node that satisfies a predicate function."""
if not search_current:
node = node.parent
while node is not None:
if pred(node):
return node
node = node.parent
return None | a69be92c468758ea1faf366c2881588e8f6fd688 | 701,888 |
import json
import click
def maybe_print_as_json(opts, data, page_info=None):
"""Maybe print data as JSON."""
if opts.output not in ("json", "pretty_json"):
return False
root = {"data": data}
if page_info is not None and page_info.is_valid:
meta = root["meta"] = {}
meta["pagi... | 5c84deb086001e0406dc8df9df4510ddc301e0e8 | 701,889 |
def float_like(x, /) -> bool:
"""
Tests if an object could be converted to a float.
Args:
x (Any): object to test
Returns:
bool: Whether the object can be converted to a float.
"""
try:
float(x)
return True
except ValueError:
return False | ed34d52e34bc7c09242fde6cd0890381df297325 | 701,890 |
def get_structure_numbers(structure, momenta_dict):
"""Return the number of the parent and children of a given structure
according to some momenta dictionary.
"""
legs = structure.get_all_legs()
children = frozenset((leg.n for leg in legs))
if structure.name() == "S":
return None, child... | db9548b1e26402bb38e9c33741ca38aa866fd217 | 701,891 |
def check_bin(number, index):
"""
用于某些二进制标志位的场景
返回一个 int 类型变量的某一二进制位的值,index 从 1 开始,即
>>> check_bin(2, 1)
0
>>> check_bin(2, 2)
1
"""
try:
return int(bin(number)[2:][-index])
except IndexError:
return 0 | d5c54f3121f56c028fb20e6bfcd51395cd58aa05 | 701,892 |
def parse_exclusion_file(exclusion_file, exclusion_column):
"""
Reads in the specified column of the specified file into a set.
"""
exclusion_list = set()
with open(exclusion_file) as infile:
for line in infile:
to_exclude = line.split('\t')[exclusion_column]
exclus... | 3ae8430a96ed1883691cd63b86cd26d24c6f7652 | 701,893 |
def min_sum_space_improved(arr):
"""
A method that calculates the minimum difference of the sums of 2 arrays consisting of all the elements from the input array.
Wrong problem description (as it talks about sets): https://practice.geeksforgeeks.org/problems/minimum-sum-partition/0
Correct problem descri... | b8eb4f22e44d2d5104b2f4436908aa85ee07ac2d | 701,894 |
from typing import Dict
def encode_token_tx(token_tx: Dict) -> bytes:
"""
Creates bytes representation of token transaction data.
args:
token_tx: Dictionary containing the token transaction data.
returns:
Bytes to be saved as token value in DB.
"""
token_tx_str = ''
token... | 4100d4dacdeea4a588906151a02f9adef874aaec | 701,895 |
def distance(strand_a, strand_b):
"""
Compare two strings and count the differences.
:param strand_a string - String representing a strand of DNA.
:param strand_b string - String representing a different strand of DNA.
:return int - number of differences between 2 strands.
"""
if len(stran... | 012e0b1640e738b17dc6a4fb4a01c1f53e0e7639 | 701,896 |
import sys
def unzscore(im_norm, zscore_median, zscore_iqr):
"""
Revert z-score normalization applied during preprocessing. Necessary
before computing SSIM
:param im_norm: Normalized image for un-zscore
:param zscore_median: Image median
:param zscore_iqr: Image interquartile range
:retur... | aa74e5a2b8e757d569003b4a4f21675e97875a01 | 701,897 |
def values_to_rgb(ranges, values):
""" Converts a three dimensional tuple to a RGB map
@param ranges The mininum and maximum of each dimension
@param values The value to transform
"""
r_color = (float(values[0]) - float(ranges[0][0])) / float(ranges[0][1])
g_color = (float(values[1]) - float(ran... | 2dabe98b78e873e1aaff91577461e0991402ec64 | 701,898 |
def lam(m, f, w):
"""Compute lambda"""
s = 0
for i in range(len(f)):
s += f[i] * w[i]
return float(m)/float(s) | 6a71eb0020a5c2d86d88504f9867150c0fa7e248 | 701,899 |
import numpy
def in_domain(X, a_array, c_array):
"""
Check is a given point is inside or outside the design domain
"""
flag = 1
for n in range(numpy.shape(a_array)[0]):
a = a_array[n]
c = c_array[n]
dist = numpy.dot(X-c,a)
if(dist > 0.7):
flag = 0
if(abs(dist)<0.7):
flag = 2
return flag | e39e779b456ea8df4f217d1c2ed5eaddf498881a | 701,900 |
def clamp(x, inf=0, sup=1):
"""Clamps x in the range [inf, sup]."""
return inf if x < inf else sup if x > sup else x | 42c178afc0bdfc02fd31fe3f211f23cc04b40d2e | 701,901 |
def _get_item_kind(item):
"""Return (kind, isunittest) for the given item."""
try:
itemtype = item.kind
except AttributeError:
itemtype = item.__class__.__name__
if itemtype == 'DoctestItem':
return 'doctest', False
elif itemtype == 'Function':
return 'function', Fal... | c597db3de4447c68f3d8187e2f988e6c81e19d00 | 701,902 |
def mapattr(value, arg):
"""
Maps an attribute from a list into a new list.
e.g. value = [{'a': 1}, {'a': 2}, {'a': 3}]
arg = 'a'
result = [1, 2, 3]
"""
if len(value) > 0:
res = [getattr(o, arg) for o in value]
return res
else:
return [] | 34e45bcf804d37feb5995b88534cca78679d8cfb | 701,904 |
def _rxcheck(model_type, interval, iss_id, number_of_wind_samples):
"""Gives an estimate of the fraction of packets received.
Ref: Vantage Serial Protocol doc, V2.1.0, released 25-Jan-05; p42"""
# The formula for the expected # of packets varies with model number.
if model_type == 1:
_expec... | 610fa2c2aa83e6d0c9cf9c93961ba8aa6b496188 | 701,905 |
def string_in_list(str, substr_list):
"""Returns True if the string appears in the list."""
return any([str.find(x) >= 0 for x in substr_list]) | b6e8ce2f918fec0b9a671f1c557f6f1d005c734e | 701,906 |
import copy
def build_kfold_config(params_dict, train_path, dev_path):
"""按k-fold拆分好的数据,构造新的json配置,用来启动训练任务
:param params_dict: 原始json配置构造出来的param_dict
:param train_path: k-fold拆分之后的训练集路径,list类型
:param dev_path: k-fold拆分之后的评估集路径,list类型
:return: task_param_list: 生成新的json配置,用来启动run_with_json
"""... | e13a7468a2fa3fd33219abfdf3347579a82de518 | 701,908 |
import numpy
def makeMostCommonPatternHeuristic(weights):
"""Return a function that chooses the most common (currently most-used) pattern."""
def weightedPatternHeuristic(wave, total_wave):
print(total_wave.shape)
# [print(e) for e in wave]
wave_sums = numpy.sum(total_wave, (1, 2))
... | 514bd14e6f04896165d2068a3ddaa77e778e19c5 | 701,909 |
def getTagNames(domain):
"""
Returns a list of tag names used by the domain.
:param domain: a domain object
:type domain: `escript.Domain`
:return: a list of tag names used by the domain
:rtype: ``list`` of ``str``
"""
return [n.strip() for n in domain.showTagNames().split(",") ] | f24ccdec61eca07cef283ed4e9d981236b530c62 | 701,910 |
def matching(fingerAi, finger_i):
"""
Matching entre dos huellas
"""
it = 0
ta = 0
tb = 0
for i in range(len(fingerAi)):
if fingerAi["f0"].iloc[i]==finger_i["f0"] and \
fingerAi["f1"].iloc[i]==finger_i["f1"] and \
fingerAi["utime"].iloc[i]==finger_i["... | 2ca3c16c5a9ac126314a39598719c8f7f64fa97a | 701,911 |
import socket
def is_gce_instance():
"""Check if it's GCE instance via DNS lookup to metadata server"""
try:
socket.getaddrinfo('metadata.google.internal', 80)
except socket.gaierror:
return False
return True | 74605bca73a9a46b629212c87f154aa9a4920a1d | 701,912 |
def get_count_value(context, fieldname):
""" {% get_count_value fieldname %}
"""
return {"value":fieldname} | 9356b602b2685341f402193c830842e656acc6cb | 701,913 |
def rle_kyc(seq: str) -> str:
""" Run-length encoding """
counts = []
count = 0
prev = ''
for char in seq:
# We are at the start
if prev == '':
prev = char
count = 1
# This letter is the same as before
elif char == prev:
count += 1... | c617ca2bfe62baed5e141c65ec923297f27ac488 | 701,914 |
def is_legal_parameter(name):
"""
Function that returns true if the given name can be used as a
parameter in the c programming language.
"""
if name == "":
return False
if " " in name:
return False
if "." in name:
return False
if not name[0].isalpha():
... | de4426f5fc14740439c8f278d19e8ec9944e1a2f | 701,915 |
def unity():
"""Return a unity function"""
return lambda x:x | 5e7aa6bfe20f0534244ed0932b3bf87bf7505230 | 701,916 |
def num_added_features(include_am, include_lm):
""" Determine the number of added word-level features (specifically AM and LM) """
added_feature_count = 0
if include_am:
added_feature_count += 1
if include_lm:
added_feature_count += 1
return added_feature_count | 83f344ad693f846f7a6dda0bcef429565d96870b | 701,918 |
def _get_mudata_autodetect_options_and_encoding_modes(
identifier: str, autodetect: dict, encodings: dict[str, dict[str, list[str]]]
) -> tuple[bool, dict | None]:
"""
Extract the index column (if any) and the columns, for obs only (if any) from the given user input.
This function is only called when d... | 1b763bba23957e71897bc40acaf020088f75feb3 | 701,919 |
def retrieve_cnv_data(store, solution, chromosome=''):
""" Retrieve copy number data for a specific solution
"""
cnv = store['solutions/solution_{0}/cn'.format(solution)]
if chromosome != '':
cnv = cnv[cnv['chromosome'] == chromosome].copy()
cnv['segment_idx'] = cnv.index
return cnv | 2c77415909ff27a3b3fd00e7abb8d25b67b6ea8f | 701,920 |
def banner(text: str, *, borderChar: str = '='):
"""Print 'text' as banner, optionally customise 'borderChar'."""
border = borderChar * len(text)
return '\n'.join([border, text, border]) | 76d27b762173e35a15e0e445eccea85cdef3b327 | 701,922 |
def parse_turn(turn):
"""Parse the input from the user for valid player strings and play positions
Args:
turn (string): Input string from the user that contains the played
position (0-8)
Returns:
(int/None): Returns interger on success or None on failure
"""
t... | 90abe0050ed6413931f8b50e622e4083c2fa4d87 | 701,923 |
def phonenumber(anon, obj, field, val):
"""
Generates a random US-style phone number
"""
return anon.faker.phone_number(field=field) | 8d19ba96b805fd117e2ceb9a926bb1f8a9966e0b | 701,924 |
def noop(obs):
"""
Transform that does absolutely nothing!
"""
return obs | 95ad1168d804c1021f328090068c7d6a260b7ca4 | 701,925 |
import numpy as np
def RectangularGrid(dX, iMax, dY=None, jMax=None):
"""Return a rectangular uniform rectangular mesh.
X and/or Y grid point locations are computed in a cartesian coordinate
system using the grid step size and grid points.
Call Signature:
RectangularGrid(dX, iMax, dY=No... | 15445a2e700d3e0989a47e198732582a51c30d5f | 701,926 |
def add(a,b):
"""
This function returns the sum of the given numbers
"""
return a + b | 9998c4a350973839aeb8f64fe0ba555297f35ccc | 701,927 |
import random
def _is_prime(number, attempts=10):
"""
Miller-Rabin primality test.
A return value of False means n is certainly not prime. A return value of
True means n is very likely a prime.
"""
if number != int(number):
return False
number = int(number)
if atte... | 05fa3b4a8c9266b491449cc908392c535f5b2196 | 701,928 |
import os
def touch(filename, mtime):
""" doc me """
with open(filename, 'a+'):
pass
os.utime(filename, (mtime, mtime))
return 0 | aaa272ba33ff25b2e83cfa7aa308cc115bd8fb6a | 701,929 |
def flags_to_release(is_minor=False, is_major=False):
"""Convert flags to release type."""
if is_minor and is_major:
raise ValueError("Both `is_minor` and `is_major` are set to 'True'.")
if is_minor:
return "minor"
if is_major:
return "major"
return "normal" | e4f80774b72da544f20fe6ead5816dbed2a3755c | 701,930 |
from typing import Union
import yaml
def read_yaml(path: str) -> Union[dict, list]:
"""Loads yaml at given path
Args:
path (str): path to yaml file
Returns:
Union[dict, list]: dictionary or list loaded from yaml depending on the yaml
"""
with open(path, encoding="UTF-8") as yaml_... | 66138b8968865d8951ae366ab3adb0c342bbfabe | 701,931 |
def is_legal(x, y, img):
"""
Check if (x, y) is a valid coordinate in img
Args:
x (int): x-coordinate
y (int): y-coordinate
img (numpy.array): Image
Returns:
bool -> True if valid, False otherwise
"""
if 0 <= x < img.shape[1] and 0 <= y < img.shape[0]:
... | bc86f6b032932e4fb33b3d1983fc2a8586176e5f | 701,932 |
def prepare_playlists(user,labelled_data):
"""
prepares the user's playlists for upload and display
Args:
user (SpotifyUser)
labelled_data (DataFrame or array-like)
Returns:
Dictionary: uploadable playlists in JSON format
"""
return user.generate_uploadable_playlists(la... | 85a7843997cb759b866e30d6d70f8fdecfc95dc5 | 701,933 |
def add(i):
"""得到114个add函数对应的的字符串"""
return ".add(user_id_list[" + str(i) + "][0], \n" \
"\tpeople[" + str(i) + "], \n" \
"\txaxis3d_opts=opts.Axis3DOpts(type_='value', min_='dataMin', max_='dataMax'), \n" \
"\tyaxis3d_opts=opts.Axis3DOpts(type_='value', min_='dataMin', max_=... | 5ba345b2e6ed224f06fffab47aef44c01328fe80 | 701,934 |
import configparser
import os
import sys
def read_config(config_file):
"""Read configuration file infomation
:config_file: Configuration file
:type config_file: string
"""
cfg = configparser.ConfigParser()
try:
cur_dir = os.path.dirname(os.path.abspath(__file__))
if os.sep... | 3c8fffbad9eb95e59b4cceda01824f726440b1c4 | 701,935 |
def rates_for_yr(rates_all_years, sim_year):
"""
Filter specific rates for a given year
Parameters
----------
rates_all_years : pandas DataFrame
rates, to be filtered by year
sim_year : int
year being simulated
Returns
-------
pop_w_rates : pandas DataFrame
... | 616cec13b0a686c2c7504c187c31dafaa7f88b6f | 701,936 |
def parse_output(output_file):
"""Parse output file for void fraction data.
Args:
output_file (str): path to simulation output file.
Returns:
results (dict): total unit cell, gravimetric, and volumetric surface
areas.
"""
results = {}
with open(output_file) as orig... | 4659c2014861f8467d9c2e1b1dc69c0bbef34cda | 701,937 |
import os
import sys
def generate_passphrase(passphrase_length, word_list):
"""Generate the passphrase string.
For each word, read 2 bytes from the kernel-space CSPRNG via ``os.urandom``
and convert them to an integer which serves as a list index. A list of
65,536 words is probably enough so we don'... | dc6aa86392f1c49f47c6f169ec98ef5e555f9451 | 701,938 |
import os
def processed_file_path(source_path, asset_roots, target_directory,
target_extension):
"""Take the path to an asset and convert it to target path.
Args:
source_path: Path to the source file.
asset_roots: List of potential root directories each input file.
target_dire... | 749bda062d90dae1763d802f2a557d50682e8a4d | 701,940 |
def zoom(scale, center, group):
"""zoom(scale, center, group) -> float
Change the zoom and pan of a group's display. The scale argument is the new zoom factor.
If the scale is given, but not the center, the zoom is set to that factor and the view is
positioned so the cursor is pointing at the same place it was bef... | fe6c5cafed738d5e53a043fa86e66b22cab0a6af | 701,941 |
import numpy
def get_topic_terms(model, topicid, topn, id2token):
"""
Return a list of `(word_id, probability)` 2-tuples for the most
probable words in topic `topicid`.
Only return 2-tuples for the topn most probable words (ignore the rest).
"""
topic = model.state.get_lambda()[topicid]
to... | b0ca1fd35fb7e8ce89a497c37bfd82b9dd884027 | 701,944 |
import json
def load_label(label_path):
"""
Loads a label from a JSON file
"""
with open(label_path, 'r') as label_file:
label = json.load(label_file)
return label | f6a2873abee024d64ede78f18a96f0a1b95abd0b | 701,945 |
def resize(anns, size, output_size):
"""
Parameters
----------
anns : List[Dict]
Sequences of annotation of objects, containing `bbox` of [l, t, w, h].
size : Sequence[int]
Size of the original image.
output_size : Union[Number, Sequence[int]]
Desired output size. If size... | 800135ac9d65f55ae96d04fc645ac0d2b913b76c | 701,947 |
def has_overlap(x0, xd, y0, yd):
"""Return True if the ranges overlap.
Parameters
----------
x0, y0 : float
The min values of the ranges
xd, yd : float
The widths of the ranges
"""
return x0 + xd >= y0 and y0 + yd >= x0 | 6b2a6eff892e28376ed08bf8f60c67f49cdeff44 | 701,948 |
def gen_col_list(num_signals):
"""
Given the number of signals returns
a list of columns for the data.
E.g. 3 signals returns the list: ['Time','Signal1','Signal2','Signal3']
"""
col_list = ['Time']
for i in range(1, num_signals + 1):
col = 'Signal' + str(i)
col_list.append(c... | 35fe1457c9e256f90f7695e066dcc3202f212d98 | 701,949 |
import numpy
def cropobjects_merge_bbox(cropobjects):
"""Computes the bounding box of a CropObject that would
result from merging the given list of CropObjects."""
# Find extremes. This will define the output cropobject.
t, l, b, r = numpy.inf, numpy.inf, -1, -1
for c in cropobjects:
t = m... | 559e96dda48cb5e733c59a3168032037e0eb06e4 | 701,950 |
def generate_nested_list(root,nodes):
"""
Generates a nested list representation of the tree
with specified node as root. Useful for checking
equality of trees or subtrees.
To do: make the nested list form a property that is computed when needed.
"""
nl = []
if root.children is None: r... | fa75493c8ccc4b720ee404baa9eb3996ce78f3eb | 701,951 |
def abstract(func):
"""
An abstract decorator. Raises a NotImplementedError if called.
:param func: The function.
:return: The wrapper function.
"""
# noinspection PyUnusedLocal
# pylint: disable=unused-argument
def wrapper(*args, **kwargs):
raise NotImplementedError('{} has... | 3497ae41c4987499cddc610e518a8a9251cadb31 | 701,953 |
def non_related_filter(questions_df, non_related_ids):
"""
Splits a questions dataframe between related and non-related discussions,
based on an Ids list of non-related discussions.
:param questions_df:
> A pandas dataframe of stackoverflow questions containing posts Ids;
:param non_... | b7e64287b2bdb6a8999bcd8e7efd8e2787b991dd | 701,954 |
import math
def sin(x):
"""Return sin of x (x is in radians)"""
return math.sin(x) | c5b091892e54df064b61a109812b3ea1206b1713 | 701,955 |
def format_pin(pnum, relatedpnum):
"""Formats a Parcel ID Number (PIN) from a BS&A PNUM."""
try:
if relatedpnum is None or relatedpnum.startswith('70-15-17-6'):
p = pnum
else:
p = relatedpnum
p = p.split('-')
del p[0]
p = ''.join(p)
except Inde... | 8338fd5b329cf37d3fa59cd1b7d1f71e6694d706 | 701,956 |
from datetime import datetime
def condense_log_events(log_stream, log_events):
"""Condense log events into single strings. expects list of dicts."""
condensed_events = []
for event in log_events:
event_datetime = datetime.fromtimestamp(event['timestamp'] / 1000)
message = "{} | {} | {}".fo... | 94bfdc73d9fad7151162ca3e1bf114cc11950067 | 701,957 |
import os
def trickle(session_config):
"""Return a dict with "trickled down" / inherited config values.
This will only work if config has been expanded to full form with
:meth:`config.expand`.
tmuxp allows certain commands to be default at the session, window
level. shell_command_before trickles... | a429f4102f40ced0ee47ad3ed39d1f678e35c3ab | 701,958 |
import datetime as dt
def current_year():
""" Returns the current year. """
now = dt.datetime.now()
return now.year | 34fe2695dfb224d0db39af7dffc084058b93518a | 701,959 |
def get_router_port(endpoint):
""" get the network device and port of where the endpoint is connected to.
Args:
endpoint (endpoint): endpoint
A routerport is a dict with the following keys:
router (string): name of the netork device
port (string): port on the router.... | 30c331169a0c5e1a6b0bf91b8ad43c1db64dc532 | 701,960 |
import networkx
def createGraph(input_edge_list):
"""
From list of edges create and return a graph.
:param input_edge_list: list of edges
:returns G: the graph
"""
# first thing, how are the nodes separated in an edge
with open(input_edge_list, 'r') as f:
l = f.readline()
... | 5a92864aa78cc99218c45031c80a6b89a836f134 | 701,961 |
def dummy_callable(obj):
"""A callable that you probably shouldn't be using :)"""
return [] | 2a0c71bd1a558d3df1c40c5a384fa98bf3cc15ad | 701,962 |
import math
def cie76(c1, c2):
"""
Color comparision using CIE76 algorithm.
Returns a float value where 0 is a perfect match and 100 is
opposing colors. Note that the range can be larger than 100.
http://zschuessler.github.io/DeltaE/learn/
LAB Delta E - version CIE76
https://en.wikipedia.... | 9470b66231252decd8be7f07af2591ddf1278edc | 701,963 |
from pathlib import Path
def parse_lst(lst_path):
"""Extract audio names of nnenglish."""
audio_names = []
with open(lst_path) as fd:
for line in fd:
audio_path, lang = tuple(line.strip().split())
if lang != "nnenglish":
continue
audio_name = Pa... | 82ed0e7a0c13269416e4530157f2a67a68712676 | 701,964 |
import random
def add_angle(r):
"""
Add angle for each r value to make up a coordinate of a polar coordinate.
"""
coords = []
for ri in r:
theta = random.random() * 360
coords.append((ri, theta))
if len(coords) == 1:
return coords[0]
else:
return coords | 0e91e9c7999627885218dde42bc2849e89071eff | 701,965 |
from typing import OrderedDict
def load_status_info(sfile, fudge=None):
""" Parse the output of pb_run_status.py, either from a file or more likely
from a BASH <() construct - we don't care.
It's quasi-YAML format but I'll not use the YAML parser. Also I want to
preserve the order.
"""... | 13e6b546d93847b0321da2cb659150345b6a8b20 | 701,966 |
def get_tags_from_message(message):
"""
Given a message string, extracts hashtags and returns a comma-separated list
:param message: a Hipchat message body
"""
tags = {word.strip('#') for word in message.split() if word.startswith('#')}
return ','.join(tags) | 528f7702f43f8f81adf942c79b292f508773d205 | 701,967 |
def tf_read_img(tf, filename):
"""Loads a image file as float32 HxWx3 array; tested to work on png and jpg images."""
string = tf.read_file(filename)
image = tf.image.decode_image(string, channels=3)
image = tf.cast(image, tf.float32)
image /= 255
return image | 662fc1c9840e67fb0ff3fae4b12da5179e286e25 | 701,968 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.