content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def match_client(project_data, client_name):
"""
Given a project's json data, sees if the client name matches
"""
if client_name is None:
client_name = ""
if "clientName" in project_data and project_data["clientName"] == client_name:
return True
return False | 21e142a6994738d02b306177cfc7a9563be2edfa | 589,065 |
def clean_version(version):
"""Clean version name (usually a branch name) so it can be used as a
tag name for a Docker image."""
return version.replace("/", "_").replace("-", "_") | 68f89fefe8382883316543bee2c5465850633208 | 589,066 |
def encontrarMediana(lista):
"""Função que encontra a mediana de uma lista de valores.
INPUT:
lista: lista de valores númericos
ex: { 270, 310, 702}
OUTPUT:
median_trip: valor calculado da mediana, valor do centro da lista ordenada, do menor para maior
ex: 310
"""
lista = sorted(lis... | 3ae8b8a76fc690116d46b90438b3b136d0fd152b | 589,069 |
def ts2sec(ts):
""" Convert timestamp to seconds """
return ts * 1e-9 | 7e55b63ae57296b93441e10f3f16b771a1354bd2 | 589,070 |
def join_tags(tags: list) -> str:
"""Generate String Tag with Array of Tags
Args:
tags (list): Array of Tags
Returns:
str: String of Tags
"""
tagString = f'#{" #".join(tags)}'
return tagString | a34720cd4f922e42346aabcf2d1e798ddc376239 | 589,071 |
def get_last_opening_parenthesis(string):
"""
Returns index of the the parenthesis that opens the last closing parenthesis
For example, in "∀x ∈ f(x) (Px v (Qx v Rx))" will return the index of the parenthesis before Px
"""
num_parentheses_left = 0
num_parentheses_right = 0
for char_index in... | d66581b6530104767ed9bd58251c8429cf21486c | 589,075 |
def _has_at_least_one_translation(row, prefix, langs):
"""
Returns true if the given row has at least one translation.
>> has_at_least_one_translation(
{'default_en': 'Name', 'case_property': 'name'}, 'default', ['en', 'fra']
)
true
>> has_at_least_one_translation(
{'case_proper... | a3d23b4dd2e01ee88240af756bc6a25a467a1ec8 | 589,077 |
def index_closed(client, index_name):
"""
Return `True` if the indicated index is closed.
:arg client: The Elasticsearch client connection
:arg index_name: The index name
:rtype: bool
"""
index_metadata = client.cluster.state(
index=index_name,
metric='metadata',
)
r... | 1a8d8e3730c84497ebac9ab3eb2369e4136a55af | 589,081 |
def eq_10_virtual_origin(D: float, Q_dot_kW: float):
"""Equation 10 in Section 8.3.1 PD 7974-1:2019 calculates virtual fire origin.
:param D: in m, fire diameter.
:param Q_dot_kW: in kW, fire heat release rate.
:return z_0: in m, fire's virtual origin.
"""
z_0 = -1.02 * D + 0.083 * Q_dot_kW **... | f2b22a21493d0f08be05533a4627f0f95e65541e | 589,083 |
def map_val(val, in_min, in_max, out_min, out_max):
"""
Function based on the map function for the arduino
https://www.arduino.cc/reference/en/language/functions/math/map/
"""
return (val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min | f4caed41e549387966e36904545a5bd18001740c | 589,088 |
def run_cqm_and_collect_solutions(cqm, sampler):
"""Send the CQM to the sampler and return the best sample found.
Args:
cqm (ConstrainedQuadraticModel): The CQM for our problem
sampler: The CQM sampler to be used. Must have sample_cqm function.
Returns:
dict: The first feasible ... | 6719c67cd2cadd12b1dfb1f898144c3e738cf0f4 | 589,089 |
import pickle
def read_pickle(file_name=None):
"""
Read a pickle file and return the dictionary
:param file_name:
:return: dictionary
"""
if file_name is not None:
loaded_file = open(file_name, "rb")
features = pickle.load(loaded_file, encoding="UTF8")
return features
... | adc5bb46f6c9a500a68ee651cdc3d47479ef4914 | 589,090 |
import six
def indent(text, prefix):
"""
Indent text or a number of text lines (with newline).
:param lines: Text lines to indent (as string or list of strings).
:param prefix: Line prefix to use (as string).
:return: Indented text (as unicode string).
"""
lines = text
newline = u""
... | c922a11dfe191fc6da62bfa95d732241df7c339f | 589,092 |
from typing import Optional
from typing import Dict
def rect(x0: float, y0: float, x1: float, y1: float,
xref: str = "x",
yref: str = "y",
fill_col: str = "grey",
opacity: float = 1.,
frame_width: float = 0,
frame_col: Optional[str] = None,
layer: str = "... | 953934e3dbc6ca1d2c28ad4a14d1e483b1fe124e | 589,097 |
import shlex
def repr_command(argv):
"""Represent an argument array as a string.
Args:
argv: The arguments of the command.
Returns:
A string which could be pasted into a shell for execution.
"""
return ' '.join(shlex.quote(str(arg)) for arg in argv) | 23406785a208d35db8730345e8fa4074e854d3ad | 589,102 |
def get_job_name(job: dict) -> str:
"""Create a job name. Defaults to group name, then rule plus wildcards."""
if job.get("type", "") == "group":
groupid = job.get("groupid", "group")
jobid = job.get("jobid", "").split("-")[0]
jobname = "{groupid}_{jobid}".format(groupid=groupid, jobid=j... | e11f66f4dab76166b39ef3dd71cfca648c12ec36 | 589,103 |
import re
def active(request, pattern):
"""Return 'active-nav' string when pattern matches request's full path."""
if re.match(pattern, request.get_full_path()):
return 'active-nav'
return None | c8f6f247b7c0e78380a6d7e92f80246128947cc6 | 589,115 |
def get_yearweek(yearweekstr: str) -> tuple:
"""Transform string of form '2020-W10' into tuple (2020, 10)
"""
return tuple(map(int, yearweekstr.split('-W'))) | d8a4753d126e12709f41e1058753fd06762c765f | 589,116 |
def get_action_text(action):
"""
Get a text respresentation of the Action
:param action: Model, Action model instance
:returns: String, text description of an Activity Action
"""
context = {
'actor': action.actor,
'verb': action.verb,
'action': action.action,
'tar... | 5cf61462137af9d2beca4e75f7e02296d5a915e8 | 589,120 |
def getattr_dunder(obj, attr):
"""Gets attribute of object. Works recursively
if attr contains double underscores."""
first, dunder, rest = attr.partition('__')
value = getattr(obj, first)
if rest:
return getattr_dunder(value, rest)
return value | f5f2cf21ffbe49ea296c3f25cf9f20515f6db531 | 589,122 |
def licenses(markdown_links=False):
"""
Returns all of the licenses for drop-mod's dependencies.
"""
license_list = [
{
"name": "Drop",
"license": "Apache 2.0",
"link": "https://github.com/AtlasC0R3/drop-moderation/blob/master/LICENSE",
"changes": ... | ea52c59ee7b3c12d57c3babae0711592518878e6 | 589,125 |
import hashlib
def hash_password(password: str) -> str:
"""Take password input, hash, convert to text and make upper case"""
return hashlib.sha1(password.encode()).hexdigest().upper() | 42bc55cdbd572fd3c1f4cce63b072a0bce520a11 | 589,127 |
def select_n_subjects(df, n):
""" Returns the first n subjects from df.
:param df Dataframe with responses
:param n Number of subjects to select
:return: dataframe with selected subjects.
"""
#get ordered number of subjects
subj_ids = sorted(list(set(df["sub"])))
selected = s... | d38411b63b25fa47cb248a69ffdf370bd2a099a1 | 589,131 |
def mpl_color(plotly_color):
"""
Convert a plotly color name to a matplotlib compatible one.
Parameters
----------
plotly_color : str
A plotly color value, e.g. `"#FF0023"` or `"rgb(0,255,128)"`.
Returns
-------
str
"""
plotly_color = plotly_color.strip() # remove any ... | 6979e6914560ed5810c947e61d228e9d8bbca70f | 589,137 |
def get_metric_params(metrics):
"""Gets public parameters for a list of metric instances.
Args:
metrics: A list of metric instances.
Returns:
Dictionary of metric parameters {metric_name: dict of params for metric}.
Each entry is also a dictionary {metric_param: param_value}.
"""
metric_params =... | 6def0eba814985a651688f7b9784f60492577a68 | 589,140 |
import json
import requests
def validate_private_contribution(contribution_id,username="",password="",verbose=True):
"""
validate private contribution in MagIC
Parameters
----------
contribution_id: int
ID of MagIC contribution to delete
username : str
personal username for Ma... | 00d785cd1b9b5954201d8650fde534abb5dc5ac7 | 589,141 |
import re
def find_verses(message_body):
""" Uses regex to search comment body for verse quotations. Returns
a list of matches if found, None otherwise. """
regex = (r"(?<=\[)(?P<book>[\d\w\s]+)\s(?P<chapter>\d+)\:?(?P<verse>\d+"
r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])")
matches... | 0238cb42043979d8f673cbb66aaecdd3383677d4 | 589,148 |
import re
def parseClockTimeTag(tag):
"""
Parses 'WhiteClock'/'BlackClock' PGN headers and returns the time the
player playing that color has left on their clock in milliseconds
"""
match = re.match("(\d{1,2}):(\d\d):(\d\d).(\d{1,3})", tag)
if match:
hour, minute, sec, msec = match.gro... | 56b3f079ea63ff641a8683b072ebbea3089bb784 | 589,151 |
import torch
def flipfb(tensor):
"""
Flips a given tensor along the third dimension (front to back)
Parameters
----------
tensor
a tensor at least three-dimensional
Returns
-------
Tensor
the flipped tensor
"""
return torch.flip(tensor, dims=[2]) | b29f0838c5ffcd2d3bde985d7c3a4531d2f508f1 | 589,158 |
def _CalcThroughput(samples):
"""Calculates the throughput in MiB/second.
@type samples: sequence
@param samples: List of samples, each consisting of a (timestamp, mbytes)
tuple
@rtype: float or None
@return: Throughput in MiB/second
"""
if len(samples) < 2:
# Can't calculate throu... | 0f7c973532833ab75ac41fec85c1f7f80983447b | 589,160 |
def get_D(uv_hat, n_channels):
"""Compute the rank 1 dictionary associated with the given uv
Parameter
---------
uv: array (n_atoms, n_channels + n_times_atom)
n_channels: int
number of channels in the original multivariate series
Return
------
D: array (n_atoms, n_channels, n_... | 0c6518d119ace13179d86a1f7ff832245c4501c5 | 589,161 |
import re
def edit_dist_func(value):
"""Edit function expression to be latex and plot readable.
Args:
value (str): the distribution function expressed as a string.
ex: "(-0.8696 + 2.087*math.exp((x)*0.0031))*3.1236056887012746e-06"
Returns:
a tuple containing
- latex... | 2f784d3c8119e1dea620e869c0b9f63d6b3fe75d | 589,162 |
from datetime import datetime
def get_date_string_from_ts(ts: datetime) -> str:
"""Returns the string of a given date"""
return datetime.strftime(ts, "%Y-%m-%d") | abbcf5ec546af2c3177eac01b0fb6a9517885f90 | 589,163 |
def list2lookup(lst):
"""
Create a dict where each key is lst[i] and value is i.
"""
return dict((elm, i) for i, elm in enumerate(lst)) | 332f5ffaa5189f364f7fa5f6109fa86d2b496a7a | 589,164 |
import functools
def _wrap_function(func):
"""Wraps a function with a wrapper that discards a single arguments.
This is to allow functions to be used as methods similarly to using
staticmethod, but still contain a reference to the class and return True for
inspect.ismethod calls.
Args:
func: A functio... | 9bb229a4b411a02365fd6fdcbcc709ae86c2939a | 589,165 |
def for_loop(function, argument_list):
"""Apply a multivariate function to a list of arguments in a serial fashion.
Uses Python's built-in for statement.
Args:
function: A callable object that accepts more than one argument
argument_list: An iterable object of input argument collections
... | c3215459c48e5bd7610ff833ebe55eb83c0d8c29 | 589,168 |
def get_best_so_far(db, datarun_id):
"""
Get a series representing best-so-far performance for datarun_id.
"""
# generate a list of the "best so far" score after each classifier was
# computed (in chronological order)
classifiers = db.get_classifiers(datarun_id=datarun_id)
y = []
for l i... | 5ba72f3594c8f4898c8abe461a2e3300722279e5 | 589,175 |
def difference_lists(stat_list1, stat_list2):
"""Returns the values that are in the first list and aren't in the second"""
return list(set(stat_list1) - set(stat_list2)) | fb1baa698ba340d118d5e19a7a013a40b961c30c | 589,180 |
def __create_code_block(message):
"""Create a code block"""
return f"```\n{message}```" | 6acd3a0d5bebb0305ad0c48c91bfe6ad85608c44 | 589,182 |
def _has_unicode_fields(array):
"""
Returns True if any fields in a structured array have Unicode dtype.
"""
dtypes = (d[0] for d in array.dtype.fields.values())
return any(d.kind == 'U' for d in dtypes) | 4d9746a78dcb7bd9fc2963527b0925453a628670 | 589,183 |
def GetListOfFeatureSizes(feature_sizes):
"""Extract the list of the dimensionality of each feature
from string of comma separated values.
Args:
feature_sizes: string containing comma separated list of feature sizes
Returns:
List of the dimensionality of each feature.
Elements in the first list... | d5c724834d3667535bc001e9699e34b3033bb91b | 589,186 |
def header_names(hdr_tuples):
"""
Given a list of header tuples, return the set of the header names seen.
"""
return set([n.lower() for n, v in hdr_tuples]) | 0ab503296d4ee8c2f36e02f57d11a2083a369019 | 589,188 |
def is_comparable(q1, q2):
"""
True if q1 and q2 have identical keys
"""
return set(q1['options'].keys()) == set(q2['options'].keys()) | b703feddb4886d5e67ed14c2a663362415d6ebbb | 589,198 |
def to_dict(obj):
"""Convert a dictionary-like object to a dictionary.
>>> to_dict({'key': 42})
{'key': 42}
>>> to_dict("key=42")
{'key': '42'}
>>> to_dict("key")
{'key': None}
>>> to_dict(None)
{}
"""
if isinstance(obj, dict):
return obj
elif isinstance(obj,... | 72803210fdbe45c5360887329f3317eb1d8ef566 | 589,200 |
def create_sentences_out_of_dataframe(data):
"""
Create sentences out of a dataframe of tagged data containing the columns "Words" and "Tags"
:param data: (pandas DataFrame) where the first element of each line corresponds to a word,
where ### is the end of a sentence word, and where the second element ... | 2d428bdda22b79883e2dc76863c60a7aedafee12 | 589,201 |
from typing import Tuple
def _parse_broker(broker: str) -> Tuple[str, int]:
"""Parse a host:port string and return its components."""
errmsg: str = "bad broker; use host:port"
host, *port_list = broker.split(':')
if not host:
raise Exception(errmsg)
if not port_list:
return (hos... | 2207a0303b7502a9f70f27be59b2c14b753abbd8 | 589,206 |
import functools
def with_lock(lock):
"""Make sure the lock is held while in this function."""
def decorator(func):
@functools.wraps(func)
def _with_lock(*args, **kwargs):
with lock:
return func(*args, **kwargs)
return _with_lock
return decorator | 39df1d16b7572f1114bf964a32e0bfe90133912d | 589,208 |
def round_to_integer(matrix, offset = 128):
"""returns 2D array with each element rounded to intergers"""
intensity = []
for i in range(len(matrix)):
# Iterate through each row
row = []
for j in range(len(matrix[0])):
# Iterate through each element in r... | 2326f452672b4b19ed4fa5442a93074876ad210d | 589,209 |
def scoreEvaluationFunction(currentGameState):
"""
This default evaluation function just returns the score of the state.
The score is the same one displayed in the Pacman GUI.
This evaluation function is meant for use with adversarial search agents
(not reflex agents).
"""
return current... | bbae8f61114c009183755d4c3c1af3328aea36e8 | 589,217 |
def get_prefix_stripper(strip_prefix):
""" Return function to strip `strip_prefix` prefix from string if present
Parameters
----------
prefix : str
Prefix to strip from the beginning of string if present
Returns
-------
stripper : func
function such that ``stripper(a_string... | bf3a3ecb1c9048e3396a96c116d3a44578df0b8c | 589,219 |
def is_solution(cell):
"""Returns True if the cell is a solution cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('solution', False) | 46eb301b607722c10d569553b10d0c5c87b741ab | 589,223 |
def check_description(description, check_term=' and '):
"""
Check if the first argument contains the 2nd argument
:param description: str
:param check_term: str
:return: bool
"""
if description.find(check_term) >= 0:
return True
return False | 9a7de313b16d14cf5a1bcb7623b820301bd38eb8 | 589,226 |
def create_display_name(field):
"""
Given a string, creates the suitable "default" display name: replace
underscores with spaces, and capitalize each word.
:return: the converted string
"""
return ' '.join(_.capitalize() for _ in field.split('_')) | 3f1eeb0a23ead6b649147f72994f449b615b3fc0 | 589,228 |
from typing import Union
def all_lower(o: Union[str, tuple, list, set, dict]) -> Union[str, tuple, list, set, dict]:
"""
Lower the letter cases of all elements in ``obj``.
Will **NOT** modify the ``o`` itself.
Do the following corresponding to its type:
:class:`str`
> return the lower c... | 1970172333879ee6dfa3b6abffc5741f42023049 | 589,229 |
import pkg_resources
def get_user_agent_default(pkg_name='cloudaux'):
"""
Get default User Agent String.
Try to import pkg_name to get an accurate version number.
return: string
"""
version = '0.0.1'
try:
version = pkg_resources.get_distribution(pkg_name).version
except ... | d792c9b8a78da401ad569d47c23304f770b9df39 | 589,230 |
from typing import List
def form_array(msg: str, height: int) -> List[List[str]]:
"""
Form an array of size height x len(msg) containing the message in msg in a zig-zag pattern.
:param msg: the message to use to populate the array
:param height: the height of the array
:return: the array containin... | 2348b6af681898af5e7edeb1f07b34ad29c4083d | 589,236 |
def update_site(site_name, location, rest_client):
""" Update a site.
:param deployment_id: A Cloudify deployment ID or name.
:type deployment_id: str
:param location: The longitude and latitude of the site.
:type location: str
:param rest_client: A Cloudify REST client.
:type rest_client: c... | 48d083db9521c2821231212be972d0f29d2a6914 | 589,239 |
def get_model_root(model):
"""
This function finds the root model for any given model. The root model is
the highest concrete model that it descends from. If the model doesn't
descend from another concrete model then the model is it's own root model so
it is returned.
Examples:
>>> get_mode... | d39756e46a0b0705c51be5f788a5f5226601a726 | 589,241 |
def tile_to_quadkey(z, x, y):
"""Transform tile coordinates to a Bing quadkey.
Slippy map tiles cache numeration starts from 0 level with one tile. On 1 level four tiles etc
Bing uses quadkey tile coordinates, so minimal cache level is 1 (four tiles). Single tile at zero level not addressed.
https://d... | d438360e986bdf317f2e8672a16ebbe40ce12d38 | 589,243 |
def select_k_best(points, descriptors, k):
""" Select the k most probable points (and strip their probability).
points has shape (num_points, 3) where the last coordinate is the probability.
Parameters
----------
points: numpy.ndarray (N,3)
Keypoint vector, consisting of (x,y,probability).
... | fd75025cc97600d29849814b17a05be43cc11457 | 589,246 |
def PyObject_Hash(space, w_obj):
"""
Compute and return the hash value of an object o. On failure, return -1.
This is the equivalent of the Python expression hash(o)."""
return space.int_w(space.hash(w_obj)) | 09ca9f582d19e71324bc0dea27e57d0ac6cd56ab | 589,250 |
def encode_generics(token):
"""Convert a string like IAmGeneric<Foo,Bar> into IAmGeneric<Foo,Bar>."""
return token.strip(",").replace("<", "<").replace(">", ">") | 1a24354dba29e44d1c21813cb603c6669794fdd6 | 589,251 |
from pathlib import Path
def Get_DirectoryOfFilePath(file_path):
"""
Get source directory from file path
:param file_path:File Path
:return:Directory
"""
p = Path(file_path)
return p.parent | f0373e3e316219389eae6d072a2c7b60c9921175 | 589,255 |
import re
import six
def strip_uri_prefix(path):
"""
Remove potential version prefix in URI.
"""
return re.sub(r'^(/v\d+)?', '', six.text_type(path)) | 629c04be71a17916119e7c9a43ce7bea8e89b344 | 589,257 |
def is_sized_intlist_arg(arg):
"""Returns True for arguments declared as IntList[k], but False for IntList."""
return (arg['simple_type'] == 'IntList') and ('size' in arg) | d26224620ff0da6faa0bde6d7cd326e6d4a3cf44 | 589,259 |
from typing import Dict
from typing import Any
from typing import List
async def _async_migrate(entities: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
"""Migrate the YAML config file to storage helper format."""
return {
"entities": [
{"entity_id": entity_id, **info} for entity_id, ... | 7283848e4530205b0460cff7b99f858b08745546 | 589,262 |
import random
import string
import copy
def setParams(params, fuzz):
"""
:Description: This function sets the Fuzz in the POST Parameter.
:param url: Target URL
:type type: String
:param fuzz: Fuzzing string
:type fuzz: String
:return: The post parameter ... | e2121a24ac7b0c197f1cb3f629feadb04d118153 | 589,264 |
def max_num_decims(num1, num2):
"""
Given two numbers 'num1' and 'num2', returns
the maximum number of decimals found in them.
"""
num_max_decs = 0
if ("." in num1) or ("." in num2):
if ("." in num1) and ("." not in num2):
num1A, ... | 43107b49af9fdf1dd97b13fd0d2ff860333deece | 589,265 |
def _SubtractMemoryStats(end_memory_stats, start_memory_stats):
"""Computes the difference in memory usage stats.
Each of the two stats arguments is a dict with the following format:
{'Browser': {metric: value, ...},
'Renderer': {metric: value, ...},
'Gpu': {metric: value, ...},
'Process... | bcb8a17bacc4b2136e568d314661bdb62bc2fb7d | 589,267 |
import dill
def run_dill_encoded(what):
"""
Run a function that's been encoded with Dill (this allows me to do multiprocessing).
http://stackoverflow.com/a/24673524
"""
fun, args = dill.loads(what)
return fun(*args) | 70e5ccd8fa8e2b369cb45f80993bb6196287fc28 | 589,271 |
def get_line_params(x0, y0, x1, y1, norm=False):
"""
Return A,B,C where the line from (x0,y0) to
(x1,y1) is Ax + By + C = 0
set norm=True to get the unit vector of the
normal
"""
A = y1 - y0
B = -(x1 - x0)
C = x1 * y0 - y1 * x0
if norm:
n = (A ** 2 + B ** 2) ** 0.5
... | 6c4c99171010ccf14d3a0d37bcd56fbe696e3fc7 | 589,274 |
def get_max_memberships_for_project(project):
"""Return tha maximun of membersh for a concrete project.
:param project: A project object.
:return: a number or null.
"""
if project.owner is None:
return None
if project.is_private:
return project.owner.max_memberships_private_pr... | a172cd4f2e095f3d6dfbc8b7f9c556a6c1b1e9f7 | 589,275 |
def getFansInZone(zone_num, profiles, fan_data):
"""
Parses the fan definition YAML files to find the fans
that match both the zone passed in and one of the
cooling profiles.
"""
fans = []
for f in fan_data['fans']:
if zone_num != f['cooling_zone']:
continue
#... | 8336d434ed8a8d90c05e96fdba02d1cdbd75a828 | 589,276 |
def eccentric_location_earth_orbit_vec(juliancentury: float) -> float:
"""Calculate the eccentricity of Earth's orbit"""
return 0.016708634 - juliancentury * (0.000042037 + 0.0000001267 * juliancentury) | e8f80726ef0aeca180b63773a1614787e8508cec | 589,282 |
def exchange(programs, move):
"""Exchange, written xA/B, makes the programs at positions A and B swap places."""
a, b = [int(i) for i in move[1:].split('/')]
programs_ = list(programs)
tmp = programs_[b]
programs_[b] = programs_[a]
programs_[a] = tmp
return ''.join(programs_) | 4fe2d1dff2b7cf6875a270f5213aaa37524c3387 | 589,285 |
def listify(o):
"""Ensure an object is a list by wrapping if necessary"""
if isinstance(o, list):
return o
return [o] | 7b1015dfd84b007be3597401ff6035bcd0b8a181 | 589,287 |
def geo_name(year, release, summary_level):
"""Resolve a year, release and summar level number into a URL geography group name"""
if int(summary_level) in (140, 150):
return 'Tracts_Block_Groups_Only'
else:
return 'All_Geographies_Not_Tracts_Block_Groups' | c4e72ea3f3bcfea456679d0e7255224e2105311f | 589,289 |
def tidy_split(df, column, sep='|', keep=False):
"""
Split the values of a column and expand so the new DataFrame has one split
value per row. Filters rows where the column is missing.
Params
------
df : pandas.DataFrame
dataframe with the column to split and expand
column : str
... | 5a3d4651d9feb99ed9b240cb0d53d8217c3c8021 | 589,292 |
import torch
def shapenet_collate_fn(batch):
"""
Collate function to be used when wrapping IndoorSceneGraphDataset in a
DataLoader. Returns a tuple of the following:
- imgs: FloatTensor of shape (N, C, H, W)
- objs: LongTensor of shape (O,) giving object categories
- boxes: FloatTensor of sha... | 4210d65c9eb442dcfdf2d5edcf7fd9c30309bdf8 | 589,294 |
import re
def strip_timezone_name(timestring: str) -> str:
"""Removes extra timezone name at the end. eg: "-0800 (PST)" -> "-0800" """
pattern = r"([+]|[-])([0-9]{4})[ ]([(]([a-zA-Z]{3,4})[)]|([a-zA-Z]{3,4}))"
if re.search(pattern, timestring) is None:
return timestring
split = timestring.spl... | ea602add996851ca7ba0b4593b7d5610fa9c308d | 589,297 |
import re
def _single_line_filter(value: str) -> str:
"""Reduce a string to a single line with no insignificant padding."""
regex = re.compile(r"\s{2,}")
return regex.sub(" ", (value or "").replace("\n", " ")).strip() | 62c44f2f02aae4eb404225a705e8e1df70d98496 | 589,298 |
def detect_orm(input_text_data: str,):
"""Simple detecting ORM by text sample."""
if 'django' in input_text_data:
return 'django'
if 'sqlalchemy' in input_text_data:
return 'sa'
raise Exception("Unknown ORM") | 4e67ef76c3b89eeb7aaa6f29753bfc21abab9ac6 | 589,299 |
from typing import Tuple
def get_feature_dimensions(parameters : dict) -> Tuple[int, int, int, int]:
"""
Returns dimensions of all node features.
"""
n_atom_types = len(parameters["atom_types"])
n_formal_charge = len(parameters["formal_charge"])
n_numh = (
int(not parameter... | 0a53bfd146999a978b5c34371ac1d0b11a9866c0 | 589,301 |
def iterative_matrix_multiplication(matrix_1,matrix_2): #Iterative Multiplication O(n^3)
"""
input: (matrix_1, matrix_2) of dimensions lxm and mxn respectively
output (matrix) of dimensions lxn, the product of the two input matrices
"""
product=[[0 for c in range (len(matrix_2[0]))]for r in range(len(matrix_1))]
... | f4dfd0a33a45be18314ca68203ceec8ead4565b5 | 589,306 |
def get_drive_by_mountpoint(mountpoint):
"""
This accepts a mountpoint ('/mnt/enclosure0/rear/column2/drive32') and returns the drive:
drive32
"""
return (mountpoint.split("/")[5]) | 2779c4a5c8589b90e5e9bcfeb2cb06587c8ecbb4 | 589,310 |
def getValueFromObject(x, y):
"""
Returns a value from a dictionary x if present. Otherwise returns an empty
string
"""
return x[y] if y in x else '' | 15bf70aab5cd1265570cdc7a510f47b0efb25e65 | 589,314 |
import six
import operator
def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
"""Expected inclusion_unlimited_args_kwargs __doc__"""
# Sort the dictionary by key to guarantee the order for testing.
sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0))
return {"resu... | 58c903759bc10a3fb215cf5cdbeca9deef72c0d3 | 589,318 |
def split_s3_path(path):
"""
Args:
path: a string representing an s3 path including a bucket
(bucket_name/prefix/prefix2)
Returns:
A tuple containing the bucket name and full prefix)
"""
return path.split('/', 1) | ac0bd82ccad6f77a9acc63838eacbf8e2e6ae980 | 589,319 |
import json
def read_dict_from_file(filename):
"""
This function reads a dictionary
from an external JSON file
Arguments
filename : name of the file
Returns
dct : dictionary with the contents of 'filename'
"""
with open(filename, "r") as file:
dct = j... | 4f9e920888ba38cff4d79fd6fcf221309b198ed5 | 589,326 |
import random
def random_name_generator(range, ogc_type):
"""creates a random name for the new record, composed by a number of <range> figures,
followed by '_<ogc_type>' """
numerical_name_side = str(random.randint(0, 10**range)).zfill(range)
return numerical_name_side + "_" + ogc_type | 45f679a69fc86bb6abcc907b2d10a6dce71e546c | 589,327 |
from typing import Any
def value_missing(value: Any) -> bool:
"""
Check if a value is missing.
:param value: Value to check
:return: True if None (missing) else False
"""
return value is None | 2439b4dbd860c25c6b96757bbc5158b6f0ef7d3a | 589,328 |
import re
def _is_youtube(input_url: str) -> bool:
"""Verify if input url is a valid YouTube link."""
if bool(
re.match(
r"http(?:s?):\/\/(?:(www|m)\.)?youtu(?:be\.com)*",
input_url,
)
):
return True
return False | 8bd32acba834201bc10a5a1cb3af08bc920f3538 | 589,331 |
def basinhop_status(res):
"""
Determine whether an optimization result was successful or not, working
around differences in scipy < 0.17.0 and scipy >= 0.17.0.
Parameters
----------
res : OptimizeResult
The result to parse
Returns
-------
success : bool
Whether the ... | f7b00dc5299813f75381f54a9c36317153357e3e | 589,333 |
import re
def preprocess_and_split_to_tokens(sentences):
"""
:param sentences: (array_like) array_like objects of strings.
e.g., ["I like apples", "I love python3"]
You can choose the level of pre-processing by yourself.
The easiest way to start is lowering the case (str.lower).
:return: ... | be69734163b3669a6019b94b9249c1996c29555b | 589,334 |
import copy
def zero_pad(img, pwx, pwy):
"""Pads a given image with zero at the border."""
padded_img = copy.deepcopy(img)
"""
Let's assume, padded_img = [ [1,1,1],
[1,1,1],
[1,1,1]
]
"""
... | b9bdfca7fdeb9c0a83cb57c42516b57a05fb0d14 | 589,337 |
def rfind(s, sub, i = 0, last=None):
"""rfind(s, sub [,start [,end]]) -> int
Return the highest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
Slen = len(s) # cache this... | ccb64ee9c2e06a1b5e8dd9b9323d40904d363ca8 | 589,338 |
def locate(rods, locations):
"""Combines location information with pixel rods.
Args:
rods: Chip shaped numpy array of rods
locations: Chip shaped numpy array of locations
Returns:
dict: (location):rod for each location and rod in the arrays.
Incoming locations as 3d array:
... | 75b71462cc23e8bae39b2d89de060364f94d28c2 | 589,339 |
import random
def dummy_version_packet() -> bytes:
"""Constructs a packet with a dummy version.
Such packet makes the server return "Version Negotation Packet".
Returns:
quic.Packet
"""
connection_id = bytes([random.getrandbits(8) for _ in range(8)])
public_flags=bytes.fromhex('09')
... | cb1a8ecbd46aa56adcaebf0cfcb7c8d94ae16cb9 | 589,341 |
import torch
def bpdist2(feature1, feature2):
"""Compute pairwise distances of features.
Args:
feature1 (torch.Tensor): (batch_size, channels, num_inst1)
feature2 (torch.Tensor): (batch_size, channels, num_inst2)
Returns:
distance (torch.Tensor): (batch_size, num_inst1, num_inst2... | f961214b2596772216be6c009330fb79b495c3df | 589,345 |
from typing import Tuple
import re
def parse_expression(expression: str, cast: bool = True) -> Tuple:
"""Parse rio-tiler band math expression.
Args:
expression (str): band math/combination expression.
cast (bool): cast band names to integers (convert to index values). Defaults to True.
R... | cfb40e16baec0a792589c93e1e0454df6cf12324 | 589,347 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.