content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _make_table_subsections(dict_of_variables, plural):
"""
Adds Value | Variance columns for the section.
"""
s = "s" if plural else ""
html = []
for key, section in dict_of_variables.items():
for name, val in section.items():
html.append(f"<th class='sc-subheader'>Value{s}<... | fe9ec60834c75d2001aecafddd9eeb44217f3cab | 28,611 |
def idx2word(idx,word_model):
"""
inverse of above
"""
return word_model.wv.index2word[idx] | b1dbf63b4090e76880c1bb6e6ac5b8be78341f8d | 28,612 |
def fetch_from_graph(list_of_names, graph):
""" Returns a list of shared variables from the graph """
if "__datasets_added__" not in graph.keys():
# Check for dataset in graph
raise AttributeError("No dataset in graph! Make sure to add "
"the dataset using add_datase... | 0dd8cb4446f126b7f7a1f4a189d818168782ffc7 | 28,614 |
def to_full_year(two_digit_year, threshold=80):
"""Converts a year given by two digits to a full
year number.
Input params:
threshold: up to which ending the year should be thought
of as 1900s.
"""
ending = int(two_digit_year)
return (1900+ending) if ending > threshold else (2000+ending) | 346654e1106795fa3d64d0d05ede16074c8a181e | 28,615 |
import os
import re
def read_server_user_file(server_path):
"""Reads the dot server file according to a format described in the documentation pages."""
temp_dict = {}
if (os.access(server_path, os.R_OK) and os.access(server_path, os.F_OK)):
with open(server_path, 'r') as server_user_file:
server_user_file = s... | 582d77b8c7c2a4b200e3ba64230e737243f146c4 | 28,616 |
import multiprocessing
def calculate_number_of_workers():
"""Set the number of processes to use, minimum of 1 process"""
output_number_of_workers = multiprocessing.cpu_count() - 1
if output_number_of_workers < 1:
output_number_of_workers = 1
return output_number_of_workers | f84db2be25fd780ed57e193028fac77c01930191 | 28,617 |
def create_supplemental_metadata(metadata_columns, supplemental_metadata):
"""Function to identify supplemental metadata store them"""
for metadata_column_list in metadata_columns:
for column in metadata_column_list:
supplemental_metadata.pop(column, None)
return supplemental_metadata | bfc5e9c3a1df4cd1eb3a523fdadad8599f1655de | 28,618 |
def identityfunc(arg):
"""Single argument identity function.
>>> identityfunc('arg')
'arg'
"""
return arg | 6987908c3229623fcd5201978aa33f2362caa54d | 28,619 |
def is_mixed_case(string: str) -> bool:
"""Check whether a string contains uppercase and lowercase characters."""
return not string.islower() and not string.isupper() | 230a452a2690fda4a90f59e8aaede8f8233c78a7 | 28,621 |
import hashlib
def md5(string):
"""
生成一个字符串的md5值
:param string:
:return:
"""
md5_obj = hashlib.md5()
md5_obj.update(string.encode("utf8"))
return md5_obj.hexdigest() | 4763cb8090a829131dfdcddd32e860a6fb1e5c7a | 28,622 |
def get_timestamp(integer):
"""
Parses integer timestamp from csv into correctly formatted string for xml
:param integer: input integer formatted hhmm
:return: output string formatted to hh:mm:ss
"""
string = str(integer)
if len(string) == 1:
return '00:0{}:00'.format(string)
eli... | 81b4fa1e9237ee37abfe067b76b2e8656b409473 | 28,623 |
import base64
def CreateMessage(sender, to, subject, tempMessage):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Retur... | 7c3c017a46174d3068c935376194ab2fd81f4ce2 | 28,624 |
def get_thread(service, thread, userid="me"):
"""Get a message."""
thread = service.users().threads().get(
userId=userid,
id=thread['id']
).execute()
return thread | 72b532bb1cf83d3fe5765e716bcaeebdc8fc31c4 | 28,625 |
from typing import List
def _sanitize_key_and_value(items: List[str]) -> List[str]:
"""Removes unwanted characters on key and value"""
# if there are more than two items, we return the list unchanged, so an error will be raised later
if len(items) != 2:
return items
key, value = items
key ... | 4a5bad5262434afb31a41f9499097a87e51587dd | 28,626 |
import logging
def rouge_log(results_dict):
"""Log ROUGE results to screen and write to file.
Args:
results_dict: the dictionary returned by pyrouge
dir_to_write: the directory where we will write the results to"""
log_str = ""
for x in ["1", "2", "l", "s4", "su4"]:
log_str += ... | fe6d4602413fd7d90d257eb752aa4f5b108d7acd | 28,629 |
import os
import fnmatch
def get_all_defconfigs():
"""Get all the defconfig files under the configs/ directory."""
defconfigs = []
for (dirpath, dirnames, filenames) in os.walk('configs'):
dirpath = dirpath[len('configs') + 1:]
for filename in fnmatch.filter(filenames, '*_defconfig'):
... | 3b28f6100a0b8269bc20e922e2a9beb19866c055 | 28,630 |
import hashlib
import struct
def pkcs12_derivation(alg, id_byte, password, salt, iterations, result_size=None):
"""Compute a key and iv from a password and salt according to PKCS#12
id_byte is, according to https://tools.ietf.org/html/rfc7292#appendix-B.3 :
* 1 to generate a key
* 2 to generate an in... | e819121a8f6dc211b335dfc78cec0d1f0e5314ec | 28,631 |
def rellenaLista(maxTrials,tipoDummy):
"""
Funcion que nos permite rellenar listas con un valor
predefinido
maxtrial -> int
dumy-any
"""
lista=[]
for i in range(maxTrials+1):
lista.append(tipoDummy)
return lista | 6ea3cc43a3534b9ae49f39b5e4dc8b21fe9db984 | 28,632 |
import subprocess
import time
def submit_job(job):
"""
Submit a kinbot run usung subprocess and return the pid
"""
command = ["python","kinbot.py","%s"%job[2:],"&"]
process = subprocess.Popen(command,stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(1)
pid =... | b4d987bcba655cc8a6b49819fa62cf89b416dcc3 | 28,633 |
def assign_ret_all_i(pot_y, pot_y_var, pot_y_m_ate, pot_y_m_ate_var, l1_to_9,
share_censored, ret_all_i, n_x, idx=None):
"""Use to avoid duplicate code."""
if idx is None:
idx = ret_all_i[0]
pot_y[idx, :, :] = ret_all_i[1]
if pot_y_var is not None:
pot_y_var[idx, :, ... | 9fb7dea80fe2d32d2e2b2fe68892b53ecb2ea0c3 | 28,634 |
from bs4 import BeautifulSoup
import re
def _parse_table(html, id, include_headers=True):
"""
Parse HTML table with given ID.
Keyword arguments:
html -- the HTML to parse
id -- the ID of the table to parse
include_headers -- whether to include the headers in the output (default True)
Ret... | e4317f657645f9de4a9055b1b4dc23ca7b75c56c | 28,635 |
def using_append_to_construct_a_list(n):
""" Constructs [1, 2, 3, ... n] by using the append list method. """
new = []
for k in range(1, n + 1):
new.append(k)
return new | 529946ad34ec3c4b86a2decabffc052fd74e7cbe | 28,636 |
def is_single_bool(val):
"""Check whether a variable is a ``bool``.
Parameters
----------
val
The variable to check.
Returns
-------
bool
``True`` if the variable is a ``bool``. Otherwise ``False``.
"""
# pylint: disable=unidiomatic-typecheck
return type(val) =... | 24a18577e08d43c36bdb89a196eb1406608528a5 | 28,637 |
def largest_product(arr):
"""
Returns the largest_product inside an array incased inside a matrix.
input <--- Array of array with 2 value inside each
output <--- Largest Product of pair inside Matrix
"""
largest_product = 0
for container in arr:
x, y = container
if x * y > la... | 5a38f957c9f71a58a8bdbf902cda6d47aaedf12a | 28,638 |
def response_type_cmp(allowed, offered):
"""
:param allowed: A list of space separated lists of return types
:param offered: A space separated list of return types
:return:
"""
if ' ' in offered:
ort = set(offered.split(' '))
else:
try:
ort = {offered}
e... | 1a5dafe085820472128b9a5cfdc74fdce4acdf4f | 28,639 |
def update_navigator_object(nav_obj, coll_descr, schema_descr):
"""Updates navigator object. Inserts new dataset, new perspective
or new issue, it depends on what collections are in navigator object
already. Returns dataset description that was added/updated.
nav_obj -- previous navigator object
... | f89fa754073b0a09c3537f816a37408611c71604 | 28,640 |
import configparser
def config_parser(config_file):
"""
Configuration file parsing.
Returns dictionary with configuration parameters:
'one_auth_file' - Opennebula sessions credential file path,
'key_file' - AES key file path,
'workers_quantity' - ZMQ workers quantity,
'server_ip' - IP addr... | 8847d8344caeed24b6673dc34712430b8892d18b | 28,641 |
def always_true(*args, **kwargs):
"""Always returns True, no matter the arguments."""
return True | 94d8e3845fecf0ea2d991bbd09a03c5fd14c4ca8 | 28,642 |
def average_error(state_edges_predicted, state_edges_actual):
"""
Given predicted state edges and actual state edges, returns
the average error of the prediction.
"""
total=0
for key in state_edges_predicted.keys():
#print(key)
total+=abs(state_edges_predicted[key]-state_edges_... | 40d132682e49b556e8cc0fc71015947202b9cf08 | 28,643 |
import re
def remove_bracketed_text(s):
"""
Removes text in brackets from string :s: .
"""
s = re.sub(r'\([^\()]+?\)', '', s)
s = re.sub(r'\[[^\[]]+?\]', '', s)
s = re.sub(r'\[[^\[]]+?\]', '', s)
return s.strip() | 13290df1b16eae86dca8f9cc00be93660b25b741 | 28,644 |
import os
def load_reco2dur(reco2dur_file):
"""load_reco2dur."""
# returns dictionary { recid: duration }
if not os.path.exists(reco2dur_file):
return None
lines = [line.strip().split(None, 1) for line in open(reco2dur_file)]
return {x[0]: float(x[1]) for x in lines} | bed26676f63d4741377f3de99b6beff271b39431 | 28,645 |
def getExposure(header={}):
"""
:param header:
:return:
"""
expTime = max(float(header.get('EXPOSURE', 0)),
float(header.get('EXPTIME', 0)),
)
return expTime | d1459d72b26b2cc132079919b57feb671985bb82 | 28,648 |
def expand_dims_as(x, y):
"""Expand the shape of ``x`` with extra singular dimensions.
The result is broadcastable to the shape of ``y``.
Args:
x (Tensor): source tensor
y (Tensor): target tensor. Only its shape will be used.
Returns:
``x`` with extra singular dimensions.
"... | b914d4cc47916dc98ff535ff964b80d943f88d87 | 28,649 |
import re
def get_branches(aliases):
"""Get unique branch names from an alias dictionary."""
ignore = ['pow', 'log10', 'sqrt', 'max']
branches = []
for k, v in aliases.items():
tokens = re.sub('[\(\)\+\*\/\,\=\<\>\&\!\-\|]', ' ', v).split()
for t in tokens:
if bool(re.s... | 25cd6ed33275229d1124b6dfbec503840104dd26 | 28,650 |
def limit_phase_deg(phase,minphase=-180):
"""
Brazenly stolen from
https://stackoverflow.com/questions/2320986/easy-way-to-keeping-angles-between-179-and-180-degrees
"""
newPhase=phase
while newPhase<=minphase:
newPhase+=360
while newPhase>minphase+360:
newPhase-=360
retu... | 45be276475d2602e352c8b91a9705b1bf5290fb2 | 28,653 |
import os
def get_remote_vivado():
"""Return the address of the remote Vivado synthesis server as set by the,
REMOTE_VIVADO environment variable, otherwise return None"""
try:
return os.environ["REMOTE_VIVADO"]
except KeyError:
return None | 57a4b85dcffae1e6cae445b30651653d1d1637d2 | 28,655 |
import locale
def get_locale_currency_symbol():
"""Get currency symbol from locale
"""
locale.setlocale(locale.LC_ALL, '')
conv = locale.localeconv()
return conv['currency_symbol'] | 06f0363aaa4693a72fb53050e7d14fd297eff647 | 28,656 |
def calculate_first_vertices(dfd, zfd, Dc, hcc, wc, hc, hcd, lcd, psp, Q_100):
"""Compute the first batch of vertices based on the user inputs
Args:
Returns:
pt#i (double): General coordinate where x is the horizontal, z is vertical, and y is in/out of the domain
Q_100 (double): Velocity of second... | 3f66c12e85c60d7572600d9ca30c4226555789f9 | 28,658 |
import subprocess
def create_bladeGPS_process(run_duration=None, gain=None, location=None, dynamic_file_path=None):
"""Opens and returns the specified bladeGPS process based on arguments.
Args:
run_duration: int, time in seconds for how long simulation should run
gain: float, signal gain for the broadcast... | 56587e0878db57faa282ee806b0e5b2bb0002d67 | 28,659 |
def findNearestCoordinateOnFurthestFieldMap(freeMap, moveMap, maxFreePlaceIndex, speed, ownx, owny):
"""
Finds the nearest reachable coordinate in the next bigger area
:param freeMap: Map with free places/areas
:param moveMap: Map with maximum moves from players current position
:param maxFreePlaceI... | e63fddecd13a7e8a634740be20abe3ccf22d7dd6 | 28,661 |
def get_gap_between_two_equipment_items(first_item_str, second_item_str, gap_length) -> str:
""" Specifically made for the print_character_equipment function, because we want to have an
even gap between every printed items, we need to do this calculation to get the appropriate
amount of whitespace character... | 8b578e56737b646de9d54d7ddb005667493408ca | 28,662 |
from difflib import SequenceMatcher
def did_you_mean(unknown_command, entry_points):
"""
Return the command with the name most similar to what the user typed. This
is used to suggest a correct command when the user types an illegal
command.
"""
similarity = lambda x: SequenceMatcher(None, x... | 445dfb59344ea78fdc496f4b9cdaab39ef233bd3 | 28,663 |
import requests
import json
def RequestForMonthly(url, key):
"""[Makes a request to API with created URL.]
Arguments:
url {[string]} -- [url to make request from api.]
key {[string]} -- [Key for ExchangeRate currency, EUR to KEY.]
Returns:
[dictionary] -- [returns response text d... | 4e15bc62ab306094003bdfaf7ce04c45d410a45b | 28,664 |
def get_waze_navigation_link(xy_tuple):
"""
Create a navigation link from a tuple containing an x and y tuple for Waze.
:param xy_tuple: Tuple of (x,y) coordinates.
:return: String url opening directly in waze for navigation.
"""
return 'waze://?ll={lat},{lon}&navigate=yes'.format(lat=xy_tuple[1... | cd6e08453b84856e55922ee9ba7b042bc55d5901 | 28,667 |
def dictionary_table1():
"""Creates dictionary to rename variables for summary statistics table.
:return: dic
"""
dic = {"gewinn_norm": "Rank improvement (normalized)", "listenplatz_norm": "Initial list rank (normalized)",
"age": "Age", 'non_university_phd': "High school", 'univer... | e8a727049f5bd590c14c82f211bd266865724494 | 28,668 |
import yaml
def load_yaml(yml_path):
"""Load parameter from yaml configuration file.
Args:
yml_path (string): Path to yaml configuration file
Returns:
A dictionary with parameters for cluster.
"""
with open(yml_path, 'r') as stream:
data_loaded = yaml.safe_load(stream... | b123f1084c28dc6624d56036bac8d20278d5acea | 28,669 |
def format_list(str_list):
""" convert a list of strings to a string with square brackets "[\"something\", \"something\"]"
which is suitable for subprocess.run
"""
list_repr = ['\"{}\"'.format(item).replace("\"", "\\\"") for item in str_list]
joint_str = ",".join(list_repr)
return joint_str | e4e9ff96445413d7cfc4251ecbc1dca9a64339bb | 28,670 |
def format_percentile(q):
"""Format percentile as a string."""
if 0 <= q <= 1.0:
q = 100.0 * q
return '{:3.1f}%'.format(q) | 7451f8bb53b47a72e20c4cb94402922d497dff43 | 28,671 |
import itertools
def rankable_neighbours(chiral_cands):
""" Checks if the chiral atom candidates have rankable substituents on each site (i.e. discounting those whose
neighbour list contains the same univalent atoms).
:param chiral_cands: Atoms to test.
:return: maybe_chiral, not_chiral: lists of po... | 0ec982e667dfdad5fc060cd169f0db85544ad068 | 28,672 |
def rm_deleted_data(data):
"""移除已删除的数据"""
return [item for item in data if item.delete_time is None] | 032e9db81d990b16323410a22c796da0c9af9263 | 28,673 |
def find_in_list(list_one, list_two):
"""
Function to find an element from list_one that is in list_two
and returns it. Returns None if nothing is found.
Function taken from A3
Inputs:
list, list
Outputs:
string or None
"""
for element in list_one:
if ele... | f6fbd1ce96ee2e9cb4fed130dd2aa35a19fa68e1 | 28,674 |
def ternary_expr(printer, ast):
"""Prints a ternary expression."""
cond_str = printer.ast_to_string(ast["left"]) # printer.ast_to_string(ast["cond"])
then_expr_str = printer.ast_to_string(ast["middle"]) # printer.ast_to_string(ast["thenExpr"])
else_expr_str = printer.ast_to_string(ast["right"]) # pri... | f88fc65b684bff7ad61e0bc64d17b65bbe7735e5 | 28,675 |
import os
def read_subject_names(path):
"""Reads the folders of a given directory, which are used to display some
meaningful name instead of simply displaying a number.
Args:
path: Path to a folder with subfolders representing the subjects (persons).
Returns:
folder_names: The na... | 8693fb67b54a644da2275d70895be4c23838142b | 28,676 |
def defaultify(value,default):
"""Return `default` if `value` is `None`. Otherwise, return `value`"""
if None == value:
return default
else:
return value | f13b30e0ccc06d09d5be6fe9f82d8d99495f5b32 | 28,677 |
def my_contains(elem, lst):
"""Returns True if and only if the element is in the list"""
return elem in lst | d859f1a26d7f87deef9e11b8d3f3e8648ecc141d | 28,678 |
def repr_author(Author):
"""
Get string representation an Author namedtuple in the format:
von Last, jr., First.
Parameters
----------
Author: An Author() namedtuple
An author name.
Examples
--------
>>> from bibmanager.utils import repr_author, parse_name
>>> names = ['Last', 'First Last', '... | f15bba99a1c6466a6b3e0fbd30ac32109f6447b5 | 28,679 |
import numpy
def get_perfect_reliability_curve():
"""Returns points in perfect reliability curve.
:return: mean_forecast_prob_by_bin: length-2 numpy array of mean forecast
probabilities.
:return: mean_observed_label_by_bin: length-2 numpy array of mean observed
labels (conditional event f... | bc473f5f79f9b0fcaa66cbdeeca8b29ec5ac5c97 | 28,680 |
import json
def load_data(filename):
"""加载数据
返回:[(text, summary)]
"""
D = []
with open(filename, encoding='utf-8') as f:
for l in f:
l = json.loads(l)
text = '\n'.join([d['sentence'] for d in l['text']])
D.append((text, l['summary']))
return D | 8f1686443c444282fd576137c4cb371b60cd1555 | 28,681 |
def getFirstPlist(textString):
"""Gets the next plist from a set of concatenated text-style plists.
Returns a tuple - the first plist (if any) and the remaining
string"""
plistStart = textString.find('<?xml version')
if plistStart == -1:
# not found
return ("", textString)
plistE... | 19de59d42661488ad254a7afa8aded4f3f17bf1a | 28,682 |
def createTables(connection):
"""
createTables: creates tables in database connection for stockmarket
connection - sql connection object
return: boolean success or fail
"""
DBcurr = connection.cursor()
success = True
# try to create all database tables
try:
DBcurr.execute("CR... | 931010a495bd674e4a977095cce9e41124226389 | 28,684 |
import argparse
def initialize_arguments():
"""
Run through an argument parser and determine what actions to take.
"""
parser = argparse.ArgumentParser(
description="Run tests on agents in capture.py with ease.")
parser.add_argument(
"test", help="The name of the test to run, o... | 6f06ab5b3283db8f5ad770df19d04c6b5ad1cb63 | 28,685 |
def _ibp_add(lhs, rhs):
"""Propagation of IBP bounds through an addition.
Args:
lhs: Lefthand side of addition.
rhs: Righthand side of addition.
Returns:
out_bounds: IntervalBound.
"""
return lhs + rhs | b63b538cc1d412932bec86285077f786e5a9cd4e | 28,687 |
def show_and_get_competitions_list(api):
"""Show and return kaggle competitions.
This function show kaggle competitions which can get kaggle API and returns the list.
----------
Args:
api(KaggleApi_extended): authenticated kaggle API instance.
Return:
competitions(List(kaggle_mo... | 9d57e2ae4a8451d7870bab0749ba4ec2a35f1f33 | 28,689 |
import logging
import json
def load_db(db_file):
"""
Load the saved embeddings database
Argument
--------
db_file: JSON file with computed embeddings
"""
db = {}
logging.info('loading weighted vectors from {0}'.format(db_file))
with open(db_file, 'r') as f:
for line in f:
... | d7da6fe957ef3fc85e3ce8920653dab20ddd000b | 28,690 |
def train_model_and_get_test_results(model, x_train, y_train, x_test, y_test, **kwargs):
"""
Train the model on given training data and evaluate its performance on test set
Args:
model: various ML models
x_train: Training data
y_train: Training targets
x_test: Testing data
... | f3f8de07874796045a1268fd415d822c004a87aa | 28,691 |
def convert_proxy_to_string(proxy):
""" This function convert a requests proxy format to a string format """
return proxy['http'].split('//')[1] | 7e4fbb7b075fb2139fda83b52f562699c85a6b32 | 28,692 |
def ReadFile(path, mode='r'):
"""Read a given file on disk. Primarily useful for one off small files."""
with open(path, mode) as f:
return f.read() | cf007c6fcf826eccde7f42b87542794f1d4d8cb0 | 28,693 |
def get_region(region):
"""付録 A 暖冷房負荷と外皮性能の算定に係る設定
A.1 地域の区分
Args:
region(int): 省エネルギー地域区分
Returns:
int: 省エネルギー地域区分
"""
return region | 6f07eeee3d1114746e0597a6e72a7ac755d3137a | 28,696 |
from typing import List
def scale_row(row: List[float], scalar: float) -> List[float]:
"""
Return the row scaled by scalar.
"""
return [scalar * el for el in row] | d44901244199b9d39529a3e3bccc7a9eab9d332e | 28,697 |
def parse_map_line(line):
"""
:param line:
:return:
"""
tchrom, tstart, tend, tstrand, blockid, qchrom, qstart, qend, qstrand = line.strip().split()
return tchrom, int(tstart), int(tend), tstrand, blockid.split('.')[0], qchrom, int(qstart), int(qend), qstrand | e2b2b6298a8ff0b73541c752cf773dd50ae4e0b3 | 28,698 |
def get_action_value(mdp, state_values, state, action, gamma):
""" Computes Q(s,a) as in formula above """
result = 0
for to_state in mdp.get_all_states():
transition_probability = mdp.get_transition_prob(state, action, to_state)
reward = mdp.get_reward(state, action, to_state)
resul... | 226d8e01054552ae1108d3d83e0e438ddc821df9 | 28,702 |
def convert_shell_env(env):
"""Convert shell_env dict to string of env variables
"""
env_str = ""
for key in env.keys():
env_str += "export {key}={value};".format(
key=key, value=str(env.get(key)))
return env_str | 4f777dbeb2534529dbf76e2b5a203e4b2de7ed63 | 28,704 |
import requests
def get_identity_token(scopes='https://www.googleapis.com/auth/cloud-platform'):
"""
Getting an identity token from a google authorization service.
:param scopes: https://cloud.google.com/deployment-manager/docs/reference/latest/authorization
:return: bearer token
"""
host = '... | 70acf41bd322b70ce7d258688698d511e0c2211b | 28,707 |
def get_auc(labels, preds, n_bins=10000):
"""ROC_AUC"""
postive_len = sum(labels)
negative_len = len(labels) - postive_len
total_case = postive_len * negative_len
if total_case == 0:
return 0
pos_histogram = [0 for _ in range(n_bins+1)]
neg_histogram = [0 for _ in range(n_bins+1)]
... | 5fb872d728502f95e69066d53ca408329b1f588d | 28,708 |
def listify(maybe_list):
"""
Ensure that input is a list, even if only a list of one item
@maybeList: Item that shall join a list. If Item is a list, leave it alone
"""
try:
return list(maybe_list)
except:
return list(str(maybe_list))
return maybe_list | 07e8562d8759d386320f2b11c56c7193d14c6966 | 28,709 |
import argparse
def parse_arguments(arguments):
"""
This function parses command line inputs and returns them for main()
:branches: this is the total number of parallelizations to be run
:branch: this is a fraction of the parallelizations, e.g. 1 of 4
:config: full path to config.ini (or just con... | cdacf9ea2176f8e35fe225780c86d790ff3de7e2 | 28,710 |
def split_comma_separated(text):
"""Return list of split and stripped strings."""
return [t.strip() for t in text.split(',') if t.strip()] | 5030ff3dac88de0ef82f929cfcc5adf913b124a0 | 28,711 |
import re
def get_language_code_from_file_path(path):
"""
Retrieves the language code from the path of a localization-file by using a regex.
:param path: str
:returns: The language code of the file.
:type path: str
:rtype: str
"""
# Attention, this regex only works under os's with a ... | 8ca37c9756ea39f0384004d8ec823c279d51918b | 28,713 |
def scrap_insta_tag(inst) -> str:
"""
Scrap @instagram_tag from instagram account HTML.
"""
try:
inst_tag = inst.body.div.section.main.div.header.section.div.h2.string
except AttributeError:
inst_tag = inst.body.div.section.main.div.header.section.div.h1.string
return inst_tag | 75dfc2c8e5b997b97c8aa3bf85098a17c0d7438e | 28,716 |
import pickle
def read_pickle(name):
"""
Reads a pickle file
:param name: Path to the pickled file to read
:return: The deserialized pickled file
"""
with open(name, "rb") as input_file:
return pickle.load(input_file) | 4021e5f3aeba9824d07998658d88f9971843585f | 28,717 |
from typing import List
from typing import Dict
def build_final_outputs(outputs: List[Dict], old_new_dict: Dict) -> List[Dict]:
"""
Receives outputs, or a single output, and a dict containing mapping of old key names to new key names.
Returns a list of outputs containing the new names contained in old_new... | 930d9026ad731c8689110a2fd1bef0b3b13e79d9 | 28,718 |
def transform_box_format_gt(box):
"""x1,y1,x2,y2 to x1, y1, w, h"""
x1, y1, x2, y2 = box.x1, box.y1, box.x2, box.y2
return [x1, y1, x2 - x1, y2 - y1] | 10b32ec5f51a2ee5a558bf74345df4528c65b0ec | 28,719 |
import os
import msvcrt
import tty, termios, sys
def getch() -> str:
"""
Returns a single byte from stdin (not necessarily the full keycode for
certain special keys)
https://gist.github.com/jasonrdsouza/1901709#gistcomment-2734411
"""
ch = ''
if os.name == 'nt': # how it works on windows
... | a4adaf13b9024ee088e474ecaf003e6f60cdc54b | 28,721 |
def calc_corr_matrix(wallet_df):
"""Calculates the Pearson correlation coefficient between cryptocurrency pairs
Args:
wallet_df (DataFrame): Transformed DF containing historical price data for cryptocurrencies
"""
corrmat_df = wallet_df.corr()
return corrmat_df | 7d76f496783f129749888d7913a93919a5570273 | 28,722 |
import re
def parse_tags(s):
"""
Return a list of tags (e.g. {tag_a}, {tag_b}) found in string s
"""
return re.findall('{(\w+)\}*', s) | 28849f326ff6019b9e41ee6fa0f48cfebff0811e | 28,724 |
def cmp_name(first_node, second_node):
"""
Compare two name recursively.
:param first_node: First node
:param second_node: Second state
:return: 0 if same name, 1 if names are differents.
"""
if len(first_node.children) == len(second_node.children):
for first_child, second_child i... | 6dfe9c46a7d58de26745f745daf5491228312886 | 28,725 |
def replace_found_bytes(old_hdr,find,replace=None):
""" Find and replace bytes, if replace is None they are zeroed out """
assert type(old_hdr) is bytes and type(find) is bytes, "Wrong input type"
assert len(old_hdr) >= len(find),"Find must be smaller or equal input bytes"
if (replace is None):
... | c6c3ffcb627a19cf6d6b51f1c658057cd3bef1cb | 28,726 |
def count_parameters(model) -> int:
"""Count parameters in a torch model.
Parameters
----------
model : torch.nn.module
The model from which you want to count parameters.
Returns
-------
int
Total number of parameters in the model.
"""
return sum(p.numel() for p in ... | a3f398bb5969cd4d81c1702089698a2ed9d79d31 | 28,727 |
def set_indent(TokenClass, implicit=False):
"""Set the previously saved indentation level."""
def callback(lexer, match, context):
text = match.group()
if context.indent < context.next_indent:
context.indent_stack.append(context.indent)
context.indent = context.next_inden... | 194471f4b115b050e46d1b792291993207cd3c55 | 28,728 |
import csv
def get_csv_log_file_data(folder_list):
""" The Function takes a list of folders and returns combined list of entries
and the folder of the entry, taken from from the driving_log.csv file."""
csv_lines = []
# For the driving_log.csv file from imput list of folders:
# In this ... | 1945fae6695116052864c1a93f19e2198b24662f | 28,730 |
def ns(request):
"""Use this fixture in all integration tests that need live K8S cluster."""
return request.config.getoption("--namespace") | b8beac982e1e70136e8a8fa9f49eeda11d9c2ea3 | 28,731 |
import logging
def clean_geolocation_data(geolocation_data, attr_to_remove=None):
"""Remove attributes from geolocation data.
If no attributes are provided, return a copy of the same data.
:param geolocation_data: Full geolocation data
:type: dict
:param attr_to_remove: List of attributes to rem... | 9ef7a5c2777b556b81c1d21ec775ae6963c857ca | 28,734 |
def select_relevant_edges(all_edges, selected_ids):
"""Select relevant edges for those profiles that are relevant"""
source_condition = all_edges["source"].isin(selected_ids)
sink_condition = all_edges["sink"].isin(selected_ids)
return all_edges.loc[source_condition & sink_condition] | 20353158d68877ab9f877efe92bfa1e67053382f | 28,735 |
import warnings
def runtime_warning():
"""Abnormal behaviour during runtime."""
warnings.simplefilter('error', RuntimeWarning)
try:
warnings.warn("can fail", RuntimeWarning)
except RuntimeWarning:
return "something might go wrong"
finally:
warnings.simplefilter('ignore', R... | 4439de99c7c7478f63965a3a9e13b86e62de675c | 28,737 |
def h3(text):
"""h3 tag
>>> h3('my subsubheading')
'<h3>my subsubheading</h3>'
"""
return '<h3>{}</h3>'.format(text) | 196d30c7b3b0e6219ef4ce3a2edfd42a3bb13f46 | 28,738 |
def get_skin_cluster_influence_objects(skincluster):
"""
Wrapper around pymel that wrap OpenMaya.MFnSkinCluster.influenceObjects() which crash when
a skinCluster have zero influences.
:param skincluster: A pymel.nodetypes.SkinCluster instance.
:return: A list in pymel.PyNode instances.
"""
... | ebb686bc4ca718db104fccb08b4332de1df9d3d3 | 28,739 |
def get_kwargs_set(args, exp_elem2dflt):
"""Return user-specified keyword args in a dictionary and a set (for True/False items)."""
arg_set = set() # For arguments that are True or False (present in set if True)
# Add user items if True
for key, val in args.items():
if exp_elem2dflt is not None... | d742ca18bd8df6930b466cdd7d63037572376479 | 28,740 |
from typing import List
from typing import Dict
def _parse_md_table_rows(
md_table_rows_text: str, keys: List[str]
) -> List[Dict[str, str]]:
"""Return a list of row dictionaries."""
print(f"Attempting to parse rows: ```\n{md_table_rows_text}\n```")
result: List[Dict[str, str]] = []
rows_raw: List... | 76946a333a50dec48ca008745cefc59eb7c86dbd | 28,741 |
def find_sum_of_arithmetic_sequence(requested_terms: int, first_term: int, common_difference: int) -> int:
"""
Finds the sum of an arithmetic sequence
:param requested_terms:
:param first_term:
:param common_difference:
:return: the sum of an arithmetic sequence
"""
return int((requested... | fc4f3fec94737674096ff9e0a22c6001690c6101 | 28,742 |
def max(linked_list):
"""Excercise 1.3.27 Find max in linked list."""
head = linked_list.root
if head is None:
return
current_node = head
max = 0
while current_node is not None:
if current_node.item > max:
max = current_node.item
current_node = current_node.ne... | 993ca37939f03bafec035d04eed76d1dfdd6e50c | 28,745 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.