content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def to_px8(p):
"""Convenience method to convert pymunk coordinates to px8
"""
return int(p[0]), 128 - int(p[1]) | 1f5ff363d9e0e9c1cd2f47fc3e26cc8649575cd4 | 638,219 |
import re
def is_timevar(expr):
"""
An time variable must be a single lowercase 't' or 'n' character followed by
zero or more digits. Do we need a separate type for utterance time n?
@param expr: C{str}
@return: C{boolean} True if expr is of the correct form
"""
assert isinstance(exp... | a45d07341733a325729ed27294f62b7d8a3a2db4 | 638,220 |
def _preprocess_csv(temp_df):
"""
Returns
-------
preprocessed/cleaned dataframe
"""
if 'Solar [kW]' in temp_df.columns:
temp_df = temp_df.drop(columns='Solar [kW]')
if 'Grid [kW]' in temp_df.columns:
temp_df = temp_df.drop(columns='Grid [kW]')
if 'Usage [kW]' in temp_df.... | cfee69d296fd3f593708dffebb24c6403674b686 | 638,221 |
def find_menu_name_by(self, pos, root_css):
"""根据菜单位置查找菜单名称"""
css = f"{root_css} li[data-pos='{pos}']"
li = self.driver.find_element_by_css_selector(css)
# 可能菜单处于隐藏状态,执行脚本获取text
js = "return arguments[0].innerText;"
return self.driver.execute_script(js, li) | 894db6283c2cdf41be6de6d6a3026f372337018e | 638,222 |
def debounce(func):
"""
prevent func from being called twice with the same arguments
:param func:
:return:
"""
func.debounce = True
return func | a1bb1f1bb5e759e42c848a6e13c40a2b8b36344c | 638,223 |
def compose_ngrams_regex(emoji_regex):
""" Compose a regex expression to parse out Ngrams
:param emoji_regex: a regular expression that matches emojis
:return: a compiled regular expression that matches ngrams
"""
pattern = '(' + emoji_regex
pattern += r"|(&\S+;)"
pattern += r"|(https?:\/\/\... | fb5a138286bf4d9717da01d6fc6053901e7c6bd9 | 638,224 |
def getDifferentsAtoms(atomsCoords):
"""renvoie une liste de tous les différents atomes rencontrés dans le dictionnaire atomsCoords
Juste pour voir les données que nous aurons besoin dans le dictionnaire 'atomicMass'
"""
atoms = set()
for coo, atom in atomsCoords.items():
atoms.add(atom)
... | 3448dc418c7785f31cf35e94698926394e4b5787 | 638,225 |
import math
def ID2Coord(gridID, grid_info):
"""
Given a grid ID, decide the coordinate of that grid
:param gridID: Given Grid ID
:param grid_info: Grid map information
:return: Grid Map Coordinates of that grid in format of (row, col)
"""
row = math.floor(gridID / grid_info['lngGridNum'])... | 367f6138341a23859e46fae0b091295f0b1743a8 | 638,226 |
def example_user(django_user_model):
""" Неадминский юзер. """
return django_user_model.objects.exclude(pk=1).first() | 9f2eed5de65e44e886321f40891be6fdc24ea26a | 638,228 |
import pickle
def load_dispatch_results(iteration, year, scenario):
"""Load scenario results"""
with open(f'output/dispatch_plan/uc-results_{iteration}_{year}_{scenario}.pickle', 'rb') as f:
results = pickle.load(f)
return results | e5267d8410cdda7e39815cfecd7010789661c768 | 638,229 |
def isSymbolNumber(command, sortedSymbols):
""" isSymbolNumber checks whether given command has Stock Symbol number and it is in the loaded Stock Symbols. """
return ((len(command.strip()) > 0) and command.strip().isdigit() and int(command.strip()) < len(sortedSymbols)) | 815bbc2b03ffa38f0a0a4f89c0d07166506da751 | 638,230 |
def matsub(a, b):
"""
Subtracts one array from another.
:param a: (ndarray)
:param b: (ndarray)
:return: (ndarray) product of a - b
"""
return a - b | 7751fa1bf79a9e2c85cd458e7c729b7eebbb8cbb | 638,231 |
def nested_map(f, obj):
"""Maps `f` recursively inside any dicts/lists/tuples in `obj`.
Args:
f: A function taking a single object as input. f's input must NOT be a
dict, list, or tuple, or any subclass of those.
obj: Either an input object to f or some nested structure of collections
of (c... | 9f7075f1fc132fbb933c7e2370b6f21f6eeb72ac | 638,233 |
import numpy as np
def balance(dataframe, label, n=500):
"""
Create a balanced sample from imbalanced datasets.
dataframe:
Pandas dataframe with a column called 'ls
text' and one called 'label'
n:
Number of samples from each label, defaults to 500
"""
... | bf612460610a0e8c0f1ddbb2b71635d25707b476 | 638,234 |
def intersect_shapes(shapes_a, shapes_b, shapes_b_sindex=None):
"""Find intersections between shapes in two lists
Parameters
----------
shapes_a : list of Shapely geometries
List of geometries to be intersected with those in shapes_b
shapes_b : list of Shapely geometries
List of geo... | 3b91a54302a732c2c98bba44d6617cf4eea52b92 | 638,235 |
import json
def fixture_file_data_json(file_data) -> str:
"""Return a json string with file information"""
return json.dumps(file_data) | fa31a53ea4a8cb6c39b640614aa6fdb1c4b8cc92 | 638,236 |
import re
def match(regEx, text):
"""
Try to match the regular expression @regEx
in the text at @text. If match is found, all occurrences
are returned, otherwise empty list is returned
"""
_regEx = re.compile(regEx)
res = _regEx.search(text)
if res:
return list(res.groups())
else:
return [] | d6eb2251b579f6e2546b32785e1e11983488d601 | 638,238 |
import subprocess
import re
def getS3Paths(path, fullpath=True):
"""
0. use subprocess to extract the AWS s3 ls contents as a string
1. remove the "b'" at the beginning
2. remove the "'" at the end
3. remove the escape characters ('\n')
4. remove all white space characters
5. split by the ... | a89478d8b83583a982391580b513f99747592e52 | 638,239 |
from typing import Optional
import os
def get_transcript_file(path: str, transcript_name: str, username: Optional[str], f_date: str) -> Optional[str]:
"""
Returns the path to a requested transcript file if exists
:param path: Path to transcripts
:param transcript_name: Name of transcript to return
... | 41542837c71911e978c4d8dc3e7f5978c3d6d4f3 | 638,240 |
def get_energies(filename):
""" Returns a dictionary with heats of formation for each xyz-file.
"""
f = open(filename, "r")
lines = f.readlines()
f.close()
energies = dict()
for line in lines:
tokens = line.split()
xyz_name = tokens[0]
hof = float(tokens[1])
... | 1e4be956bba367167d8cd6d97114e83e9df489c4 | 638,241 |
def str_mask(str):
"""指定文字列をマスク置き換えする Replace the specified character string with a mask
Args:
str (str): 文字列 string
Returns:
str: 置き換え文字列 afeter string
"""
# 1文字以上の入力があれば置き換えする If there is more than one character input, replace it
if len(str) > 0:
ret = '*' * len(str)... | 5d01f9b9c8d5fa9c95e1b4925300ecab852cd9dc | 638,243 |
import hashlib
def get_bigfile_md5(self, file_path):
"""
| ##@函数目的: 获取文件MD5值
| ##@参数说明:
| ##@返回值:
| ##@函数逻辑:
| ##@开发人:jhuang
| ##@时间:
"""
if self.isFile(file_path):
md5obj = hashlib.md5()
maxbuf = 8192
f = open(file_path, 'rb')
while True:
... | 493923fa588cbdfae4d8a3b8e2dff84022c725d2 | 638,244 |
def extract_concat_sub_text(sub_info):
"""sub_info is list(dict), each dict is {"text": str, "start": float, "end": float}"""
return " ".join([e["text"] for e in sub_info]) | 23920b6804dfeefcac17780ec478f8a129c43e1a | 638,246 |
def mutlireplace(string, replacements):
"""
Replaces multiple substrings in a string.
Parameters
----------
string : str
The string to be modified.
replacements : dict
A dictionary of the form {old: new}.
"""
for key, value in replacements.items():
string = ... | ac6898d393a1841a8578913b371fe79bcb2b4c5a | 638,247 |
import argparse
def get_parser():
"""Return an argument parser for the script."""
parser = argparse.ArgumentParser()
parser.add_argument("--tutorials", help="Directory where tutorials are located", default=None, metavar="Tutorials directory", dest="tutorials_dir")
parser.add_argument("--site-pages", h... | a3b18763e94810897becc6b36175746ee175cd31 | 638,248 |
def resolve_obco(ep_bunch):
"""Resolve the outside boundary condition of a surface.
Args:
ep_bunch (EpBunch): The surface for which we are identifying the boundary
object.
Returns:
(EpBunch, EpBunch): A tuple of:
EpBunch: The other surface EpBunch: The other zone
... | 3b29cb0a78eb132cd54cb526ec7ce80625e62e11 | 638,249 |
def get_datetime_range(start_date, end_date, time_delta):
"""
:param start_date: (datetime.datetime) First date (included)
:param end_date: (datetime.datetime) Last date (not included)
:param time_delta: (datetime.timedelta) Increment
:returns ([datetime.datetime]) All datetimes from start_date up t... | 5bba18dafdf01957ab991a4c72eed93c76ea2c88 | 638,250 |
def roc(tests=[]):
""" Returns the ROC curve as an iterator of (x, y)-points,
for the given list of (TP, TN, FP, FN)-tuples.
The x-axis represents FPR = the false positive rate (1 - specificity).
The y-axis represents TPR = the true positive rate.
"""
x = FPR = lambda TP, TN, FP, FN:... | cff775657e93545573da91ecff5327e729992ed0 | 638,251 |
import os
def derivative_filename(base, part, replace_ext=True, outputdir=None):
"""Build the filename of a derivative product of the original
file."""
if not part[0] == ".":
part = "." + part
if outputdir is None:
outputdir = os.path.dirname(base)
filename = os.path.basename(bas... | f46349d63fac4cd644eb5c5c3af1a11a2768e142 | 638,252 |
def get_index(data, name):
"""
Retourne la valeur de la position de name en tant qu'index.
:param DateFrame data: Un tableau de données.
:param str or list name: Nom(s) d'index du tableau de données data.
:return: * **I** (*int or list*) - Donne la/les positions(s) de name dans l'inde... | b4a8d7d3aaca0f7da9631645a8ea1062e43023d8 | 638,253 |
import subprocess
import difflib
def get_formatting_diff_lines(filename):
"""Calculates and returns a printable diff of the formatting changes that
would be applied to the given file by clang-format.
Args:
filename (string): path to the file whose formatting diff to calculate.
Returns:
Iterable[str]... | 1ff831d535ce2f1f3143a0d3003cb9e35332af72 | 638,254 |
def getUserLocation(user):
"""
This function is used to call the user's method getlocation that returns his gps coordinates
:param user: a user
:return: the user's location
"""
return user.getLocation() | 3f47f74fe539fab3a3282879ce4dc4a4f185359d | 638,255 |
def ParametersToFileNameBase(device_id=None, start_time=None, end_time=None):
"""Builds a file name base based on query parameters.
This method builds a file name base (lacking an extension, timestamp or
other things that may be useful to add) that describes the contents of the
file of directory of files.
A... | 682a5693aef52f0797bcc1872752f199f14004c1 | 638,256 |
def get_all_keys(items):
"""Get all keys in a list of dictionary.
Parameters
----------
items : list
List of dictionaries.
Returns
-------
list
List containing all keys in the dictionary.
"""
ret = []
if not hasattr(items, "__iter__"):
return ret
if ... | d8dca1222810cc69e0153b505ebb6db83f1e12a5 | 638,257 |
def roundToNearest(value, roundValue=1000):
"""
Return the value, rounded to nearest roundValue (defaults to 1000).
Args:
value (float): Value to be rounded.
roundValue (float): Number to which the value should be rounded.
Returns:
float: Rounded value.
"""
if roundValu... | 41eeb16cdcfc9a0081693ac3000b49a9f8598db4 | 638,258 |
def motion_h(input_line, cur, count):
"""Go `count` characters to the left and return position.
See Also:
`motion_base()`.
"""
return max(0, cur - max(count, 1)), False, False | 8f1e402fbf0dbc1b32d4db7937feae7ac1517d41 | 638,259 |
def get_mqtt_field(p_message, p_field):
""" Get the given field from a JSON message.
@param p_message: The json message
@param p_field: the 'field_name' to extract
@return: the value of the field or None if missing.
"""
try:
l_ret = p_message[p_field]
except (KeyError, TypeError):
... | e95912a6381013fcc955f29f9518efb479def209 | 638,261 |
def _make_constraint_name(tname, *cnames, suffix=''):
"""Returns a constraint name from the given components."""
constraint_name = f'{tname}_' + '_'.join(cnames)
return constraint_name[:63 - len(suffix)] + f'_{suffix}' | 55b0be29556250ba188532b6505278201d59fb41 | 638,262 |
def gen_pos_limits_from_square_path(square_path):
"""Generate position bounds for drones."""
return ([square_path[0][0], square_path[1][0]], [square_path[1][1], square_path[2][1]]) | 9c054af823fa85dc94ad43482b78adf5fb9c64f1 | 638,263 |
def xor(stream: bytes, key: int) -> bytes:
"""Apply XOR cipher to ``stream`` with ``key``.
Applying this operation twice decodes ``stream`` back to the initial state.
Parameters
----------
stream: :class:`bytes`
Data to apply XOR on.
key: :class:`int`
Key to use. Type ``u8`` (o... | 35a5978243ab39882ad257438780eb5ed5d44e45 | 638,264 |
import copy
def mutate_dropped(record, rule):
"""Mutate a record for a "DROPPED" action.
"""
if rule['filters'](record):
r = copy.copy(record)
c = []
if 'column_filters' not in rule:
return None
for column in r['columns']:
c_filters = rule.get('colum... | ed9937993ff042fe1a9038d3fb0efa0fbdf6086c | 638,265 |
def get_r( x, y = 0, z = 1):
"""Makes r (length between origin and point) for x, y, z
Returns r (scalar or array, depending on inputs)"""
r = ( x **2 + y **2 + z **2 ) **0.5
return r | f99faa53e17fa11378cffb381cb41070b89e2ee0 | 638,267 |
import re
def string_to_float(s: str) -> float:
"""
Double precision float in Fortran file will have form 'x.ydz' or 'x.yDz', this cannot be convert directly to float
by Python ``float`` function, so I wrote this function to help conversion. For example,
:param s: a string denoting a double precision... | 833c159aabbc8f3bce467914bc26cddc199ce0af | 638,268 |
from typing import Dict
def get_param_name(
parameter_definition: Dict[str, str],
param: str
) -> str:
"""
Simple function to essentially return the appropriate value of the PARAMETER_NAMES dictionary.
Args:
param: Name of the parameter of interest, with hierachical keys joined with "."
... | 0287cd3cfbdab12371a9850e07268cc83f81bf36 | 638,269 |
def time(match, player_num, word_index):
"""A utility function for the time it took player_num to type the word at word_index"""
assert word_index < len(match["words"]), "word_index out of range of words"
assert player_num < len(match["times"]), "player_num out of range of players"
return match["times"]... | b012ba5d4d033a65fc5177cb154df79d402dfa83 | 638,271 |
def parse_po(text):
"""
Parse 'po' format produced by xgettext.
Return a list of (msgid,msgstr) tuples.
"""
messages = []
msgid = []
msgstr = []
in_msgid = False
in_msgstr = False
for line in text.split('\n'):
line = line.rstrip('\r')
if line.startswith('msgid ')... | d8fbb605e934cfed3b96cd98b6420cafda028974 | 638,272 |
def I10index(citationlist):
"""根据citationlist计算i10因子。
citationlist是按顺序的每篇文章引用次数列表
"""
i10index = 0
for i in range(len(citationlist)):
if citationlist[i] >= 10:
i10index = i10index + 1
return i10index | aa00a9988c9517aeeb50f2d466a98adb78a2579e | 638,273 |
def burke_shaw(XYZ, t, s=10, v=4.272):
"""
The Burke-Shaw Attractor.
x0 = (0.1,0.1,0.1)
"""
x, y, z = XYZ
x_dt = -s * (x + y)
y_dt = -y - s * x * z
z_dt = s * x * y + v
return x_dt, y_dt, z_dt | a9802c70dd5157e9da290e7900b7b43e8e4f19b7 | 638,274 |
from typing import List
import functools
def intersect_word_lists(word_lists: List[set]) -> set:
"""Build the intersection of the word lists."""
return functools.reduce(lambda a, b: a & b, word_lists) | 137bb504c19a4019eab37bdf530ca01dde5cb2e0 | 638,275 |
def index(request):
"""Handle the contribution landing page."""
return {} | 267cec47fcb6e7f23559838f2d9c8ae302a89107 | 638,276 |
def to_list(item):
"""
Make a list contains item if item is not a list
:param item: item to convert
:return: a list
"""
if item is not None and not isinstance(item, list):
return [item]
return item | 0863ecbcb4ae7c429695df7b775f510efc15b994 | 638,277 |
import math
def determine_when_discovered_sne_disappear(
log,
redshiftArray,
limitingMags,
observedFrameLightCurveInfo,
ripeDayList,
plot=True):
"""
*Given the observed frame lightcurve, determine when the discovered SNe become too faint to be detected.*
**... | 93baf862da98beaf8075e02f1e381b93aae83317 | 638,278 |
def for_and_backward(model, batch, maps, optimizer, loss_fn):
"""Does one forward and one backward step, including weight updates, using
the given batch. Returns the loss."""
prediction = model(batch)
loss = loss_fn(prediction, maps)
# Calculate gradients
loss.backward()
# Update model param... | 5d95583173dad8db55196d3a1799656888cad322 | 638,281 |
import grp
def get_group_grp(gid):
"""get group info
Args:
gid (int): gid of the group
Returns:
grp.struct_group
"""
return grp.getgrgid(gid) | bc63b1887fecc7e59b535d0b006b81f3fab36e8a | 638,282 |
def read_2D_list(path):
"""
Reading a list of list.
"""
with open(path, "r") as f:
output_list = [[float(x) for x in line.split()] for line in f]
return output_list | 9308b3c6dac854731a4c9e7d4a692d9dbd75f279 | 638,283 |
def _rounding_rectified(x):
"""
Rounding with straight-through gradient estimator.
:param x: Tensor
:return: Rounded tensor.
"""
raise NotImplementedError
sample = tf.round(x)
return sample, lambda dy: tf.multiply(dy, sample) | 8f5e476ab1a03206b91e81902f89f423c09392f9 | 638,284 |
import math
def _db2gain(db):
"""Convert 100ths of dB to linear gain."""
return math.pow(10.0, float(db)/1000.0) | afac35b8610e6d80953f343ffdf24e16ca01e3ee | 638,285 |
def check_same(li):
"""Check if all elements in the list are the same and not equal ' '.
Returns False of the value in the list."""
same = all([i == li[0] for i in li])
if same and li[0] != ' ':
return li[0]
return False | ff41f06706a5fce7cdcff4e10fd4dd6d4e74545b | 638,287 |
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0:
val = val - (1 << bits)
return val | db52a1bee586bbf70c636124b335cbc9071e8e9f | 638,288 |
def parse_is_account_bimodal_response(resp):
"""
Parse a response from RpcIsAccountBimodal.
Returns (True, peer-addr) if the account is bimodal, (False, None)
otherwise.
"""
is_bimodal = resp["IsBimodal"]
ip = resp["ActivePeerPrivateIPAddr"]
if ip.startswith("[") and ip.endswith("]"):
... | d18305ead4bfc349d4ecf44dc057712ab64be887 | 638,289 |
import torch
def kldloss(logits, weight):
"""
logits: N * C * H * W
weight: N * 1 * H * W
"""
val_num = weight[weight > 0].numel()
logits_log_softmax = torch.log_softmax(logits, dim=1)
num_classes = logits.size()[1]
kld = -1 / num_classes * weight * logits_log_softmax
kld_r... | 8aa07e2b7ee43bfb938adb9a399fa2419b5d4aec | 638,290 |
from typing import List
def get_mask_colors(scene: dict) -> List[List[float]]:
"""
Loads the unique mask colors from the scene dictionary
Parameters
---
scene (dict)
Scene dictionary containing info about the scene
Result
---
List[List[float]]
"""
masks = []
for o... | 7a065664d70d23baaa8621977ddb92e77acbc1e9 | 638,291 |
def getmaxport(dev):
"""
Gets the maximum outlet number of a device.
@return: maximum outlet number
"""
assert dev.idVendor == 0x04b4
if dev.idProduct == 0xfd10:
return 0
if dev.idProduct == 0xfd11:
return 1
return 4 | 1b6c2cb6d9459ccee9d70709dd1393e6f3aab269 | 638,292 |
def any2unicode(text, encoding='utf8', errors='strict'):
"""Convert `text` (bytestring in given encoding or unicode) to unicode.
Parameters
----------
text : str
Input text.
errors : str, optional
Error handling behaviour if `text` is a bytestring.
encoding : str, optional
... | 7dbdacd9249ed495594685f379604348f8f6cfb5 | 638,293 |
def spacy(sentence_vector, nlp_language):
""" Function to lemmatize an array of sentences.
Args:
sentence_vector (array): Array containing text.
nlp_language (object): Spacy pipeline.
Returns:
numpy.array: Array containing the lemmatized words.
"""
lemma... | 0e86ebf03be8acc2893f30e82ade2a6a8bc3233e | 638,294 |
def bits_to_int(bits):
"""Converts a list of bits into an integer"""
val = 0
for bit in bits:
val = (val << 1) | bit
return val | fe2024817f3659b6304577e7c325168690e74392 | 638,295 |
def config_filename():
"""
"""
return 'config.yml' | 08a23f353387ae0f980db14f1cf9c7d761711c08 | 638,296 |
from typing import List
from typing import Tuple
def cleanlines(
x: List[float], y: List[float]
) -> Tuple[List[float], List[float]]:
"""Clean the distance lines.
(I think) this function cleans the distance lines such that they don't
extend too far.
Args:
x: The x coordinates of a line.
... | 1a9659ff7ddc892e1e57ff65e19581bd57c34913 | 638,300 |
def CheckMult(x):
"""Checks is the present product is still dividable by all numbers in
the list"""
for h in range(2,20):
if x%h!=0:
return False
break
return True | 195be649a01166da4e6a5c57167458a72312015d | 638,301 |
import subprocess
from typing import Optional
def which(editor: str) -> Optional[str]:
"""Find the full path of a given editor.
Return the full path of the given editor, or None if the editor can
not be found.
:param editor: filename of the editor to check, ie 'notepad.exe' or 'vi'
:return: a fu... | 9b4b969da64769cdcc3dd927c46c855e1ff34975 | 638,302 |
import os
def is_cellomics_mask(fn):
"""Determine whether a file is a Cellomics mask image.
Parameters
----------
fn : string
The filename.
Returns
-------
is_mask : bool
True if the filename points to a Cellomics mask image.
Examples
--------
>>> mask_fn = '... | 0169a27178d037a223c17de18914ca2439d0955d | 638,303 |
from typing import Sequence
from typing import Generator
from typing import Any
def _get_tasks_from_blocks(task_blocks: Sequence) -> Generator:
"""Get list of tasks from list made of tasks and nested tasks."""
NESTED_TASK_KEYS = [
'block',
'always',
'rescue',
]
def get_nested_... | e006ce19d4c9d4b833a058d86aea374111b35303 | 638,304 |
def _contains_library_name(file, library_name):
"""
Checks if the file contains the specified line.
:return: True if the file contains the specified line
"""
for line in file:
line = line.strip()
line = line.split()
if len(line) == 3:
if line[1] == library_name:
... | c94771b882eb605e809b95175c6a524016f1a521 | 638,305 |
def get_value(value):
"""Convert the given string value to a proper python object.
ast.literal_eval may work better.
"""
try:
if str(value).startswith('0x'):
return int(value, 16) # Was given hex. This allows "0x12" = 18
else:
return int(value)
except (Value... | 3c4de0582d131372bc5c3e8b12c87e49d252b541 | 638,306 |
def from_string(val):
"""Return simple bool, None, int, and float values contained in a string
Useful for converting items in config files parsed by
`configparser.RawConfigParser()` or values pulled from Redis
"""
_val = val
if type(val) != str:
pass
elif val.lower() == 'true':
... | c98eb7bf9966760cfdb756a115728e255986c7d9 | 638,307 |
def parse_hex(string):
"""Parse a string as a hexadecimal value."""
return int(string, 16) | e5ce1ba5b0542d0dcad8855fd352431670f5682b | 638,308 |
def only_for_development():
"""
Create a filter that is only considered when development is toggled.
"""
def _inner(context):
return context["development"]
return _inner | 8df4899a4642003a1434020fc0535583f2d6bd43 | 638,309 |
import torch
def box_xy_to_wh(x):
"""
Converts co-ordinates from (x1, y1, x2, y2) to
(x, y, w, h)
"""
x1, y1, x2, y2 = x.unbind(-1)
x = (x2 + x1)/2
y = (y2 + y1)/2
w = (x2 - x1)
h = (y2 - y1)
return torch.stack([x, y, w, h], dim=-1) | d728a70c70a65242f76a3041d994efaa93846b85 | 638,310 |
def SDEWrapper(layer):
"""For transitioning from SDELayer outputs to Dense layers
"""
init_fn, apply_fn = layer
def apply_fun(params, inputs, rng, **kwargs):
preds, postw, postkl, priorx, priorw, priorkl = inputs
preds, postkl = apply_fn(params, (preds, postkl), rng, **kwargs)
return preds, postw, p... | f9ab33ad11cddfca8bc54b9472367a3080eaedc8 | 638,311 |
def hbnb():
"""
Return desired string for /hbnb route
"""
return "HBNB" | 1f952603a1cfd118c348625521eec26b6230f1c5 | 638,312 |
import re
def close_parentheses_or_braces(string):
"""
Add a missing parenthese or brace to close one open
If the paranethese or brace is at the begining of the string,
it will be removed instead. That's because if it was closed with a pair
at the end of the string, the whole string will be c... | d9602aabaee871949559d2bbb3ee41930f65c71f | 638,313 |
def scalar_eq(a, b, precision=0):
"""Check if two scalars are equal.
Keyword arguments:
a -- first scalar
b -- second scalar
precision -- precision to check equality
Returns:
True if scalars are equal
"""
return abs(a - b) <= precision | e3d3cb091119d38825a37a5e745ab302f976cbb7 | 638,314 |
import re
def identify_url(url):
"""Identify from which site a url is.
Return values:
'letras' for 'letras.mus.br'
'vagalume' for 'vagalume.com.br'
'unknown' if not able to identify.
"""
if not isinstance(url, str):
raise ValueError('url is not a string')
url = url.strip()... | d5f48efb2e7c7d6a0e22641939b379c7a75ca333 | 638,315 |
def load_data(folder, spark, stmt:str, attr:str):
""" Loads the pivoted data into a spark dataframe.
"""
return spark.read.parquet(folder + "/" + stmt + "/" + attr) | 719ce317afd861be38383f574f0af8025d5d1cba | 638,316 |
def flatten_list(_list):
""" [(1,2), (3,4)] -> [1, 2, 3, 4]"""
return sum([list(item) for item in _list], []) | 42caee7ee37fc14fd74eba784ac3b76326754a37 | 638,317 |
def validate_byr(birth_year: str) -> bool:
"""byr (Birth Year) - four digits; at least 1920 and at most 2002."""
return len(birth_year) == 4 and int(birth_year) >= 1920 and int(birth_year) <= 2002 | 5ec2c850a7f48bfdb49d62259689b6b6f87cdec3 | 638,318 |
def is_restart_command(command_text: str) -> bool:
"""
>>> is_restart_command("restart")
True
>>> is_restart_command("restart game")
True
>>> is_restart_command("take lamp")
False
"""
return command_text.startswith("restart") | 5fbfe40e11df015a7d159db6da6d7f213d67330f | 638,319 |
def try_to_add(entry,dict,keys,position):
""""try to add position to dict and create key if it fails"""
try:
dict[keys[0]]['%s_%s'%(keys[1],entry)] += [position]
except KeyError:
if keys[0] not in dict:
dict[keys[0]] = {'%s_%s'%(keys[1],entry):[position]}
else:
... | 3b02b4a47f0dc1f2ef339d2e6fee54a0539b821a | 638,320 |
import os
def list_files_of_type(path_name, extension):
""" Return a sorted list of files in a directory, with a specific extension
:param path_name: the path to search in
:param extension: the file extension to search for
:return: a sorted list of all files in path_name with extension
"""
if... | 616699e4889d21307723449ddc857bfe364e19f2 | 638,321 |
def _strip(string):
"""
Removes unicode characters in string.
"""
return "".join([val for val in string if 31 < ord(val) < 127]) | 12aa6b9ae6c2b3c5283ee837819d48d35be39e74 | 638,322 |
import os
def choose_item(indir, tag='', exclude_tag='', itext='** Choose item from list **'):
"""
Choose an item from a directory listing. You have to supply the directory to look in.
Use './' to look in the current directory. Use the optional keyword arguments
tag and exclude tag to refine the lis... | f73e0cae044443bdcbbbb63ba5f79d414ef1a543 | 638,323 |
def measurement_ids_and_names(experiment_proto):
"""List all measurement IDs and names for an experiment.
Results are sorted by measurement ID.
Args:
experiment_proto: selection_pb2.Experiment describing the experiment.
Returns:
measurement_ids: tuple of integer IDs for each measurement.
column_n... | c065d0451e8d1b90a34e36c097cc99f9836d728c | 638,324 |
from datetime import datetime
def noclook_last_seen_to_dt(noclook_last_seen):
"""
Returns noclook_last_seen property (ex. 2011-11-01T14:37:13.713434) as a
datetime.datetime. If a datetime cant be made None is returned.
"""
try:
dt = datetime.strptime(noclook_last_seen, '%Y-%m-%dT%H:%M:%S.%... | 88eab5db655c32323004a14bab458962f90fda73 | 638,325 |
def split_dataframe(df, chunk_size):
"""
splits a pandas dataframe into a list of sub-dataframes by size of chunk_size
"""
df = df.iloc[::-1] #reverse the dataframe
chunks = list()
for i in range(len(df)): #for amount of days in df
if len(df[i:i+chunk_size]) is chunk_size:
... | 2d8597d27e2d326298941d0bd38d99a3fa0f3524 | 638,326 |
def _is_dunder(name):
"""Returns True if name is a __dunder_variable_name__."""
return len(name) > 4 and name.startswith('__') and name.endswith('__') | 9dc571eab0f47ab94860bbc56a67140ec1b52498 | 638,327 |
def get_matching_items_from_dict(value, dict_name):
"""
Return all items in a dict for which the label matches the provided value.
@param value: the value to match
@param dict_name: the dict to look in
"""
matches = [dict_name[x]["items"]
for x in dict_name if x.lower() == value]... | 4e2d720ebca42c41a87833ebfa9b502955ec7840 | 638,328 |
from datetime import datetime
def json_datetime_converter(dt):
"""
Convert datetime objects to strings for json.dumps().
**Parameters**
``dt``
Datetime object to convert to a string
"""
if isinstance(dt, datetime):
return dt.__str__()
return None | 74fcf2d3e8b0d391f4dedf594d543c88eac2723b | 638,329 |
def paging_modes(yaml_string, isa):
"""
This function reads the YAML entry specifying the valid
paging modses supported by the SATP CSR and returns the mode(s)
for the framework to generate tests
"""
split_string = yaml_string.split(' ')
values = (split_string[-1][1:-1]).split('... | 33ed08b8785560ad5c556dcb6247a125b45d209e | 638,330 |
def orangePurchase2(m):
"""
Calculate how many oranges can be bought with a set amount of
money. The first orange costs 1, and each subsequent exponentially costs more than the previous
(the second costs 2, the third costs 4, and so on).
:param m:total amount of money available (nb m<2,147,483,647)... | f4c9d0791f9f09ca8c0194a184979fcc53297163 | 638,332 |
def build_entity(key, value):
"""
build_entity return a dict that can be passed back to rasa as an entity
using the given string key and value
"""
return {"entity": key, "value": value, "start": 0, "end": 0} | 3e29ed0d9dc3adad003ff95b75a8c46edd0becce | 638,333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.