content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import ast
def _check_vals(item):
"""
Check if item is evaluatable and returns the value of it.
Example 'False' should return False
'ABC' should return 'ABC'
PARAMETERS: String (the value from a key/value pair)
RETURNS : type of evaluated string
"""
try:
val = ast.l... | 2310fec4c6ba07112e9dc759f492caf66d5dca53 | 37,848 |
import hashlib
import six
import base64
def CalculateMd5Hash(file_path):
"""Calculate base64 encoded md5hash for a local file.
Args:
file_path: the local file path
Returns:
md5hash of the file.
"""
m = hashlib.md5()
with open(file_path, 'rb') as f:
m.update(f.read())
return six.ensure_text(... | 2a24ce3dd4f6e5f9d9a5d9be5632e6d481fd690b | 37,851 |
def read_connection_data_from_external_file(filepath, separator="="):
"""Reads SQL server connection information from an external file.
Keeping this information external is potentially important for security reasons.
The format of this file should be:
server = [server_name]
database = [database_name]
Arguments... | f12a659f302f7a8252f29673fa916b6ac997663f | 37,852 |
import json
def load_filename(loc: str) -> dict:
"""Open a filename, parse it as JSON."""
with open(loc) as fh:
return json.load(fh) | 9b8984926573dbcbff16a7fcee4b20e5e85fe6e0 | 37,853 |
def lin_poly_solve(L, M):
"""
Return the point defined as the intersection of two lines
(given as degree-one polynomials in some field).
"""
x0,x1,x2 = M.parent().gens()
a0 = L.coefficient(x0)
a1 = L.coefficient(x1)
a2 = L.coefficient(x2)
b0 = M.coefficient(x0)
b1 = M.coefficient... | 5ebacff94b80dd4b1b54ac7742d0c9a37db596c8 | 37,854 |
def toRGB(hex_color_str):
"""
transform hex color string to integer tuple.
e.g. r,g,b = toRGB('0xFFFFFF')
"""
return int(hex_color_str[2:4],16)/255., int(hex_color_str[4:6],16)/255., int(hex_color_str[6:8],16)/255. | 5821d5f0d42d1a53982eb81739fe81e47d75fa23 | 37,855 |
def lookup_object(spec):
"""
Looks up a module or object from a some.module:func_name specification.
To just look up a module, omit the colon and everything after it.
"""
parts, target = spec.split(':') if ':' in spec else (spec, None)
module = __import__(parts)
for part in parts.split('.')... | e09c30d1cf3f523b790208dec60ec9fc1a309b1d | 37,856 |
def test():
"""interesting!"""
return 6 | ae932353dcdf1fe54fd326bb35fc5c38be9a8001 | 37,857 |
def default(d, k, i, default=None):
"""Returns d[k][i], defaults to default if KeyError or IndexError is raised."""
try:
return d[k][i]
except (KeyError, IndexError):
return default | c48c57b7698f23e075d45043917e2427e1b39c2d | 37,858 |
import struct
def exifdata_tostring(stored_bytes, datatype, decoder):
"""Convert Exif value to displayable string, based on datatype.
1st parameter = Exif value as a byte string (as stored in Jpeg file)
2nd parameter = Exif datatype, as an integer
3rd parameter = reference to an ExifDecoder object, f... | ea25aa6f4b467bbddf3cb8157cdec7fa8dec8ba0 | 37,859 |
def line_1d(x, slope, offset):
"""Return the value of a line with given slope and offset.
Parameters
----------
x : float or iterable of floats
The x-value to calculate the value of the line at.
slope : float
The slope of the line. Must be finite.
offset : float
The y-of... | 9befd9fdd13db12e27be4e000501c09a51c231e8 | 37,860 |
def _rainbow(x):
""" Eq. 3 of sron_colourschemes.pdf """
r = ((0.472 - 0.567 * x + 4.05 * x**2)
/ (1.0 + 8.72 * x - 19.17 * x**2 + 14.1 * x**3))
g = (0.108932 - 1.22635 * x + 27.284 * x**2 - 98.577 * x**3
+ 163.3 * x**4 - 131.395 * x**5 + 40.634 * x**6)
b = 1.0 / (1.97 + 3.54 * x - 68.... | 8c055c3ad3fe02bb2d874e34d7b00cf0f467e0e4 | 37,862 |
import numpy
def simpson_2d(f):
"""
Approximate the integral of f from a to b in two dimensions,
using Composite Simpson's rule.
@param f: 2D numpy array of function values
@return: approximation of the definit integral
"""
n = int((f.shape[0] - 1) / 2)
i = 2 * numpy.arange(1, n + 1)... | dfc4c2d9c604024e6338f7b677c3951a209f42ca | 37,865 |
from typing import Tuple
def dict_to_full_tree(tree: dict) -> Tuple[dict, str]:
"""Converts a dict of form
{
'id' : str,
'title': str,
'selftext' : str,
'author' : str,
'comments' : {'id' : {'id': str,
'parent_id': str,
... | f30e9d677b91554e8a864bbe2cb83e5a0295e534 | 37,866 |
def public(endpoint_func):
"""A simple decorator for skipping auth steps on certain endpoints,
if it's a public page, for instance.
"""
endpoint_func.is_public = True
return endpoint_func | 0781028165a04070d18962bb24f7e98b33672549 | 37,868 |
from pathlib import Path
import os
def get_query_for(resource_name: str) -> str:
"""Get graphQL query for a resource."""
basepath = Path("app/queries/")
files_in_basepath = basepath.iterdir()
for file in files_in_basepath:
if file.name.lower() == f"{resource_name}.graphql".lower():
... | 626717647f8ebea61536a568c4d450398302067f | 37,869 |
def pathToLoc(p):
"""Associate path with location.
v1.0 should be specifying location but older YAML uses path
-- this provides back compatibility.
"""
if "path" in p:
p["location"] = p["path"]
return p | da52538477d68e421409ccfadf8220b14174a439 | 37,870 |
def read_annotations(filename, tagset, labeled):
""" Read tsv data and return sentences and [word, tag, sentenceID, filename] list """
with open(filename, encoding="utf-8") as f:
sentence = []
sentence.append(["[CLS]", -100, -100, -100, -100, -100, -100 -1, -1, None])
sentences = []
sentenceID=0
for line ... | 4ec6312c875dcca988433d2741d52a28edc67769 | 37,872 |
import logging
def setup_logger(logger_name="capsule", extra_kwargs={}):
"""Simple wrapper to setup a logger and return it.
Used by the LOG constant which is used through the project
Args:
logger_name (str, optional): The name for the logger. Defaults to "capsule".
extra_kwargs (dict, opt... | 3ca67726ef0884901762141758a80a4f0086ad75 | 37,873 |
def get_similar_artists(h5,songidx=0):
"""
Get similar artists array. Takes care of the proper indexing if we are in aggregate
file. By default, return the array for the first song in the h5 file.
To get a regular numpy ndarray, cast the result to: numpy.array( )
"""
a=[]
n=0
while (n !=... | 05650e399be0fa7c7ca0713416a9155ad09cdb77 | 37,874 |
import pickle
def restore_model(model, train_set, model_name, directLong, log_dir_pass):
"""
Function to restore model for training continuation
Args:
model (RGAN|RCGAN): uninstantiated model to restore
train_set (numpy.ndarray|(numpy.ndarry,numpy.ndarray)):
output of "loadData" i... | 178987c89c546ed12f81db7f0eae02f1ea3e418e | 37,876 |
def decimal_all_finite(x_dec_list):
"""Check if all elements in list of decimals are finite.
Parameters
----------
x_dec_list : iterable of Decimal
List of decimal objects.
Returns
-------
y : bool
True if all elements are finite.
"""
y = all(x.is_finite() for x in ... | 610f95d7022047a8b020d5af48ceb3923d168e5d | 37,877 |
def _sanitize_re(str):
"""
When doing searches that starts with *, ?, +, ie. special regexp chars,
MySQLdb and psycopg2 will throw "OperationalError: (1139, "Got error
'repetition-operator operand invalid' from regexp")".
This function returns a regexp string with the starting special chars
e... | c8c8af26de6baa27b06b3c81df1fb95a578cc42c | 37,880 |
def coord_shift180(lon):
"""Enforce coordinate longiude to range from -180 to 180.
Sometimes longitudes are 0-360. This simple function will subtract
360 from those that are above 180 to get the more user-friendly
[-180, 180], since slicing is a lot easier.
Parameters
----------
lon: nump... | cdf4ccbfc0e0dbb0201012826b88720934231d32 | 37,881 |
def temperature_over_total_temperature(
mach,
gamma=1.4
):
"""
Gives T/T_t, the ratio of static temperature to total temperature.
Args:
mach: Mach number [-]
gamma: The ratio of specific heats. 1.4 for air across most temperature ranges of interest.
"""
return (1 + (... | a1fea37f80df9eff21716f273b6270cfa7fcd302 | 37,882 |
def isPalindrome(s):
"""
:type s: str
:rtype: bool
"""
s = ''.join(c for c in s if c.isalnum())
if not s:
return True
start, end = 0, len(s)-1
while (abs(start-end)>1):
if (s[start].lower() != s[end].lower()):
return False
start... | c72b0d0be9fe63d9815782f22ef3bc3e60364957 | 37,883 |
from functools import reduce
def words_in_chapters(chapters: list) -> list:
"""
Returns all words in the given chapters, without any special characters (no punctuation or quotation characters)
:param chapters: Chapter objects
:return: all words in the given Chapters as a list of words
"""
ret... | ef30472d3096f7b5cf58cab2ab7bdeed41c9fa85 | 37,885 |
import typing
def _exclusion_in(type_, name) -> typing.Tuple: # pylint: disable=unused-argument
""" do not cast Integer based primary keys """
return name, '=' | 6f24245800ce91c8fb947050a7f1d63f53ecba9e | 37,886 |
import json
def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the res... | d3cdff425da3a7a01369ae89890d1d00ab7fe000 | 37,888 |
def get_host_format(node):
""" Return host entries """
host_format = f"{node['ip_addr']} scale_cluster_quorum={node['is_quorum']} scale_cluster_manager={node['is_manager']} scale_cluster_gui={node['is_gui']} scale_zimon_collector={node['is_collector']} is_nsd_server={node['is_nsd']} is_admin_node={node['is_admi... | 2f54de38929da21172451dfd6f004c201072cec0 | 37,889 |
def slices_overlap(slice_a, slice_b):
"""Test if the ranges covered by a pair of slices overlap."""
assert slice_a.step is None
assert slice_b.step is None
return max(slice_a.start, slice_b.start) \
< min(slice_a.stop, slice_b.stop) | db9cfc0dcfa64f6c7c52f2410a140088f9d03b13 | 37,890 |
def get_requirements(fname):
"""
Extracts requirements from requirements-file <fname>
"""
reqs = open(fname, "rt").read().strip("\r").split("\n")
requirements = [
req for req in reqs
if req and not req.startswith("#") and not req.startswith("--")
]
return requirements | 1b091b89cf6835f544560eb8e2235d9bb02f2952 | 37,892 |
import sqlite3
def get_current_db(table_name, db_name):
""" connect to current database and return contents of specified table"""
# Connect to db
db_conn = sqlite3.connect(db_name)
c = db_conn.cursor()
column_name = []
# This enables column access by name: row['column_name']
db_conn.row_fa... | 8ac99c1b26acc955c4c3ac25117aec045a4f1eb5 | 37,893 |
import pickle as pkl
def loadVariable(filePath:str):
"""
Use python module pickle to load variable.
"""
return pkl.load(open(filePath,"rb")) | a3e4af490b1f3c8ddf9173e65c95e35fc54ad849 | 37,895 |
import re
def ros_name_for(s: str):
"""Obtain a ROS-allowed name"""
return re.sub('[^a-zA-Z0-9_]', '_', s) | cc7698d26412508976a9530e5936b402e3bdd0c5 | 37,896 |
import os
def path(*args):
"""
Args:
args: relative path from this directory
('stackrl/envs/data').
Return:
The absolute path to 'stackrl/envs/data/arg0/...' or,
if no arg is given, to this directory.
"""
return os.path.join(
os.path.dirname(__file__),
*args,
) | 893a39f867e0184416c7d9d8a5962d4abaefb41b | 37,897 |
def output_contigs(g):
""" Perform searching for Eulerian path in the graph to output genome assembly"""
V = g[0]
E = g[1]
# Pick starting node (the vertex with zero in degree)
start = list(V.keys())[0]
for k in list(V.keys()):
if V[k].indegree < V[start].indegree:
start = k
... | 2b38c4e172322e1f92db76be890160c7bdc82d55 | 37,898 |
def create_result(m, d, y):
""" Creates result """
result = ''
if m < 10:
result += '0' + str(m)
else:
result += str(m)
result += '/'
if d < 10:
result += '0' + str(d)
else:
result += str(d)
result += '/' + str(y)
return result | c87b9d97e22cfc642ed6bca363f998e3fa35546e | 37,899 |
def change(total, coins):
"""
recursive solution, time consuming and maximum recursion depth exceed
"""
if total == 0:
return 0
count = total
for coin in coins:
if total - coin >= 0:
_count = change(total - coin, coins)
if _count + 1 < count:
... | f4d923327607de005a1149f2fbfc8bd8062ac9e3 | 37,900 |
def camelcase(name):
"""Converts a string to CamelCase.
Args:
name (str): String to convert.
Returns:
str: `name` in CamelCase.
"""
return ''.join(x.capitalize() for x in name.split('_')) | 2a0052d52faf1aabb45ae9909f76482c927ba395 | 37,901 |
import re
def change_ext(filename, new_ext):
"""return a new filename, with the extension changed.
"""
return re.sub(r"\.\w+$", new_ext, filename) | efca714e3856c3e06fb850ac10a5c7a357fa2ca8 | 37,902 |
from typing import Dict
from typing import Callable
def is_current_builder() -> Dict[str, Callable]:
"""Inject a function to evaluate whether or not a result is current."""
def is_current(result: dict) -> bool:
"""Determine whether the result is the current version."""
if result["submitted_da... | 5faa72aa1b7a9f52bf639f3cf307301870740c37 | 37,903 |
def completed(lines):
"""
Check if the output file shows successful completion
"""
return lines[-1][:14] == 'TOTAL RUN TIME' | 2dcb9ff850086f4e7496a46a82c510297f0488d6 | 37,905 |
import torch
import random
def create_sample_batch(speaker_data, batch_size, vector_dim):
"""
Return torch tensors ((input1, input2), target) for siamese
network training (for mutual information).
Constructs each batch to have roughly equal amount of target
and non-target samples to keep training... | 71edfa9f239b84a8414a645d391330f929cd2e2d | 37,909 |
import six
def safe_shadow(text):
"""
Shadow string to first and last char
:param text:
:return:
>>> safe_shadow(None)
'None'
>>>safe_shadow("s")
'******'
>>>safe_shadow("sssssss")
's******s'
>>> safe_shadow(1)
'******'
>>> safe_shadow([1, 2])
'******'
"""... | 46d63b4a598bbc45ae32335e105539f7c43f1c9e | 37,910 |
def _merge_notebooks_feedback(notebook_ids, checksums):
"""
Returns a list of dictionaries with 'notebook_id' and 'feedback_checksum'.
``notebook_ids`` - A list of notebook IDs.
``checksum`` - A dictionary mapping notebook IDs to checksums.
"""
merged = []
for nb_id in notebook_ids:
... | 6e45fa2f5889b94b9dd6e0164ab7554e284fa3b9 | 37,912 |
def decode_output(outputs):
"""decode outputs into boxes and masks"""
return [], [], [] | 41fbcb020dd2aed1bcc7596552377c188b2eb6a3 | 37,914 |
def linenumber(target):
""" Given a python callable try and determine the source line number where it is defined """
if hasattr(target, "__code__"):
code = getattr(target, "__code__")
return code.co_firstlineno
if hasattr(target, "__func__"):
return linenumber(getattr(target, "__fu... | be9618ad861d85a66b705dedbb859d76a7604b19 | 37,915 |
import os
import glob
def get_table_defs():
"""Return a dictionary containing the columns for each database
table, as taken from the table_definition text files.
Returns
-------
table_defs : dict
A dictionary whose keys are detector/file_type/extension
configurations (e.g. 'wfc_fl... | 2aa26326774d1f437d04b6bc8d9c54aaa40919ec | 37,916 |
def size_format(size):
"""
文件大小格式化
:param size: byte
:return:
"""
if size < 1000:
return '%i' % size + 'size'
elif 1000 <= size < 1000000:
return '%.1f' % float(size/1000) + 'KB'
elif 1000000 <= size < 1000000000:
return '%.1f' % float(size/1000000) + 'MB'
eli... | e05621272060e3d5e3ced70001a49643172645e2 | 37,917 |
import random
def generate_random(power: int) -> list:
"""
Generate list with 2 ** power random elemnts.
"""
array = [random.random() for i in range(2 ** power)]
return array | b822277c6f4ca0a28339ef2feddfcec485e4d686 | 37,918 |
def findmax(L):
"""
>>> L1 = [ 1, 4, 5, 10 ]
>>> findmax(L1)
10
>>> L2 = [ 1, 3, 9, 33, 81 ]
>>> findmax(L2)
81
"""
return max(L) | 3fbb99b5189ee8a4a4867642ec4ebc73f06c04f0 | 37,920 |
import re
def camel_case(s):
"""Convert a snake_case string (maybe with lowerCaseFirst) to CamelCase."""
tokens = re.sub(r"([A-Z])", r" \1", s.replace("_", " ")).split()
return "".join(w.title() for w in tokens) | d0201daf285ddeeb88d507d156fa97d38a03b388 | 37,921 |
def dayOfWeek(julian):
"""Get day of week from a julian day
:param `julian`: the julian day
:returns: the day of week as an integer and Monday = 1
"""
return int((julian + 1) % 7) | 0aa478cb8d597097a73f998cb6d4de128a06611c | 37,922 |
import re
def is_valid_name(project_name):
"""
judge name is valid
:param project_name:
:return:
"""
if not re.search(r'^[_a-zA-Z]\w*$', project_name):
print('Error: Project Name must begin with a letter and contain only letters, numbers and underscores')
return False
retur... | a64948f2133a69fe46b8a640c844c15654306296 | 37,925 |
def recall(tp_count, targets_count):
"""Calculates recall.
:param tp_count: Number of true positives.
:param targets_count: Number of targets.
:return: The recall rate.
"""
if targets_count == 0:
return 0.0
else:
return tp_count / float(targets_count) | 985c5c4567c9be12e4bd248d2a3054a2def1f29f | 37,926 |
from typing import List
import csv
def cast_csv_2_list(csv_str: str, delimiter: str = ',', quote_char: str = '"',
csv_quoting: int = csv.QUOTE_MINIMAL, skipinitialspace: bool = True) -> List[str]:
"""
konvertiere einen csv String in eine Liste von Strings. Ist csv_str nicht vom typ string,... | 8468ca424c3faad6024aef3719db242152fa6b60 | 37,927 |
def intersect_interval(interval1, interval2):
"""Computes the intersection of two intervals.
Parameters
----------
interval1: tuple[int]
Should be `(x1_min, x1_max)`
interval2: tuple[int]
Should be `(x2_min, x2_max)`
Returns
-------
x_intersect: tuple[int]
Should be the intersection. If th... | 5db8daefa083b680c89a970224e2fc67a07beb5e | 37,928 |
def read_requirements(filepath):
"""Parses a dependency file"""
with open(filepath) as requirements:
required = requirements.read().splitlines()
required = [item for item in required if not item.startswith('#')]
return required | 78f186130ff765cb1bb8177844f85a8bbf249ba6 | 37,929 |
from typing import Any
import argparse
def parse_args() -> Any:
"""
Define an argument parser and return the parsed arguments
"""
parser = argparse.ArgumentParser(
prog='generator.py',
description='takes a pgn file and produces chess puzzles')
parser.add_argument("--file", "-f", he... | 7d96885646d91c4ff2765c466d9aab92faf11b14 | 37,930 |
def stage_feature_module_list():
"""
:return: dictionary with a features as keys and a list of modules to be included
if those features are selected AND there are stages as values
"""
stage_feature_modules = {
"markets": ["system.load_balance.fix_market_participation"]
}
return stag... | aad3eacc81d6d4f003270aa19fdc754df678b8bb | 37,931 |
def get_order_by_from_request(request):
"""
Retrieve field used for sorting a queryset
:param request: HTTP request
:return: the sorted field name, prefixed with "-" if ordering is descending
"""
sort_direction = request.GET.get("dir")
field_name = (request.GET.get("sort") or "") if sort_di... | 9324e8e03bb8b5a48cd37f3daf6807712b57ad97 | 37,933 |
def turn_strat_into_label(stratum):
"""
Convert age stratification string into a string that describes it more clearly.
Args:
stratum: String used in the model
Returns:
label: String that can be used in plotting
"""
if 'up' in stratum:
return stratum[4: -2] + ' and up'
... | fb2ce3810359a150948905913ba48e7627875769 | 37,934 |
def diff(prev_snapshot, next_snapshot):
"""Return a dict containing changes between two snapshots."""
snapshot_diff = {
'left_only': [],
'right_only': [],
'changed': [],
'common': [],
}
for path in set(prev_snapshot.keys()) | set(next_snapshot.keys()):
if path i... | 040be0018e4b517cfc884a1e4a0f9cc030032fa9 | 37,936 |
def make_table_row(contents, tag="td"):
"""Given an iterable of string contents, make a table row.
Args:
contents: An iterable yielding strings.
tag: The tag to place contents in. Defaults to 'td', you might want 'th'.
Returns:
A string containing the content strings, organized into a ta... | 346301a77954829f6869a47ace6c1de52d787ffa | 37,938 |
def _gauge_pair():
""" Track gauge as a pair of (sum, count) """
return [0, 0] | df91d575a0e96560140e0060695e4a91794c99fc | 37,939 |
def typical_price(data, high_col='High', low_col='Low', close_col='Close'):
"""
Typical Price
Source: https://en.wikipedia.org/wiki/Typical_price
Params:
data: pandas DataFrame
high_col: the name of the HIGH values column
low_col: the name of the LOW values column
close_c... | 3c47cb01d4bd02351269f00c394d73abca862bc8 | 37,940 |
from typing import Optional
def _get_description(experiment_config: dict) -> Optional[str]:
"""Returns the description of the experiment described by
|experiment_config| as a string."""
return experiment_config.get('description') | 2262b8bb5b17e3ecb408bd3f2d133753dd0a1bbe | 37,942 |
def get_family_name_from(seq_name_and_family):
"""Get family accession from concatenated sequence name and family string.
Args:
seq_name_and_family: string. Of the form `sequence_name`_`family_accession`,
like OLF1_CHICK/41-290_PF00001.20. Assumes the family does not have an
underscore.
Returns:... | d75d48c72ebee14ef43edf9d0ab42b2f85999713 | 37,943 |
def __clean_indicator_info(indicators):
"""
Cleans the strings contained the the indicator / category dataframe
Parameters
----------
indicators : pd.DataFrame()
A dataframe of indicator information
Returns
-------
indicators : pd.DataFrame()
A dataframe of indicator... | 3d5f883fc48c03638a4dee8d9746a7269fc04f6e | 37,944 |
def turn_list_to_int(list_):
"""converts elements of a list to integer"""
list_ = [int(i) for i in list_]
return list_ | f4ee0f763c35a7218e9163ff15dab8bfd653b0d3 | 37,945 |
from bs4 import BeautifulSoup
def extract_html_links(text):
"""
Grab any GOV.UK domain-specific links from page text.
:param text: Text within a details sub-section, refer to filtered for keys.
:return: list of links
"""
links = []
try:
soup = BeautifulSoup(text, "html5lib")
... | c7debea7ef2b3c8d239cde39b40913d9f141d3fb | 37,946 |
def assertContainsExportItems(item_tuples, export_group_schema):
"""
:param item_tuples: list of ("path", "label") tuples representing each export item:
eg: [("form.group.question2", "question_label")]
"""
actual = {
(item.readable_path, item.label)
for item in export_group_schema.i... | 40296743a6e8c7c2e6efec83da58d61c19e89ca4 | 37,947 |
def pow(a, b):
"""
Finds a^b using recursion.
Params:
a (float) - Base
b (int) - Exponent
Returns:
Value of a^b (float)
"""
if(type(b) != int):
print("ERROR: pow() not callable with doubles!")
return 0
if(b == 0):
return 1
else:
return a * pow(a... | e903a8a430453cc57460a124a2485b7de57473e2 | 37,948 |
import os
def skip_optional(func):
"""function decorator"""
def wrapper(connector_access, local_result_file, metadata):
local_file_path = os.path.join(local_result_file['dir'], local_result_file['name'])
if not os.path.isfile(local_file_path):
if local_result_file.get('optional'):
... | a842bb1c5926241ceda83d1c75ceeeffc7bc6518 | 37,949 |
def twr(rors):
"""The Time-Weighted Return (also called the
Geometric Average Return) is a way of calculating
the rate of return for an investment when there are
deposits and withdrawals (cash flows) during the period.
You often want to exclude these cash flows so that we can
find out how well t... | d9346efca7f8db311643818a8f13f30ab0ee12f5 | 37,951 |
def NoEmbedding(X):
"""Return X without changes."""
return X | c33dd4175999dab4eb3568753f8d4980c809b294 | 37,952 |
def find_sequence_with_x(consensus, single_sequences):
"""
Determine the correct consensus sequence with X replacing consolidated nucleotides, based on the original
sequences to be consolidated
"""
output_sequence = ''
for position, nt in enumerate(consensus):
if nt == 'X':
... | 9e993c0774f26bf69c2e8dee8b31b693d48224d1 | 37,954 |
def bytes_split(bytes_, length):
"""Split bytes into pieces of equal size."""
n_pieces, excess = divmod(len(bytes_), length)
if excess:
raise ValueError('Bytes of length {} cannot be equally divided into '
'pieces of length {}'.format(len(bytes_), length))
return [bytes_... | 7c70146e4ebbef70371e7cfb3ce3a1abe6df3c97 | 37,955 |
def diamag_correction(H, H0, Mp, Mpp, m_sample, M_sample, Xd_sample, constant_terms=[], paired_terms=[]):
"""
Calculates a diamagnetic correction of the data in Mp and Mpp and calculates
the corresponding values of Xp and Xpp
Input
H: amplitude of AC field (unit: Oe)
H0: strength of applied... | 6b29fd46ff6fd2457b6b3572efc544c3d84956c1 | 37,956 |
def median(a, i, j, k):
"""
Return median of 3 integers from array a.
:param a: Iterable of elements
:param i: start element index
:param j: end element index
:param k: middle element index
:return: return median of values at indices i, j and k.
"""
ai, aj, ak = a[i], a[j], a[k]
... | 968c5b91d1a0bcafa77821d02e96963c7839261e | 37,958 |
from typing import Union
from datetime import datetime
import os
import locale
import re
def to_datetime(date_string: str, language: str) -> Union[datetime, str]:
""" Converts a date string to a datetime object """
locales = {"pt": "pt_BR.utf-8", "en": "en_US.utf-8"}
""" correct problem with locale in Wi... | 582412ec380331a35af951b0390ab6485a048b29 | 37,960 |
def is_permutation_dict(s1, s2):
"""Uses a dictionary to store character counts."""
n1 = len(s1)
n2 = len(s2)
if n1 != n2:
return False
if s1 == s2:
return True
ch_count = {}
for ch in s1:
if ch_count.get(ch, 0) == 0:
ch_count[ch] = 1
else:
... | 308653cf26d8b8f6722bbed2e0b82c1b9853d921 | 37,962 |
def rearange_base_link_list(table, base_link_index):
"""Rarange base link to beginning of table"""
value = table[base_link_index]
del table[base_link_index]
table.insert(0, value)
return table | 08d94b515d6c1e1fcaf47fecdda7816d7fcb6470 | 37,963 |
import html
def decode_html_entities(v):
"""Decodes HTML entities from a value, converting them to the respective
Unicode characters/strings."""
if isinstance(v, int):
v = str(v)
return html.unescape(v) | 852fa968ab99e0618eb1d845b6ef74322e137a42 | 37,964 |
import os
def get_relname(path, relative_to):
"""Get relative path name, where '.' is converted to ''."""
path = os.path.relpath(path, relative_to)
if path == '.':
path = ''
return path | e8852c90619a434a87abe8ef8ee89f9b0eee7689 | 37,965 |
def exe_success(return_code: int) -> bool:
"""Check if **return_code** is 0
Args:
return_code (int): Return code of a process.
Returns:
bool: True if return code is equal to 0
"""
return return_code == 0 | cfea5a87f750c3629714832cb0758fcd3c18ad9a | 37,966 |
def extract_pairs_from_lines(lines):
"""Extract pairs from raw lines."""
collected_pairs = []
for i in range(len(lines) - 1):
first_line = lines[i].strip()
second_line = lines[i+1].strip()
if first_line and second_line:
collected_pairs.append([first_line, second_line])
... | 071d75bf422fa2ef61daff301837c85c0e0f3af6 | 37,967 |
def _replace_nan_with_none(
plot_data,
plot_keys):
"""Replaces all instances of nan with None in plot data.
This is necessary for Colab integration where we serializes the data into json
string as NaN is not supported by json standard. Turning nan into None will
make the value null once parsed. The vis... | 887fff7f110945f8444f5ffec205828edf63f1f6 | 37,968 |
def build_confirmar_cohortes_query(filters, page, request, tipo_unidad_educativa, unidad_educativa_id):
"""
Construye el query de búsqueda a partir de los filtros.
"""
# Filtra que el año de la última cohorte sea menor o igual al año en curso y el estado sea controlado
if tipo_unidad_educativa == 'e... | b5a6a9fcc390695d25435e282520a2ef3b6b81c9 | 37,969 |
def filterKeys(schema):
"""
Saves only input and output dataset info
"""
newSchema = {}
newSchema['RequestStatus'] = schema.get('RequestStatus', "")
newSchema['InputDataset'] = schema.get('InputDataset', "")
newSchema['OutputDatasets'] = schema.get('OutputDatasets', "")
if schema['Reque... | 0aef9cffb732a02c31185ce5cf1f090d71e7170e | 37,970 |
def time2str(t):
"""Extract two string of YYYYMMDD and HH from a datetime object
Args:
t (datetime.datetime)
"""
YYYYMMDD = str(t)[0:10].replace('-', '')
HH = str(t)[11:13]
return YYYYMMDD, HH | a3ac6398ba748b1d399773a7fe935d95a62ec41e | 37,971 |
def reverse(text):
"""<string> -- Reverses <string>."""
return text[::-1] | a649991f3f989874e5ae88befd5205e38722e2ac | 37,972 |
def vcorrcoef(x, y):
"""
Compute correlation coefficients.
:param x,y : 2D tensor: (batch, d)
:return score: tensor: (batch)
"""
x_sub_mean = x - x.mean(dim=1).view(x.shape[0], 1)
y_sub_mean = y - y.mean(dim=1).view(y.shape[0], 1)
r_num = (x_sub_mean * y_sub_mean).sum(dim=1)
... | e6cc4a669b101a0d0e8d26767158c0907a052b48 | 37,973 |
def bytearray_to_long(byte_array):
"""
Converts a byte array to long.
:param byte_array:
The byte array.
:returns:
Long.
"""
total = 0
multiplier = 1
for count in range(len(byte_array) - 1, -1, -1):
byte_val = byte_array[count]
total += multiplier * byte_val
multiplier *= 256
... | 7dee1685dacd7e693a6cc50bf0ac704f78aa42bd | 37,974 |
def identity(*args):
"""
Return whatever is passed in
"""
return args if len(args) > 1 else args[0] | f0f1276beb43a13c49311974013caa330588e734 | 37,975 |
def WordStartWithUppercase(word):
"""Return whether a word starts with uppercase letter"""
if len(word) == 0:
return False
firstChar = word[0]
return firstChar == firstChar.upper() | 71b775fa9168abac586470e2a454194ce9103efe | 37,976 |
def greatest_sum_of_subarrays(nums):
"""
:param nums: array
:return: max sum of subarray
"""
max = sub_sum = float('-inf')
for n in nums:
if sub_sum + n <= n:
sub_sum = n
else:
sub_sum += n
if sub_sum > max:
max = sub_sum
return max | bd2a427f3f9d24a4cdd9b5871b50a71d75440f5b | 37,977 |
import os
def get_files(dirname, reverse=False):
""" Return list of file paths in directory """
# Get list of files
filepaths = []
for basename in sorted(os.listdir(dirname)):
filename = os.path.join(dirname, basename)
print(filename)
if os.path.isfile(filename):
fi... | 561a56d6280c3677f8d940fcb843580f80e3128e | 37,979 |
def heading_level(line):
"""Return heading level of line (1, 2, 3, or 0 for normal)"""
for i in range(4):
if line[i] != '#':
return i
return 3 | 47a21dd52d827b33dc467c02a31ce16c85b2b41b | 37,980 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.