content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from datetime import datetime
def to_datetime_str(date: datetime) -> str:
"""
Returns the formated datetime string.
:: Output example: '2021-07-15T0:0:0Z' FORMAT : "%Y-%m-%dT%H:%M:%SZ"
"""
return date.strftime("%Y-%m-%dT%H:%M:%SZ") | 58ce51329861f84bccb36a69f36e176e5d2706fd | 586,771 |
import re
def clean(text):
"""
Cleans text, removes excess tabs, CRs, spaces
:param text: raw text string
:return: clean text string
"""
text = re.sub('\s*\n\s*', '\n', text)
text = re.sub('[ \t]{2,}', ' ', text)
return text.strip() | 57475bb5e2955d33cdefa7ba593413affa3293e2 | 586,773 |
def get_pr_link(repo_name: str, pr_number: int) -> str:
"""
Build a pull request URL for manual browser access using full repository name and PR number
:param repo_name: full repository name (i.e. `{username}/{repoanme}`)
:param pr_number: PR number used on GitHub
:return: A pull request URL
"""... | e18e76b2b2ad612a4de64dec2e6cb1215fe40b52 | 586,774 |
def lookup_class(ref):
""" Look up an object via it's module string (e.g., 'glue.core.Data')
:param ref: reference
:type ref: str
:rtype: object, or None if not found
"""
mod = ref.split('.')[0]
try:
result = __import__(mod)
except ImportError:
return None
try:
... | c8a712dc6ba430dd957280bd817abd197497e925 | 586,776 |
def pe2(limit=4000000):
"""
Sum of the even-valued Fibonacci sequence
>>> pe2()
4613732
"""
a, b, s = 1, 2, 2
while b <= limit:
a, b = b, a + b
if not b & 1:
s += b
return s | f26051c7b42e78433727d7105305a2cad58918ae | 586,782 |
import re
def camel_to_snake_case(s):
"""Converts a camel cased to a snake cased string.
:param s: a camel cased string
:return: a snake cased string
"""
snake_cased = re.sub('([a-z0-9])([A-Z])', r'\1_\2', re.sub('(.)([A-Z][a-z]+)', r'\1_\2',
... | 3225e6f97ab66bd6ace6468ab0a9c5a6aeacff39 | 586,783 |
def earliest_date(timespan):
"""
Returns the earliest date in a timespan.
"""
if timespan[0] < timespan[1]:
return timespan[0]
else:
return timespan[1] | a7b4c0a8599a77122a79a672f6b4fb6b9652ed5a | 586,784 |
def uint_to_str(i):
"""Convert a uint to a string."""
s = ''
while True:
if i>127:
s += chr(i&127|128)
i >>= 7
else:
return s+chr(i) | 9b5590eaa082c318c7be11ed6fd70907a3ff2a36 | 586,787 |
import torch
def choice(probabilities: torch.Tensor) -> torch.Tensor:
"""Selects elements with probability proportional to the given weights.
Args:
probabilities (torch.Tensor): Tensor of shape `(..., N)`. Arguments are sampled
over the last dimension according to the weight.
Returns... | c4b820f41de87e578c52ffbf659c0c6a33f1d2cb | 586,790 |
def summary_groupby_col_type(source_type):
"""
Returns the type of a groupby column in a summary table
given the type of the corresponding column in the source table.
Most types are returned unchanged.
When a source table is grouped by a list-type (RefList/ChoiceList) column
the column is 'flattened' into t... | 7b589fd4a2675ee935adaff4871190c787c823b4 | 586,791 |
import math
def nCr(n, r):
"""
Calculates nCr.
Args:
n (int): total number of items.
r (int): items to choose
Returns:
nCr.
"""
f = math.factorial
return int(f(n) / f(r) / f(n-r)) | c67778226e5bcfbac73abc2965178f089fa04be3 | 586,797 |
from pathlib import Path
def expected_yaml(local_fixtures: Path) -> Path:
"""Path to local fixtures expected yaml."""
return local_fixtures / "expected_yaml" | f77e9b1d601e159dd01ff65c8a6ae4abf028ffa4 | 586,801 |
def contains_dollar_sign(input_string):
"""
check if string contains '$'
>>> contains_dollar_sign("$5")
True
>>> contains_dollar_sign("5")
False
"""
return any(_ == "$" for _ in input_string) | e2f4c523d3b5bb06a8d74afef99550b2d22f31e2 | 586,802 |
def hash_key(aMap, key):
"""Given a key this will create a number and then convert to
an index for the aMap's buckets."""
return hash(key) % len(aMap) | 179869154845e7da1ab4e50218ddc7f1f04cf7cb | 586,803 |
import uuid
def jsonrpc_request(method, params, call_id=None):
"""
Marshal an RPC request in JSON-RPC 2.0 format.
See http://www.jsonrpc.org/specification for details.
:param method: remote method to invoke
:param params: parameters to remote method
:param call_id: value of JSON-RPC 'id' par... | 6a5a05f7042b046a77736b637d509961fce98642 | 586,804 |
def merge_dicts(*args):
"""Merge multiple dictionaries into a new dictionary as a shallow copy."""
merged_dict = {}
for input_dict in args:
merged_dict.update(input_dict)
return merged_dict | 4328c53d4b1c8b423465d3e69a4df6253869ec0e | 586,806 |
def get_output_port(controller, s1, s2):
"""
Gets output port of a switch2switch connection
:param controller:
:param s1:
:param s2:
:return:
"""
return controller.data_map[s1][s2]['in_port'] | c712409000281449ea6af040cd00918cc6d18240 | 586,807 |
import torch
def distance_matrix_vector(anchor, positive):
"""Given batch of anchor descriptors and positive descriptors calculate distance matrix"""
d1_sq = torch.sum(anchor * anchor, dim=1)
d2_sq = torch.sum(positive * positive, dim=1)
eps = 1e-12
return torch.sqrt(torch.abs((d1_sq.expand(posit... | 83274367deb5d41ccf2d1bb22a003fa476698d5f | 586,808 |
def AcCheckProgs(context, programs, selection=None, value_if_not_found=None,
path=None, pathext=None, reject=[]):
"""Corresponds to AC_CHECK_PROGS_ autoconf macro.
Check for each program in **programs** list existing in **path**. If one is
found, return the name of that program. Otherwise, c... | 8c12590e837856c4b44cc340a4e94d872c7fe185 | 586,809 |
def next_smallest(target, in_list):
"""
Returns the next Lowest number in the in_list.
If target is smaller the the last number in in_list, will return the first
item in the list.
"""
next_lowest = None
for item in in_list[::-1]:
if item < target:
next_lowest = item
... | 04ad8c8c9a1e99ef0761ee9372992c0506cc9ee3 | 586,811 |
def version_tuple(version):
"""
Parse the plugin version number into a tuple
"""
try:
ret = tuple(map(int, version.split(".")))
except:
ret = (0,)
return ret | 3fa3a818aa8037390f4d29a6657dea1f27bcbd67 | 586,814 |
def _read_file_to_string(file_path: str) -> str:
"""Returns the contents of the given file as a string
"""
with open(file_path) as file:
contents = file.read()
return contents | ee861cc47af5313ead86aca46d455f8c634e419a | 586,816 |
import torch
def gamma_pdf(alpha, beta, x):
"""
PDF for a Gamma(alpha, beta) distributed RV.
"""
return torch.pow(beta, alpha) / torch.exp(torch.lgamma(alpha)) \
* torch.pow(x, alpha - 1) * torch.exp(-beta * x) | bd35bc48504014120e6497a2825a9bf77d01c0af | 586,820 |
def same_entity(cluster, argument, graph):
"""
Receives a cluster and an argument mention and returns whether this argument mention
is similar to the cluster, i.e. if the arguments in the clusters are all mentions of the same
coreference chain.
:param cluster: the cluster of mentions
:param argu... | a8d42f9430d345ed4363c3010c9bdbea21da202b | 586,821 |
import math
def osm_lat_lon_to_x_y_tile(lat_deg, lon_deg, zoom):
""" Gets tile containing given coordinate at given zoom level """
# taken from http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames, works for OSM maps
lat_rad = math.radians(lat_deg)
n = 2 ** zoom
xtile = (lon_deg + 180) / 360 * ... | 5e0d124668370a74800092b5184673092836d030 | 586,826 |
def empty_str(value: str) -> bool:
"""Return True if string is empty (whitespace don't count) or None.
"""
return True if value is None else value.strip() == '' | 23420f8dacb8447f9338cf34a66bb7c21284d6bb | 586,828 |
def flatten(d: dict, _key_prefix: tuple = tuple()) -> dict:
"""Convert nested dict `d` to a flat dict with tuple keys.
Input `_key_prefix` is prepended to the keys of the resulting dict,
and is used internally for recursively flattening the dict."""
result = {}
for key, value in d.items():
f... | 77af309bd60ed88fab93dfb32fa92f20071fd79a | 586,830 |
def contains_sequence_or_url(video_path: str) -> bool:
"""Checks if the video path is a URL or image sequence."""
return '%' in video_path or '://' in video_path | 912333499928a4f3da237fb04aea83685dc64c5b | 586,831 |
import calendar
def monthly_labels(t1, t2, every=6):
"""Returns labels for the months between two dates.
The first label corresponds to the starting month, while the last label
corresponds to the month after the ending month. This is done for better
bracketing of the plot. By default, only the label ... | 7d6ec776bb13eccdd028fa577a54ae36dfa197bf | 586,835 |
import requests
def get_languages(api_url):
"""
Return supported languages as a list of dictionaries.
Args:
api_url (str): API base url.
Returns:
List[dict]:
Supported languages as a list of dictionaries.
Each dictionary contains three keys, ``name``, ``code`... | c36b6e914ad3f3ce35aa1fd166d37d2c25ed8527 | 586,837 |
def find_hadoop_java_stack_trace(lines):
"""Scan a log file or other iterable for a java stack trace from Hadoop,
and return it as a list of lines.
In logs from EMR, we find java stack traces in ``task-attempts/*/syslog``
Sample stack trace::
2010-07-27 18:25:48,397 WARN org.apache.hadoop.map... | c49dbacdddaf79f19a37ec6f763ef88eb9456539 | 586,839 |
def convert_to_single_atom_aromatic_string(aromatic_atom_labels):
"""
Checks the triple of aromatic atom labels and returns the one with lower atom name
Parameters
----------
aromatic_atom_labels: list of str
triple of atom labels
Returns
-------
str: A label of a single atom re... | 4f65076f3d4630347768596358cc6cfcfbc7d98f | 586,843 |
def index_to_row(index):
"""
Returns the row name of given 0-based index.
Parameters
----------
index : int
0-based row index.
Returns
-------
unicode
Row name.
Examples
--------
# Doctests skip for Python 2.x compatibility.
>>> index_to_row(0) # docte... | 6ff37571f41b171b9c204aec910d3ba7009fd092 | 586,845 |
def from_json(json_data: dict, delimeter: str = "|") -> str:
"""Transforms JSON into a plain text
:param json_data: JSON object that needs to be converted to plain text
:param delimeter: Delimeter to be used in the plain text
:type json_data: dict
:type delimeter: str
:return: Plain text from J... | a6eb193a91fbd346f4235a8829614d7dbbb8df8b | 586,846 |
def get_clip_recording_file(clip):
"""
Gets the recording file containing the specified clip.
Parameters
----------
clip : Clip
the clip whose recording file is to be gotten.
Returns
-------
RecordingFile or None
the recording file containing the specif... | 42256cca2f0205a15f088d63ca1e7ff9ec377915 | 586,847 |
def database(result):
"""
Normalize the database name.
"""
if result["database"] == "PDBE":
return "PDB"
return result["database"] | 83c2e26fa337b97442cb8ad01510f1908a55a98b | 586,850 |
def get_class_weights(label_column):
"""
The function fetches for class weights from the data,
let :label_column: pandas series of string labels
"""
weights = {}
counts = label_column.value_counts()
weights[0] = (1/counts['4top'])*(len(label_column))/2.0
weights[1] = (1/counts['ttbar'])*(len(label_column))/2... | 7cf82b97675a7e83219f8fa8c8629f393be72797 | 586,852 |
import random
def randChooseWeighted(lst):
"""Given a list of (weight,item) tuples, pick an item with
probability proportional to its weight.
"""
totalweight = sum(w for w,i in lst)
position = random.uniform(0, totalweight)
soFar = 0
# We could use bisect here, but this is not going t... | 7abb650d9df32f2e12412a31173336507a0b3738 | 586,861 |
def get_annotation_url(cfg):
"""Returns (str): LogDog stream URL for the configured annotation stream.
Args:
cfg (Config): The bootstrap config.
"""
return 'logdog://%(host)s/%(project)s/%(prefix)s/+/recipes/annotations' % {
'host': cfg.host,
'project': cfg.params.project,
'prefix': cfg.p... | 8c88c23d6ff1fa3fe02e70a4944102c4e268477d | 586,862 |
def map_llc_result_to_dictionary_list(land_charge_result):
"""Produce a list of jsonable dictionaries of an alchemy result set
"""
if not isinstance(land_charge_result, list):
return list(map(lambda land_charge: land_charge.to_dict(),
[land_charge_result]))
else:
... | 40fe98c22281e4e0121cd3f53f9619f4c2c37568 | 586,864 |
def test_for_single_dict(source: str, calc_results: dict) -> bool:
"""
Returns True if 'source' is a str representing a variable name
within 'calc_results' whose value itself is a single-level
dictionary of keyword values.
"""
gotten = calc_results.get(source, "")
return isinstance(gotten, ... | 345a604e050ddafadd00225e6acbc8e2cece5ff6 | 586,865 |
def crop(img, i, j, h, w):
""" Crop an image.
Args:
img (numpy.ndarray): image to be cropped.
i: upper pixel coordinate.
j: left pixel coordinate.
h: height of the cropped image.
w: width of the cropped image.
Returns:
(ndarray): the cropped image.
"""
... | d62c9f117963dabd2188f8f755afceae99fa67aa | 586,866 |
def symbol_converted(symbol):
"""
Input: symbol in the form '0005.HK' (from Alpha Vantange data)
Output: symbol in the form '5' (for TWS)
"""
slice_index = 0
for i in range(0,4):
if symbol[i]=='0':
slice_index = i+1
else:
break
return symbol[slice_inde... | f220965491d9d5af2f6d515a5332115c73c64af1 | 586,868 |
def _get_url(document):
"""Return the URL for the given JSON-LD document."""
return document['@id'] | 6fb28708b763b9de6cc4aa7820411eec99d41d11 | 586,873 |
from typing import OrderedDict
def create_object_detection_label(annot_dict):
"""
Uses an annotation (parsed to a dictionary from an XML file) to create a
python dictionary that represents a label for the object detection task.
The resulting dictionary has the following format:
{
"image-s... | 8a285e578a1fef1f9ea864ee60a859ec5d176bc4 | 586,874 |
async def get_next_version(db, ref_id: str) -> int:
"""
Get the version number that should be used for the next index build.
:param db: the application database client
:param ref_id: the id of the reference to get the next version for
:return: the next version number
"""
return await db.in... | 9dacefccd5cf0e83978c05d0d754ea3659aa1761 | 586,877 |
def dformat(val, ndigits, slen):
"""
Right-pads a decimal with spaces such that there are max_exp number of characters after the dot
and the complete string is max_len characters in width.
"""
digits = ndigits + val.as_tuple().exponent if val.as_tuple().exponent < 0 else ndigits + 1
return f"{f... | 92480d5c4300004fa2b9cf2c55842e5f8cdb10d8 | 586,878 |
import torch
def cross_entropy_accuracy(preds, targets):
"""Accuracy for regular CrossEntropyLoss"""
_, preds = torch.max(preds, dim=1)
acc = 100*(preds == targets).float().mean()
return acc | 7cda01ae54b8e68d14148a96997704f0d07e32f4 | 586,879 |
def lerp(x, x0, x1, y0, y1):
"""Linear interpolation of value y given min and max y values (y0 and y1),
min and max x values (x0 and x1), and x value.
"""
return y0 + (y1 - y0)*((x - x0)/(x1 - x0)) | 27f1302343bee358424efa72b1c42bed4b009f4e | 586,880 |
import torch
def pad_framewise_output(framewise_output, frames_num):
"""Pad framewise_output to the same length as input frames.
Args:
framewise_output: (batch_size, frames_num, classes_num)
frames_num: int, number of frames to pad
Outputs:
output: (batch_size, frames_num, classes_num)... | 146d3b94f18a5fa36e6a5c0b8f598d801e05e7c5 | 586,881 |
import re
def snake_case_str(s):
"""
Translate a string like "foo_Bar-baz whee" and return "foo_bar_baz_whee".
"""
return re.sub(r'([^a-z0-9]+|^)(.)', lambda m: f'{"_" if m.group(1) else ""}{m.group(2).lower()}', s, flags=re.IGNORECASE) | 150edd828e30a585170c053b797e9e6990cae20b | 586,885 |
def check_your_guess(ans, your_guess, turns, history):
"""
The function checks whether the format of user's guess is correct
and calculates how many left chances (depends on the format).
:param ans: str, the answer
:param your_guess: str, the letter user guesses
:param turns: int, how many left ... | 5b43858b8ce2af7f9683118fc318bdfbb702ffe8 | 586,887 |
from pathlib import Path
import re
import random
def _get_files_and_labels_list(dataset_dir):
"""Get a list of filenames and labels from the dataset directory
"""
file_list = []
lib_names = sorted(f.name for f in Path(dataset_dir).iterdir() if re.match(r"^n[0-9]+$", f.name))
class_id = {v: i for i... | 5c9cb6d0e8327ae847f0b8f1cb8c43cd312ddba9 | 586,889 |
from typing import List
from typing import Dict
def compute_probabilities_output(prob_list_output: List[Dict]) -> Dict[str, float]:
"""
A function to compute the probability for parallel experiment on two qubits.
Args:
prob_list_output(List[Dict]): List of probability dictionaries.
Returns:
... | 2288562c4bf32c3f74596ce1bdac6e820a8a2b6f | 586,891 |
import math
def knn(points, p, k):
"""
Calculates k nearest neighbours for a given point.
:param points: list of points
:param p: reference point
:param k: amount of neighbours
:return: list
"""
return sorted(points, key=lambda x: math.sqrt((x[0] - p[0]) ** 2 + (x[1] - p[1]) ** 2))[0:... | 923d46de8ca6e8d11e19b6d455ee450687b1a349 | 586,893 |
def get_service_id_from_instance_id(instance_id):
"""Extracts the service_id from the instance_id. instance_ids begin with a service_id followed by a period"""
return instance_id.split('.')[0] | 9ae493dd6b4e644131cce0f372feb4633c0d2d13 | 586,895 |
def resolve_username(obj, _):
"""Convert 'username' from bytes to string."""
return obj.username.decode() | d567ff719e816a8c1520663f23f4375a23542bec | 586,896 |
def matching_paren_index(expression, open_paren_index):
""" Return the index of the parenthesis matching the one in the indicated position."""
count = 1
for i in range(open_paren_index + 1, len(expression)):
if expression[i] == "(":
count += 1
elif expression[i] == ")":
... | 89f3c019de5ffb94521baec36545ed179c1b850b | 586,897 |
import pickle
def pickle_data(data, pathToPickleFile):
"""
Pickle data to the specified file.
Example use: pickle_data(ground_truth_dict, os.path.join(output_dir, 'ground_truth.pkl'))
:param data: variable / data structure to pickle, e.g. myDict
:param pathToPickleFile: file for pickling, e.g. 'da... | 83315e4a4aed733d52ff072a1aa5e9eb0b63c6e9 | 586,905 |
import itertools
def match(thresh_results, test_records):
"""
Compares the results learned from data mining with a verification case for which the actual results are known
and outputs a "Match Factor" based on how well the automation matched the actual results as if they weren't known.
Imports the r... | d1d427c45e6b0074e4cab43d11a7b1c94e29fbba | 586,906 |
import re
def email_parser(email):
"""email parsing function to extract useful information(username and domain) from email"""
#list holding information to parse and parsed_info variable holding the extracted(splits) info with parsed output
info_to_parse, parsed_info, = ['username','domain'], re.split(r"@",em... | 7920c7001b74c3f45bb124f620ce15ac060c288c | 586,908 |
import json
def object(obj):
"""
Return a jsonified string represenation of obj if obj is jsonifiable else
return obj untouched
"""
if isinstance(obj, dict) or isinstance(obj, list):
return json.dumps(obj)
return obj | 6ed017531c2f16546ebefd6a6e50661aba5056fe | 586,911 |
def function_arn_to_uri(function_arn):
"""
This function takes the ARN of a lambda function and
returns its URI that is used by apigateway to call the
function.
For example
::
arn:aws:lambda:us-west-2:756048602902:function:hello_world
becomes
::
arn:aws:apigateway:us-west... | dc725d23308837e4b6503d4009271eb9d00ff5a2 | 586,916 |
import torch
def graph_collate_fn(batch):
"""
The main idea here is to take multiple graphs from PPI as defined by the batch size
and merge them into a single graph with multiple connected components.
It's important to adjust the node ids in edge indices such that they form a consecutive range. Other... | a74db17daf39a04c1b8c864327046de19a52d24a | 586,917 |
import time
import calendar
def jinja_resilient_datetimeformat(value, date_format="%Y-%m-%dT%H:%M:%S"):
"""custom jinja filter to convert UTC dates to epoch format
Args:
value ([str]): [jinja provided field value]
date_format (str, optional): [conversion format]. Defaults to "%Y-%m-%dT%H:%M:%... | 30e165886bdcb7db46d5ab2217bb2f59546a6e69 | 586,919 |
from typing import Union
from typing import Any
def get(d: dict, keys: Union[str, list[str]], safe: bool = True) -> Any:
"""Get dict value by keys.
Args:
d (dict): Target dict.
keys (List[str]): Keys.
safe (bool, optional): Safe or not.
Raises:
KeyError: Not found key on ... | 0a819a1afde80c4f3c975508266afeb4c039f6b0 | 586,922 |
def left_join(HM1, HM2):
"""Left join 2 hash maps."""
final = dict()
for key in HM1:
final[key] = [HM1.get(key), None]
for key in HM2:
if key in final:
final[key][1] = HM2.get(key)
return final | a1f3d5f1ff4e074d4edc256f57edbb9d142d85cf | 586,930 |
def _create_auth_token_header(auth_token):
"""
Create request header which supplies an auth token.
Args:
auth_token |str| = The auth token
Returns:
|dict| = Header containing an "X-AUTH-TOKEN" key
Raises:
|None|
"""
return {'X-AUTH-TOKEN': '{}'.format(auth_token)} | edc5c8a2680b6639d1bfe6cf521d91413c96c78f | 586,933 |
def serverUtilisation(arrival_rate: float, departure_rate: float) -> float:
""" Calculate the expected server Utilisation of the system with the given
parameters.
Params:
- arrival_rate: The exponential mean of arrival for the clients
- departure_rate: the exponential mean of the departure ... | 089dbf660764413ac4b76de5b73820b3287763fe | 586,936 |
from typing import Union
from typing import Iterable
import re
def clean_uids(uid_set: Union[str, Iterable[str]]) -> str:
"""
Prepare set of uid for use in IMAP commands
uid RE patterns are not strict and allow invalid combinations, but simple. Example: 2,4:7,9,12:*
:param uid_set:
str, that i... | 27460ff5a34785ecd1bcb0febdb4a830f142ac08 | 586,937 |
import _ast
def UnaryOpMap(operator):
"""Maps operator strings for unary operations to their _ast node."""
op_dict = {
'+': _ast.UAdd,
'-': _ast.USub,
'not': _ast.Not,
'~': _ast.Invert,
}
return op_dict[operator]() | 28cd159cf00d1e4d823f856b0ad466d205c5fa30 | 586,948 |
def get_profile_event(_request: dict) -> dict:
"""
Reconstruct webhook body
@param _request: POST request
@return: webhook event
"""
return {
"type": _request.get("type"),
"origin": _request.get("type"),
"message": _request.get("message"),
"profile": _request.get(... | 8359bba30a6db6502c02ed3bf4d1075e9c41bd3b | 586,949 |
def _convert_train_id_to_eval_id(prediction, train_id_to_eval_id):
"""Converts the predicted label for evaluation.
There are cases where the training labels are not equal to the evaluation
labels. This function is used to perform the conversion so that we could
evaluate the results on the evaluation se... | 66b6bae48e39b833408e2a3ec776c1386fdf28eb | 586,950 |
def fn_query(query_vec, q="*", cosine=False):
"""
Construct an Elasticsearch function score query.
The query takes as parameters:
- the field in the candidate document that contains the factor vector
- the query vector
- a flag indicating whether to use dot product or cosine similar... | 8116eb2e3485d78000e3bf54419bd8acad625065 | 586,955 |
import socket
def connect(addr, family=socket.AF_INET, bind=None):
"""Convenience function for opening client sockets.
:param addr: Address of the server to connect to. For TCP sockets, this is a (host,
port) tuple.
:param family: Socket family, optional. See :mod:`socket` documentation for availab... | ddf96aa4326228d6ad1c6fd89e85cbf0d36d4a5f | 586,956 |
import re
def IsTokenUri(uri):
"""Determine if the given URI is for requesting an access token."""
if uri in ['https://accounts.google.com/o/oauth2/token',
'https://www.googleapis.com/oauth2/v3/token',
'https://www.googleapis.com/oauth2/v4/token',
'https://oauth2.googleapis.... | 20ad88bde7aa35a0f7b8330ec4830ca7c8bf1376 | 586,958 |
def get_inventory_config(conf_type: str, inventory: dict) -> dict:
"""Return the configuration for a the config type as input
The returned value will contain a dictionary with 'name' as key
and the config as value
Args:
conf_type (str): type of configuration to initialize
inventory (di... | 0874481b5cc4e6a23f2cae21b125fb024584eccb | 586,963 |
def process_query_results(writer, result, repo_type):
""" Processes the query results for the repository search.
Uses the writer to record the repository information.
Args:
writer: CSV writer to record the data in a CSV file.
result: the results from the query.
repo_type: the repos... | abdef5eef4f8bf8c9cb60884399b9b9a36d810ef | 586,964 |
import calendar
def datetime_to_unixtimestamp(datetime):
"""Convert datetime to Unix timestamp."""
return int(calendar.timegm(datetime.timetuple())) | 7ed8376f724abe4ef043565dd8a4415d4447a11a | 586,965 |
import re
def attribute_is_list(attr):
"""
Checks if attribute denotes a list, and returns the name of the list and the given list index if so
:param attr: attr or attr[index]
:return: attr, index or None
"""
list_index_update = re.match("(.+)\\[([0-9]+)\\]", attr)
if list_index_update:
... | 22a83395f35270f292767db3fa3bec5020b63e87 | 586,966 |
def _LoadPathmap(pathmap_path):
"""Load the pathmap of obfuscated resource paths.
Returns: A dict mapping from obfuscated paths to original paths or an
empty dict if passed a None |pathmap_path|.
"""
if pathmap_path is None:
return {}
pathmap = {}
with open(pathmap_path, 'r') as f:
for ... | 48b9b73926b77081587e898dd89744b68478ba0b | 586,968 |
def generate_model_config(name, n_filters, nonlinearity='relu'):
""" Generates a spec describing how to build the model
Args:
name: name for this model config
n_filters: list of num filters for each layer - [n_layers]
Returns:
model_spec
"""
model_config = {
'name': name... | 7f4fdd31882131a77cdd7fd8e2441e7ba29c7500 | 586,971 |
def set_digital_out(id, signal):
"""
Function that returns UR script for setting digital out
Args:
id: int. Input id number
signal: boolean. signal level - on or off
Returns:
script: UR script
"""
# Format UR script
script = "set_digital_out(%s,%s)\n"%(... | ac4d24aed6129bab0122f9ecc4a00d8616151967 | 586,974 |
def batch_mc_acc(predicted):
""" Compute the accuracies for a batch of predictions and answers """
N, C = predicted.squeeze().size()
_, predicted_index = predicted.max(dim=1, keepdim=True)
return (predicted_index == C - 1).float() | d5258ab5eb831adbd90c1e5688b999a1d73c4a62 | 586,975 |
import torch
def template_edge_loss(meshes, template_mesh):
"""
Computes mesh edge length regularization loss averaged across all meshes
in a batch. Each mesh contributes equally to the final loss, regardless of
the number of edges per mesh in the batch by weighting each mesh with the
inverse numb... | 09fd636b21b6fe4cfe45a220b3f61c3c8cda42d1 | 586,979 |
def fixture_all_countries(south_africa, nigeria, egypt, kenya):
"""
Returns a map of all country objects.
"""
return {
"south_africa": south_africa,
"nigeria": nigeria,
"egypt": egypt,
"kenya": kenya,
} | 054cc2d98fd9d5a58a183a68c13c25208dfea4e9 | 586,980 |
import torch
def ln_sub_divTH(x : torch.Tensor, alpha : torch.Tensor, beta : torch.Tensor) -> torch.Tensor:
"""
out = (x - beta[None, :, None]) / alpha[None, :, None]
"""
return (x - beta[None, :, None]) / alpha[None, :, None] | 7b85119f4f978ca1d8168ee7a7bad42fed8dac5e | 586,981 |
def _transform_gmt(gmt):
"""Convert ACSN correspondence GMT file into a dictionary."""
acsn_hgnc_dict = {}
for line in gmt:
parts = line.strip().split('\t')
acsn_hgnc_dict[parts[0]] = parts[2:]
return acsn_hgnc_dict | 06325a24a4f1957d528feb1bdb24b2f0348f96c9 | 586,982 |
from typing import List
from typing import Any
def items_str(
items : List[Any],
quotes : bool = True,
quote_str : str = "'",
commas : bool = True,
comma_str : str = ',',
and_ : bool = True,
and_str : str = 'and',
oxford_comma : bool = True,
spac... | 41cd852b52960ad9ebb12d8040bdec67c1b4aa23 | 586,988 |
def choices_from_list(source, prepend_blank=True):
"""
Convert a list to a format that's compatible with WTForm's choices. It also
optionally prepends a "Please select one..." value.
Example:
# Convert this data structure:
TIMEZONES = (
'Africa/Abidjan',
'Africa/Accra',
... | 37552fb8fd771a0a1cfd5ac2cf2909952ec442bf | 586,989 |
def flatten_nested_dict(nested_dict):
"""Flatten a nested dict with the keypath as key.
Args:
nested_dict (dict): Nested dict to flatten.
Returns:
dict - A dict with keypath as key and plan informations in dict form as
value.
Example:
>>> flatten_nested_dict(dictionary... | 547062786a21c1d49a4bb27648ff5e808e0f394c | 586,995 |
from typing import Counter
def degree_histogram(H):
"""Returns a degree histogram including bin centers (degree values).
Parameters
----------
H : Hypergraph object
The hypergraph of interest
Returns
-------
tuple of lists
First entry is observed degrees (bin centers),
... | 2a2a66ac1976808c007d8a4d544195b402485007 | 586,996 |
def tag(tag):
"""Select a single tag."""
return {'tag': tag} | 801a52c625cd8edd21c6bdf1d77e259f478f7c0c | 586,999 |
def _parse_condor_submit_job_id(condor_submit_out):
"""Parse job id from condor_submit output string.
Assume format:
Submitting job(s).
1 job(s) submitted to cluster 8.
"""
return float(condor_submit_out.split()[-1]) | 1066646bb054ddd917a5b7c6c1760d54eda3f69b | 587,000 |
from typing import Dict
from pathlib import Path
def _get_arg(
root_dir: str,
tmpdirname: str,
nb_to_py_mapping: Dict[Path, Path],
project_root: Path,
) -> Path:
"""
Get argument to run command against.
If running against a single notebook, it'll be the filepath of the converted
noteb... | e1c50b811fc0fef0cae2a976f69aa9c3eba5031c | 587,002 |
import re
def get_strings_with_bad_escaping(strings):
"""Find strings that contain quotes that are not escaped
The string 'hello "world"' is not allowed, the string
'hello \\"world\\"' is fine, since the string will remain properly
escaped when stuck into a js file
"""
quotere = re.compile(r"[... | 986500d4fc7e2d963284522198863b2a99cfa300 | 587,003 |
import functools
def getattr_partial_aware(obj, att_name, *att_default):
""" Same as getattr but recurses in obj.func if obj is a partial """
val = getattr(obj, att_name, *att_default)
if isinstance(obj, functools.partial) and \
(val is None or att_name == '__dict__' and len(val) == 0):
... | 7abd5e11b44c313d98a1ba131d11b039f596ee7b | 587,006 |
import typing
from functools import reduce
import operator
def get_by_path(root: dict, path_list: typing.List[str]):
"""
Access a nested object in root by item sequence.
:param dict_object: the dictionary to access
:param path_list: the list of strings containing the path
:return the value of the ... | 80887ef4832b6abd788f9469536532321d68e889 | 587,008 |
def url_to_id(url):
"""Take an url and return the youtube id that it contains."""
return url.split(sep='watch?v=')[1].split('=')[0] | 6870bfa6a7d54e424b2489e23f9322bae28ac51d | 587,018 |
import string
import random
def randomstring(strlen=12, prefix=''):
"""
Generate a random string from the set of ascii letters and
decimal digits.
Parameters:
strlen Length of generated string including prefix.
prefix Prefix string to random string.
Returns:
String.
"""
n = strlen - ... | d3aeaefc33b7a7d53677696c5d6cd972c222fc1b | 587,019 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.