content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_client_ip(request):
"""Extract client ip from request headers
Retrieves rows pertaining to the given keys from the Table instance
represented by big_table. Silly things may happen if
other_silly_variable is not None.
Args:
request: django HttpRequest object.
Returns:
... | 09c0a65f71f070ca3f927924e9d23bd6d3ddaa62 | 581,140 |
def validate_dicts(ground_truth: dict, predicted: dict) -> bool:
"""
Validate GT and pred dictionaries by comparing keys
Args:
ground_truth (dict): mapping from (track_id + timestamp) to an element returned from our csv utils
predicted (dict): mapping from (track_id + timestamp) to an eleme... | d89a9e2cb6541f2aa1fa991c470d1e5161428a48 | 581,141 |
def table_formatter(rows):
"""Format the rows (a list of col/cell lists) as an HTML table string."""
row_cells = [''.join([f'<td style="font-size: 14px; padding: 20px;">{cell}</td>'for cell in row]) for row in rows]
trs = [f'<tr>{cells}</tr>' for cells in row_cells]
return f'<table class="lemma-table">{... | 26aa48f2ee320acef75bddfce723084ba190dd9e | 581,142 |
from typing import List
import random
def generate_divisions(divisor: int) -> List[str]:
"""Returns a list of division questions for the given divisor."""
# Define dividends (i.e. numbers 1-12), and randomise order
dividends = [index * divisor for index in range(1, 13)]
random.shuffle(dividends)
... | c0f5e2b02063aca2dcad3c12452e7c815fea2c18 | 581,143 |
def normalize_stop_positions(positions):
"""Normalize stop positions between 0 and 1.
Return ``(first, last, positions)``.
first: original position of the first position.
last: original position of the last position.
positions: list of positions between 0 and 1.
"""
first, last = position... | cbb979f0096435f9c0b20e9d0c30ba876b4be5f5 | 581,153 |
def getDifficultyEditRedirect(entity, params):
"""Returns the task difficulty levels edit redirect for the specified entity.
"""
return'/%s/task_difficulty/%s' % (
params['url_name'], entity.key().id_or_name()) | 666afc9ffcbccb82dce62aeb84b3a1013f52b46e | 581,155 |
def code() -> str:
"""
Example G-code module, a tree.
Please simulate first, before milling.
"""
return """
G91
G0 X13 Y13
G0 X6 Y6
G0 X4 Y4
G0 X-4 Y-4
G0 X-4 Y4
G0 X4 Y-4
G0 X-6 Y-6
G0 X-6 Y6
G0 X4 Y4
G0 X-4 Y-... | 7d18984e2bf6ce496ffdbcac2bc6c3ffe4c60499 | 581,157 |
import copy
import json
def argv_to_dict(argv, defaults={}, dot_dict=True):
"""
Convert a list of (simple) command-line arguments to a dictionary.
Parameters
----------
argv : list of strings
E.g., ``sys.argv[1:]``.
defaults : dict
Default dictionary
dot_dict... | aa830617ad15f85294cbcd1222ac2ba954a3ec5f | 581,158 |
def StringToFloat2(value):
"""Convert a float value into a string with two decimal places."""
if value:
return '%.2f' % value | 28994742084d5668fa0de137c7fd04cffc771cf9 | 581,162 |
def dnd_accept(self, source, event):
"""
Decide what object will accept the drop.
The returned object will become the new target for the drop operation.
:param source: The object being dragged.
:param event: The tk event that resulted in this call.
Usually a motion event.
:re... | 57f2e2d433ca05295ab40dcb83d255dc3940c746 | 581,165 |
def get_index(level, lesson):
"""Return index from level and lesson
"""
if level == 1:
return (level - 1) * 30 + lesson
else:
return (level - 1) * 30 + lesson - 5 | 93b14cb3f70c0bc72f603bc365fc984bae435873 | 581,166 |
import zipfile
def get_rootdir(zip_filename: str):
"""
Get the name of the root directory of the contents of a zip following extraction.
"""
zip_filepath = "data/" + zip_filename
with zipfile.ZipFile(zip_filepath, "r") as zip_ref:
rootdir = zip_ref.namelist()[0]
return rootdir | 58aa4d59e87dfb5b1e0b910abc1891f56085d334 | 581,172 |
def is_in_references(references, doi):
""" Search for a doi in a list of references.
Args:
references (Iterable): References to loop through.
doi (str): DOI of work to search for.
Returns:
bool: True if doi is in any of the references, else False.
"""
url_doi = doi.replace(... | 39ee944c416f518170e1aea9418317432d507836 | 581,175 |
def clamp(value: float, min_value: float, max_value: float):
"""Clips the given [value] in the given interval [min_value, max_value]"""
return max(min_value, min(value, max_value)) | aa72f2a00ed89327f5e566395b5033ee41fa060c | 581,178 |
def concatenate_title_and_text(title, text):
"""Concatenates title and content of an article in the same string.
The two parts are separated by a blank space.
:param title: The tile of an article
:type title: str
:param text: The text content of an article
:type text: str
:return: The strin... | 759d6a0564fa539f36bd2448363c7c22a025726a | 581,179 |
def get_trader_fcas_availability_max_quantity_condition(params) -> bool:
"""At least one quantity band must have positive value"""
# Quantity greater than 0 for at least one quantity band for the given service
max_quantity = max(params['quantity_bands'].values())
return max_quantity > 0 | 4eaac2bb8ca9806764a9547bbb66b135ca9f13e4 | 581,182 |
def yn(boolean: bool) -> str:
"""Converts 'True' or 'False' to 'Yes' or 'No'"""
return "Yes" if boolean else "No" | 1dff3391823c45684908be2dd6b43fcd342efbbd | 581,183 |
import hashlib
import six
import random
def generate_activation_key(user):
"""
The activation key for the ``User`` will be a
SHA1 hash, generated from a combination of the ``User``'s
pk and a random salt.
"""
salt = hashlib.sha1(six.text_type(random.random())
.encode('a... | 9176ae6bb960ca0ca6715743ad5efc5925773aab | 581,187 |
def has_data_load(bpr):
"""
Checks if building has a data center load
:param bpr: BuildingPropertiesRow
:type bpr: cea.demand.building_properties.BuildingPropertiesRow
:return: True or False
:rtype: bool
"""
if bpr.internal_loads['Ed_Wm2'] > 0:
return True
else:
... | 2a49ebd5dce529318b5bb185119c4e3b62406ce5 | 581,188 |
def generate_name(testcase_func, param_num, param):
"""Used to generate parameterized method names like test_code_cell_n"""
return "test_code_cell_%s" % param.args[0] | 0b5d439b22984207fa4d21cfe821fb5616c04d5b | 581,192 |
import ast
def str_dic(chaine):
"""Convertion d'une chaine en distionnaire
:param str chaine:
:rtype: dic
:Exemple:
>>> s_dic = "{'key':value}"
>>> str_dic(s_dic)
{'key': 'value'}
"""
return ast.literal_eval(chaine) | c35f898a2fc66930f924bf072a1a6e00c1a639a4 | 581,195 |
def _get_points(point):
"""
Return list of possible neighbor points to a given point
"""
return [[point[0], point[1] + 1],
[point[0], point[1] - 1],
[point[0] + 1, point[1]],
[point[0] - 1, point[1]]
] | afdcf339e3e47c24cc45a59f7d031004bd8344e6 | 581,198 |
def AddBitbucketServerConfigArgs(parser, update=False):
"""Set up all the argparse flags for creating or updating a Bitbucket Server config.
Args:
parser: An argparse.ArgumentParser-like object.
update: If true, use the version of the flags for updating a config.
Otherwise, use the version for creati... | 1f8b00fdec3e353428f4772a0754ff9e5ecf89ec | 581,199 |
def display_hour_range(value):
"""
Function that either displays the hour range input or hides depending on the
time radio button selected.
Args:
value: Contains the time radio button option selected.
Returns:
A dictionary that communicates with the Dash interface whether to
... | 62179bdc0f7195a807764b6e0279a6170288d054 | 581,200 |
def is_valid_rgb(r, g, b):
"""
check that an rgb color is valid
:params r,g,b: (0,1) range floats
:return: True if valid, otherwise False
"""
return all([0 <= x <= 1 for x in (r, g, b)]) | 6bad5e19a7d66512e385a2078d6f965f4851add1 | 581,203 |
import torch
def enclosing_box_aligned(corners1:torch.Tensor, corners2:torch.Tensor):
"""calculate the smallest enclosing box (axis-aligned)
Args:
corners1 (torch.Tensor): (B, N, 4, 2)
corners2 (torch.Tensor): (B, N, 4, 2)
Returns:
w (torch.Tensor): (B, N)
h (torch.Te... | 81a5acfec433c7f2d45ab5da9d172fa9f7cff9d9 | 581,205 |
import ipaddress
def cidr_to_netmaskv6(cidr):
"""Creates a decimal format of a CIDR value.
Args:
cidr (int): A CIDR value.
Returns:
netmask (str): Decimal format (IPv6) representation of CIDR value.
Example:
>>> from netutils.ip import cidr_to_netmaskv6
>>> cidr_to_net... | 98479329578a4e0cc4aa437e3e5ac7ea4a3e7daa | 581,206 |
def __get_pcs_steps(in_file):
"""
Get a list indicating the type of step for each step in a PCS data file.
Parameters
----------
in_file: str
Path to PCS file
Returns
-------
steps: list
A list of step types. for numeric data, the step type is 'data', for
other... | edcbb213388020194160e2e1910ede989ebbc26c | 581,208 |
def convert_array_to_return_string(board):
"""Converts an array of 'x','o', None into a string of 'x','o','!'
"""
board = [space if space != None else '!' for space in board]
board = ''.join(board)
return board | cd8c9ac922403e9e8b9ccab26e253b559fc09fcf | 581,214 |
from typing import Mapping
from typing import Any
def _get_value(obj: Mapping[str, Any], keypath: str):
"""Gets a value from a dictionary using dot-separated keys.
Args:
obj: A dictionary, which can be multi-level.
keypath: Keys separated by dot.
Returns:
Value from the dictionary using multiple k... | 25c5cbf9a5a6671427cf75c4604afd8a9bce9630 | 581,215 |
def model_data_from_agg_obj(agg_obj):
"""
Returns model data as a 1D ndarray from an aggregator's *PhaseOutput* class, which we call an 'agg_obj' to
describe that it acts as the aggregator object for one result in the `Aggregator`. This uses the aggregator's
generator outputs such that the function can ... | 5c245e3d351b326a3565e3cae230da5e25a0efe2 | 581,216 |
def buildGCDTable(n):
"""
Build the gcd table for all pairs (x,y) with x,y <= n.
"""
result = [[0 for x in range(n)] for y in range(n)]
for i in range(n):
for j in range(i,n):
if i == 0 or j == 0:
result[i][j] = 1
result[j][i] = 1
elif ... | 5a71b6fe539b8177eb0fd94061009d190b8bef24 | 581,221 |
def snake_to_camel(string):
"""Convert a snake case to camel case"""
return "".join(word.title() for word in string.split("_")) | 08604980ec0d1d0cef4c2722aca0098ff270d27c | 581,222 |
import math
def percentile(values, percent, key=lambda x: x):
"""
Find the percentile of a list of values.
Params:
values (list): Sorted list of values.
percent (float): A value from 0.0 to 1.0.
key (function): Optional key function to compute value from each value on list.
R... | e8caf3f03cec71d9c2f07ad71731c3d3db65ee65 | 581,224 |
def cmd_succeeded(output, ignored_outputs=None):
"""Check if the given output contains an error.
Most commonly a succeeded command will return an empty string. However, some
commands even though have succeeded return an informative message to the
caller. This helper function checks the status of a give... | ce2a9b77ddb061d0d491771e16860dc7b3036d10 | 581,232 |
def split_ids(ids, existing=None):
"""Split the child or parent ID fields from the MAG FoS ORM.
Args:
ids (str): Comma-delimited string of ids
existing (set): Only return IDs found in this set.
Returns:
ids (set): A set of ids split out of the input.
"""
if ids is None:
... | 9fe1298a54bce9d0af634248840ccb7ab25f5c22 | 581,233 |
def evaluate_accuracy(tp: int, tn: int, fp: int, fn: int) -> float:
"""Accuracy (ACC).
$ACC=\dfrac{TP + TN}{TP + TN + FP + FN}$
Args:
tp: True Positives
tn: True Negatives
fp: False Positives
fn: False Negatives
"""
try:
return (tp + tn) / (tp + tn + fp + fn... | 8f5d6dbdd9454e2b1754b5e9efc7ec849ad45724 | 581,236 |
def hinted_tuple_hook(obj):
"""
This hook can be passed to json.load* as a object_hook. Assuming the incoming
JSON string is from the MultiDimensionalArrayEncoder, tuples are marked
and then reconstructed into tuples from dictionaries.
Args:
obj (object): Object to be parsed
Returns:
... | 35b0cd13e574cce0a75e59f52267a26374fa7ab7 | 581,237 |
def check_singlefile_content_with_store(check_singlefile_content): # pylint: disable=redefined-outer-name
"""Fixture to check the content of a SinglefileData before and after .store().
Checks the content of a SinglefileData node against the given reference
content and filename twice, before and after call... | 51b77663447f33bbb5f8a3f0d3ead009ad2485c1 | 581,238 |
from typing import Tuple
def swap(things: Tuple[int, int]) -> Tuple[int, int]:
"""
Swaps its arguments.
"""
return (things[1], things[0]) | 8cf6a3ea908931220e03bea9e9bf6484280949ab | 581,240 |
def round_if_near_integer(a, epsilon=1e-4):
"""
Round a to the nearest integer if that integer is within an epsilon
of a.
"""
if abs(a - round(a)) <= epsilon:
return round(a)
else:
return a | db30fe7e340366b420f4578199ebfa95d120e319 | 581,243 |
def get_target_os_arch(conanfile):
""" Returns the value for the 'os' and 'arch' settings for the target context """
if hasattr(conanfile, 'settings_target'):
settings_target = conanfile.settings_target
if settings_target is not None:
return settings_target.get_safe('os'), settings_t... | c32495c89d7f26ffcdd98b958c0e966cef333485 | 581,244 |
def nth_from_last(lst, n):
"""
Given a linked list and n, find the nth element from the
end of the list.
"""
if n<0:
raise ValueError("Negative values for n not allowed!")
curr = lst
result = lst
i = 0
while curr.next is not None:
curr = curr.next
if i >= n:
... | a51884b16cd65c2cd04190f0ebcd38a7dff56a15 | 581,247 |
import _lzma
import _pickle
def unpickle(filename):
"""Load an object from a .xz compressed pickle file."""
with _lzma.open(filename, "rb") as file:
return _pickle.load(file) | 940a7cd5c552f8296d28f4a9d7327c404b0d4b2d | 581,248 |
def trace_object_dict(nobj, traces, object=None, background=None, params=None, tracelist=None):
""" Creates a list of dictionaries, which contain the object traces in each slit
Parameters
----------
nobj : int
Number of objects in this slit
traces : numpy ndarray
the trace of each objec... | de58abd60c4ee86a6884461277b1a3ccc998aec2 | 581,249 |
import inspect
def add_stage_arguments(cls):
"""Adds the arguments specified in a class's ARGS entry to its docstring."""
if cls.__doc__ is None:
cls.__doc__ = ''
lines = inspect.cleandoc(cls.__doc__).splitlines()
# have only one blank line before args
while lines and (not lines[-1] or l... | 6193429204c707906a5a628403d946a4d00c5f4c | 581,253 |
def cost_speed(vehicle_info, predictions, trajectory):
""" Computes cost of driving at a given speed.
Args:
vehicle_info: A VehicleInfo tuple.
predictions: A dict of predictions for vehicles.
trajectory: A Trajectory tuple.
Returns:
A cost in [0, 1].
"""
# Cost of... | 5c926e999e2a969d01d3807802d0b494be15bf3f | 581,259 |
def Drop(x, **unused_kwargs):
"""Drops one element."""
del x # Just for the compiler.
return () | 0dfb948270351f0f36d99c3748a0d64efd5845c5 | 581,261 |
def table_exists(table_name, curr):
"""Checks whether a table with name 'table_name' exists in the database.
Parameters
----------
table_name: string
Name of the postgresql table to be checked.
curr: database cursor
Returns
-------
result: boolean
Returns True if the ta... | e8e6e5778740a36d1ae05d847be3495ee13cd295 | 581,265 |
def ask(question, options, default):
"""
Ask the user a question with a list of allowed answers (like yes or no).
The user is presented with a question and asked to select an answer from
the given options list. The default will be returned if the user enters
nothing. The user is asked to repeat his... | baf3e9e00b01573921e94bd7c508ee7fb0381392 | 581,268 |
def isUnmarked(s):
"""If string s is unmarked returns True otherwise False.
"""
if len(s) > 0: return s[0] != '*'
else: return False | 447d01212f86567359a12c24b4b3472b330eafa1 | 581,269 |
from typing import Any
import importlib
def resolve_dotted_path(path: str) -> Any:
"""
Retrieves attribute (var, function, class, etc.) from module by dotted path.
.. code-block:: python
from datetime.datetime import utcnow as default_utcnow
utcnow = resolve_dotted_path('datetime.datetim... | 7fa2439bff33124ae7ff77016068a7f259f7a586 | 581,271 |
def get_regex(value):
"""Returns regex string based on main parameter"""
return r'({}:\s*)(.+\S)'.format(value) | a3df732852b6f6b055d9be986fceed65b0e9b777 | 581,279 |
import unicodedata
import codecs
def validate_ae_title(ae_title):
"""Return a valid AE title from `ae_title`, if possible.
An AE title:
* Must be no more than 16 characters
* Leading and trailing spaces are not significant
* The characters should belong to the Default Character Repertoire
... | 9ff7147892f31859be9803cf41ce63b585137ec2 | 581,280 |
def are_pairwise_disjoint(it, raise_error=False):
"""
Determines whether a collection of elements are pairwise disjoint.
:param it: iterable of elements
:param raise_error: if a (descriptive) error shall be raised in case the
elements iterables are not disjoint
:return: true if all elements are... | 4e48f51434ef8508e59571ed03c5d96f226cc9d8 | 581,281 |
def remove_call_brackets(call: str):
"""Return the given string with the trailing `()` removed, if present.
NOTE Made redundant by `str.removesuffix("()")` in Python 3.9+
"""
if call.endswith("()"):
return call[:-2]
return call | 00cee2e371b3edc9db208155df10e42cf78c796e | 581,284 |
def crop_center(img,cropx,cropy):
"""
Central cropping of array
Params:
img : np.ndarray
Image to be centrally cropped
cropx : int
x size of cropping
Returns: cropped image (np.ndarray)
"""
y,x = img.shape
startx = x//2-(cro... | 785a91a10348f00fd2a204153813cb0aedea14b6 | 581,289 |
def write_to_pandas(da,
column_dict={},
name='name'):
"""Write xr.DataArray to pd.DataFrame
Parameters
----------
da: xr.DaraArray
column_dict: dict (optional)
Dictionary containing new pd.DataFrame column names and corresponding values
... | b1ca6b17db7e4b7b261102a1f50d4d6adae3c735 | 581,290 |
def hz2bark(freq):
"""
Function hz2bark calculates Bark scale.
Use Traunmueller-formula for f > 200 Hz
Linear mapping for f <= 200 Hz
@param freq: Frequency.
@returns: Corresponding Bark scale for given frequency.
"""
z_less_200 = freq / 102.9
z_greater_200 = 26.81... | 92f6dc081f131637bc330eccbdea72562da69f10 | 581,295 |
def strided_subset(sequence, count):
"""Returns a strided subset of a list."""
if count:
stride = max(1, len(sequence) // count)
return sequence[::stride]
return sequence | 0c5f4ecc61586688547afaa858bbaf4bcb95af73 | 581,299 |
def feature_importance(clf, feature_names):
"""
Give sorted features according to their importance in the classification
Parameters
----------
clf : sklearn estimator
fitted classifier with attribute "feature_importances_"
feature_names: str
name of the features ... | 31e2c2f6292afc98e3b4229cacb60c2556c260b8 | 581,300 |
def symbols(x: int) -> int:
"""
Returns length of int in symbols
:param x:
:return: int
"""
if x == 0:
return 1
s = 0
if x < 0:
s = 1
while x != 0:
x = x // 10
s += 1
return s | daf0127b61e2719a41bb023b21de481448168145 | 581,302 |
import logging
def get_object_contents(client, bucket, key):
"""Read the specified file from the object store and return its contents.
Parameters:
client: str, the boto3 client object
bucket: str, target bucket location
key: str, target filename with prefix
Returns:
Conte... | 31ea723473c9062e4b674dd64e291c75e17c8641 | 581,306 |
def list_to_string(l):
"""
e.g. [1, 2, 4] --> '124'
"""
return ''.join(list(map(str, l))) | f4677a5f6649048526e016f4f9f96d1fb0b28082 | 581,307 |
def is_comp_node(graph, node):
"""Returns True for Component or PseudoComponent nodes."""
return 'comp' in graph.node.get(node, '') | 2f6abcb41a54b07a4a6cb1de4637db3d0ac7fa07 | 581,315 |
def is_num(text):
"""Check if text can be parsed as a number."""
try:
float(text)
except:
return False
else:
return True | 6c396d8802e6a25d95445ae789fdb8d00111a81f | 581,316 |
def inmon_http_method(
method_int # type: int
):
"""Parse InMon-defined HTTP method numbers"""
if method_int == 0:
return "Other"
elif method_int == 1:
return "Options"
elif method_int == 2:
return "Get"
elif method_int == 3:
return "Head"
elif method_int == 4:
return "Post"
elif method_int == 5:
r... | f677eaf5ad3321abf4cde911e6b57336f3180340 | 581,317 |
def to_byte_array(string: str) -> bytearray:
"""
convert a string into a byte list. Skip all characters that are not in the range
of ISO/IEC 8859-1 character set to avoid undefined behavior
According to PEP3333, "Native" strings (which are always implemented using the type named str)
that are used ... | 75434454388d798051568fbb596b0abd0d6c4859 | 581,319 |
def cut_and_padding(seq, max_len, pad=0):
"""
cut or pad the sequence to fixed size
Args:
seq: sequence
max_len: the fixed size specified
pad: symbol to pad
Returns:
fixed size sequence
"""
if len(seq) >= max_len:
return seq[:max_len]
else:
... | 4296e72562c701335e30f0bcfaf00870c8cf6271 | 581,322 |
def isolates(G):
"""Return list of isolates in the graph.
Isolates are nodes with no neighbors (degree zero).
Parameters
----------
G : graph
A networkx graph
Returns
-------
isolates : list
List of isolate nodes.
Examples
--------
>>> G = nx.Graph()
... | 16ef5e78e891474b96e0d3ba0e3765ec4a13a0a7 | 581,323 |
def slug(value):
"""
Slugify (lower case, replace spaces with dashes) a given value.
:param value: value to be slugified
:return: slugified value
ex: {{ "Abc deF" | slug }} should generate abc-def
"""
return value.lower().replace(' ', '-') | 2dbd51d92a0941c6c9b41fc6f9e56eb19b4b8f46 | 581,324 |
def _user_can_manage_leaders(user, group_profile):
"""Can the given user add and remove leaders?"""
# Limit to users with the change_groupprofile permission
return user.has_perm("groups.change_groupprofile") | c4252e1ac21015372c47ce137a9cb5bdeaf7e5d5 | 581,326 |
from typing import Counter
def DurfeeSquare_metric(bpmn_graph):
"""
Returns the value of the Durfee Square metric
("Durfee Square equals d if there are d types of elements
which occur at least d times in the model (each),
and the other types of elements occur no more than d times (each)")
... | dc661552e433bfa276d929fa1dbc70c9e0ba9400 | 581,328 |
def event_to_json(event):
"""
Converts an event class to its dictionary representation.
Underlying eventsourcing library does not provide a proper event->dict conversion function.
Note: Similarly to event journal persistence flow, this method supports native JSON types only.
"""
return vars(eve... | ab9fa918f15abb0a8f18ab3bae576b0a2588cef8 | 581,329 |
def getminmax(coords):
"""
Given an iterable of (x, y), return minx, miny, maxx, maxy.
"""
i = iter(coords)
try:
x, y = i.next()
minx = maxx = x
miny = maxy = y
except StopIteration:
return None, None, None, None
for x, y in i:
if x < minx:
... | 451b9041612d1f5ad4de41b335d7fb15d8fee386 | 581,330 |
import re
def nanopb_rename_delete(lines):
"""Renames a delete symbol to delete_.
If a proto uses a field named 'delete', nanopb happily uses that in the
message definition. Works fine for C; not so much for C++.
Args:
lines: The lines to fix.
Returns:
The lines, fixed.
"""
delete_keyword = r... | 55a4d629232c0744116b21234157910868b60797 | 581,331 |
def suppress_none(value):
""" Returns empty string for none, otherwise the passed value """
return value if value else "" | 22b89dcd58b5955c1ba26591f6ddd9812a09460a | 581,334 |
def find_near_node(s, node, offsetresolver, offset=None):
"""
Find the begin and end position of string S if it exists on the same line as NODE
"""
line = offsetresolver.lines[node.lineno-1]
if not offset:
offset = offsetresolver.nodeoffset(node)
begin = offsetresolver.src.index(s, offse... | 10de0452621cede7cfd9f03a990e824ef292bcb0 | 581,348 |
def get_userlink(data):
""" Creates markdown-styled userlink from data """
username = data.get('sender').get('login')
userurl = data.get('sender').get('html_url')
return "[{}]({})".format(username, userurl) | f6bb2c5ec526aa4327020565ed6588c44c71b503 | 581,349 |
def split_in_half(keys_56bits):
""" Split the 56 bits key into two equal half """
left_keys, right_keys = keys_56bits[:28], keys_56bits[28:]
return left_keys, right_keys | 80df999c10be557af91f9687cdb04a3bda4df228 | 581,353 |
def mask_by( var, maskvar, lo=None, hi=None ):
"""masks a variable var to be missing except where maskvar>=lo and maskvar<=hi. That is,
the missing-data mask is True where maskvar<lo or maskvar>hi or where it was True on input.
For lo and hi, None means to omit the constrint, i.e. lo=-infinity or hi=infini... | 4aa3d3eb1b63b78f6ac415dcf6b23f7745bb813e | 581,363 |
from typing import Tuple
import math
def get_bicubic_params(cubic_filter: str) -> Tuple[float, float]:
"""Return the parameter b and c for the bicubic filter
Source: https://www.imagemagick.org/discourse-server/viewtopic.php?f=22&t=19823
https://www.imagemagick.org/Usage/filter/#mitchell
... | 8bd8161f536096d029071255e68cf79c58a74a70 | 581,374 |
import warnings
import math
def modified_arr_k(T, params, R=8.314):
"""Returns the value of k determined by the Arrhenius rate.
INPUTS
=======
T: float
Temperature in a Kelvin scale
params: list, length = 3
params[0]: A
params[1]: b
params[2]: E
R: float, optio... | 35cf522c9371a34cddc4df5e6518dd9d777e8685 | 581,375 |
def IN(attribute, val):
"""
Check if the value contains the attribute
"""
return attribute in val | 90bf4bb721e198d86758ff90ad6dff9399f0fc1c | 581,377 |
def duration(time):
"""Convert seconds to HH:MM:SS"""
time = int(time)
hours = time // 3600
mins = time % 3600 // 60
secs = time % 60
if len(str(hours)) == 1 and hours != 0:
hours = f"0{hours}"
if len(str(mins)) == 1:
mins = f"0{mins}"
if len(str(secs)) == 1:
secs... | 2e9a3eee2dbf39b01ac64fd81c2de809823459bc | 581,379 |
import hashlib
def calc_hash(s3_object, chunk_size=1024 * 1024):
"""Calculate md5 and sha256 hash for an object chunk by chunk."""
md5_hash = hashlib.md5()
sha_hash = hashlib.sha256()
chunk = s3_object.read(chunk_size)
while chunk:
md5_hash.update(chunk)
sha_hash.update(chunk)
... | 048d053b26aba5b946ff3aa4b6a40d5894e576f3 | 581,382 |
def mody_list(x):
"""Take a list and print as a string with commas and 'and' before the last word ."""
i = 0
new = ''
while i < len(x)-2:
new = (new + str(x[i]) + ', ')
i = i + 1
new = (new + str(x[-2]) + ' and ' + str(x[-1]))
return new | d7bccddd08874bfd24b05e7a457b5e878e203031 | 581,383 |
import re
def author_id_strip_dashes(author_id):
"""
Given an author id of the form {service}/author/{uuid},
safely convert the uuid of form xxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxxxxxxx to one without dashes
"""
author_dash_free = author_id.split('/')
author_dash_free[-1] = re.sub('-', '', author_das... | f74d750ed85e6461bfac328baebedb99f76a7430 | 581,384 |
def not_in_abbreviations(abbreviations):
"""Constraint returns True only if the course is not in any of the given department abbreviations."""
def satisfies(course):
return course.abbreviation not in abbreviations
return satisfies | 17cf036560b1f87eaa0499bcb35e4313561e5d98 | 581,387 |
def get_words(utterance):
"""Splits an utterance into words, removes some characters not available in spoken dialogue systems,
uppercases the text.
:param utterance: a string
:return: a list of string (words)
"""
for c in '?!.,':
utterance = utterance.replace(c, ' ').replace(' ', ' ')
... | 5998d0fb2baa3dbb0ae14c87d57d998b07802419 | 581,388 |
import re
def NormalizeErrorMarker(output):
"""Normalizes the error marker, which is different on Windows vs on Linux."""
return re.sub(r' error: ', ' Failure\n', output) | 1a3a41634bbadd69d0780694b0d6876aa5a5f6f4 | 581,393 |
from typing import Dict
def _get_env_hyperparameters() -> Dict[str, str]:
"""Gets the env variable for hyperparameters. This should only be added if the customer has
provided hyperpameters to the job.
Returns:
(Dict[str, str]): The set of key/value pairs that should be added as environment variab... | 17f05e74796217fc0f58c593ad0f60602e7aef56 | 581,394 |
import requests
import math
def is_ok(url: str) -> bool:
"""
Returns True if the provided URL responds with a 2XX when fetched via
a HTTP GET request.
"""
try:
resp = requests.get(url)
except:
return False
return True if math.floor(resp.status_code / 100) == 2 else False | 9287f7342d01ab368be6cb20ddc2d7bb26d58af9 | 581,395 |
from re import finditer
def verbose_name(form_class):
"""returns the verbose_name property of a Meta class if present or else
splits the camel-cased form class name"""
if hasattr(form_class, "Meta") and hasattr(form_class.Meta, "verbose_name"):
return getattr(form_class.Meta, "verbose_name") # no... | 7b14d528782d470fe4ada091b2cd87f24108aabf | 581,396 |
def _reverse(lst):
"""Return the reverse of lst without mutating lst"""
nlst = lst.copy()
nlst.reverse()
return nlst | 10017b0a2c0475d8dc1a791ce11622dc159f41d8 | 581,401 |
import requests
import json
def get_git_releases_json(url, params={}):
""" Gets the JSON release information from github. """
response = requests.get(url=url, params=params)
data = json.loads(response.text)
# pprint.pprint(data)
return data | 4d6f7c80519bb02c7e924477b09a3d64efda30a0 | 581,404 |
import string
def normalize(sent):
"""
Noktalama işretlerini kaldıran fonksiyon
:param sent: Tokenleştirilmiş sözcük listesi
:return: liste
"""
tokens_without_punct = [''.join(c for c in s if c not in string.punctuation) for s in sent] # removes punct
tokens_without_punct_spaces = [s for... | 505901eaacaf7909e757a6065464a8e193236739 | 581,405 |
def get_attack_type(action: int, game_config) -> int:
"""
Utility method for getting the attack type of action-id
:param action: action-id
:param game_config: game configuration
:return: action type
"""
if not game_config.reconnaissance_actions:
attack_defense_type = action % game_c... | bc61214cc98de776626b172fe42c3a1a42696583 | 581,407 |
from datetime import datetime
def fill_with_now(timestamps: list[datetime]) -> list[datetime]:
"""fills a list of datetime objects with the current time if the list is not
complete.
to know if the list is complete, we check if the number of elements is even.
Args:
timestamps (list[datetime]):... | 23c8b7b0d6576041578f8231320db17c367d8a24 | 581,408 |
def get_offer_poster_name(html_parser):
"""
This method returns the poster's name (and surname if available).
:param html_parser: a BeautifulSoup object
:rtype: string
:return: The poster's name
"""
element = html_parser.find(class_="box-person-name") or html_parser.find(class_="seller-box_... | a9e79a23bfe869fa15a7e690cd0a6887d085809d | 581,410 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.