content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def MAX(src_column):
"""
Builtin maximum aggregator for groupby
Example: Get the maximum rating of each user.
>>> sf.groupby("user",
... {'rating_max':tc.aggregate.MAX('rating')})
"""
return ("__builtin__max__", [src_column]) | 59d030a07fafb6f254149d264b3a4feb9431ed28 | 634,434 |
def base_url(application_settings, base_path):
""" Returns the service URL."""
return 'http://localhost:%s%s' % (application_settings['APP_PORT'], base_path) | 1976659865ed11ddadcb4b6bfad87e362550c926 | 182,932 |
def create_element(type, props=None, *children):
""" Convenience function to create a dictionary to represent
a virtual DOM node. Intended for use inside ``Widget._render_dom()``.
The content of the widget may be given as a series/list of child nodes
(virtual or real), and strings. Strings are converte... | 4160c04e9c3031879fab3501914f75a61139f55e | 119,407 |
from typing import Dict
from typing import Union
def od_parse(data: str) -> Dict[str, Union[str, list]]:
"""Parse od command output without argument, return a dict with the following keys: hex, ascii, list, text
Returns:
dict: with key hex, ascii, list, text
"""
text, asc_data, hex_data, list_... | c9eb69a988063009971af373dd88da6101a0dfe8 | 646,050 |
def unix_to_windows_path(path_to_convert, drive_letter='C'):
"""
For a string representing a POSIX compatible path (usually
starting with either '~' or '/'), returns a string representing an
equivalent Windows compatible path together with a drive letter.
Parameters
----------
path_to_conve... | d3c23e2c19be4b81be135ae84760430be852da41 | 2,603 |
def is_valid_structure(ext):
""" Checks if structure format is compatible with GROMACS """
formats = ['tpr', 'gro', 'g96', 'pdb', 'brk', 'ent']
return ext in formats | 1b2af60c2f60df0eb5aa8a43fd8df5494d8b7830 | 563,474 |
def versions_match(versions):
"""Check if the versions are the same"""
base = None
for name in versions:
if base is None:
base = versions[name]
elif base != versions[name]:
return False
return True | 6d02c9170302a18e14dfac393f1b573d491d3545 | 653,346 |
def split(iterable, function):
"""
Split an iterable into two lists according to test function
:param iterable iterable: iterable of values to be split
:param function function: decision function ``value => bool``
:returns: tuple(
list with values for which function is `True`,
list ... | ede20fcc80bd126410a8417d1e91dee2e530c9af | 41,121 |
def load_text(input_file):
"""Load text from a text file and return as a string."""
with open(input_file, "r") as file:
text = file.read()
return text | effaea8e8f19f15d59abadbe4a71b6a3d8828f90 | 336,998 |
def binary_string(number: int) -> str:
"""Number to binary string
:param number: some number (an integer) to turn into a binary string
:return: Some string which is the binary string
:rtype: str
.. doctest:: python
>>> binary_string(200)
'11001000'
>>> binary_string(10)
... | aa22bcc4ddd5546805db333c9b0be2e7f0e1c703 | 681,850 |
def delete_max_length(data_in, data_out=None, max_length=20):
"""
Delete phrases with more than `max_length` characters.
"""
idx_to_remove = [count for count, sent in enumerate(data_in)
if len(sent) > max_length]
print(idx_to_remove)
for idx in reversed(idx_to_remove):
... | 0af5e71f6815b5f5e0086c262433a24da9c59695 | 423,809 |
import re
def find_application_includes(path):
"""
Build a set that contains the vtk includes found in the file.
:param path: The path to the application file.
:return: The includes that were found.
"""
includes = set()
include_hdr1 = re.compile(r'((?:vtk|QVTK).*\.h)')
include_hdr2 = ... | 96f5e4ae024d691ece9188e66c6b0d795150d513 | 236,158 |
def train_network(net, epochs, training_data, validation_data, batch_size, callbacks, verbose=1):
"""
train a network on data for a fixed number of epochs
parameters:
net: network to train
epochs: number of epochs
training_data: training data under the format of numpy arrays (inputs,... | d89704adc14bf2b609fa7bdb2300d59c4b2b5b1f | 648,267 |
def get_current_valid_edges(current_nodes, all_edges):
"""
Returns edges that are present in Cytoscape:
its source and target nodes are still present in the graph.
"""
valid_edges = []
node_ids = {n['data']['id'] for n in current_nodes}
for e in all_edges:
if e['data']['source'] in ... | 3f09ac58e7d7beb9bd68a99653bb8ccc6db1909a | 297,969 |
import csv
def read_from_csv(fn):
"""Read in the CSV file and return a list of (email, password) tuples"""
users = []
csvfile = csv.reader(open(fn, "r"))
for row in csvfile:
if row[0] != "":
users.append(row)
return users | f495330ce4cc8d7d325ff7b16795faa0bafec063 | 88,481 |
def scurve(start,end,n,s):
"""Return an S-Curve with a constant velocity section from start to end with
n points. The start and end S-curves each have s points"""
ys,ye = start,end
s1 = [ (ye-ys)*(x*x-s*s)/(2*s*float(n-1))+ys for x in range(0,s) ]
cv = [ (ye-ys)*(x-s)/float(n-1)+ys for x in range(s,s+n) ]
s2 = [ ... | a16ba1143cdeff9a8392a2c993b88918dff82350 | 646,470 |
import yaml
def read_yaml(file_path):
"""
Reads YAML file and return a dictionary
"""
with open(file_path) as f:
return yaml.safe_load(f) | e3d29ad6bd2e233f058ba65521e36d9c0564e570 | 521,217 |
def extended_gcd(a, b):
"""
I don't claim any copyright on this. I copied it from the internet somewhere.
Extended Greatest Common Divisor Algorithm.
Returns:
gcd: The greatest common divisor of a and b.
s, t: Coefficients such that s*a + t*b = gcd
Reference:
https://en.wi... | 93222993bafb69fd96dbd3d963edcd0c243225b4 | 350,313 |
def ms_to_cs(ms):
"""Convert Millisecons to Centiseconds"""
return ms / 10 | 19114824f6495215c4caa77cd458118ca2b17594 | 389,876 |
import operator
def filter_by_count(df, col, method, value, norm=False):
"""Filter a dataframe to return a subset of rows determined by their
value_counts(). For example, we can return rows with users who appear
at least 5 times in the dataframe, or with users who appear less than 10
times, or who app... | fd700dfe3daf641b72e4a29d40061f8d5e4e14f5 | 326,810 |
def reorder_minibatch(minibatch_data, minibatch_label):
"""
Helper method that sorts the minibatch data and labels so that the samples are
sorted in order from longest to shortest. This is makes it more efficient to
pad different-length samples, according to
https://stackoverflow.com/questions/510... | 9993250026b5c3bf81c4b3bd91889548684201bc | 488,758 |
def fmt_ms(ms):
"""Take a time in milliseconds and convert it to mm:ss.ms"""
time = int(ms)
minutes = int(time / (60 * 1000))
time -= minutes * (60 * 1000)
seconds = time / 1000
return str(minutes) + ':' + "{seconds:.3f}".format(seconds=seconds) | c9d256d7f6a59b25748016f024f2fdf44db7d687 | 377,975 |
import math
def evap_fract_time_fingas(heavy, c1, time, T, c2 = None):
"""
Return the evaporated fraction []
source : (Fingas, 2015)
Parameters
----------
heavy : True if the fuel need to follow a ln, else it will be a sqrt
C : fingas constant
time : Time from the spill [s]
T : Te... | 9241a61b15ad8df26be787b657ddad4c6de8e3a1 | 368,840 |
from pathlib import Path
import json
def load_dict(file_path: Path) -> dict:
"""Loads a json file into a dictionary."""
with file_path.open('r') as infile:
return json.load(infile) | c2f8c0806b327d947c982c2ad2facd7b7d9b0417 | 364,197 |
def guarded_unpack_sequence(it, spec, _getiter_):
"""Protect nested sequence unpacking.
Protect the unpacking of 'it' by wrapping it with '_getiter_'.
Furthermore for each child element, defined by spec,
guarded_unpack_sequence is called again.
Have a look at transformer.py 'gen_unpack_spec' for a... | 8c16e404a238eea45d8286feaafa9f8e78aa1f01 | 490,238 |
def no_resize(packing, cell):
"""Don't do any resizing"""
return packing, cell | 4d50c6c5219c37bd848905788060cb5c096041d8 | 128,775 |
import requests
def read_build_cause(job_url, build_id):
"""Read cause why the e2e job has been started."""
api_query = job_url + "/" + str(build_id) + "/api/json"
response = requests.get(api_query)
actions = response.json()["actions"]
cause = None
for action in actions:
if "_class" i... | 80c3aafc29ae9eed1a7e4165962c4a50281779dd | 675,989 |
def _parse_package_name(name: str) -> str:
"""
Force lower case and replace underscore with dash to compare environment
packages (see https://www.python.org/dev/peps/pep-0426/#name)
Args:
name: Unformatted package name
Returns:
Formatted package name
"""
return name.lower()... | 0257cbae7d8c25b31d089c983a0185c67cff6e2d | 678,053 |
import pickle
def load_pickle(file_pkl):
"""Receives a path of a pickle file and loads it.
:param file_pkl: str referencing a .pkl file
:returns: the object loaded"""
with open(file_pkl,'rb') as open_file:
object = pickle.load(open_file)
return object | 16726cf976821e02c263ec6705203e127f34feb3 | 142,714 |
def nice_bytes(number, lang='', speech=True, binary=True, gnu=False):
"""
turns a number of bytes into a string using appropriate units
prefixes - https://en.wikipedia.org/wiki/Binary_prefix
spoken binary units - https://en.wikipedia.org/wiki/Kibibyte
implementation - http://stackoverflow.com/a/1094... | 89680dabf2e71c15769e2d1c33b54f6a10cdec67 | 586,462 |
import re
def smart_truncate1(text, max_length=100, suffix='...'):
"""Returns a string of at most `max_length` characters, cutting
only at word-boundaries. If the string was truncated, `suffix`
will be appended.
"""
if len(text) > max_length:
pattern = r'^(.{0,%d}\S)\s.*' % (max_length-le... | cf957435d6d7d168d819670fed0dcd52d7ff0f67 | 309,022 |
def train_val_test_split(time_series, train_start_timestamp, train_end_timestamp, val_end_timestamp):
"""
Splits a given time series in training data, validation data and test data.
Args:
time_series (pandas.core.series.Series): input time series.
train_start_timestamp (string): initial timestamp of trai... | eeb18f27b4afda423125787af82d21d5a961d041 | 278,024 |
def grid_frames(params: dict):
"""
Generate frame parameters for individual grid data frames when performed in step mode.
:param params: run parameters
:return: list of dictionaries representing a frame each
"""
return (
{
'name': params['name'],
'uuid': params['... | 338bc0a6e4f0d34daa2ca725448c032f1ba99269 | 137,079 |
from typing import Any
from typing import Union
import re
def replace_variables(
input_string: str, interface: Any, key: Union[int, None] = None
) -> str:
"""
In a string, attempt to replace all the "$$X" variables with their
definitions from the interface. If not found in the interface, it skips the
... | 6827b9907772fe81b026bd6009fcc4670787d656 | 431,211 |
def _BuildCustomMetricUtilizations(args, messages):
"""Builds custom metric utilization policy list from args.
Args:
args: command line arguments.
messages: module containing message classes.
Returns:
AutoscalingPolicyCustomMetricUtilization list.
"""
result = []
if args.custom_metric_utilizati... | 74ba408772546b30a0b9fce1a681a9ef6ea295af | 194,421 |
def gcd(number1: int, number2: int) -> int:
"""Counts a greatest common divisor of two numbers.
:param number1: a first number
:param number2: a second number
:return: greatest common divisor"""
number_pair = (min(abs(number1), abs(number2)), max(abs(number1), abs(number2)))
while number_pair[... | 9f22c315cc23e2bbf954f06d416a2c44f95ddbb7 | 705,416 |
def win_check(board, mark):
"""
function that takes in a board and checks to see if someone has won.
:param board: the board to check
:param mark: the last mark in placed in the board
:return: True if game is win or False otherwise
"""
return ((board[7] == mark and board[8] == mark and board... | 38cad514d38aa42fdb88ebe4cb174f2999a9ae9b | 664,866 |
def normalize_timedelta(timedelta):
"""
Given a string like "1w" or "-5d", convert it to an integer in milliseconds.
Integers without a suffix are interpreted as seconds.
Note: not related to the datetime timedelta class.
"""
try:
return int(timedelta) * 1000
except ValueError as e:
... | 097d519e9b6a41b67d61c4b2af09be6e47fdb91f | 487,524 |
def flatten(a):
"""recursively flatten n-nested array
example:
>>> flatten([[1,2],[3,4],[5,6,[7,8],]])
[1, 2, 3, 4, 5, 6, 7, 8]
"""
if isinstance(a, list):
b = list()
for a_ in a:
if isinstance(a_, list):
b.extend(flatten(a_))
else:
... | d58e5f32446c1b750b4da676faff480461646e54 | 307,298 |
def chop_end_of_string(str_input, str_remove):
"""Function that strips the supplied str_remove from the end of the input
string
Parameters
----------
str_input: `str`
A string to be chopped
str_remove: `str`
The string to be removed from the end of the input
... | 792b95a6ae33faffdd4632f2785c3161ebea9bad | 258,672 |
import random
def pick_pivot(l, r):
""" Picks a pivot element at random from the 25-75% input percentile.
Params:
l - left most index to pick as pivot
r - right most index to pick as pivot
Return:
int - a randon number in [l, r]
"""
return random.randint(l, r) | 4638a4df1de7d317276ad64b129165d46141cee4 | 453,523 |
def throughput_history(summaries):
"""Calculates the change in completion for a list of summaries.
Args:
summaries (List[ProjectSummary]): List of project summaries to analyze
Returns:
List[int]: The change in number of items complete between each set of two summaries provided.
"""
h... | 5d1b2d2b4d285d9002ca56586f32ce0916981e55 | 311,061 |
from typing import Dict
def get_headers(token: str) -> Dict[str, str]:
"""
Returns authorization header for the data registry with the provided token.
:param token: personal access token
:return: Authorization headers
"""
return {"Authorization": f"token {token}"} if token else {} | 79b47ed3c81f2162ade773db9fc0d933d9f00942 | 150,900 |
def hook_TakeOver(state):
"""Implements `DeepState_TakeOver`, returning 1 to indicate that it was
hooked for symbolic execution."""
return 1 | a9bc8000a9873f655cb361b0df4a67dffbb99742 | 160,465 |
def _theoretical_logit_grad(x):
"""Reference implementation for the gradient of the logit function."""
return 1 / (x * (1.0 - x)) | 6baf81891db30961b5e35d6f2e98a5397bca797f | 294,479 |
def chrtonam(c):
"""Find unique elements in an iterable and in what order they appear.
Return a 3-tuple (uniqelements, eltoindex, map):
uniqelements -- elements in order of first appearance
eltoindex -- map from elements to their indices in uniqelements;
equivalent to dict((el, i) for (i, el) in uniqelements)
... | 38d901196a81ebdf29441fc4bfde64a76929d4a3 | 488,055 |
def get_computers_with_policy_and_relay_list(api, configuration, api_version, api_exception, relay_list_id, policy_id):
""" Search for computers that are assigned to a specific policy and relay list.
:param api: The Deep Security API modules.
:param configuration: Configuration object to pass to the api cl... | 4fd4603cea8c1a2484daa582d74982ef756019f3 | 136,955 |
def is_unitless(ds, variable):
"""
Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable
"... | 8574327f657e67d2165f247a8892c38eab89784f | 648,232 |
def encode(tokenizer, question, context):
"""encodes the question and context with a given tokenizer"""
encoded = tokenizer.encode_plus(question, context)
return encoded["input_ids"], encoded["attention_mask"] | b821896a42414d9df617fd9c8a2456d26f23e724 | 414,117 |
from typing import Iterable
def scheduler_story(keys: set, transition_log: Iterable) -> list:
"""Creates a story from the scheduler transition log given a set of keys
describing tasks or stimuli.
Parameters
----------
keys : set
A set of task `keys` or `stimulus_id`'s
log : iterable
... | 7b6a3bb377ff962acdd9bd47855a83e388fc56be | 116,993 |
def splitstring(string, split_character=' ', part=None):
"""
Split a string based on a character and get the parts as a list
string:
The string to split
split_character:
The character to split for the string. The default is ' '.
part:
Get a specific part of the list. The default is N... | 9bf12cbb989380ccab8a3dd88bf12490ad1bf0c3 | 297,260 |
def parse_data(data, objects_format, separator=" "):
"""
Takes a list of strings and a list of objects format and returns a list of objects formatted according to the objects format.
Example:
parse_data(['forward 10', 'left 90', 'right 90'], [{'key': 'command, 'format': str}, {'key': 'value', 'forma... | 55702626a122957834566073f32ba2612bb4fbb5 | 537,334 |
from typing import Dict
from typing import Any
def _make_pod_envconfig(
config: Dict[str, Any], relation_state: Dict[str, Any]
) -> Dict[str, Any]:
"""Generate pod environment configuration.
Args:
config (Dict[str, Any]): configuration information.
Returns:
Dict[str, Any]: pod enviro... | 3f41f89f9bdf25ab6a75c5206943df5437092d1c | 74,376 |
def ClusterKey(cluster, key_type):
"""Return a cluster-generated public encryption key if there is one.
Args:
cluster: Cluster to check for an encryption key.
key_type: Dataproc clusters publishes both RSA and ECIES public keys.
Returns:
The public key for the cluster if there is one, otherwise None... | 073ce9fb790b8fcdaabded2c8f9a4ec649f10850 | 643,752 |
def best_neighbor_match_check(k_neighbors_labels):
""" Returns the value with the most repetitions in `k_neighbors`. """
k_neighbors_labels.sort()
longest_repeats = current_repeats = 0
current_value = best_match_value = k_neighbors_labels[0]
for value in k_neighbors_labels:
if value == current_value:
current_... | d56ab1a5683768767da2bc00306e1aaa3665343a | 441,227 |
def file_to_string(sql_path):
"""Converts a SQL file holding a SQL query to a string.
Args:
sql_path: String containing a file path
Returns:
String representation of a file's contents
"""
with open(sql_path, 'r') as sql_file:
return sql_file.read() | f63542f756ac85efdb1ec82ec9ed4f629e548fee | 609,970 |
import torch
def compute_distances(x, n_particles, n_dimensions, remove_duplicates=True):
"""
Computes the all distances for a given particle configuration x.
Parameters
----------
x : torch.Tensor
Positions of n_particles in n_dimensions.
remove_duplicates : boolean
Flag indi... | e6d39e9855c57f5a926054df032cd70ba58d38e9 | 87,573 |
def combine(intervals):
"""combine overlapping and adjacent intervals.
>>> combine([(10,20), (30,40)])
[(10, 20), (30, 40)]
>>> combine([(10,20), (20,40)])
[(10, 40)]
>>> combine([(10,20), (15,40)])
[(10, 40)]
"""
if not intervals:
return []
new_intervals = []
inte... | e30fc920ab5d1174551412603d2bb95a865438e0 | 466,301 |
import math
def _atand(v):
"""Return the arc tangent (measured in in degrees) of x."""
return math.degrees(math.atan(v)) | c395efa781f3ea6aa0d6ab6926a09325cd7ea0ea | 147,524 |
def get_key_padding_mask(padded_input, pad_idx):
"""Creates a binary mask to prevent attention to padded locations.
Arguements
----------
padded_input: int
Padded input.
pad_idx:
idx for padding element.
Example
-------
>>> a = torch.LongTensor([[1,1,0], [2,3,0], [4,5,0... | 234d5f947b7042c5edad68e9b8162e4bbf6963f3 | 20,113 |
def rank_features(explanation):
""" Given an explanation of type (name, value) provide the ranked list of feature names according to importance
Parameters
----------
explanation : list
Returns
----------
List contained ranked feature names
"""
ordered_tuples = sorted(explanation, ... | f1d14296434f800fc03313cb447a44a2c11ea123 | 661,727 |
def interval_width(interval):
"""Returns half the width of an interval, given by a list"""
return (interval[1]-interval[0])/2+(interval[1]+interval[0])/2 | 77147c99368ef5591cd7a3dc97badde9a21d17e9 | 328,397 |
def uniqify(seq): # Dave Kirby
"""
Return only unique items in a sequence, preserving order
:param list seq: List of items to uniqify
:return list[object]: Original list with duplicates removed
"""
# Order preserving
seen = set()
return [x for x in seq if x not in seen and not seen.add... | a1a15b06f2c632c9a95dca7b687177e264e5551e | 102,491 |
from typing import Union
def _create_table_row(key: str, value: Union[str, int], highlight: bool = False) -> str:
"""
Create table row for stats panel
"""
template_stats_data = """
<tr style="border-bottom: 1px solid;">
<th style="text-align: left">{key}</th>
<td style="text-align:... | 362154b67151f9f6c1d996c1e9ee67cbcf8b7ea3 | 61,313 |
def dict_to_list(dictionary, order_list):
""" Create a list from dictionary, according to ordering in order_list """
#assert sorted(order_list) == sorted(dictionary.keys())
wc_list = []
for wc_name in order_list:
wc_list.append(dictionary[wc_name])
return wc_list | 8d61f8fe2729ab6cfec0258771180d7106b372ac | 232,041 |
import requests
def make_request(endpoint):
"""
Make a request to the given URL and return the response.
"""
return requests.get(
f"https://api.audioboom.com{endpoint}",
# The API needs version specifying
headers={'Accept': 'application/json; version=1'}
).json()["body"] | 8811fcf685980e8bc043bd6cfeab9942942a39fa | 424,941 |
from typing import List
def list_squares(n: int) -> List[int]:
"""Generates a list of squares of numbers from 0 to n using list comprehension.
doctests:
>>> list_squares(2)
[0, 1, 4]
>>> list_squares(5)
[0, 1, 4, 9, 16, 25]
"""
x = [i ** 2 for i in range(0, n + 1)]
return x | e88dc5807fb81a39d48f92bae5d8cb692769861c | 114,480 |
def cell_trap_getter_generator(priv_attr):
""" Generates a getter function for the cell_trap property.
"""
def getter(self):
if getattr(self, priv_attr) is None:
data =\
(
self.gfpffc_bulb_1 - self.gfpffc_bulb_bg
)/self.gfpffc_bulb_bg
... | 15217adbd96ce44b361444867e5d9c6d202440f4 | 13,951 |
def set_difference(dependent,independent):
"""
This function compares two lists, and takes their set-theoretical
difference:
dependent - independent
arguments: dependent, independent
"""
return list(set(dependent)-set(independent)) | bd7e85b53fda26378330f780e57b89c0d05d5d33 | 562,464 |
def new_value_part_2(seat: str, visible_count: int) -> str:
"""
Returns the next state for one seat.
"""
if seat == "L" and visible_count == 0:
return "#"
elif seat == "#" and 5 <= visible_count:
return "L"
else:
return seat | 6b8dcaecfd5a62fbb8a5c9333dc8ec180cc814ca | 654,295 |
def create_rg_azure(resourceGroup, tag, source):
"""Create Terraform Module for Azure Resource Group."""
tf_module_rg = {
"source": "%s/m-azure-rg" % source,
"resourceGroupName": resourceGroup['name'],
"resourceGroupRegion": resourceGroup['region'],
"tagEnvironment": tag
}
... | bbde0748b54063a00004bb1590b22fb2b634b7eb | 144,534 |
def lambda_handler(event, context):
"""
Expects input of the form:
[ [ Input, [ O1 ] ], ... [ Input, [On ] ] ]
Returns: [ O1, ... On ]
"""
return [ e[1][0] for e in event ] | c27ba001018491de387ecdb0b670bf01f8dfd47d | 555,920 |
def create_tlink_attributes(reltype, id1, id2, link_id, origin):
"""Create a dictionary with tlink attibutes.
Arguments:
reltype - string
id1 - string
id2 - string
link_id - string of the form l\d+
origin - string
Returns a dictionary."""
# NOTE: this method should ... | 032db530493ce3ace31782c1e8e9db9c045df681 | 163,636 |
def prettify_cve_announcement(cve_announcement, api_url):
"""Format a cve_announcement to be human friendly."""
return (
f"[{cve_announcement.cve_code}] {cve_announcement.content}\n"
f"Score: {cve_announcement.score}\n"
f"Exploit code maturity: {cve_announcement.exploit_code_maturity}\n"... | 0a8d8890954703e4aaf47aecf7159b9ecdc38822 | 429,390 |
def _autoname_plots(plotlist, sequential=False):
"""
Automatically name any plots that were not given a name by the user.
"""
namelist = []
count = 0
for plot in plotlist:
if plot.get('type') == 'figure':
continue
name = plot.get('axes')
if name is None:
... | d34f409e7a8e6bb6e931c2680dd68a785e4082b1 | 545,218 |
def maybe_add_slash(path):
"""Add a final trailing slash if it wasn't there already"""
with_trailing_slash = path if path.endswith('/') else path + '/'
return with_trailing_slash | 117f670b47ad6e6d1df26c54d09ed0c771c2d273 | 582,437 |
def expected_error_node_kwargs(node_kwargs):
"""Return the expected error message depending on node_kwargs."""
if 's' in node_kwargs:
return "Please use 'node_size' and not 'node_kwargs'"
elif 'c' in node_kwargs:
return "Please use 'node_color' and not 'node_kwargs'" | b935445f34542a8257c76194fae55fa188a2e31c | 489,283 |
def del_from_dict(dictionary, srcip, dstip):
"""Removes an entry from the given dictionary.
Assumed is that srcip and dstip exist in the dictionary.
:param dictionary: dictionary to remove an entry from
:type dictionary: dictionary
:param srcip: source ip
:type srcip: string
:param dstip: destination ip
... | 2833371c38ff09cb4f9a7cc7e0af16b41973c3f6 | 275,205 |
def create_function_from_source(function_source, imports=None):
"""Return a function object from a function source
Parameters
----------
function_source : unicode string
unicode string defining a function
imports : list of strings
list of import statements in string form that allow ... | 2fa6c5ed6778270a4a2b1c2e02c0203a3d463e10 | 637,299 |
def slice_z_center(mesh):
"""Slice mesh through center in z normal direction, move to z=0."""
slice_mesh = mesh.slice(normal='z')
slice_mesh.translate((0, 0, -slice_mesh.center[-1]), inplace=True)
return slice_mesh | 3278fec43db960698866443bc10e79a260b5eeb2 | 299,652 |
import zlib
def decompress_data(data):
"""
Decompresses the data with zlib
:param data:
:return:
"""
return zlib.decompress(data) | 6dd778eae0331291d979d82a8fe9aad17a92e48a | 557,633 |
def isblankstr(line):
"""
check for blank string
:param line:
:return bool:
"""
return len(line.strip()) == 0 | 0719369d0d83ca0b36bc8969ccea541b122b9906 | 382,278 |
def iterable_response_to_dict(iterator):
""" Convert Globus paginated/iterable response object to a dict """
output_dict = {"DATA": []}
for item in iterator:
dat = item
try:
dat = item.data
except AttributeError:
pass
output_dict["DATA"].append(dat)
return output_dict | 9764718a922a310b2892e1896657dd2af24e7a8f | 47,912 |
def _check_size(node, size=0):
"""Recursive function, visits all nodes and counts number of elements. Return
the number of elements."""
if node is None:
return size
else:
size += 1
size = _check_size(node.left_node, size) # Go down the left tree
size = _check_size(nod... | d7693cc1caba672a1e6f7f5a527d731ce3dd9690 | 355,539 |
def GetUpdatesUrl(project_name, max_results=1000):
"""Construct the URL to the issues updates for the given project."""
return ('http://code.google.com/feeds/p/%s'
'/issueupdates/basic?max-results=%d' %
(project_name, max_results)) | b0b369420391a8faf2cb99e0a2398475e9c022ed | 497,673 |
from pathlib import Path
def _get_data_size_of_dir(path: Path) -> float:
"""Returns the data volume / size of a directory given at path.
Parameters
----------
path : Path
Path for which the size should be determined
Returns
-------
float
Value between 0 and the max size o... | 4e37752889f67837584b9b8859d131765238dc51 | 537,251 |
from typing import Type
from typing import Any
from typing import Set
def _get_all_subclasses(cls: Type[Any]) -> Set[Type[Any]]:
"""Returns a list of all classes that inherit directly or indirectly from the given class."""
subclasses = set()
def recurse(cl: Type[Any]) -> None:
for subclass in cl.... | 3ae35c1e5f967211ae2865b51c536d4e68a1a92b | 443,880 |
def coco2pascal(box):
"""Convert bounding box coordinates from Coco format to Pascal VOC.
Go from [x, y, width, height] to [x1, y1, x2, y2].
"""
x, y, width, height = box
return [x, y, x + width, y + height] | 484b6a51e68d98df6b13b487cb0d7989c81765e4 | 213,171 |
def merge(ll, rl):
"""Merge given two lists while sorting the items in them together
:param ll: List one (left list)
:param rl: List two (right list)
:returns: Sorted, merged list
"""
res = []
while len(ll) != 0 and len(rl) != 0:
if ll[0] < rl[0]:
res.append(ll.pop(0))
... | 0b88eea3733d0ac2739faff57b36faf6841d0446 | 663,103 |
def filtrar_cortas(texto, chars=0):
"""Filtra líneas en texto de longitud chars o inferior.
Parameters
----------
texto : str
Texto que se quiere filtrar.
chars : int
Mínimo número de caracteres en una línea de texto.
Returns
-------
str
Texto filtrado.
"""
... | 3a1568f94e31965f962a0a969271154555bf24ec | 471,601 |
def get_numeric_columns(df):
"""
# Returns a list of numeric columns of the dataframe df
# Parameters:
# df (Pandas dataframe): The dataframe from which extract the columns
# Returns:
# A list of columns names (strings) corresponding to numeric columns
"""
numeric_columns = lis... | 6ec1cb8d1a8dd9c4cb49f17257b137e9ec0d4210 | 654,222 |
def dotp(a, b):
"""Dot product of two equal-dimensioned vectors"""
return sum(aterm * bterm for aterm,bterm in zip(a, b)) | 502fba46bf2284a1b7d48572c38cef1d1a188c11 | 576,307 |
def line_plot(ax, x, ys, labels=None, styles=None, param_dict=None):
"""
A helper function to make a line graph
Parameters
----------
ax : Axes
The axes to draw to
x : array
The x data
ys : array
The y data
labels : list
The ys labels
param_dict : di... | 837867df9029f9a1c78cf448079e19e3ba9a17b3 | 627,669 |
def reconstruction_loss(reconstruction, orig):
"""
Computes the reconstruction loss
:param reconstruction: batch x im_size
:param orig: batch x im_ht x im_wd
:return rloss: The reconstruction loss
"""
rloss = ((reconstruction - orig.view(orig.size(0),
... | 24e25a08f35ff9724ace694f08d8c2f7ce597d01 | 309,124 |
def generate_uniform_prior(params, indent=4):
"""
Generates the JAGS prior declarations for a list of parameters. The
strings are generated using a specifiable number of indentation
whitespaces.
"""
prior_strings = []
for p in params:
prior_strings.append(
"{}{} ~ dunif(... | a1e3d670466643f7f18e25296d974218c874218e | 159,498 |
def aggregate_values_from_key(host_state, key_name):
"""Returns a set of values based on a metadata key for a specific host."""
aggrlist = host_state.aggregates
aggregate_vals = set()
for aggr in aggrlist:
if key_name in aggr.metadata:
aggregate_vals.add(aggr.metadata[key_name])
... | e720c5aec3af230edfd0f3180357be9c858f9ba9 | 500,513 |
def compute_frequencies(words):
"""
Args:
words: list of words (or n-grams), all are made of lowercase characters
Returns:
dictionary that maps string:int where each string
is a word (or n-gram) in words and the corresponding int
is the frequency of the word (or n-gram) in wo... | 47f6c1f717a080277ea13fd1255def1bb444b2ea | 174,983 |
def is_int(s : str) -> bool:
"""
Check if string is an int.
"""
try:
float(s)
except Exception as e:
return False
return float(s).is_integer() | f83b1c7c683807397880f685cf6913d2270f5252 | 100,808 |
def url_from_id(id):
"""Returns URL of article with given ID"""
return "https://www.ncbi.nlm.nih.gov/pubmed/" + id | 3dff22b1c8f20f3379de682af01d768ef75412ca | 225,632 |
def get_environment(certificate):
"""Return environment associated with certificate. """
STAGING_ENV = "Fake LE Intermediate X1"
for component in certificate.get_issuer().get_components():
if component[0] == 'CN':
if component[1] == STAGING_ENV:
return 'staging'
... | e83379a87b30b15cbe58e6909850ad33a556b63a | 396,102 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.