content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import numpy
def _numpy_array(data, dtype=None, copy=True):
"""
Single function to create an array.
@param data data
@param dtype dtype
@param copy copy
@return numpy array
"""
if isinstance(data, numpy.ndarray):
res = data
... | f8baa06314454046171963c9f4f7da8bf965d536 | 640,158 |
import re
def as_size(size):
"""
Return a size string as an integer
"""
if isinstance(size, (int, float,)):
return int(size)
# exact size in a string
m = re.match(r'^\d+$', size)
if m:
return int(size)
# gigabytes
m = re.match(r'^([\d\.]+)gb?$', size, flags=re.I)
... | 267fc4b70e331200eb824d80187a59c86bd447a9 | 640,159 |
def thermal_time_constant_as_considered_load(TauR, dTOr, dTOi, dTOu, n):
""" Returns the average oil time constant in minutes (for a given load)
As per IEEE C57.91-2011
TauR = Thermal time constant at rated load
dTOr = Top oil rise at rated load
dTOi = Top oil rise initial
dTOu = Top oil rise ul... | 9412a33a04bee3b28b785e2c9965ffef81c92aaa | 640,161 |
def clean_yelp(df_business, df_photos):
"""
-function that contains logic filter and join yelp datasets
-df_business: input dataframe that contains Yelp business data
-df_photos: input dataframe that contains Yelp photo data
-returns cleaned and joined dataframe
"""
df_business['restaurant'... | 7e0d3c67536a35f98e26ce6ef9d3815166e66841 | 640,163 |
def attr_equals_val(object, attr, val):
"""return 1 of the object has attribute attr and it equals val"""
rv = 0
try:
oval = getattr(object, attr)
if oval == val: rv = 1
except: pass
return rv | 8ffcedf0ffe625eb94dcf6e3da084a9c7dfde58e | 640,164 |
def max_min_lists(list1, list2, rates):
"""
gives the longest and the shortest lists from 2 lists
:param list1: list no. 1
:param list2: list no. 2
:return: longest and shortest lists
"""
if list1[0] == rates[0]:
return (list2[1], list1[1])
else:
return (list1[1], list2[1... | 10203af07402d4de895aa8ec3f73731a4bdd8099 | 640,165 |
import re
def is_valid_ipv6(ip):
"""Validates IPv6 addresses.
"""
pattern = re.compile(r"""
^
\s* # Leading whitespace
(?!.*::.*::) # Only a single whildcard allowed
(?:(?!:)|:(?=:)) # Colon iff it would be part of a wildcar... | 0e979266b681a3149835e13aa82c6ae144762843 | 640,166 |
def from_settings(settings):
"""Return a dict created from application settings.
Args:
settings (dict): An application's settings.
Returns:
dict: The database-specific settings, formatted to use with
:func:`connection_url`.
"""
return {
k.replace('DATABASE_', '... | 56e03e01a0222f9aa560a9ebf585e51473c2406f | 640,167 |
import time
def timeit(method):
"""
A Python decorator for printing out the execution time for a function.
Adapted from:
www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods
"""
def timed(*args, **kw):
time_start = time.time()
result = m... | 0a2ab147343fdb5bd54818b7c474bbb6d59d7f90 | 640,168 |
def offset_to_next_multiple(num, mult):
"""Calculates the amount needed to round num upward to the next multiple of mult.
If num is divisible by mult, then this returns 0, not mult.
"""
if mult == 0:
return 0
else:
offset = mult - (num % mult)
if offset == mult:
... | 189260be93961d52bd834c4b5b930875417f5d43 | 640,170 |
def secondary_spherical(rho, phi):
"""Zernike secondary spherical."""
return 20 * rho**6 + - 30 * rho**4 + 12 * rho**2 - 1 | 825178bd82ba3119409aa529c4950f2875ab92be | 640,171 |
def isolate_zeros(array_2d, array_3d):
"""
Finds Zeros in each array within each column and row of the 3D array, if 1 zero is found in each while the value
in the 2D array is equal to 0 that value is added to the 2d array based on the index + 1
:param array_2d: 2D Array 9x9
:param array_3d: ... | bc6131a1541d82284f67c4373fca1d1afdce8575 | 640,172 |
import math
def U(x, y):
"""Mishra's function to be optimised"""
return math.sin(y) * math.e ** ((1 - math.cos(x))**2) + math.cos(x) * math.e **((1 - math.sin(y))**2) + (x - y) ** 2 | 4ecf83cb7cdfca3ee96ef4d0e6ae5e947609e982 | 640,173 |
def merger(l):
"""
This function takes a list of strings as a parameter and return list of grouped, consecutive strings
:param l: List of strings
:return:
"""
if not l:
print("Error in merge with empty list")
elif len(l) == 1:
return l
else:
# Divide the list from... | 07aaa71edcb488574f5ed4c7370fdf0459e62420 | 640,174 |
def create_reversed_flag_getter(name, shift):
"""
Creates a reversed flag getter function.
Parameters
----------
name : `str`
The flag's name.
shift : `int`
Bit shift value.
Returns
-------
reversed_flag_getter : `FunctionType`
"""
locals_ = {}
f... | 2ee2e0126ebc09f0425cc72f9548684b7b1a00f5 | 640,175 |
def pointer_bottom(x, model_hparams, vocab_size):
"""Like identity_bottom() without converting to float."""
del model_hparams, vocab_size # unused arg
return x | b8c4ca3c03fffe820acc0431a1b464e244a2fb6e | 640,176 |
def Extraction_path(entity1, entity2, path=[], path1={}):
"""
输出:两点之间的所有路径
"""
# entity1=self.Graph[0].index(entity1)
# entity2=self.Graph[0].index(entity2)
# print('path',path) 取消注释查看当前path的元素
path = path + [entity1]
# print('path',path) 取消注释查看当前path的元素
if entity1 == entity2:
... | 78318802123a8bd93f0d43196c218d9b5ffa4e6b | 640,178 |
def get_punctuation_count(doc):
"""Returns list of punctuation values of sentences."""
return [s._.punct for s in doc.sents] | 7d457b535aefacdb69e8da660e73cf35c448e467 | 640,179 |
def compute_centroid(tf, points):
# points {[2, ?]} tensor of float_64
"""Computes the centroid of the points."""
return tf.reduce_mean(points, 0) | d63b1848d9d5fc69ee97062ed06b4f5de60862a9 | 640,180 |
def get_hesitancy_dict(geo_df):
""" Return dictionary of hesitancy proportions.
Input:
geo_df: (dataframe) location geomatic dataframe typically output
from get_county_mapping_data().
Output:
Dictionary with keys not_hesitant, hesitant_or_unsure, and
strongly_hesita... | c2f50e481b674a2d8ac878b748699626a812cbf3 | 640,182 |
def raw_mnist_features(x):
"""
@param x (n_samples,m,n) array with values in (0,1)
@return (m*n,n_samples) reshaped array where each entry is preserved
"""
return x.reshape(x.shape[0],(x.shape[1]*x.shape[2])).T | 79b09d78bbad0167467a6414e4ddb33665cb69c0 | 640,183 |
def getCountDF(df, character, preds, job_labels, word2vec_model, mentions, full, decreasing):
"""
Generate vector similarities and return DataFrame for count score
"""
if job_labels.get(character):
for label in job_labels.get(character):
for rank, pred in preds:
# Add... | 6c56d15a524484688bb46c3e685accc3b1663f9c | 640,184 |
from datetime import datetime
def convert_dayofweek(unixtime):
"""
Convert Unixtime to local day of week
Takes unix time as input, returns an int, 0-6, corresponding to days of the week
relative to today. Today = 0, tomorrow = 1, etc.
"""
dayofweek = datetime.fromtimestamp(int(unixtime)).strft... | 921a2db01554f8d573686a551ad0d954c7e342b0 | 640,185 |
import os
def _get_readme_contents() -> str:
"""Get the contents of the project readme if available, else return a static string. This allows the package to work correctly with `tox` packaging
When this is called as part of the actual packaging process, the cwd should be the base project directory.
Retu... | 0820043e0157bfc0f084438dead041e568b18f41 | 640,186 |
def classic_order(num, modulus):
"""Find the order classically via simple iteration."""
order = 1
while True:
newval = (num ** order) % modulus
if newval == 1:
return order
order += 1 | d64334be2c50829aeb3f1a63a653922a1d106082 | 640,187 |
from bs4 import BeautifulSoup
def get_img(html):
"""
获取图片标签
:param html: HTML内容
:return: 页面所有img标签对象
"""
soup = BeautifulSoup(html, 'html.parser')
return soup.find_all('img') | 251ac39cea1c472692646d369af4cb8aab295d19 | 640,188 |
def fixed_embeddings_name(channel_id):
"""Returns the name of the fixed embedding matrix for some channel ID."""
return 'fixed_embedding_matrix_%d' % channel_id | 6d344e8c3b4f8e0e0ff69c38900f308154b1cdcf | 640,189 |
import json
def convert_format_in_metrics_list(metrics):
"""Converts from human-friendly metadata format to BigQuery friendly format.
Before:
'metadata': {'file': 'example.py'}
After:
'metadata': [{'key': 'file', 'value': '"example.py"'}]
Args:
metrics: A list of metrics dicts.
Returns:
... | 738c55a14ea6021e6b4bb6386e37ff5374092256 | 640,190 |
def postorder_traversal(node):
"""
recursive implementation of postorder traversal in which root is processed after left and right child
:param node: Node of a binary tree
"""
if node is None:
return None
postorder_traversal(node.left)
postorder_traversal(node.right)
print(node.... | d7e31fe74caec41966b27f0c780054254e3ec5a6 | 640,191 |
import textwrap
def wrap_text(text: str, max_length=40):
"""Rivittää pitkän tekstin kapeampaan muotoon"""
result = ""
for paragraph in text.splitlines():
res = textwrap.wrap(
paragraph,
initial_indent="\t",
subsequent_indent="\t\t ",
break_long_words... | 6dbe0ccdb22edb32469e635f1687c32b9539fd39 | 640,192 |
import subprocess
def try_run(command, ignore=False):
"""
Try to execute ``command`` and return its output as string.
Return ``None`` if command not found. Return ``None`` if execution
fails and ``ignore=False`` (default). Otherwise, return output of
``command`` as string. Here, output always mea... | 379076a789e59e4e45b120d9857fe44a9bf1ab38 | 640,193 |
def uniform_but_one_dataset_no_weight(n, p):
"""Generates an unweighted dataset according to the AMS lower bound.
Args:
n: The size of the dataset
p: The frequency moment (used as a parameter in the lower bound)
Returns:
A list of keys, where all keys appear once, except for one key which
accoun... | ffb8c4dfd4a2db713d4ebeeb6cca3a3836f5a010 | 640,194 |
def func(arg):
"""
:param arg: taking args
:return: returning square
"""
x = arg*arg
return x | 555be574e26d4c0f7746571cbaf3c105e036d88f | 640,195 |
import os
def _check_valid_path(file_path):
""" Validity check of input file path """
if not file_path:
return file_path
elif isinstance(file_path, list):
for file in file_path:
if not isinstance(file, str):
raise TypeError("The type of file path should be 'str'... | 3e49f125b386f4f20f87bee3390f4a644038f432 | 640,196 |
def entry_to_string(length,index,filename):
"""Converts an entry to a string"""
length_s = "0"*10 + str(length)
length_s = length_s[-10:]
index_s = "0"*11 + str(index)
index_s = index_s[-11:]
filename = " "*40 + filename
filename = filename[-40:]
return length_s+";"+index_s+";"+filename+"\n" | 5c6c560d1775f524ad9d032c77ca44c6ee7f8fa8 | 640,198 |
from typing import Callable
from typing import List
from typing import Tuple
from typing import Any
import inspect
def get_func_arguments_types_defaults(func: Callable) -> List[Tuple[str, Tuple, Any]]:
"""
Parse function arguments, types and default values
Args:
func: a function to be xeamined
... | 85226fe2b86c73a605eec0338190bc8cfe53e010 | 640,199 |
def get_lines(self):
"""The list returned contains all the Line of the SurRing
Parameters
----------
self : SurfRing
A SurfRing object
Returns
-------
line_list : list
list of lines delimiting the surface
"""
line_list = self.out_surf.get_lines()
line_list.ext... | 9a9966fa86ed8f4a5aebc996fa4252ad67d12ffb | 640,200 |
def step_backward(position, panel_l, panel_r, connection_map):
"""
This function sounds as the character moves from the reflex board to the plug.
Its similar to the previous one, but vice versa
:param position: Position of the char in the list.
:param panel_r: The list that represents the right sid... | 305d15498a9577b006d68c04cfe9fc74f2b40bca | 640,201 |
def _formatDostring(*args, **kwargs):
""" Decorator to put before a function to be able to format it on import.
>>> from formated_docstring import _formatDostring
>>> @_formatDostring(__file__=__file__)
>>> def run_tests(args):
>>> '''run tests on methods in {__file__}
>>>
>>> usage... | c8c2cbfec29219952831ad075f432c8c8a908736 | 640,202 |
import binascii
def hex(b) -> str:
"""
Returns the hexily version of the binary datas.
:param b: binary datas
:return: the string
"""
return binascii.hexlify(b).decode('utf8') | 77141aefdde7af177cc36eb3317679a3f5743df0 | 640,204 |
def find_players(packages, opponentLocation, playerLocation):
"""Check if opponent is in packages"""
i1,i2 = (-1,-1)
j1,j2 = (-1,-1)
acc = 0
for i in range(len(packages)):
for k in range(len(packages[i])):
if opponentLocation == packages[i][k]:
i1, i2 = i,... | e9d68baae945d13d8c02cc90827d23b730f45dfc | 640,205 |
import requests
import json
def lookup(symbol):
"""Look up quote for symbol."""
# reject symbol if it starts with caret
if symbol.startswith("^"):
return None
# reject symbol if it contains comma
if "," in symbol:
return None
url = "https://api.worldtradingdata.com/api/v1/st... | fe5f77687333022c82e16bf0cb367102d29df487 | 640,207 |
def get_last_change(path):
"""
Figure out when the given path has last changed, recursively if a directory
"""
last_changed = path.stat().st_mtime
if path.is_dir():
for entry in path.glob("**/*"):
entry_changed = entry.stat().st_mtime
if entry_changed > last_changed:... | 1b1c2d58fa982ae83c2d84115e22f1b30773e377 | 640,209 |
import re
def valid_verb(verb, ling_features):
"""check if the verb is V3 or Ving"""
return re.search(r'ing', verb) is not None or (
verb in ling_features.keys() and ling_features[verb].tag_ in ['VBN', 'VBD']) | 61e634a15e23fa873809effe47f81afd342ac923 | 640,210 |
def slice2enlist(s):
"""Convert a slice object into a list of (new, old) tuples."""
if isinstance(s, (list, tuple)):
return enumerate(s)
if s.step == None:
step = 1
else:
step = s.step
if s.start == None:
start = 0
else:
start = s.start
return enumerat... | 9414afdb247e2f7eadc35a77edbcc78ec7353d1e | 640,211 |
from typing import OrderedDict
import six
def _extract_simplified_filter_fields(filter_fields):
"""
Takes the filter_fields and simplifies them to a form django-filter can understand
"""
# If we are just dealing with a list we are fine
if not isinstance(filter_fields, dict):
return filter_... | f36d8a9804d45071f19aa5e5e3d0a87d1883d5f5 | 640,212 |
import html
def convert_unicode_to_html(text):
"""Convert unicode text to HTML by escaping it."""
return html.escape(text).encode("ascii", "xmlcharrefreplace").decode() | fbc448a9d63d69bdaa5223b98e5d0c2cc1f455dd | 640,214 |
import time
def timeMilis(plusSecs=0, plusMins=0, plusHours=0):
"""
Return current time in milis if no arguments.
If arguments are present it will be current time plus argument time.
Arguments:
plusSecs {int}: Add this amount of seconds to current time
plusMins {int}: Add this amount ... | 8a1800be78acb9e6fad78469d253ed137bde02a9 | 640,215 |
def _app_complete_on_provider(application, provider):
"""
Determines if an Application is completely available on a Provider, i.e. all active ApplicationVersions have a
ProviderMachine + InstanceSource on given Provider.
Args:
application: Application object
provider: Provider object
... | 9fb3d4671a9cfd0b6207306b48314a0b303a6b52 | 640,216 |
def ins_all_positions(x, l):
"""Return a list of lists obtained from l by inserting x at every possible index."""
res = []
for i in range(0, len(l) + 1):
res.append(l[:i] + [x] + l[i:])
return res | 82621c1c027126bc839ba28ab1bc338abf077e5b | 640,217 |
def findPath(g, start, end, path=[]):
""" Uses DFS to find a path between a start and an end node in g.
If no path is found, returns None. If a path is found, returns the
list of nodes """
path = path + [start]
if start == end:
return path
if not start in g:
return None
for n... | 2a9b85b342b861e61cbd0bc14880a4cfe47d1faf | 640,218 |
def euler(dydx, x0, y0, x, h):
"""
Euler Method for solving diferential equations
Parameters:
dydx: Diferential equation
x0: Initial x
y0: Initial y
x: Value of X
h: Height
Returns:
y: Aproximation of y
"""
y = y0
while x0 < x:
y = y + ... | 796e316b367b6ca1a23a17673125e6554189496f | 640,219 |
import time
def distance_of_time_in_words(from_time, to_time=0, include_seconds=False):
"""
Reports the approximate distance in time between two datetime objects or integers.
For example, if the distance is 47 minutes, it'll return
"about 1 hour". See the source for the complete wording list.
... | 950553ad425ada69b3ea23a1633d6903ddc69768 | 640,220 |
def _buylrd(x):
""" Eq. 2 of sron_colourschemes.pdf """
r = (0.237 - 2.13 * x + 26.92 * x**2 - 65.5 * x**3
+ 63.5 * x**4 - 22.36 * x**5)
g = ( (0.572 + 1.524 * x - 1.811 * x**2)
/ (1.0 - 0.291 * x + 0.1574 * x**2) )**2
b = 1.0 / (1.579 - 4.03 * x + 12.92 * x**2 - 31.4 * x**3
... | 0c7adbf9f3d3ab599dda5fff380290e2c5bbec17 | 640,221 |
def _set_grid(ts_search, ts_dct):
""" Set the TS grid
"""
if ts_search in ('molrad_vtst', 'radrad_vtst', 'vrctst'):
if 'rad' in ts_dct['class']:
grid = ts_dct['grid']
else:
grid = ts_dct['var_grid']
else:
grid = ts_dct['grid']
return grid | 5c6df828d3287b4b32893392c89727a8ee2fa66e | 640,223 |
def ok(ret_code: int) -> bool:
"""Convert a posix exit code to a boolean."""
return ret_code == 0 | 93c9e724804112e6d48f5e2392482e9afb997c25 | 640,224 |
import sys
import os
def getConfigPath():
"""Returns the path for configuration data for all major platforms
Returns(str): config path
Args:
Returns:
"""
if sys.platform == 'linux':
configpath = os.path.normpath(os.path.expanduser('~/.config/phobos'))
elif sys.platform == '... | 3c459f1dec1fa6631d182def021511c6ec80547d | 640,225 |
import pathlib
def _glob(filenames, pattern: str, invert: bool = False):
"""Applies a glob pattern to a string list of file names.
Args:
filenames: The list of file names.
pattern: The glob pattern to apply.
invert: If True, returns file names which evaluate to False.
Returns:
... | 2cf5e00d1e757461e167c0c8325c621abf6e2997 | 640,226 |
def unrequitted_friendships_v1(G):
"""Answer to unrequitted friendships problem."""
unrequitted_friendships = []
for n1, n2 in G.edges():
if not G.has_edge(n2, n1):
unrequitted_friendships.append((n1, n2))
return unrequitted_friendships | a2b2545dce99953d221175129fa57ac2be57e53e | 640,227 |
def drop_empty(arr):
"""
Drop empty array element
:param arr:
:return:
"""
return [x for x in arr if not isinstance(x, list) or len(x) > 0] | 38c5c01774541a1c615d49c18accda8e9108832f | 640,228 |
def flatten_list(lofl):
"""
Flatten a list of lists.
"""
new_list = []
for item in lofl:
if type(item) == list:
rl = flatten_list(item)
new_list.extend(rl)
else:
new_list.append(item)
return new_list | b7307b23de20ff84b6ee250ffaf099049d063930 | 640,230 |
def hello_world():
"""Hello world example."""
return """\
<!DOCTYPE html><head><title>Flask test</title></head>\
<body style="font-family:monospace;">Hello, simply run\
<pre style="color:blue;">curl -X POST localhost:6969/upload\
-F file=@"assets/archive_name.tar.gz" ... | 43cb1462bf6274beef6e03eea0306b63bfb23197 | 640,231 |
def sq_km(value):
"""value is a float representing a surface using square kilometers as unit
this tag simply format mille with space and leave only two digits in decimals"""
if not isinstance(value, str):
value = str(value)
try:
integer, decimal = value.split(".")
except ValueError:
... | 8acf4e60d8307213b8ff69f8c8192f71ce31496e | 640,232 |
def calc_intensity(locations):
""" Calculate intensity per location"""
max_duration = float(max(locations.values()))
result = {}
for key, value in locations.items():
result[key] = value/max_duration
return result | ea6a8fe0f8c6a882ebaf6452b09635b7ec702a9e | 640,233 |
import math
def split_dataset(inputs, targets, train_perc=0.7, val_perc=0.1, test_perc=0.2):
"""
Splits dataset into training, validation and test set
Output:
train-, validation- and test inputs : (percentage * n)x2 dimension FloatTensor
train-, validation- and test targets : (percentage * n... | ae64a7660f39eff77ce18a39ef398a5e3397b0ea | 640,234 |
import torch
def bmmt(mat1, mat2):
"""batch matrix matrix transpose product"""
return torch.einsum("bij, bkj -> bik", mat1, mat2) | 00fec63c95f9d6789e1141cec86067c8c5a01cfe | 640,235 |
def assign_weights(context):
"""
Assign weights to securities that we want to order.
"""
long_weight = 0.5 / len(context.longs)
short_weight = -0.5 / len(context.shorts)
return long_weight, short_weight | 93a5d72985e4aed919d35346f67004b148c45517 | 640,237 |
def fake_role(**kwargs):
"""Fixture to return a dictionary representing a role with default values set."""
kwargs.setdefault("id", 9)
kwargs.setdefault("name", "fake role")
kwargs.setdefault("colour", 7)
kwargs.setdefault("permissions", 0)
kwargs.setdefault("position", 55)
return kwargs | 5c2e700ca0f0158ee0b827808a9a82ea7b6be494 | 640,238 |
def declare_variables(variables, macro):
"""
This is the hook for the functions
- variables: the dictionary that contains the variables
- macro: a decorator function, to declare a macro.
"""
variables['baz'] = "John Doe"
# Note - will need to switch the /master in the docs repo
# to match the... | e925094f760c557ac68ff2aad5d9ea526b96d28c | 640,239 |
def sorted_shopping_list(shopping_list, mapping, departments_order):
"""
Getting shopping list, department-to-products mapping and
departments order inside shop, returns products from shopping list,
ordered by department location, effectively giving you
optimal way to go through the market.
... | cfaf86523ebb7baab2af33756d7c44907091c9c1 | 640,241 |
def degFormatter(deg):
"""Formats degrees as X˚
Args:
deg: float
Returns:
string
"""
return "${:d}^\circ$".format(int(deg)) | 3efd98c59334f1b4ff59fb18fc19a6aaa3d2618d | 640,242 |
def get_grams(sentence, n):
"""
Returns phrases i.e. windowed sub
strings with range (1-N) window
Keyword arguments:
sentence -- utterance (str)
n -- max_ngram (int)
"""
all_grams = []
for l in range(1, n + 1):
grams = [" ".join(sentence[i:i + l]) for i in range(len(sentence... | e23d88476231cf7912adadbee2f4159be81f262b | 640,243 |
def item_huisnummer_adapter(obj, request):
"""
Adapter for rendering an object of
:class:`crabpy.gateway.crab.Huisnummer` to json.
"""
return {
'id': obj.id,
'huisnummer': obj.huisnummer,
'postadres': obj.postadres,
'status': {
'id': obj.status.id,
... | f6a3f14b0dbeeb32af4280c460121e9653eb78eb | 640,244 |
def save_epoch(epoch, filename):
"""Save an epoch to a given filename
:param epoch:
The epoch that should be saved.
:type epoch: Epoch
:param filename:
The filename where to save the epoch
:type filename: str
"""
return epoch.save(filename) | 5db36429d6a6999441f3719c38c89b474f53c0ff | 640,245 |
def get_next_picture(picture, pictures_per_tag, remaining_id):
"""
:param picture:
:param pictures_per_tag:
:return:
"""
potential_next_picture_tags = picture.tags & set(pictures_per_tag)
if len(potential_next_picture_tags) == 0:
print('stooooop!')
return None
eligible... | 31a3d07c3f3332a95d2192397af661a5069f9d97 | 640,246 |
from typing import Dict
import subprocess
from typing import Sequence
import sys
def _get_finished_processes(
processes: Dict[str, subprocess.Popen],
print_output: bool
) -> Sequence[str]:
"""Returns the keys of any finished processes."""
finised_processes = []
for chunk, process in processes.item... | 358565dbb077038a8315c94cb9f525f915d6a7dc | 640,247 |
def dateToInt(date, strfmt='%Y%m%d'):
""" Converts a datetime date into int
Parameters:
-----------
date : datetime
date in datetime format
strfmt : string
format in which the int date will be generated
Example:
dateToInt(dt.date(2015,10,23),'%Y')
"""
... | 4cbdb6b94fa7b86ef59cb5636bbe17ced56f3cbe | 640,248 |
import os
def get_filename(which, options, sample_idx=None):
"""This function returns a filename generated from the current configuration"""
### init any tags
prune_tag = ''
if options.do_prune:
prune_tag = '_pruned'
validate_tag = ''
if options.validate_sg:
validate_tag = '.v... | 97502103124e7e9a134b8c04741ced385e2b1cd9 | 640,249 |
def shout(text):
"""Return text in uppercase."""
return text.upper() | aaf06325592a836d57edbfd7c3774594edf87813 | 640,250 |
import os
def phylofile(famdir, famid, ext):
"""
Creates a filename using my gene family format
famdir/famid/famid.ext
"""
return os.path.join(famdir, famid, famid + ext) | c3ce2ed1951fc8798f1752c4d3150500216c2dfa | 640,251 |
def changeword(word):
""" SH -> S2
"""
newword = word.replace('SH','S2')
return newword | ca98d337a7713ef4b577e560969f0967fa450b1f | 640,252 |
def maximum(attrs, args):
"""Check if the external ACL codegen for maximum should be used."""
type_a = args[0].checked_type
type_b = args[0].checked_type
return (type_a.dtype == "float32") and (type_b.dtype == "float32") | 0c69ccc22d8a4fc0bd8d3ef663d0e6955e6def4f | 640,253 |
def _window_has_intervening_extrema(window, contour, mode):
"""
Steps 8/9. If there exists a sequence of equal maxima or minima, check if the sequence
contains an intervening opposite extrema, i.e. if a sequence of two equal maxima contains
a minima between them.
>>> maxima_group = [
... (2, [2, {1}]),
... (4... | f2ce05aa779679415d1542c4a190fae6a49ff65b | 640,254 |
def get_refdes_parts(anno_record):
""" Given an annotation record with a reference designator, return the corresponding subsite, node and sensor.
"""
subsite = None
node = None
sensor = None
refdes = anno_record.get('referenceDesignator')
if '-' not in refdes:
subsite = refdes
el... | 54a3996fab9811c7110eeb9e817afa49c359b419 | 640,255 |
import os
from subprocess import check_output, CalledProcessError, STDOUT
def _create_version():
"""
Helper function for building the version string
"""
version = "Unknown"
root = os.path.dirname(os.path.abspath(__file__))
try:
with open(os.path.join(root, "VERSION.txt"), 'r') as f:
... | ecb403735720ff6692e1072feaf718e1721b25cd | 640,256 |
def check_association_rules(row, rules, headerPositionList):
"""
This function check if the row satisfies any of the association consistency rules providede by the user.
Args:
row(list): the row to check
rules(list): list of correct bindings for the parameters
heaerPositionList: hea... | 11c2f9fc7ef40b4784d117a26ff649253fce2c99 | 640,257 |
def build_cli_options(dic):
"""
return a sorted list of command line options specified in the options
dictionary `dic`
"""
# - flags
flags = ['--%s' % opt for opt in dic
if dic[opt] == True]
flags.sort()
# - key-values
keyvals = ['--%s=%s' % (opt, dic[opt]) for opt in di... | 3a7a2b5e45d2867545e8d0dd6d1396983cf8fcd1 | 640,258 |
from typing import Optional
def _serialize_comment(prefix: str, comment: Optional[str]) -> str: # pylint: disable=unsubscriptable-object
"""Serialize a comment, with an optional prefix."""
return "%s%s" % (prefix, comment) if comment else "" | 99acb1b16f0f8628a516687cf88af8587c6d317c | 640,259 |
import os
import sys
def get_path_to_wmcore_root():
"""
Work out the path to the WMCore root from where the script is being run. Allows for
calling setup.py env from sub directories and directories outside the WMCore tree.
"""
return os.path.dirname(os.path.abspath(os.path.join(os.getcwd(), sys.ar... | e68d65d8ee0825e753ba1ba2c528f42cea5c4381 | 640,260 |
import yaml
import argparse
def config_file(string):
"""
Create a config file
:param string: name of yaml file used for config.
:returns: Dictionary of configuration information.
"""
config_dict = {}
try:
with open(string) as f:
g = yaml.safe_load_all(f)
fo... | 90b7447be388bf2574e9718adbc29f3a7c62dec2 | 640,261 |
import torch
def add_dp_v2(input_tensor, clip_value=5.0, variance=1.0, device=torch.device('cuda')):
"""
gpu compatible version
:param input_tensor: variable
:param clip_value: clipping value of 2-norm
:param variance: variance of gaussian noise
:param device:
:return: variable with dp app... | d7ef3ae28488c98bddfd02e88d5b30c488c15f6f | 640,262 |
def safe_filename(name):
"""Utility function to make a source short-name safe as a
filename."""
name = name.replace("/", "-")
return name | fb2ccf5b3cd4511c36ac7fac9b8cdfb7bff1291d | 640,263 |
def get_intensity_matrix(pixels, option):
"""Set the measure of brightness to be used depending upon the
option chosen, we chose between three measures namely luminance,
lightness and average pixel values
"""
intensity_matrix = []
for row in pixels:
intensity_matrix_row = []
for ... | c6719e7fa2b65f812622bb25c51861f5ee198e6b | 640,265 |
def format_sheet(sheet):
"""
Rename columns
"""
return sheet.rename(columns={
sheet.columns[0]: "mat",
sheet.columns[-3]: 's_price',
sheet.columns[-2]: 'r',
sheet.columns[-1]: 'date'
}) | 954c2f3519903d1009f1a6424afbd5a57919009b | 640,266 |
def rectangle_dot_count(vertices):
""" Count rectangle dot count include edge """
assert len(vertices) == 2
width = abs(vertices[0][0] - vertices[1][0])
height = abs(vertices[0][1] - vertices[1][1])
dot_count = (width + 1) * (height + 1)
return dot_count | 2e330a5137482e7bf1eb2396936c61a0497bbe62 | 640,267 |
import os
def parse_attachment_entries(entries):
# list -> list
"""Parse the attachments entries.
Args:
entries: entries of attachments.
Returns:
List of entry context dict containing the attachments metadata.
"""
entry_context = []
for entry in entries:
if entry.... | 4d32d6e536e5c001752a786a2bf7eef5970fcd54 | 640,268 |
def GiB(val):
"""Calculate Gibibit in bits, used to set workspace for TensorRT engine builder."""
return val * 1 << 30 | b21be2501b4e2011b38cb44d2159e97f7b0aa851 | 640,269 |
import numpy
from typing import Sequence
from typing import cast
def segmenter(data_stream: numpy.ndarray) -> Sequence[int]:
"""
Split up a signal that should be "steady"
Return a list of all indices which should represent
boundaries and be tossed out
Args:
data_stream: numpy array of 1d ... | e2ad6ea17607acd82989f6399eac096749d4d276 | 640,270 |
def gete2wlandw2el_fromdf(df, missingval='*'):
"""Get dict inputs for the EM algorithm from a pandas dataframe.
Parameters
----------
df: pandas.DataFrame
dataframe, indexed by the question, and where column names
represent the various workers. Entries are the labels assigned
by... | 3c51a1f8b58718867e8309555388b2832ad0dfeb | 640,271 |
from typing import Optional
import re
import logging
def Prompt(message: str, validator: str = '.*') -> Optional[str]:
"""Prompt the user for input.
Args:
message: the prompt message displayed to the user
validator: a regular expression to validate any responses
Returns:
a response string if succe... | ce9bdcde354fe1a99413771641364cd24a882d7e | 640,272 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.