content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def only_printable(string):
""" Converts to a string and removes any non-printable characters"""
string = str(string)
return "".join([s for s in string if s.isprintable()]) | 2ee68c5fa77a04a58bb717918833b70e8c6f59bc | 656,004 |
def name_class(classname):
"""Change AMQP class name to Python class name"""
return classname.capitalize() | 676111fcbeb6005f17f09f21af5a817a2487a54c | 656,005 |
def create_averaging_function(threshold):
"""Creates and returns a function to group by.
Creates the averaging function to be used with the itertools.groupby()
function. Takes a threshold value in seconds as input to average groups
of similar event times.
"""
key = None
def averaging_functi... | ea3c08bacfc8f2571afdca20ce34dbc7e318397e | 656,006 |
def calculateFrameTime(speed, ratio):
"""
Calculates the frame time interval from chopper parameters.
Chopper speed in rpm given, but calculations are in Hz.
The interval is the time between pulses of chopper 5 because chopper 5
has only 2 slits
returns the frame time in s
"""
speed /=... | eca95d90fee99891c7b4922731b9b4722bf5fddf | 656,007 |
def computedcg(set_pkg, lst_rec, num_recom):
""" Compute DCG for a list of recommended apks against the User apks """
if len(lst_rec) > num_recom:
lst_rec = lst_rec[0:int(num_recom)]
intersection = set_pkg.intersection(lst_rec)
if not intersection:
return 0.0
dcg = 0
for ele in... | 0637794695850af412dbed220e2d0b3184ec77cf | 656,008 |
def _convert_url(url, website):
"""
Private function to clean a given page URL.
Parameters
----------
url: String.
URL for the news stories to be scraped.
website: String.
Nickname for the RSS feed being scraped.
Returns
-------
page_url: String.
... | 27af90f63db28f92570226db982a09db3e74d9f5 | 656,009 |
def normalize_order_number(order_number: str) -> int:
"""
Normalizes Sierra order number
"""
return int(order_number[2:-1]) | 687afc219fd69cc061a96065fbdd914d0e85ca50 | 656,010 |
def pretty_dict_repr(d):
"""Represent a dictionary with human-friendly text.
Assuming d is of type dict, the output should be syntactically
equivalent to repr(d), but with each key-value pair on its own,
indented line.
"""
lines = [' {0!r}: {1!r},'.format(k, v) for (k, v) in sorted(d.items()... | 210b794fb4f5d623bbb83b8dd82e3f9d431ff183 | 656,012 |
def read_input(prompt: str, dictionary: list) -> str:
"""Read user word input"""
while True:
line = input(prompt).upper()
if line in dictionary:
return line
else:
print ("Invalid Input, try again") | 1ca11931bb0e1fdec130137d63c9cd5c216cffed | 656,013 |
def compose_j(n, Nvec):
"""
Eq. 4 in Poly Fits Derivation. Routine to compose the j counter from
the n values. Can also be used as Eq. 10 with the i counter and the nhat
values.
inputs:
n = list of integer values representing the independent variables'
exponents for the... | d9a7f7b92a7c3dadb801c2c86a2497f7b26fafc4 | 656,014 |
import pwd
def get_owners():
"""get a list with the users defined in the system"""
owners = [e[0] for e in pwd.getpwall()]
return owners | 5476530b7951d84508e5e65875e2a75b396c4a14 | 656,015 |
import os
def get_files_of_type_in_folder(folder_path, extension):
"""Get a list of all files in folder, with a specific particular extension.
Folder path is a string path, and extension is something like: '.las', '.tif', etc."""
filenames = os.listdir(folder_path)
filenames = [
os.path.join(f... | f7b71fff0dd3c1d7065f77711508bc0f0f9d0db8 | 656,016 |
from typing import TextIO
def open_read_text(filepath: str) -> TextIO:
"""Open a text file for reading and return a file object."""
return open(filepath, mode="r", encoding="utf-8") | c31f27e74df1e0d8ac342583dd40e89df281172d | 656,017 |
import numpy
def parse_datafile(filename, time_column, data_column):
"""Gets specified time_column and data_column numbers from a comma-separated file. Start counting at zero."""
f = open(filename,'r')
time = list()
data = list()
for line in f:
line = line.split(',')
if len(line) >... | 11f566cff19e2e7b2feac7bea61df3e586522039 | 656,018 |
def _update_tik(tik_instance, input_x_ub, broadcast_0_local_ub, block_index, res):
"""_update_tik"""
with tik_instance.for_range(0, 64) as cc0:
data_temp = tik_instance.Scalar("float32")
data_temp.set_as(input_x_ub[cc0])
tik_instance.vector_dup(64, broadcast_0_local_ub[cc0 * 64], data_te... | fb3f3a299f86a6c141629a0d77a1a364d344bbea | 656,019 |
import inspect
def get_default_hook(obj, default_hooks):
"""Finds the default save/load hook to use with the given object.
Follows the Method Resolution Order, i.e., if no hook is registered for
the class of the object itself, also searches classes which the object
inherits from.
Arguments
-... | 1909bc8d3a4706ee9a9518b2159171d7b879f563 | 656,020 |
def calc_cost(distance):
"""
distance = 1; answer = 1
distance = 2; answer = 3 (distance + 1) * (distance / 2)
distance = 3; answer = 6
distance = 4; answer = 10 (distance + 1) * (distance / 2)
distance = 5; answer = 15
distance = 6; answer = 21 (distance + 1) * (distance / 2)
"""
if... | 08844013d72f629e7277760a0b8b2b371f731c3b | 656,021 |
def get_template_path(relative_path, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
The calculated value is cached for the lifetime of the current request.
"""
return relative_path | ac8466b73424355282a073958e4ef08c39e58758 | 656,023 |
import sys
def _PixelDataBase___iter__(self):
"""
Create and return an iterator/generator object for traversing
this pixel data object.
"""
width = self.GetWidth()
height = self.GetHeight()
pixels = self.GetPixels() # this is the C++ iterator
# This class is a facade over the pix... | 6e25ec0f160d6c2616e993c42bf4d6e115270303 | 656,024 |
def datetime_arange(start_datetime, end_datetime, step):
"""
:param start_datetime: datetime.datetime(2010, 12, 1)
:param end_datetime: datetime.datetime(2010, 12, 30, 23, 59, 59
:param steps: datetime.timedelta(seconds=5)
:return:
"""
dt = start_datetime
result = []
while dt < end_... | 6042c4cd498779738c36af63f5f8ed250bb50eef | 656,026 |
from typing import List
import os
def _retrieve_keys() -> List[str]:
"""Retrieve the necessary keys to communicate with Twitter and Slack APIs."""
env_vars = (
"TWITTER_CONSUMER_KEY",
"TWITTER_CONSUMER_SECRET",
"TWITTER_ACCESS_TOKEN",
"TWITTER_ACCESS_TOKEN_SECRET",
"SLA... | d41c0c0af9d94a367262b7a44adec4c74d381266 | 656,027 |
def chunk(chunk_cls, name, chunk_array, chunk_mask):
"""A fixture object for chunks"""
return chunk_cls(name, chunk_array, chunk_mask) | 14171b1d185f6c695c93279c7069e42b249c4e3b | 656,028 |
import os
def normalize_and_reduce_paths(paths):
"""Return a list of normalized paths with duplicates removed.
The current order of paths is maintained.
"""
reduced_paths = []
for p in paths:
np = os.path.normpath(p)
if np not in reduced_paths:
reduced_paths.append(np)... | 19ccef46131e634eb469dac7affcdc6e490997ac | 656,029 |
def safe(f):
""" return a new function that's the same as f,
except that it outputs infinity whenever f produces an error """
def safe_f(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
return float('inf') # this means infinity in Python
return safe_f | 74c8db9e1759f866ac6d02fe76e62e5ad81d233e | 656,030 |
import os
def imod_setup_sta(artia_root, dirs_start_with):
"""
Write out the info file necessary to run the MATLAB set up script for sub-tomogram averaging in Artiatomi
Args:
artia_root: The Artiatomi project directory
dirs_start_with: A prefix for the data subdirectories within the Artiat... | f0007c87f81a688b38d341c17783522e55f3e54f | 656,032 |
def events():
"""Returns test events fixture."""
return [{"id": idx} for idx in range(10)] | c11dc2bf891086fc438911a4d51cb8123fa51c9d | 656,033 |
def resources_to_layout(resources):
"""Given a `list` of resource object [a,b,c], extract the frame and join them like [[a.frame], [b.frame], [c.frame]]"""
res = []
for a in resources:
res.append([a.frame])
return res | 6496ada34999d057633ebaa13ebc21ea53b32978 | 656,034 |
def province_filter(province):
"""
去掉省份 市等信息
"""
return province.replace(u"市", '').replace(u"省", '').replace(u"自治区", '').replace(u"维吾尔自治区", '').replace(u"特别行政区",
'').replace(
u"回族自治区", '') | 617878aab19ab7e8e54483235b2e0ce10c3a391b | 656,036 |
def look_for_books(citation_elements, kbs):
"""Look for books in our kb
Create book tags by using the authors and the title to find books
in our knowledge base
"""
title = None
for el in citation_elements:
if el['type'] == 'QUOTED':
title = el
break
if title... | 4eca0d2013c29695439a7cda91a96d6cb7112a5a | 656,037 |
def _make_parameters(signature):
"""Return actual parameters (that can be passed to a call) corresponding to
signature (the formal parameters). Copes with bare `*` (see PEP 3102) e.g.
shutil.copyfile's signature is now "src, dst, *, follow_symlinks=True":
return "src, dst, *, follow_symlinks=follow_syml... | faf37f5c00b1edac35ad77b398245b727ef5ccb5 | 656,038 |
def solution(n: int = 10) -> str:
"""
Returns the last n digits of NUMBER.
>>> solution()
'8739992577'
>>> solution(8)
'39992577'
>>> solution(1)
'7'
>>> solution(-1)
Traceback (most recent call last):
...
ValueError: Invalid input
>>> solution(8.3)
Traceback ... | f7592101aea6598a480be3d3898af1979c48449f | 656,039 |
def _get_file_type(fname):
"""Return the type of a file."""
if fname.endswith('.nii.gz') or fname.endswith('.nii'):
return 'NIfTI-1'
if fname.endswith('.png'):
return 'PNG'
if fname.endswith('.jpg'):
return 'JPEG'
if fname.endswith('.mnc'):
return 'MINC'
if fname.... | f5371eb17e96353bac58632ba8cd212bbf6fa698 | 656,040 |
def locale_to_source_path(path):
"""
Return source resource path for the given locale resource path.
Source files for .po files are actually .pot.
"""
# Comment this for now as js-lingui does not provide .pot files, only .po
# Commenting these lines is enough to make it work
# if path.endswi... | 45a9a5de06754ad8327c836f43645d18764f2cb2 | 656,041 |
def failure_traceback(fail):
"""
:param fail: must be an IFailedFuture
returns a traceback instance
"""
return fail.tb | 5f67b4cdef34200bfa3b0e0b3d478935ceff6d93 | 656,043 |
def get_curvature(rocs, states, top_type, bottom_type):
"""
Table reading function for retrieving the curvature and contour length change.
"""
return rocs[int(states[int(top_type)])][int(states[int(bottom_type)])][int(top_type)][int(bottom_type)] | e20e346abb565f8c96fbce940fa2e41f215d1915 | 656,044 |
import hashlib
def get_url_data_stub(url):
""" Stub function replacing get_url_data """
# No actual web request is made, instead
# the file is opened and data returned
filename = hashlib.md5(url).hexdigest()
try:
with open(filename, 'rb') as f:
return f.read()
except OSErr... | b38e1b6939abb3010e81de80e00d647f1636b76b | 656,045 |
def forecast_variables():
"""
List of the plottable variables from the GLDAS 2.1 datasets used
"""
return [
('Air temperature', 'Tair_f_tavg'),
('Rainfall flux', 'Rainf_f_tavg'),
('Soil moisture content', 'SoilMoist_inst'),
('Total evapotranspiration', 'Evap_tavg'),
] | f10336f06d6caf4db8d6f161b0c5778729ceb08a | 656,046 |
def image_suffix(func,options):
"""
Returns the suffix for this image operations and options
Parameter func: the image operation
Precondition: func is a string
Parameter options: the image options
Precondition: options is a dictionary
"""
suffix = func
if len(options) > 0:... | c77c8374a045780ce71a2e0bb4e4ef567d16ede8 | 656,047 |
import logging
def get_bearer_token():
"""extract secret from vault, if using a vault"""
try:
with open('/var/run/secrets/kubernetes.io/serviceaccount/token', 'r') as secretFile:
return secretFile.read().replace('\n', '')
except FileNotFoundError:
logging.error('Secret not foun... | 48614d0c8d39e376b2ddc721ae1a08f1377d30cc | 656,048 |
import argparse
import os
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Stack the given HDF5 container into a new file')
parser.add_argument('input_files', help='Files to stack', nargs=argparse.REMAINDER)
def check_extension(extensions, filename):
... | 5781faad98955606b257e9eac1cf5263529853d3 | 656,050 |
def neighborhood_size(node, neighborhoods):
"""
SCAN Section 3.1 Definition 1
"""
return len(neighborhoods[node]) + 1 | 35e5cf1f8a5ee0623503873edefeb58d884481ea | 656,051 |
def get_stochastic_depth_rate(init_rate, i, n):
"""Get drop connect rate for the ith block.
Args:
init_rate: A `float` of initial drop rate.
i: An `int` of order of the current block.
n: An `int` total number of blocks.
Returns:
Drop rate of the ith block.
"""
if init_rate ... | 11e6e23393c38bd7c93059b5900c75caa399fac1 | 656,052 |
from typing import OrderedDict
def _translate_reverse_relationships(opts, reverse_relations):
"""
DRF's `_get_reverse_relationships` uses the `get_accessor_name` method of
`ForeignObjectRel` as the key for the relationship. This function replaces
those keys with the rel's `name` property. This allows ... | 56851cb19ec4410bff5d18f08b088957a04a8ae5 | 656,053 |
def display_title(book):
"""Compute the display title of a book."""
out = book["title"]
if book.get("subtitle"):
out += f": {book['subtitle']}"
if book.get("volume_number") and book.get("fascicle_number"):
out += f" (vol. {book['volume_number']['raw']}; fas. {book['fascicle_number']['ra... | 6dc1eede5283453c94f8bfd414c148971db53c21 | 656,054 |
import os
import subprocess
def unpack_run(dir_name, run_name):
"""
Given the run directory and filename, unpack it
Parameters
----------
dir_name: string
name of the directory of the cases
run_name: string
name of the archive with compressed run data
returns: (integer,... | 004c43e1e148c7feae9f99b9fbd8d89850726edf | 656,055 |
def int_to_str_v2(n: int) -> str:
"""Convert the given integer into it's string form.
Args:
n: The integer whose string form to be gotten.
Returns:
The string form of the given integer.
"""
if n == 0: return '0'
sign, n = ('-', -n) if n < 0 else ('', n)
s = []
while n... | b88b50601aa55fdbe0da8ce2063a154860a673be | 656,056 |
import inspect
import re
def strip_source_code(method, remove_nested_functions=True):
"""
Strips the source code of a method by everything that's "not important", like comments.
Args:
method (Union[callable,str]): The method to strip the source code for (or the source code directly as string).
... | 5e50c902a6c56b2c46715ebda8a7c2aea8750b1a | 656,057 |
def hadamard_complex(x_re, x_im, y_re, y_im):
"""Hadamard product for complex vectors"""
result_re = x_re * y_re - x_im * y_im
result_im = x_re * y_im + x_im * y_re
return result_re, result_im | 5aa08bf499fd4835d97d6f8fe4bfda7595c719d1 | 656,059 |
def validate_category_or_command_name(name):
"""
Validates the given category name.
Parameters
----------
name : `str`
The name of a category or command.
Returns
-------
name : `str`
The validated name.
Raises
------
TypeError
If `name` ... | 1e58247557f486024d9d929d75e1dd212f2f41b9 | 656,060 |
import argparse
def get_table_size() -> int:
"""
Parse the inputs to the program and return the table_size.
:return: Value of the command line parameter
:rtype: int
"""
parser = argparse.ArgumentParser(description="Generate a multiplication table of prime numbers")
parser.add_argument("-... | af0542a956245c108bde654b51c1f5eba6456441 | 656,061 |
def query_transform(request, **kwargs):
"""
Merges the existing query params with any new ones passed as kwargs.
Note that we cannot simply use request.GET.update() as that merges lists rather
than replacing the value entirely.
"""
updated_query_params = request.GET.copy()
for key, value ... | 49cef933a9cd01ef93b7a38de5bd7e499edddecf | 656,062 |
def check_length(pwd, min_length=8):
"""
判断密码长度是否合法
:param pwd:
:param min_length:
:return:
"""
if isinstance(pwd, (str, bytes, bytearray)):
return len(pwd) >= min_length
else:
return 0 | bb8b2d50d7cbe6902ddadc2f275e0ceac50cf656 | 656,063 |
import argparse
def getArgs():
"""This method reads the arguments passed during using the command line interface.
Returns:
Dictionary of arguments passed
"""
parser = argparse.ArgumentParser(
description="Run Crawl Script to parse Hackathon.com website"
)
parser.add_argument(... | 4af8f5dd5df5bba83faecc5b03b1f6df301a7261 | 656,064 |
import pandas.api.types as ptypes
def is_datetime_series(obj):
"""
Check if an object is a Datetime64 series
"""
return ptypes.is_datetime64_any_dtype(obj) | 3d15c8bb212dd668c241a44d8fc77a8989bd6121 | 656,065 |
def get_relative_path_with_parameters(request):
"""
@param request:
@type request:
@return:
@rtype:
"""
path = request.path
param = list()
if 'q' in request.GET and request.GET['q']:
param.append('q=' + request.GET['q'])
if 'page' in request.GET and request.GET['page']... | 16abedcac3c5f26539f6a402880981912c7effeb | 656,066 |
def get_all_properties(data, **kws):
"""Get all property definitions from PV data.
Parameters
----------
data : list(dict)
List of dict, each dict element is of the format:
``{'name': PV name (str), 'owner': str, 'properties': PV properties (list[dict]), 'tags': PV tags (list[dict])}``.... | ca65c338681797b5bcb4b411c666d5ec4ea495e4 | 656,067 |
import os
import shutil
def generateFolder(folderName):
"""
Generate folder to place files and return full path
Parameters
----------
folderName : str
Folder name to be created
Returns
-------
[str]
Full path of the new created folder
"""
newfolderName = os.... | b4bcd2dd32528418af49482e694ac24e68ce43cb | 656,068 |
def most_common(items):
"""Wanted functionality from Counters (new in Python 2.7)
"""
counts = {}
for i in items:
counts.setdefault(i, 0)
counts[i] += 1
return sorted(counts.items(), key=lambda x: x[1])[-1] | 5f618fadd12c5d24ccabf8198c3deba9157cd65b | 656,069 |
import uuid
def uid():
""" return a unique id for a pane """
return 'pane_{}'.format(uuid.uuid4()) | 77512380bd7e168cf6d3945ba6ae2560af17c3cc | 656,070 |
def _find_node_by_name(nodes, name):
"""
Loop through a list of nodes and return the one which has the matching display name
:param nodes: List of nodes
:param name: Target name
:return: Matching node, None otherwise
"""
# Nodes always have unique names, thus there's no need for duplicate ch... | 1ac64ff148e771e416052a16f304ee5e496c4d61 | 656,071 |
import decimal
def to_precision(x, p):
"""
returns a string representation of x formatted with a precision of p
Based on the webkit javascript implementation taken from here:
https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp
"""
decimal.getcontext().p... | 50f39780cbbaa2cc8d6afb19e39fb0e9e62d68ce | 656,072 |
def mapfmt(fmt: bytes, size: int) -> bytes:
"""
Changes the type of of a format string from 32-bit to 64-bit.
WARNING: doesn't handle strings.
Example
-------
>>> mapfmt(b'2i 6f')
b'2q 6d'
"""
if size == 4:
return fmt
return fmt.replace(b'i', b'q').replace(b'f', b'd') | 6e872e916700bf185e2342a607908670590e3fb5 | 656,073 |
def get_library_interface_type_name(config):
"""Get the LibraryInterface type name, based on the service_class_prefix config setting."""
service_class_prefix = config["service_class_prefix"]
return f"{service_class_prefix}LibraryInterface" | 8097e9c954570677473ac73997d7ce00aa890268 | 656,074 |
import time
def parse_sfx_now(input_time: str) -> int:
"""Parse Signalfx Now into SignalFx API epoch milliseconds
:raise: ValueError
"""
if input_time == "Now":
return int(time.time()) * 1000
raise ValueError(f"{input_time} is not Now") | bd56c6ad75b9b0823f77d690344f87d89cb2c3b2 | 656,075 |
import numpy
def _get_fixed_vel_model(dt=None):
"""get linear dynamical system matrices A and C
dt is the time-step in seconds
"""
# distance units are in m
# time units are in sec
# thus, velocity is (m/sec)
ss = 6 # length of state vector (state size)
os = 3 # length of observati... | 09bf2bb9565be0ab1ed959ca3993ad880328ef94 | 656,076 |
def readlines(path):
"""Read a file into a list of lines."""
with open(path) as f:
return f.readlines() | 9e9c36fcbdc89fbf796546d26e664cad30494cb0 | 656,077 |
def split_number(number):
"""
Splits the given number in to thousand grouped list
ex: 12,345,678 => ['12','345','678']
:param number: the number to be splitted
:return: a list of splitted number (thousand grouped numbers)
NOTE: The numbers in the list are converted into strings
"""
if '... | 2238d62e792b028984bf82584ba47d89885e17b0 | 656,079 |
def derivative_feature_vectors(_vocabulary):
"""Set up the fixed length feature vector.
:param _vocabulary:
:return: feature vector with artificial cardinality
"""
feature_vector_1_tmp = {}
feature_vector_2_tmp = {}
for feature in _vocabulary[0:min(len(_vocabulary), 125)]:
feature_... | 29405fea660afd0947c8443224d9839f215f48bd | 656,080 |
def Vcell_Calc(Enernst, Loss):
"""
Calculate cell voltage.
:param Enernst: Enernst [V}
:type Enernst : float
:param Loss: loss [V]
:type Loss : float
:return: cell voltage [V] as float
"""
try:
result = Enernst - Loss
return result
except TypeError:
pr... | d400459481333d583459c6cefebc1e7446bee66e | 656,081 |
def remove_bots(members):
"""Removes bots from a list of members"""
bots = []
for member in members:
if member.bot:
bots.append(member)
for bot in bots:
members.remove(bot)
return members | 16721756a12ebe8478117eb2ea387e99bc68c9a3 | 656,082 |
def get_available_operations():
""" Function returns available operations for primary and secondary nodes """
primary_operations = ['lagged', 'smoothing', 'gaussian_filter', 'ar']
secondary_operations = ['lagged', 'ridge', 'lasso', 'knnreg', 'linear',
'scaling', 'ransac_lin_reg',... | bb33a9c26d90fc09734b8b52edf1fdc4678db58a | 656,083 |
def add_csv(filename: str) -> str:
"""Add '.csv' extension to each
ticker name.
"""
return filename + '.csv' | 3980e1f6f6d69096c3a83fb13ecb30f1ddb264d8 | 656,084 |
def to_flags(value):
"""Return a (flags, ednsflags) tuple which encodes the rcode.
*value*, an ``int``, the rcode.
Raises ``ValueError`` if rcode is < 0 or > 4095.
Returns an ``(int, int)`` tuple.
"""
if value < 0 or value > 4095:
raise ValueError('rcode must be >= 0 and <= 4095')
... | a1fda96e1f5cb40c441c85929b6787f994308ca3 | 656,085 |
from typing import Dict
from pathlib import Path
import tempfile
import shutil
import os
def create_test_archive(
path_contents: Dict[str, str], extension: str, format: str
) -> Path:
"""
Create an archive with the specified characteristics.
Caller is responsible for deleting.
"""
with tempfi... | b64e9b2e1b637707ce8a2a59c00ff0e65fb624d4 | 656,086 |
import locale
def get_month_name(month):
"""
Get the month's name in the currently activated locale.
:param month:
:return:
"""
locale_key = "MON_%d" % month
option = getattr(locale, locale_key)
month_name = locale.nl_langinfo(option)
return month_name | d4cad991d21c0c90ddd8287f6a8dc2a7e6bba7dc | 656,087 |
import random
def t03_SingleClientManyPuts(C, pks, crypto, server):
"""Uploads many files for the same user and checks they all uplad
correctly."""
alice = C("alice")
kv = {}
for r in range(100):
uuid1 = "%08x" % random.randint(0, 100)
uuid2 = "%08x" % random.randint(0, 100000)
... | d794aef4b031f2301430f95787efc2ed3eb5f18e | 656,088 |
def get_domains(options):
"""
Fetches all domains currently requested
:param options:
:return:
"""
domains = [options['common_name']]
if options.get('extensions'):
for name in options['extensions']['sub_alt_names']['names']:
domains.append(name.value)
return domains | 480d7a6aea3d320b9d5d02d41c3044fad985401f | 656,089 |
def parse_path(path):
"""
http://www.w3.org/TR/2014/WD-html-json-forms-20140529/#dfn-steps-to-parse-a-json-encoding-path
"""
original = path
failure = [(original, {'last': True, 'type': object})]
steps = []
try:
first_key = path[:path.index("[")]
if not first_key:
... | 788292724bc81fbaa953c59e9821469d851db62d | 656,091 |
import pickle
def read_as_pickle(path: str):
"""Read in pickle file."""
with open(f'{path}.pickle', 'rb') as handle:
return pickle.load(handle) | 70842c647a1fd68ac5b1a89765fe9e31053570bf | 656,092 |
def is_callID_active(callID):
"""Check if reactor.callLater() from callID is active."""
if callID is None:
return False
elif ((callID.called == 0) and (callID.cancelled == 0)):
return True
else:
return False | f54a05fde58db53319bc34cca79629011e2f2ffd | 656,094 |
def build_property_spec(client_factory, type='VirtualMachine',
properties_to_collect=None,
all_properties=False):
"""Builds the Property Spec.
:param client_factory: Factory to get API input specs
:param type: Type of the managed object reference property
... | 8369b03fa22cab90f5bf22dd4cacc824ec352d5a | 656,096 |
import configparser
import tempfile
import os
def save_style_to_tempfile(style):
"""Build yapf style config file."""
cfg = configparser.RawConfigParser()
cfg.add_section('style')
for key, value in style.items():
cfg.set('style', key, value)
# dump it to temporary file
fobj, fname = te... | 3bd931629b8430c5ed357d75bb4ff4e9cad18a88 | 656,097 |
def _clean_message(message):
"""
Cleans a message by removing the 0 bytes from the input message.
:param message: The message to be cleaned.
:return: str: The cleaned message.
"""
return message.split('\x00')[0] | 264d40553d8c769916c2882126195ea69f053764 | 656,098 |
import yaml
def get_time_limit(cwl_content: bytes) -> int:
"""Takes a CWL file contents and extracts cwl1.1-dev1 time limit.
Supports only two of three possible ways of writing this. Returns
0 if no value was specified, in which case the default should be
used.
Args:
cwl_content: The con... | 67146dfb38d35f3f077a44deba1e57304692d09a | 656,099 |
def find(string, char):
"""
Looks for a character in a sctring and returns its index.
"""
# Compared to string.find(), it returns ALL the indexes, not only the first one.
return [index for index, letter in enumerate(string) if letter == char] | 1832ac5016587e81000604cd7226067d1b400167 | 656,100 |
import struct
def get_dump_pos(log_file, log_pos, server_id):
"""
https://dev.mysql.com/doc/internals/en/com-binlog-dump.html
1 [12] COM_BINLOG_DUMP
4 binlog-pos
2 flags
4 server-id
string[EOF] binlog-filename
"""
COM_BINLOG_DU... | 032ddefd5f59427f5fd7ade2e0a094a7f1b67a64 | 656,101 |
def sort_idx(seq):
"""
:param seq: variable
:return:
"""
return sorted(range(seq.size(0)), key=lambda x: seq[x]) | 497ce16d18c72b93aee2790993761e5bc999c34b | 656,102 |
def _check_no_collapsed_axes(fig):
"""
Check that no axes have collapsed to zero size.
"""
for panel in fig.subfigs:
ok = _check_no_collapsed_axes(panel)
if not ok:
return False
for ax in fig.axes:
if hasattr(ax, 'get_subplotspec'):
gs = ax.get_subplo... | 2ecbc6a3e17f73ab4c09f606c4638ad7748ee59a | 656,103 |
import torch
def init_architectures():
"""
Assuming 7 nodes
:return:
"""
architecture_list = []
# 1
# line graph
# Conv5, Id, Id, Id, Id
node_type = torch.LongTensor([1, 1, 0, 0, 0, 0, 0, 0, 0, 0])
outbounds = [torch.LongTensor([1, 0, 0, 0, 0, 0]),
torch.LongTensor([ 1, 0, 0, 0, 0]),
... | 724bc8077fc4765eeea1495fc2b7a8f0921d8f57 | 656,104 |
import warnings
def filtfilt(signal, synapse, dt, axis=0, x0=None, copy=True):
"""Zero-phase filtering of ``signal`` using the ``synapse`` filter.
.. note:: Deprecated in Nengo 2.1.0.
Use `.Synapse.filtfilt` method instead.
"""
warnings.warn("Use ``synapse.filtfilt`` instead", Deprecati... | 389184242f68143e1876b8aa8870873ae601162f | 656,105 |
import re
def split_order_info(keydict):
"""
Designed to take as input the dictionary created by dict_from_file and for
nircam, split out and accumulate the keys for each beam/order.
The keys must have the beam in their string, the spurious beam designation
is removed from the returned dictionary.... | 4884885c23f67d2c91cb684bb126e6ce1993d12e | 656,106 |
def maxProduct(nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return False
if len(nums) == 1:
return nums[0]
mx = nums[0]
max_so_far = nums[0]
for number in range(len(nums)):
max_so_far = nums[number]
for second in range(number, le... | e2a5f0de5165a9a9b4ff993287136a8d3f0cf378 | 656,108 |
from typing import Dict
from typing import AnyStr
import json
def _decode_json_dict(json_dict: Dict[bytes, AnyStr]) -> dict:
"""
Decode a dict coming from hgetall/hmget, which is encoded with bytes as keys
and bytes or str as values, containing JSON values.
"""
return {k.decode(): json.loads(v) fo... | a0ce492e4cd27829cc1a1508954f7e0d76130338 | 656,110 |
import logging
def get_instance_group_manager_to_delete(key):
"""Returns the URL of the instance group manager to delete.
Args:
key: ndb.Key for a models.InstanceGroupManager entity.
Returns:
The URL of the instance group manager to delete, or None if there isn't one.
"""
instance_group_manager = ... | 6122c4d78cb6ab66200e6ffe7d4d709262dd1e1f | 656,111 |
def _unpack_tensors(reduced, tensor_packer=None):
"""Unpack tensors if they are packed before all-reduce."""
if tensor_packer:
return tensor_packer.unpack(reduced)
return reduced | b9f61b42873002e2b25deb04f1990afade583da4 | 656,112 |
def get_rnd_form():
"""
Assemble form for get_validate_image
:return: form in dict
"""
post_data_dict = dict()
post_data_dict['source'] = 'wsyyt'
return post_data_dict | c88fc80a1846d1101179d03eab945f3f02fbf8f0 | 656,113 |
import os
def shrink_path(filename):
""" Try to shrink a filename for display (remove the leading path if the
file is relative to the current working directory). """
cwd = os.getcwd()
prefix = os.path.commonprefix([cwd, filename])
if prefix:
filename = filename[len(prefix)+1:]
retu... | 9826a8944d743f0ac7a37e5643275da5196e446c | 656,114 |
def instance_to_class(instance, parent):
"""
Return the name of the class for an instance of inheritance type parent
"""
return parent + "_" + instance | 11c578ce782a7289aaa4fcb482ceb60699c65632 | 656,115 |
import errno
def get_exception_errno(e):
"""A lot of methods on Python socket objects raise socket.error, but that
exception is documented as having two completely different forms of
arguments: either a string or a (errno, string) tuple. We only want the
errno."""
if isinstance(e.args, tuple):
... | 78925dbac859a5b9d890f9fa4de926e1a4f91e48 | 656,116 |
def part1():
"""This view will be at the path ``/part1``"""
return 'part1' | a3bd31f78ffc616ba8ebd74cc189532d8bed334c | 656,117 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.