content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def get_matching_files(url, entry):
"""Given a search entry returned from PilotClient.get_search_entry, find
all of the partial matches in the entry. Partial matches can happen if
a base folder matches, but not the files below it. For example:
* A url: http://example.com/files/foo
* entry with f... | 33c7a22dbd66934dd76ae522eade0e64d627fd8c | 499,421 |
from pathlib import Path
def _template(name):
"""Read the specified template file."""
template = Path(__file__).parent / 'templates' / name
with open(template, 'r') as file:
return file.read().strip() | 746ba2ae2be6b1abff14953a030e3e5393df1d7b | 180,438 |
import click
def unstyle_output(msg: str) -> str:
"""
A thin wrapper around click.unstyle.
"""
s: str = click.unstyle(msg)
return s | f52dbf774c6d1567da4fb39468460e3197a1a821 | 456,050 |
def decode_ber(ber):
"""
Decodes a ber length byte array into an integer
return: (length, bytes_read) - a tuple of values
"""
ber = bytearray(ber)
length = ber[0]
bytes_read = 1
if length > 127:
bytes_read += length & 127 # Strip off the high bit
length = 0
for i ... | 3ed69a24e2ceef7e157ee2773d40bf1425b7ae99 | 406,275 |
def get_nested_attr(obj, attr, default=None):
"""Get nested attributes of an object."""
attrs = attr.split(".")
for a in attrs:
try:
obj = getattr(obj, a)
except AttributeError:
if default:
return default
else:
raise
ret... | 7f8dc82f6d08a763a0a083967ef524acbba8e983 | 680,775 |
def base36encode(number):
"""Converts an integer into a base36 string."""
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"
base36 = ''
sign = ''
if number < 0:
sign = '-'
number = -number
if 0 <= number < len(ALPHABET):
return sign + ALPHABET[number]
while numbe... | c69312809f15fc546823e54b33d4198aaa7b3149 | 394,609 |
def print_network(net, out_f=None):
"""
Prints the number of learnable parameters.
:param net: the network.
:type net:
:param out_f: file
:type out_f:
:return: number of learnable parameters.
:rtype: int
"""
num_params = 0
for param in net.parameters():
num_params +=... | 9dcfd7da51eab385dacb90d35bfeb139ed785be1 | 24,720 |
from datetime import datetime
def calculate_tz_offset(local_time_str, server_datetime_str):
"""Given a local_time without date and a server_datetime in UTC, calculate the user's
timezone offset in minutes. This is not accurate for all cases, but should be approximately
correct for the most common ones. ... | 79b098ffd6427fc2d5263569e7647d7f4bae6d8b | 584,036 |
def std_url(url):
"""
Standardizes urls by removing protocoll and final slash.
"""
if url:
url = url.split("//")[-1]
if url.endswith("/"):
url = url[:len(url)-1]
return url | 4940052d2feebd92f9cb54e7cee57318445f86c2 | 603,993 |
def get_name(metadata):
"""Return the name of an object based on the dictionary metadata. By preference: long_name, short_name, 'Unnamed'
"""
name = metadata.get("long_name", None)
if name is not None:
return name
name = metadata.get("short_name", None)
if name is not None:
retu... | f01576f90cc37168009e30ee04283e7ff2a5e927 | 80,304 |
from typing import Tuple
def extract_entitlement(entitlement: str, text: str) -> Tuple[str, str, str, str]:
"""
Extracts entitlement components from an entitlement string
Args:
entitlement: The entitlement itself
text: The actual reply text
Returns:
Entitlement components
... | 8ecee278f03535f0a3f6426cd400d76c08f8e544 | 641,460 |
def extract_name_and_id(user_input):
"""Determines if the string user_input is a name or an id.
:param user_input: (str): input string from user
:return: (name, id) pair
"""
name = id = None
if user_input.lower().startswith('id:'):
id = user_input[3:]
else:
name = user_input... | feb84b022e626bae091bb28e8d3f316bdbf1ba3d | 675,496 |
def bytes2human(n, format='%(value).1f %(symbol)sB'):
"""
Convert n bytes into a human readable string based on format.
symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
see: http://goo.gl/kTQMs
>>> from datalad.utils import bytes2human
>>> bytes2human(1)
'1.0 B'... | ffaa1c0d8672c92f9c854ae18bce0026dd38c0d7 | 488,563 |
def add_integers(a: int, b: int):
"""Sum two integers
Args:
a (int):
b (int):
Returns:
int: sum of the integer inputs a and b
"""
return a + b | 3cdd1be6670a649b69f0eaa4a274ebd4029a6d64 | 634,390 |
def _card(item):
"""Handle card entries
Returns: title (append " - Card" to the name,
username (Card brand),
password (card number),
url (none),
notes (including all card info)
"""
notes = item.get('notes', "") or ""
# Add car... | fc7d5e4b960019b05ffe7ca02fd3d1a94d69b303 | 375 |
def ndbi(swir, red, nir, blue):
"""
Converts the swir, red, nir and blue band of Landsat scene to a
normalized difference bareness index.
Source: Zao and Chen, "Use of Normalized Difference Bareness Index
in Quickly Mapping Bare from TM/ETM+", IEEE Conference Paper, 2005
DOI: 10.1109/IGARSS.200... | 5a79e2af482e56429cfe76d3ab12ae9e487573af | 690,863 |
import click
def _log_status(count, model_label):
"""
Log the output of how many records were created.
:param count: Amount created
:type count: int
:param model_label: Name of the model
:type model_label: str
:return: None
"""
click.echo('Created {0} {1}'.format(count, model_labe... | c1d223b00451abd6cc980ec0b83224d73624f3e8 | 397,481 |
def s2time(
secs: float,
show_secs: bool = True,
show_fracs: bool = True
) -> str:
"""Convert seconds to time.
Args:
secs (float):
show_secs (bool):
Show seconds (default: True)
show_fracs (bool):
Show centiseconds (default: True)
Returns:
... | cf15ae732ec0713ea181cfbbf05fba69206967a4 | 215,707 |
import tempfile
def get_spooled_file_object(s3_client, bucket, key):
"""Get a temporary spooled file object for an S3 object
:param s3_client Boto s3_client object to apply
:param bucket: Bucket to upload to
:param key: key identifying the object within the bucket
"""
result = tempfile.Spoole... | 51d3478d798fb0e3e6692ef304343f65ce1466a8 | 69,064 |
from typing import Dict
from typing import Optional
def get_new_name(attrs: Dict[str, str],
mark_name: str = '',
name_map: Optional[Dict[str, str]] = None) -> str:
"""Get new name for a node.
Args:
attrs (Dict[str, str]): A dict contains attributes of an ONNX node.
... | a541b05a4cd0021815062698d48a2fb155d60f01 | 645,008 |
def unsigned_Q(num:int) -> int:
"""Returns unsigned value of signed (or unsigned) 64-bit integer (struct fmt 'Q')
"""
return num & 0xffffffffffffffff | 623b3a41e44bb6f66551827a2ef2396650562d0c | 230,896 |
from typing import List
import re
def parse_args(line: str) -> List[str]:
"""Parse the first line of the program for the command line.
This should have the form
# cmd: mypy <options>
For example:
# cmd: mypy pkg/
"""
m = re.match('# cmd: mypy (.*)$', line)
if not m:
ret... | d768b5faf2a03a643555f6e508327a45050fca46 | 481,969 |
import hashlib
import codecs
def hash256_twice(s):
"""
Hash input with sha256 twice, reverse, encode to hex.
"""
bh = hashlib.sha256(hashlib.sha256(s).digest()).digest()
hh = codecs.encode(bh[::-1], "hex")
return hh | 3b55214077dcfd10b3ffdb28e578ada5e6b06604 | 379,378 |
def format_item(item, xmlns, key):
"""
Format a rss item and return data.
This properly format a rss item regarding the xmlns attribute and a key.
It returns the data of the item regarding it's key.
:param item: A rss item
:param xmlns: XML namespace of the rss feed
... | 10b50932eb71977b76bf4b968227b9d642ee89d5 | 88,152 |
import re
def cwb_escape(inname):
"""Replace dots with "-" for CWB compatibility."""
return re.sub(r"\.", "-", inname) | b552fc8a0ccf8d61c4febbc7617c4c0e3433f013 | 91,800 |
async def create_product(http_client, name="Product", description="Description") -> int:
"""
Create a new product, assert status code, and return product ID.
This is factored into a helper as many tests perform this operation.
"""
resp = await http_client.post("/products", json={"name": name, "desc... | 557a054c8ee1dca54d51ce8f94c7b8b04b3d4f5c | 209,842 |
def map_range(
value: float, in_min: float, in_max: float, out_min: float, out_max: float
) -> float:
"""Map a value in one range to another."""
if in_max - in_min <= 0.0:
raise ValueError("invalid input range")
if out_max - out_min <= 0.0:
raise ValueError("invalid output range")
if... | 01e05906e32d070a39b202bce1bf3d6446286179 | 88,805 |
def view_capture_stream(telstate, capture_block_id, stream_name):
"""Create telstate view based on given capture block ID and stream name.
It constructs a view on `telstate` with at least the prefixes
- <capture_block_id>_<stream_name>
- <capture_block_id>
- <stream_name>
Additionally i... | ebad45cd567dee22f3f7117fffb0fd4b3d376ccc | 501,806 |
import math
def calculate_angle(a, b, c):
"""
Returns angle (a-b-c), in degrees
All points are assumed to be locintel.core.datamodel.geo.GeoCoordinate objects
"""
b_c = math.sqrt((b.lng - c.lng) ** 2 + (b.lat - c.lat) ** 2)
a_c = math.sqrt((a.lng - c.lng) ** 2 + (a.lat - c.lat) ** 2)
a_b ... | 8823e1a7d348ab05fd00ea4359ef04224c854fb6 | 186,957 |
def attr_proc_title( binary, attrs ):
"""
Make a process title that has attr:<k>=<v> for set of attributes.
"""
return "%s %s" % (binary, " ".join( ["attr:%s=%s" % (k, v) for (k, v) in attrs.items()] )) | 3e4b28119898e5b868da678cec10637f2c6532ae | 263,526 |
def warc_datetime_str(date):
"""Amendedment to warctools' function to fix non-ISO8601 output."""
iso = date.isoformat()
if "." in iso:
iso = iso[:iso.find(".")]
if "+" in iso:
iso = iso[:iso.find("+")]
return iso + "Z" | f5932bedd398ecd5c6f3e346b1fc2ccfc024eaa5 | 612,158 |
import json
def get_keys(path):
"""
Given a path to json file, returns the keys
Parameters
---------
path: path with file name of json file
Returns
-------
returns: dict of keys
"""
with open(path) as f:
return json.load(f) | 7883661d799eca53a59e663b5248fa872189031c | 171,595 |
def multiply_two_number(a, b):
""" Returns the result of multiplying two numbers """
# unused_var = 'blah'
return a * b | 86637659dccdce4d83bdfec5c6bda6e2d922e826 | 466,462 |
def _find_tusd_object_name(params: list[dict]) -> str:
"""
Finds the tusd_objekt_navn from a list of parameters
:param params: list of workflow parameters
:return: tusd_objekt_navn
"""
for param in params:
if param['name'] == 'TUSD_OBJEKT_NAVN':
return param['value']
rais... | 5bd7dca4b1cc3ca8f109248f5e0d27f002056db3 | 491,282 |
def get_access_pdf(pdf_dir):
"""Gets a PDF file from a directory. Fails if there are multiple PDF files
Args:
pdf_dir (Path obj): directory containing PDF file
"""
pdf_files = [f for f in pdf_dir.iterdir() if f.is_file(
) and not f.name.startswith(".") and f.name.endswith(".pdf")]
if le... | 7c2c661812e25d0024884aaf302312bde9fa86dc | 155,759 |
def word_flipper(our_string):
"""
Flip the individual words in a sentence
Args:
our_string(string): Strings to have individual words flip
Returns:
string: String with words flipped
"""
word_list = our_string.split(" ")
for idx in range(len(word_list)):
word_list[idx]... | fd484079407342925fc13583fb1fbee9ee472b14 | 708,675 |
def basal_metabolic_rate(gender, weight, height, age):
"""Calculate and return a person's basal metabolic rate (bmr)
in calories per day. weight must be in kilograms, height must
be in centimeters, and age must be in years.
"""
if gender.upper() == "F":
bmr = 447.593 + 9.247 * weight + 3.098... | d9a3cb99fbcfbfe4d43075392dfe45bc34d97f9b | 415,216 |
def associative_backdate(now, backdate):
"""Correct non-associative relative-delta month math
:param now: datetime start point
:param backdate: relativedelta value to move back from now.
Asking for a relative delta back in time for a period of months and
then adding the same number of months does ... | 8ba36900c06710e659f878e4bbc364caeb4eaf67 | 53,230 |
import base64
def base64_2_str(base64_encode):
"""
Args:
base64_encode: base64编码str
Returns: str(utf-8)
"""
base64_decode = base64.b64decode(base64_encode).decode('utf-8')
return base64_decode | 0f9f520843122d25eae17f6167f589c8fdc81e5f | 567,345 |
import json
def get_inline_policies(iam_client, role_arn):
"""
Get inline policies in for a role
"""
inline_policies = iam_client.list_role_policies(RoleName=role_arn)
return [
json.dumps(iam_client.get_role_policy(RoleName=role_arn, PolicyName=policy).get("PolicyDocument", ))
... | 92f7985381f16c3224be6d3eb725b9772bdc7498 | 234,130 |
import re
def is_data_csv(fname):
"""Checks if a file is a data csv"""
return re.search(r"^iter_(\d+).csv$", fname) is not None | 4f590d472ca1c0cf4bbdea6c8157b0b20d836c4a | 505,093 |
from pathlib import Path
def AbsolutePath(*args, **kargs) -> Path:
"""Create an absolute path (useful as argument 'type')"""
return Path(*args, **kargs).absolute() | 1bf531a2d845ce37e9b34471bc183dcb75369f33 | 500,248 |
def prepare_dict(hermes_dict):
"""
Prepare a rhasspy type like dict from a hermes intent dict
"""
intent = hermes_dict["intent"]["intentName"]
out_dict = {}
out_dict.update({"slots": {s["slotName"]:s["rawValue"] for s in hermes_dict["slots"]}})
out_dict["intent"] = {"name": intent}
retur... | 64a48d88d7a713d3c58fe480632670ef9beb1676 | 187,151 |
def _merge_dicts(*dicts, **opts):
"""
The standard dictionary merge idiom, with a twist: an *opts*
keyword dictionary.
"""
target = opts
for d in dicts:
target.update(d)
return target | 570224940ac697d532778f4140792af125f8bf35 | 526,371 |
def _find_AP_and_RL_diameter(major_axis, minor_axis, orientation, dim):
"""
This script checks the orientation of the and assigns the major/minor axis to the appropriate dimension, right-
left (RL) or antero-posterior (AP). It also multiplies by the pixel size in mm.
:param major_axis: major ellipse axi... | 403c4c42c845e427422eef839d66323be6b12dba | 551,458 |
def yesno(value):
"""Convert 0/1 or True/False to 'yes'/'no' strings.
Weka/LibSVM doesn't like labels that are numbers, so this is
helpful for that.
"""
if value == 1 or value == True:
return 'yes'
return 'no' | 050baf0e4dd604644bd595a0432a7f031ef019dd | 504,159 |
import collections
def GetTurnStats(game_results):
"""Returns a histogram of game lengths (in rounds played)."""
hist = collections.Counter()
for game_result in game_results:
hist[game_result.num_rounds_played] += 1
return hist | 78a4980ffa3a71d0181499f6448c75fa7d56c422 | 689,213 |
def vcross(self, labxr="", labyr="", labzr="", labx1="", laby1="",
labz1="", labx2="", laby2="", labz2="", **kwargs):
"""Forms element table items from the cross product of two vectors.
APDL Command: VCROSS
Parameters
----------
labxr, labyr, labzr
Label assigned to X, Y, and Z-... | ed40fd87eebfae617c1a3406b07d0ec7261c83e5 | 665,295 |
def _GetWinLinkRuleNameSuffix(embed_manifest):
"""Returns the suffix used to select an appropriate linking rule depending on
whether the manifest embedding is enabled."""
return "_embed" if embed_manifest else "" | 2cf42d4a22007baa648842975f61d36406bd84cb | 585,008 |
def get_lname_for_statedict(lname):
"""
Convert layer name into the form used to address the weight tensor of the module through model_statedict().
"""
lname_bits= lname.split('_')
lname_bits.append('weight')
lname_for_statedict= '.'.join(lname_bits)
return lname_for_statedict | a68276712134ecfb6ca379ede68438c478cd6cb1 | 299,678 |
def find_command(command, all_commands):
"""
Looks up a command in a list of dictioraries, returns a dictionary from a list
:param command: Command to look up
:param all_commands: list of all commands
:return: dictionary
"""
for item in all_commands:
if item["command"] == command:
... | c57590a52acc4698e98137915e8ff46002a2f739 | 254,169 |
import hashlib
def compute_md5_hex(data):
"""Return the hex MD5 of the data"""
h = hashlib.md5()
h.update(data)
return h.hexdigest() | a7b8bea7d8f396fb319ffff55dbc05ccf194e284 | 160,126 |
def field_to_list(row, key):
"""
Transforms key in row to a list. We split on semicolons if they exist in
the string, otherwise we use commas.
Args:
row: row of data
key: key for the field we want
Reutrns:
row: modified row
"""
if not row[key]:
return row
... | accc49cbb63a6262ed23ba5e144315fc2ac8517b | 462,218 |
def active_queues(state):
"""List the task queues a worker is currently consuming from."""
if state.consumer.task_consumer:
return [dict(queue.as_dict(recurse=True))
for queue in state.consumer.task_consumer.queues]
return [] | f699478913b8b259ebc881bd728a8f0cbd2bf458 | 615,011 |
def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
"""Find the position just after the matching endchar.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
depth: nesting level at startpos.
startchar: expression opening character.
... | 97ea6f4347c21feb8287b70fbfe0935e9c2301b3 | 522,113 |
def alpha_waste(lyambda_cond_waste_avrg, rho_cond_waste_avrg, mu_cond_waste_avrg, W_mass, n_pipe_waste, L_waste):
"""
Calculates the coefficent of heat transfer(alpha) from steam to wall of pipe.
Parameters
----------
lyambda_cond_waste_avrg : float
The thermal conducivity of condensate, [W ... | b7e6ef03a8ebc62ebdae3dcd1ac196dfb80871da | 508,732 |
import json
def post_to_query_string(dico):
""" Transform a dict to a query string
>>> post_to_query_string({'foo': 'bar', 'where': {'foo': 'bar'}})
?foo=bar&where={"foo": "bar"}
:params dico the dico to convert
"""
querystring = "?"
for key in dico:
querystring ... | 21b2c43a948c148c37ba2649e8032b1f54f88926 | 586,726 |
def human_readable_resolution(r_ms: int) -> str:
""" Resolves a resolution in milliseconds to a human readable string
:param r_ms: resolution in milliseconds
:return: human readable resolution
"""
switcher = {
60000: '1 Minute',
180000: '3 Minutes',
300000: '5 Minutes',
... | bb11a0de6800d4b0b3c4f3eb848ce8764d36deea | 205,443 |
def split_by_timestamp(xyzrph: dict):
"""
Takes a Kluster xyzrph (the dictionary object that stores uncertainty, offsets, angles, etc. settings) and returns
a new dictionary for each timestamped entry.
Parameters
----------
xyzrph
dict of offsets/angles/tpu parameters from the fqpr inst... | bd57217e82e92b8aa0ea30598426db36788a64b2 | 66,797 |
def ensure_overlap(lh, mor, expr):
""" ensures label overlap with weights and expression matrix
Args:
lh (pandas DataFrame): sparse DataFrame indicating likelihood for regulators
mor (pandas DataFrame): sparse DataFrame indicating mode or regulation for transcription factors
expr (:obj:... | 716e577a6748199ad9ef95e5b2fecacca0b24cf3 | 51,737 |
def clear_handlers(logger):
"""
Clear all handlers from logger
Parameters
----------
logger : logging.logger
Logger to remove all handlers from
Returns
-------
logger : logging.logger
Logger with all handlers removed
"""
handlers = logger.handlers.copy()
for... | 40e1d086df01c1afe4168165e7a59bc0110edef2 | 454,945 |
def google_api_query(query_dict: dict) -> str:
"""Join given query args into one string.
Return query string in format required by googlapis:
https://developers.google.com/books/docs/v1/using#WorkingVolumes
"""
if not query_dict:
return ""
def allowed_google_item():
if item[1] ... | b169c0575874cf96b438d87d3e9305ffc917d96a | 561,408 |
def accuracy(y_hat, y):
"""Get accuracy."""
return (y_hat.argmax(axis=1) == y).mean().asscalar() | 9c63e1d8b7e06dc278b2965abb3931cd0f6208c7 | 691,321 |
def add_spaces(x):
"""Add four spaces to every line in x
This is needed to make html raw blocks in rst format correctly
"""
y = ''
if isinstance(x, str):
x = x.split('\n')
for q in x:
y += ' ' + q
return y | 8443f4d019022b1e4705abbeca5bbd54bc94699d | 691,179 |
def format_path(path):
"""
(str) -> str
Make sure that path ends with a backslash '/'
"""
return path if path.endswith('/') else path + '/' | 286193e6a5e775651e241e83792cb17bd2575d27 | 439,928 |
def range_overlap(ranges):
"""Return common overlap among a set of [left, right] ranges."""
lefts = []
rights = []
if ranges:
for (left, right) in ranges:
lefts.append(left)
rights.append(right)
max_left = max(lefts)
min_right = min(rights)
if min... | f8f8a907e6847dc308a537dab5033b8c49149674 | 651,142 |
import torch
def cr_matrix_vector_product(m: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
"""Returns the product of a complex matrix and a real vector.
:param m: Matrix as ``(*, m, n, 2)`` tensor.
:param x: Vector as ``(*, n)`` tensor.
:return: Result as ``(*, m, 2)`` tensor.
"""
xr = x.un... | cafc5f19441fc1c47eb9f82d0ae8992918a8df72 | 664,232 |
def restrict_chains(data, k):
"""Restrict data to people with at least k rows.
Parameters
----------
data : pandas.DataFrame
The `data` from US to be subsetted.
k : int
The minimum number of measurements needed for a person to be kept.
Returns
-------
data : pandas.DataF... | 106fc9c43d12085392a84a188dcc8d40a89ae817 | 10,871 |
import math
def xy_yaw_from_quaternion(quat):
"""Calculate the yaw angle in the xy plane from a rotation quaternion.
:param quat: A unit quaternion representing the
:type quat: Any container that has numerical values in index 0, 1, 2 and 3
:return: The yaw angle in radians projected on the xy plane
... | 255225c80bba64f0d347871584db8a4138c199b8 | 669,832 |
import re
def compile_routes(dynamic_routes):
"""Compiles the regexes in the routes table."""
routes2 = []
for (verb, path_pattern, handler_func) in dynamic_routes:
compiled_path = re.compile("^" + path_pattern + "/*" + "$")
entry = (verb, path_pattern, compiled_path, handler_func)
... | e6d5445c222fe4320f3bcfb52f94b6f9d677e1e7 | 507,304 |
def path_string(obj, **kwargs):
"""return physical path as a string"""
return "/".join(obj.getPhysicalPath()) | bae683d392b519f8c43f5e9d1415abb8cf8de636 | 20,865 |
def fancy_vector(v):
"""
Returns a given 3-vector or array in a cute way on the shell, if you
use 'print' on the return value.
"""
return "\n / %5.2F \\\n" % (v[0]) + \
" | %5.2F |\n" % (v[1]) + \
" \\ %5.2F /\n" % (v[2]) | 2340f22aa87da00abad30b9946c374f34b38496d | 2,665 |
import math
def angle_trunc(the_angle):
"""
Truncate the angle between [0, 360)
Arguments:
the_angle {float} -- angle
Returns:
float -- Angle between [0,360)]
"""
while the_angle < 0.0:
the_angle += math.pi * 2
return the_angle | 81eafdf106990a1c0921a840e1b746796fc7b8eb | 538,129 |
def loadOutputList(expt_name,outputType):
"""Loads a file containing all file names with a specified output data into a local list
Args:
expt_name (String): Name of experiment (which contains how many ever simulation output files)
outputType (String): molpos or simtime. Determines which set... | 22f98f554b7cb6161a893a2f81cc4b916460ccc6 | 76,194 |
def _compose_middleware(method, middleware):
"""Apply the given ServiceMiddleware to the provided method and return
an InvocationHandler.
Args:
method: instance method
middleware: list of ServiceMiddleware
Returns:
InvocationHandler
"""
def base_handler(method, args):
... | 79f6faa929cfbc5e8156f430bc22457cdeef6392 | 246,582 |
def remove_stopwords(df, file, path='', column = "Word"):
""" Remove stopwords from a dataframe choosing
a specific column in which to remove those words
Parameters:
-----------
df : pandas dataframe
Dataframe of counts per word per user
file : string
Name of file that conta... | 001cd22a8d62c53ea074ae0a290ce8974d857343 | 106,188 |
def fraunhofer_distance(d=1.0, wavelen=550e-6):
"""computes the Fraunhofer distance from a diffracting aperture. It is the
limit between the near and far field
Parameters
----------
d : float
largest dimension of the aperture. i.e. aperture width/diameter (in mm)
wl : float
... | 07cac7ee31003c7f31c34209547ec9d845770fe7 | 490,973 |
def clean_keys_of_slashes(record):
"""
Replaces the slashes found in a dataset keys with underscores
:param record: list containing a couple of dictionaries
:return: record with keys without slashes
"""
for key in list(record):
value = record[key]
if '/' in key:
# rep... | 126fa995e0cc434365846e14834f8d7a03ca9ccc | 521,060 |
def add(n1, n2):
"""Adds the 2 given numbers"""
return n1 + n2 | ca670819dab8230e355e1b236d9cc74ed0b3b868 | 314 |
def remove_max_edge_from_cycle(tree, cycle):
"""
Remove the max-weighted edge from a *cycle* which is contained in the given *tree*.
"""
cycle = sorted(cycle, key=lambda edge: int(edge.weight), reverse=True)
return tree.remove(cycle[0]) | 0fc5b4b725e005f07441f18b7df6e22db06b3087 | 475,319 |
def _calculate_positives_negatives(target_details):
"""
Takes expected and actual target values, generating true and false positives and negatives,
including the actual correct # of positive and negative values.
"""
true_positive = 0
true_negative = 0
false_negative = 0
false_positive =... | 43314d34e98c4e9fa959426666f17d1a7d71af44 | 104,269 |
def read_network(file):
"""
Read a (switched) Boolean network from a text file:
Line 1: number of state variables
Line 2: number of control inputs
Line 3: number of sub-networks
Line 4: transition matrix of the first sub-network (linear representation of a logical matrix)
... | 76907cb8342e3f96b88f519cb09a2c28bc6e137e | 78,297 |
def read_keywords(args):
"""This function reads the keywords from the input file and creates:
- a dictionary where the key is the old name and the value is the new name,
these keywords will be further processed.
- a list of keywords which will not be processed, typically keywords with
argument(s)... | fd261c6819424e171776130e74538b05baf6e830 | 67,920 |
def _check_pixel(tup):
"""Check if a pixel is black, supports RGBA"""
return tup[0] == 0 and tup[1] == 0 and tup[2] == 0 | a12b1a8ce51a59e37326ef8f7bc80a5e5a907a1a | 679,629 |
def clean_sort_param(request, date_sort='created'):
"""
Handles empty and invalid values for sort and sort order.
'created' by ascending is the default ordering.
"""
sort = request.GET.get('sort', date_sort)
order = request.GET.get('order', 'asc')
if sort not in ('name', 'created', 'nominat... | 3292403c2c1b8b06c2cb8b32fa40ca06b835a1eb | 354,778 |
def write_variable_length(value):
"""
Write a variable length variable.
Parameters
----------
value : bytearray
Value to be encoded as a variable of variable length.
Returns
-------
bytearray
Variable with variable length.
"""
result = bytearray()
result.in... | 59683e3028c7de59c309e1eb17377b0207467834 | 328,512 |
def date_str2csv_date(date_str):
"""Utility function to convert a JSON date string into a date that
is consistent with the representation in the csv files we work with.
Args:
date_str - the Python date string
Returns:
A date string formatted for csv
"""
return ''.join([date_str[:... | 8ea7aac0fba74c451e1b5b0775e1fa99bdec27a3 | 211,466 |
def affine_transformation(anchor_x, x0, x1, anchor_y, y0, y1):
"""Construct an affine coordinate transform and its inverse.
From a GDAL-style specification of the parameters of an affine
transformation, construct both the affine function that maps integer cell
indices to the center points of the corres... | e5b079add0655665b7f02a022993e8f6a5c6b255 | 530,121 |
import json
def get_json(file):
"""
Load JSON data into memory
file: the path to the data file
"""
with open(file) as json_file:
json_data = json.load(json_file)
json_file.close()
return json_data | e50656d07d199b607cb6fbf6053af7e7816f736a | 89,567 |
def select_from_arxivcs_mag(sconn, scur, paper_id):
""" Queries the sqlite3 table unpaywall on paper_id, returns the pdf_url (can be None)"""
# cur = conn.cursor()
query = """
SELECT pdf_url
FROM arxivcs_mag WHERE paper_id = '{}'
""".format(paper_id)
scur.execute(query)
# Only get one ... | 5ba697f886a4366b9dd848d1c80b16dac61f255d | 274,852 |
def cleanup_url(url: str) -> str:
"""Cleans up the text to be a valid URL.
Returns:
str: The cleaned up URL.
"""
url = url.replace(" ", "-")
if url.startswith("http://") or url.startswith("https://"):
return url
else:
return f"https://{url}" | b3eed31d45f7bfaa975c60212949dd8fe0e43729 | 640,985 |
def map_code_to_status(http_code: int):
"""Maps HTTP code to human-readable descriptive string"""
if 100 <= http_code <= 199:
return 'INFO'
elif 200 <= http_code <= 299:
return 'SUCCESS'
elif 300 <= http_code <= 399:
return 'REDIRECT'
elif 400 <= http_code <= 499:
ret... | c14982cf8d239ca079a30e45b901472b05dca511 | 478,202 |
import time
def string_to_date(date_string):
""" Convert a formatted string into a date."""
return time.strptime(date_string, "%Y/%m/%d:%H:%M:%S") | 1d6f15d1bed9b918be4449d8aad9577a0ab9bd87 | 186,021 |
def print_value(v):
"""double quote v if v is a string, return str(v) otherwise"""
if isinstance(v, str):
quoted = v.replace('"', r'\"')
return f'"{quoted}"'
else:
return str(v) | 487305e17639a4fd7ce60870d186f50ef4598de2 | 198,598 |
def quadratic_probe(h, i, m):
"""
Finds a possible next position using quadratic probing
Note that there are many different ways of doing this, such as
with a formula in the form ai + bi^2. This is just a simple example
Quadratic hashing reduces primary clustering: linear probing may
lead to la... | 3f202a892c2aa76077e79d365626e48b27c64462 | 300,749 |
import math
def translate_key(key):
""" Translate from MIDI coordinates to x/y coordinates. """
vertical = math.floor(key / 16)
horizontal = key - (vertical * 16)
return horizontal, vertical | 1916fb2abc97f421494c3ced21d9f8ec05936845 | 675,354 |
def parse_email(ldap_entry):
"""
Returns the user's email address from an ldapentry
"""
if "mail" in ldap_entry:
email = ldap_entry['mail'][0]
else:
email = ldap_entry['uid'][0] + "@pdx.edu"
return email | fbd25b486aae71828b1e784b5f2b128b747ba3e7 | 244,532 |
def yes_or_no(question):
"""Prompt for yes/no question"""
while True:
reply = str(input(question+' (y/n): ')).lower().strip()
if reply in ['y', 'yes']:
return True
if reply in ['n', 'no']:
return False | 72820ceef5730611e7ad11c8754581aae8e2c549 | 205,348 |
def filter_labels_by_class(obj_labels, classes):
"""Filters object labels by classes.
Args:
obj_labels: List of object labels
classes: List of classes to keep, e.g. ['Car', 'Pedestrian', 'Cyclist']
Returns:
obj_labels: List of filtered labels
class_mask: Mask of labels to k... | 854a32da802c794b0622a0a36895590823b7c780 | 699,860 |
def extract_glob_pattern(path_arg: str) -> tuple:
"""Extract glob pattern from a path"""
if not path_arg: return None, None
base_path = pattern = None
if '*' in path_arg: # we have globbing in src path
path_components = path_arg.split("/")
base_path_arr = [] # let's establish the base ... | abaa82b35dedd19e3c410a5612cdd7f30dc21b6c | 465,713 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.