content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import subprocess
def host_check(host) -> bool:
"""
Check to see if a specific host is alive
"""
proc = subprocess.run(
['ping', '-W1', '-q', '-c', '2', host],
stdout=subprocess.DEVNULL)
return proc.returncode == 0 | edca7d859ca284acded0f4021292777952c3fd16 | 696,860 |
import typing
def _get_tags(phase: str, param: str) -> typing.List[str]:
"""Get the tag names.
Parameters
----------
phase
param
Returns
-------
"""
return [param, phase, "{}_{}".format(phase, param)] | 278bb1f9d032c14287bd48a6bcfa9bfd7577f53a | 696,861 |
from typing import Dict
from typing import Union
from typing import List
def add_expenditures_cumulative_count(category_tree: Dict) -> None:
"""Add cumulative_count attribute to categories in category tree."""
def _get_all_children_expenditure_counts(children: Union[List[Dict], None]) -> int:
value =... | 1dab9228284f86c89f67c93e39e015e903846eac | 696,862 |
def get_datetime(cube):
"""Extract the time coordinate from a cube in datetime format
"""
tcoord = cube.coord('time')
tcoord_as_datetime = tcoord.units.num2date(tcoord.points)
return tcoord_as_datetime | e9975950e2e7d32a9845e55e062d11d7fa7440f6 | 696,863 |
def fill(template, hostdata, dnsdata=False):
"""Fills a generic template
Replaces a lot of repeated code"""
if dnsdata:
template.names = hostdata['names']
template.cnames = hostdata['cnames']
template.mxs = hostdata['mxs']
template.host = hostdata['host']
template.interfaces ... | 450d89360ac305c39e26ded1fcdcb53a4ead7ea1 | 696,864 |
def trim_hash(info_hash):
"""cleans up info hash"""
if len(info_hash) == 40:
return info_hash.decode("hex")
if len(info_hash) != 20:
raise TypeError("Infohash not equal to 20 digits", info_hash)
return info_hash | ffc71b8f2b92d408a4bfc58878ee36493b0f9fcb | 696,865 |
def secure_lookup(data, key1, key2 = None):
"""
Return data[key1][key2] while dealing with data being None or key1 or key2 not existing
"""
if not data:
return None
if key1 in data:
if not key2:
return data[key1]
if key2 in data[key1]:
return data[key1... | 03316d8902572f9ece66229f45fcc68212120fa5 | 696,866 |
def make_path (paths:list) -> str:
"""
把一个str的list合并在一起,并用 '/' 分割
-> ['api','goods']
<- "/api/goods"
"""
if paths == []:
return '/'
s = ''
for i in paths:
if i == '':
continue # 过滤空项
s += "/"
s += i
return s | a4e200c228c9f3d8f3ace3fb6cca94df1be16b6d | 696,867 |
import re
def pint2cfunits(value):
"""Return a CF-Convention unit string from a `pint` unit.
Parameters
----------
value : pint.Unit
Input unit.
Returns
-------
out : str
Units following CF-Convention.
"""
# Print units using abbreviations (millimeter -> mm)
s = "... | 7527a76393553282e39800dd685fd7138e78b359 | 696,868 |
def extract_form_data(response):
""" Extract the HTML form information contained in the given response. """
def add_param(element):
""" Add the info of the given element to params if it has a name """
nonlocal params
name = element.attrib.get("name", None)
value = element.attrib... | dd64ff0bc06aad143ff298d4661616363f6a50b1 | 696,869 |
def _get_outcome(guess: str, solution: str) -> str:
"""Get outcome string for the given guess / solution combination
Args:
guess: the word guessed
solution: puzzle solution
Returns:
5-character string of:
'0' = letter not present
'1' = letter present but not... | 843e7d2c38d3bd7e22b508581924ada0416adb84 | 696,870 |
def generate_save_string(dataset, embedding_name, random_state=-1, sample=-1.0):
"""
To allow for multiple datasets to exist at once, we add this string to identify which dataset a run
script should load.
Arguments:
dataset (str) : name of dataset
embedding_na... | 975fc413d86af2b5b3f24f440100efdd4013c478 | 696,872 |
def getDiffElements(initialList: list, newList: list) -> list:
"""Returns the elements that differ in the two given lists
Args:
initialList (list): The first list
newList (list): The second list
Returns:
list: The list of element differing between the two given lists
"""
fi... | a336d5f0c3073f3a656e0b79eaae2b117ba86899 | 696,873 |
import struct
def gen_rs_table(radstroke):
"""Generate the Unicode Radical Stroke data."""
def flag(s):
if s:
return 0x80
return 0
ranges = []
entries = []
num_ranges = radstroke.run_count()
dofs = num_ranges * 12 + 4
for base,mapped in radstroke.runs():
... | 3ac761b510471a9e6211b07b5eda78db9db5c3e9 | 696,874 |
def cpu_xgraph_quantizer(xgraph, **kwargs):
""" Basic xgraph quantizer """
return xgraph | bc2b5f78637108207f0c1f7d0350ff01e3325822 | 696,875 |
def limit_stop_loss(entry_price: float, stop_price: float, trade_type: str, max_allowed_risk_percentage: int) -> float:
"""
Limits the stop-loss price according to the max allowed risk percentage.
(How many percent you're OK with the price going against your position)
:param entry_price:
:param sto... | ad60d370fc44c43ea9398691c271465009f6d96e | 696,876 |
from typing import List
import os
def get_paths_in_folder(directory: str) -> List[str]:
"""Return the files in a given folder.
:param directory: folder path
:return: file names in folder
"""
return [
path
for path in os.listdir(directory)
if os.path.isfile(os.path.join(dir... | 962603fa01551f5b71d216e3b6784ea6cd0ae526 | 696,877 |
def nearest_x(num, x):
""" Returns the number rounded down to the nearest 'x'.
example: nearest_x(25, 20) returns 20. """
for i in range(x):
if not (num - i) % x:
return num - i | 5d8a9b6a77b9bec37517ca00fcc1d7a383aaaea1 | 696,878 |
def safe_join_existing_lab(lab_id, client):
"""
gets a lab by its ID only if it exists on the server
"""
if lab_id in client.get_lab_list():
return client.join_existing_lab(lab_id)
return None | fe5ccc6fcb36fd90325a6156b3dff6d199d5ee8a | 696,879 |
def pytest_report_collectionfinish(config, items):
"""Log how many and, if verbose, which items are tested in this shard."""
msg = "Running {num} items in this shard".format(num=len(items))
if config.option.verbose > 0:
msg += ": " + ", ".join([item.nodeid for item in items])
return msg | e81d3663f60505543a1b554d36e2dee26b7107f9 | 696,880 |
def extract_gist_id(gist_string):
"""Extract the gist ID from a url.
Will also work if simply passed an ID.
Args:
gist_string (str): Gist URL.
Returns:
string: The gist ID.
Examples:
gist_string : Gist url 'https://gist.github.com/{user}/{id}'.
"""
return gist_st... | 7c93c5f78cc9c5dd1b1136a82e9359a20d31265f | 696,881 |
import asyncio
def run(coroutine):
"""
Runs and returns the data from the couroutine passed in. This is to
only be used in unittesting.
coroutine : asyncio coroutine
-> coroutine return
"""
return asyncio.get_event_loop().run_until_complete(coroutine) | c862608f1abfdd234c5b4ad0be413d14123f1d6e | 696,882 |
import os
def relative_path(full_path, parent_subpath):
"""Get the relative path
Args:
path: long path: example /a/b/c
parent_subpath: sub-directory.
Example:
In [78]: relative_path("/a/b/c", '/a')
Out[78]: 'b/c'
In [79]: relative_path("/a/b/c", '/a/')
Out[79]: 'b/c'
""... | bd2c21a8763f089e47e587cfe901807df9fd5a4f | 696,883 |
def rec_mc(coins, change, knowned):
"""利用递归解决'用最少的硬币找零'问题"""
min_coins = change
if change in coins:
knowned[change] = 1
return 1
elif knowned[change] > 0:
return knowned[change]
else:
for i in [c for c in coins if c <= change]:
num_coins = 1 + rec_mc(coin... | 1480fe4be6f0c14af3a210311b4a7d3b9d592855 | 696,884 |
def null_detector(X):
"""
X is a dataframe
Function will give the null values in the dataframe
"""
return X.isnull().sum() | 3654ac56534abc92b720b35529c8dc44f5a73eff | 696,885 |
from datetime import datetime
def get_timestamp(detailed=False):
"""
get_timestamp - returns a timestamp in string format
detailed : bool, optional, default False, if True, returns a timestamp with seconds
"""
if detailed:
return datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
else:
... | 264eb48f7c205a187bc08a9b9ad73fdab05a6acb | 696,886 |
import math
def stddev(li, mean):
"""
Calculate the standard deviation of a set of data.
>>> stddev([3, 3.5, 4], 3.5)
5.0
"""
if not li:
return None
return math.sqrt(sum(x*x for x in li) - mean*mean) | d947d3bdf11841d236d28620682773d18be637f1 | 696,887 |
import os
def create_file_list(loc):
"""
create file location for reading functions
"""
file_list = os.listdir(loc)
for i in range(len(file_list)):
file_list[i] = loc + "/" + file_list[i]
return file_list | 560b658d6b3360308bf1a2111627d957ba45d997 | 696,888 |
import string
import random
def get_rand_string(size=6, chars=string.ascii_uppercase + string.digits):
"""generates a random string.
:param size: length of the string
:param chars: string of charaters to chese form, by default a-zA-Z0-9
"""
return ''.join(random.choice(chars) for _ in range(size)) | 655cad254414b265df30e160b6f4859f91680ed1 | 696,889 |
def flip(board):
"""Returns horizontal mirror image of board with inverted colors."""
flipped_board = dict()
for square, piece in board.items():
flipped_board[(7 - square[0], square[1])] = piece.swapcase()
return flipped_board | 62e3bbbe33abdd2e2d4e1ce6eae9f992b0fd275a | 696,890 |
def disable_hat_selector_dropdown(acq_state):
"""
A callback function to disable the HAT selector dropdown when the
application status changes to configured or running.
"""
disabled = False
if acq_state == 'configured' or acq_state == 'running':
disabled = True
return disabled | fce32c07f01a88d94a6258ca43c14b0641ab565f | 696,891 |
def paragraph_reversal(p: str) -> str:
"""Reverse the order of sentences in a paragraph.
This function can run in O(n) time. Because Python requires returning a
new copy of a string and not a pointer, this function does not technically
perform the operation in place.
Arguments:
p : str
... | e0f8889fe64193ab675c67947db72128e139900b | 696,893 |
import json
def cat_to_name(file):
"""
Loads a json file with mapping from category to flower name
Parameters:
file:
name of .json mapping file
Returns:
a python dictionary with mapping of categories to flower names
"""
with open(file, 'r') as f:
cat_to_name = jso... | 4545c9924c160665d984aee88d120f9648bf2f1e | 696,894 |
import os
def groupImageStats(imgFile, outImage, brik=''):
""" Strip the desired image statistics from the image file
Specifically, remove those subbricks from specified from the
supplied image, and store them in their own file that can be
manipulated more easily later on.
Params:
imgFil... | 2b5433c413fa07971b06565c93e867f99a9358e7 | 696,895 |
def list_to_string(lst):
"""
convert a list to string format for config files
"""
return ",".join(map(str, lst)) | c7eb44b84befb0d00fd72033e9cbcb50951c649c | 696,897 |
def getTime(t):
"""把OANDA返回的时间格式转化为简单的时间字符串"""
return t[11:19] | c5d3cd088a4aaee358cd65b807b387bf034adce2 | 696,899 |
def get_blue():
"""
Get color blue for rendering
"""
return [0, 0.651, 0.929] | 0a045497fb100e9019fe1cad52221ef37431cee0 | 696,900 |
def get_secs(t_string):
"""
From time_string like '00:00:35.660' returns the
number of seconds respect to '00:00:00.000'
returned value is float
"""
hours = t_string[0:2]
minutes = t_string[3:5]
secs = t_string[6:8]
m_secs = t_string[8:12]
secs_total = int(hours) * 3600 + int(... | 2401adef97845e9d7d900baf882812ebf0acae58 | 696,901 |
def confirm(msg=None):
""" Confirms the removal of the file with a yes or no input """
# Loop "forever" intended
while True:
confirm_input = input(msg if msg is not None else "Purge this directory (yes/no)?")
if confirm_input.lower() in ["y", "yes"]:
return True
if confir... | c6023f9fb72b10953afd0dbbea73a4f03db67de2 | 696,902 |
def is_kevinshome(ctx):
"""check to see if invoking user is kevinshome"""
return ctx.author.id == 416752352977092611 | 13f3bf234affe65c05f2b9cf9af89297ab5ef855 | 696,903 |
def get_conf(genotype):
"""transform a genotype(string) in some variables"""
architecture, evol_strattegy = genotype.split('--')
architecture = [[int(x) for x in conn.split('|')]
for conn in architecture.split(' ')]
use_shared, dataset = evol_strattegy.split(' ')
use_shared, d... | a4cf9353f95eb77283aa616ce66854db85cd3ca0 | 696,904 |
def find_alternating_4_cycle(G):
"""
Returns False if there aren't any alternating 4 cycles.
Otherwise returns the cycle as [a,b,c,d] where (a,b)
and (c,d) are edges and (a,c) and (b,d) are not.
"""
for (u, v) in G.edges():
for w in G.nodes():
if not G.has_edge(u, w) and u !=... | 30456f50fbf6da2a98dafe0ec837d5a4ea963b08 | 696,905 |
def is_submeter(sensor, dfdaymin, dfdaymax):
"""
Return True if this sensor is a sub-meter
sensor = sensor object
"""
other_sensors = sensor.device.get_sensors(sensortype='electricity')
other_sensors.remove(sensor)
if len(other_sensors) == 0:
print("\n{} - {}: no other... | 78ca8017d736d5d9502604b82666bc08bf7ac9c0 | 696,906 |
def add_2d(
ds,
):
"""
Regrid horizontally.
:param ds: Input xarray dataset
"""
ds['lat2d'] = ds.lat.expand_dims({'lon': ds.lon}).transpose()
ds['lon2d'] = ds.lon.expand_dims({'lat': ds.lat})
return ds | 428bca0725b6bea7d146d4501c221ef96e6c28e8 | 696,907 |
def gf_crt(U, M, K):
"""Chinese Remainder Theorem.
Given a set of integer residues `u_0,...,u_n` and a set of
co-prime integer moduli `m_0,...,m_n`, returns an integer
`u`, such that `u = u_i mod m_i` for `i = `0,...,n`.
As an example consider a set of residues `U = [49, 76, 65]`
... | 32d4fabf159487c9867ca825fb2e2c550f39b393 | 696,908 |
def mosaic_to_horizontal(ModelParameters, forecast_period: int = 0):
"""Take a mosaic template and pull a single forecast step as a horizontal model.
Args:
ModelParameters (dict): the json.loads() of the ModelParameters of a mosaic ensemble template
forecast_period (int): when to choose the mod... | 1776062056b9c4d56bbcb8db5972ce62b9eacf68 | 696,909 |
def term_to_cat_relevance(term, category, all_categories):
"""
mi R(t, cj)
:param term: term from document
:type type: str
:param category: category in which we look for
:type Category
:param all_categories: all categories
:type list
"""
return (category.t... | bfaa677bae99cef2423ebf5d16290dc5e2ff8b07 | 696,910 |
def add_log_level(logger, method_name, event_dict):
"""
Add the log level to the event dict.
"""
if method_name == "warn":
# The stdlib has an alias
method_name = "warning"
event_dict["level"] = method_name
return event_dict | c69627fcbf8c7b0ec5890b8752f1327b95bd5854 | 696,911 |
def _is_python_file(filename):
"""Check if the input file looks like a Python script
Returns True if the filename ends in ".py" or if the first line
contains "python" and "#!", returns False otherwise.
"""
if filename.endswith('.py'):
return True
with open(filename, 'r') as file_handle... | a6d99166c6b76c4ae0ad5f5036951986fd5a102b | 696,912 |
def left_join(ht1, ht2):
"""
Takes in two hashtables and returns a dictionary representing a left join of the two hashtables.
"""
join_dict = {}
for bucket in ht1._array:
if bucket is not None:
curr = bucket.head
while curr:
key = curr.data[0]
... | a70e2a1d8d4feb6ef1cdd83c2f1ec494e9d4ce5c | 696,913 |
def transpose_report(report):
""" Splits & transposes the report
"""
l_o_l = [list(c for c in code) for code in report.split("\n") if len(code)]
return list(map(list, zip(*l_o_l))) | baf3a9bdcc1095ec434cf7c9033aa2cc29d1c5b6 | 696,914 |
def RANGE(start, end, step=None):
"""
Generates the sequence from the specified starting number by successively
incrementing the starting number by the specified step value up to but not including the end point.
See https://docs.mongodb.com/manual/reference/operator/aggregation/range/
for more detai... | 3537e1e0cd28ae7d90e469a281ab373312fe075c | 696,915 |
import six
def _unicode_to_str(data):
""" Utility function to make json encoded data an ascii string
Original taken from:
http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python
:param data: either a dict, list or unicode string
:ret... | ff637b4cad60833de6c448cc3807c4928b2a94da | 696,916 |
import re
def mocked_res_client(*args):
"""Function will be used by the mock to replace resilient client"""
class MockResponse:
def __init__(self, *arg):
pass
def __contains__(self, key):
return True if key in self.__dict__.keys() else False
def _get_data(sel... | 09ceac1c44c2788534141eec135956defd2b6174 | 696,917 |
import re
def _line_type(line, delimiter=None):
"""Interpret a QDP file line
Parameters
----------
line : str
a single line of the file
Returns
-------
type : str
Line type: "comment", "command", or "data"
Examples
--------
>>> _line_type("READ SERR 3")
'... | cbc0f5f831a80b28ce9aee01049c90c65b962ff4 | 696,919 |
def get_intermediate_objective_suffix(suffix=""):
"""
Returns dictionary of dictionaries of suffixes to intermediate files.
Dict contains:
objective - initial(s) of corresponding objective(s)
filesuffix - intermediate file/variable suffix
Args (optional) :
suffix - appends t... | b00395103d3d21749f4ce3fddc913a24289b4417 | 696,920 |
def is_suffixed(suffixes, field, allowed):
"""
Check field for a suffix.
Check if a field has a specific suffix where its base is in the allowed
list.
For example if the suffix is 'Modifier', the following situation is valid:
field = 'characterStrengthModifier'
allowed = ['characterStreng... | 63cb34ee813289ed1efcdc04a4df5656d9aab29a | 696,922 |
import numpy
def voronoi_finite_polygons_2d(vor, radius=2.):
"""
https://stackoverflow.com/questions/20515554/colorize-voronoi-diagram
Reconstruct infinite voronoi regions in a 2D diagram to finite
regions.
Parameters
----------
vor : Voronoi
Input diagram
radius : float, opti... | c7e81711f552e5da824ca926ced03e4d3502fee0 | 696,925 |
def lorenz(XYZ, t, the=10, r=28, b=8 / 3):
"""
The Lorenz Attractor.
x0 = (0,1,0)
"""
x, y, z = XYZ
x_dt = the * (y - x)
y_dt = x * (r - z) - y
z_dt = x * y - b * z
return x_dt, y_dt, z_dt | 61d7ac1eb0ba1507fe4127a78ae6c83cdaeec7ef | 696,926 |
import glob
import os
def get_image_ids(path: str) -> list:
"""
Return a list of image IDs based on the contents of the ARD tarballs folder
Args:
path:
Returns:
"""
file_list = glob.glob(path + os.sep + "*SR*")
return sorted([os.path.splitext(os.path.basename(f))[0] for f in fi... | 23ccafb749d38bbfd9b52e0b6570213934163dba | 696,927 |
import time
def time_to_month(t):
"""时间戳 => 月份"""
return time.strftime('%Y%m', time.localtime(t)) | b851f332f6e9de13c10e0fc8c0cb6439092147d8 | 696,928 |
def ms_timestamp_to_epoch_timestamp(ts: int) -> int:
""" Converts a milliseconds timestamp to an epoch timestamp
:param ts: timestamp in miliseconds
:return: epoch timestamp in seconds
"""
return int(ts / 1000) | 1c27d9ef053f568bcf9e5e37309b3def5f4c8dd0 | 696,929 |
def intersection_line_plane(p0, p1, p_co, p_no, epsilon=1e-9):
"""
Copied from https://stackoverflow.com/questions/5666222/3d-line-plane-intersection
p0, p1: Define the line.
p_co, p_no: define the plane:
p_co Is a point on the plane (plane coordinate).
p_no Is a normal vector defining ... | 42ea283d5a9798a706e713dda8599c3d33a05cec | 696,930 |
import six
def inverse_dict(x):
""" Make keys or values and values of keys """
return {v: k for k, v in six.iteritems(x)} | 05239e5ff375fe2b1345f915f5745befc869062d | 696,931 |
def gen_trace_ids_exps(base_id, base_exp=None, group_size=3, group_count=5,
block_count=6, group_jump=18,inverse=False,
base_exp_group=None,skip=0):
""" Generates the list of trace_ids to load and plot. Returns a list of
lists of trace_id.
Args:
- base_id: first trace... | 3d22c9776b810784fd596f92a21758b446a084d4 | 696,932 |
def _convert_to_barycentric(point, simplex, coordinates):
""" Converts the coordinates of a point into barycentric coordinates given a simplex.
Given a 2D point inside a simplex (a line segment or a triangle), find out its
barycentric coordinates. In the case of the line (1-simplex), this would be the poin... | d895325f8a605cefaa8ecd9e2cc4edd07690b932 | 696,933 |
def filter_by_price(res, max, min):
"""
res should be the return value of search (a list of Products as dictionaries)
"""
filtered_search = []
for r in res:
if r["PriceInEuros"] <= max and r["PriceInEuros"] >= min:
filtered_search.append(r)
return filtered_search
# return... | 99c2c21b257f817998afd7c8573ceeec5239fd12 | 696,935 |
def create_dict(min_count):
"""
:param min_count: 词频出现的最少个数
:return:
"""
input_file = open("text8.txt", "r", encoding='utf-8')
word_count_sum, sentence_count, word2id_dict, id2word_dict, wordid_frequency_dict, word_freq = 0, 0, {}, {}, {}, {}
for line in input_file:
line = line.str... | fcc28b9b457a568fabae8bc67c9d2ffba3b76362 | 696,936 |
import importlib
def get_net_driver_func(benchmark_name):
"""
:param benchmark_name: This MUST be the exact name of the actual benchmark (tcp_driver_name === benchmark_name)
:return: The net_driver function of the given benchmark
"""
tcp_driver_name = "." + benchmark_name
net_driver_func = imp... | 235ff43679f2928e989e436d6e89c53d280eaa86 | 696,937 |
import base64
import requests
import json
import random
def __getCookies(weibo):
""" 获取Cookies """
cookies = []
loginURL = r'https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)'
for elem in weibo:
account = elem.no
password = elem.psw
username = base64.b64encode... | 413ed10f3b7e453975772b28c703e5cc24a38d1e | 696,938 |
import logging
def get_logger() -> logging.Logger:
"""
logging.Loggerを作成します。
Returns:
logger (logging.Logger):
logging.Loggerのインスタンス
"""
logger = logging.getLogger(__name__)
return logger | 233d118748fcddb4eb42aae0acd19fd4ce2d26b7 | 696,941 |
from typing import Counter
def is_anagram(word, _list):
"""
Checks if the given word has its anagram(s)
on the given list of words.
:param word: word
:param _list: list of words
:return a list of found anagrams
"""
word = word.lower()
anagrams = []
for words in _list:
... | dc6da021ed46e5068f16608fb9f3f78fedeea4a8 | 696,942 |
def diagonal (line):
"""Indicates whether or not `line` is diagonal."""
return (line.p.x != line.q.x) and (line.p.y != line.q.y) | b5c64e983c429023ccd2c7e57bba59511567e2d5 | 696,943 |
def cleave(sequence, index):
"""
Cleaves a sequence in two, returning a pair of items before the index and
items at and after the index.
"""
return sequence[:index], sequence[index:] | 5f542de88eb4cd7496a2308c9625cc7db766c90c | 696,944 |
def age_to_eye_diameter(age):
"""Calulates the size of an eye given an age
Args:
age (float): age of the observer
Returns:
D_eye (float): Best diameter of Eyepiece (mm)
"""
if age <= 20:
D_eye = 7.5
elif ((age> 20) and (age<= 30)):
D_eye = 7
elif ((a... | f67154b48ec3e246e6049bfcb89c67b908d896b9 | 696,945 |
def fetch_noncompressed_file(name, fido, downloader=None):
"""
Load an uncompressed file from the data registry
"""
fname = fido.fido.fetch(name, downloader=downloader)
return fname | 54437726d3b1827bf0014ea10a324181e4a8a973 | 696,946 |
def transform_zip(number):
"""Get rid of extended format ZIP code."""
zip_code = number.split("-")[0]
return zip_code | 9ef27547f501b6f77ffff0198a4965b3082c2c91 | 696,947 |
def flatten_list(list_):
"""
Flattens out nested lists and tuples (tuples are
converted to lists for this purpose).
Example:
In [1]: flatten_list([1, [[2, 3], [4, 5]], 6])
Out[1]: [1, 2, 3, 4, 5, 6]
"""
items = []
for element in list_:
if isinstance(element, (list, tuple)):
... | c914976b1ded7b43d6a2031ac51aca9299c6a2ce | 696,948 |
def base_to_dec(string, base, digits):
"""Converts strings to decimal numbers via a custom base and digits."""
if string == '':
return 0
return digits.index(string[0]) + base_to_dec(string[1:], base, digits) * base | 6f608e280e6f45207b024dddfb768ee1df961edb | 696,950 |
def vote_pourcentage(string):
"""
(str) -> int
Counts the total number of 'oui', 'abstention', and the total of words in
a given string.
Restrictions: string must contain at least one 'oui' or one 'non'.
"""
total_yes = 0
total_votes = 0
total_abs = 0
# Count all 'oui', 'abst... | bfcb80a00d8bfe650a0a50a75b5a86ecb9187f3d | 696,951 |
def jetCollectionString(prefix='', algo='', type=''):
"""
------------------------------------------------------------------
return the string of the jet collection module depending on the
input vaules. The default return value will be 'patAK5CaloJets'.
algo : indicating the algorithm type of the... | c77c2fd3afcccb1e62e1d92103ce677775fae0e4 | 696,952 |
import re
def sanitize_tag_label(label_string):
"""Return string slugified, uppercased and without dashes."""
return re.sub(r'[-\s]+', '-', (re.sub(r'[^\w\s]', '',label_string).strip().upper())) | 1fee28a86533a5fda3a34a647c445fdaa73e3c59 | 696,953 |
def strip_extension(input_string: str, max_splits: int) -> str:
"""Strip the extension from a string, returning the file name"""
output = input_string.rsplit(".", max_splits)[0]
return output | 62c388fd1cf11883f9e2b0259fb9ec7632537bd2 | 696,954 |
import os
def get_abs_dir(path: str) -> str:
"""Returns absolute path"""
return os.path.abspath(path) | 985184d7c5b4987426f44dee488416d4332cc4ae | 696,955 |
def getVertices(obj, world=False, first=False):
"""Get the vertices of the object."""
if first:
print('-----getVertices')
vertices = []
if obj.data:
if world:
vertices.append([obj.matrix_world * x.co for x in obj.data.vertices])
else:
vertices.append([x.co... | 158700e2578aeacbcb74b9695a6165a8611a86a2 | 696,956 |
import re
def header(line):
"""
add '>' if the symbol is missing at the end of line
"""
line=line.strip()
if re.match("##.*<.*", line) and line[-1:] != '>':
line=line+'>'
return line | b06488ff95d154836d622f55ebb5b26661d1fceb | 696,957 |
def safe_stringify(value):
"""
Converts incoming value to a unicode string. Convert bytes by decoding,
anything else has __str__ called.
Strings are checked to avoid duplications
"""
if isinstance(value, str):
return value
if isinstance(value, bytes):
return value.decode("utf... | c591f0b86f0f73f0ebf7f8253f7ecfd1e979a906 | 696,958 |
def normalize_expasy_id(expasy_id: str) -> str:
"""Return a standardized ExPASy identifier string.
:param expasy_id: A possibly non-normalized ExPASy identifier
"""
return expasy_id.replace(" ", "") | 30107cd75cba116b977a001f3839b1e9f32395ce | 696,959 |
import math
def break_likelihood(datalayer, feature, median_speed):
"""
Calculate break_likelihood for a point based on point speed & angle between previous & next points
:param datalayer: gps segment
:param feature: gps point id to check
:param median_speed: median speed for gps segment
:retu... | 481cfd318c4e121db80dbfe9b677251db0f72df5 | 696,960 |
def test_learning(learner, X, y):
""" vrne napovedi za iste primere, kot so bili uporabljeni pri učenju.
To je napačen način ocenjevanja uspešnosti!
Primer klica:
res = test_learning(LogRegLearner(lambda_=0.0), X, y)
"""
c = learner(X,y)
results = [c(x) for x in X]
return results | 7bc140652b05461d469d1a06dee79e392a041cd0 | 696,961 |
def get_excel_column_index(column: str) -> int:
"""
This function converts an excel column to its respective column index as used by pyexcel package.
viz. 'A' to 0
'AZ' to 51
:param column:
:return: column index of type int
"""
index = 0
column = column.upper()
column = column[::-1]
for i in range(len(column... | a42b05e2c08c3a6611c066fa49153f6dade93728 | 696,962 |
def shift_conv(matchobj):
"""
Transform '(a<b)' into 'a * 2**b'.
"""
shift = 1 << int(matchobj.group(2))
formula = '{}*{}'.format(matchobj.group(1), shift)
return formula | c17d4c8585e18cc99d9e70848a2f9e776a21cdf6 | 696,963 |
def convert_db_dict_into_list(db_dict):
"""Convert dictionary of processes into list of processes."""
db_list = []
for key in db_dict.keys():
assert key == db_dict[key]["@id"]
db_list.append(db_dict[key])
return db_list | ce0d678ffef92a66f5ce988bf2b7143248a1a60d | 696,964 |
def join(a, *p):
"""Taken from python posixpath."""
sep = '/'
path = a
if not p:
path[:0] + sep
for b in p:
if b.startswith(sep):
path = b
elif not path or path.endswith(sep):
path += b
else:
path += sep + b
return path | 5cf0783c995d4da115eae7f5f85f56eb5407f36a | 696,965 |
def est_palindrome3(s : str) -> bool:
""" ... cf. ci-dessus ...
"""
i : int
for i in range(0,len(s)//2):
if s[i] != s[-i-1]:
return False
return True | 871a169d2e82fe733ef23e8d63f466afe1c76599 | 696,966 |
def dbname():
"""
database name fixture
:return: test db name
"""
return 'jhhalchemy_test' | 4b5152fbbc2d2c70edfae16d286f69f61159950a | 696,967 |
def calculate_profit(region, country_parameters):
"""
Estimate npv profit.
This is treated as the Net Operating Profit After
Taxes Margin (NOPAT).
NOPAT ranges from ~5-15% depending on the context:
https://static1.squarespace.com/static/54922abde4b0afbec1351c14/t/583c49c8bebafb758437374e
... | 2791000709e55f7f3640c501779ef5da9a4f4e6a | 696,968 |
def taskname(*items):
"""A task name consisting of items."""
s = '_'.join('{}' for _ in items)
return s.format(*items) | c8283ea85818b3e3bac6ec5357439e8c944b05e8 | 696,969 |
def add_doc(m):
"""
Grab the module docstring
"""
return (('doc', m.groups()[0]), ) | d458adb9c58812f5cb5df5913bcc68e3ec256e4c | 696,970 |
import itertools
def generate_addresses(addr: str, mask: str) -> list:
"""generate all possible addresses from floating mask"""
generator_bits = list()
addresses = list()
addr = format(int(addr), '036b')
for addr_bit, mask_bit in zip(addr, mask):
if mask_bit == '0':
generator_b... | bbc49ab230743eaab4a305622b61402992db2225 | 696,971 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.