content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def create_search_specs(username, sort, order, text, involvement, query_opts):
"""Create GitHub issues search specification (params dict)"""
query_opts[involvement] = username
query = '+'.join(['{}:{}'.format(k, v)
for k, v in query_opts.items()
if v is not None])... | 60f9e4dfd7bcc4caf60a457a20777912260eef20 | 689,916 |
import re
def Extract(soup):
"""
Extract speaker name, mp3 and xml location online for each speech from an xml containing
information on all speeches given in a session (created by scrape_althingi_info.php)
"""
meta = []
for speech in soup.find_all('ræða'):
mp3="http://www.althingi.is/... | d7604be1bfa30039809656d1e1cac3235cad7afa | 689,917 |
def get_or_create(session, model, **kwargs):
"""
Get or create a model instance while preserving integrity.
"""
record = session.query(model).filter_by(**kwargs).first()
if record is not None:
return record, False
else:
with session.begin_nested():
instance = model(*... | bd62c01005f30f132fb6edfae1cdbc40ac7bd9de | 689,918 |
def byte_to_string(byte):
"""
Converts an array of integer containing bytes into the equivalent string version
:param byte: The array to process
:return: The calculated string
"""
hex_string = "".join("%02x" % b for b in byte)
return hex_string | e4a38e1cf78d2db8417935d833b7575d9850c639 | 689,919 |
def find(linked_list, item):
"""Excercise 1.3.21 Find function to find if item exist in linked list.
The find function takes linked list and item and returns true if exist
false otherwise
The linked list implementation already has a find method which can
be used to utilize this.
"""
if lin... | 70c924b5184a44384a0157734f0eb2d2b6b56db4 | 689,920 |
import re
def get_indent(str_):
"""
Find length of initial whitespace chars in `str_`
"""
# type: (str) -> int
match = re.search(r'[^\s]|$', str_)
if match:
return match.start()
else:
return 0 | a9de80043341b062326bfa58322c37100c91aa06 | 689,921 |
def get_acph2_m2_min(m1: float) -> float:
"""
Get minimum value of m2 (second moment) for ACPH(2) fitting.
According to [1], M2 has only lower bound since pow(CV, 2) should be
greater or equal to 0.5.
If m1 < 0, then `ValueError` is raised.
Parameters
----------
m1 : float
Retur... | e2f0982755fb09a51a1db352c92b21bfd2058e03 | 689,922 |
def clamp(value, lower=None, upper=None):
""" Returns value no lower than lower and no greater than upper.
Use None to clamp in one direction only. """
if lower is not None:
value = max(value, lower)
if upper is not None:
value = min(value, upper)
return value | c49e4b82296ea511e6eabe1daf85f769e8202130 | 689,923 |
def _finish_plot(ax, names, legend_loc=None, no_info_message="No Information"):
"""show a message in the axes if there is no data (names is empty)
optionally add a legend
return Fase if names is empty, True otherwise"""
if( not names ):
ax.text(0.5,0.5, no_info_message,
fon... | 4aaf0c0d197d12086d6dae6f69bb6733fc674751 | 689,924 |
def _get_new_block_mem_instance(op_param, mem_map, block_out):
""" Gets the instance of the memory in the new block that is
associated with a memory in a old block.
"""
memid, old_mem = op_param
if old_mem not in mem_map:
new_mem = old_mem._make_copy(block_out)
new_mem.id = old_mem.i... | 1821c62a8694b04ff05f8c7f75d41d7c443e3018 | 689,926 |
def get_name(ent, attr_dict, dataset):
"""
retrieve name from entity (D_W / D_Y / others)
"""
if ent not in attr_dict:
return ent.split('/')[-1].replace('_', ' ').lower()
if 'D_Y' in dataset:
name_attribute_list = ['skos:prefLabel',
'http://dbpedia.org... | c557f3d3b0d10336e5239569e28138be0e4874d9 | 689,927 |
def retry_requests(client, client2):
"""
Retries request to get both status codes with value 429 in fixed window time
:param client: first api client
:param client2: second api client
:return: status codes for both request in tuple
"""
code_1 = client.get("/get").status_code
code_2 = cli... | ef886aff9cb5c366a67034ab56e4793a3e0c0465 | 689,928 |
import json
import fnmatch
from pathlib import Path
def cmpmanifests(manifest_path_1, manifest_path_2, patterns=None, ignore=None):
"""Bit-accuracy test between two manifests.
Their format is {filepath: {md5, size_st}}"""
with manifest_path_1.open() as f:
manifest_1 = json.load(f)
with manifest_path_2.ope... | 7cb77a4ed39ce04064e3bc832ef249a490d16500 | 689,929 |
import random
def rand_uniform(a, b):
"""
Returns a sample from a uniform [a, b] distribution.
"""
return random.random() * (b - a) + a | 9d61bd4577f9a93832c0002f014309250279b84f | 689,930 |
def update_to_merge_list(to_merge, subexon_1, subexon_2):
"""
Add subexon_1 and subexon_2 to the to_merge list.
>>> update_to_merge_list([], 1, 2)
[{1, 2}]
>>> update_to_merge_list([{1, 2}], 2, 3)
[{1, 2, 3}]
>>> update_to_merge_list([{1, 2}], 8, 9)
[{1, 2}, {8, 9}]
"""
group = ... | 1b14fdcdc5271156790bc0b16fedd8d6f10a79b9 | 689,931 |
import os
import fnmatch
def getFiles(directory,extension):
"""
Gets a list of bngl files that could be correctly translated in a given 'directory'
Keyword arguments:
directory -- The directory we will recurseviley get files from
extension -- A file extension filter
"""
matches = []
f... | 8ea8caec0cefe65c2f6e4e2ccac2616b05785d68 | 689,932 |
import torch
def compute_rigid_transform(x, y, match, match_score):
"""
Compute the rigid body transform from x to y based on
match and match_scores.
Args:
x (torch.Tensor): size = (B, M, 3)
y (torch.Tensor): size = (B, N, 3)
match (torch.Tensor): size = (B, M), value -1 i... | b13cb7d361f0d0ec59c3802b67f0adcae51cb1f2 | 689,933 |
import pickle
def load_raw_df():
"""Return df of raw WTA scraped dataset
"""
with open("data/raw_wta_df.pkl",'rb') as picklefile:
return pickle.load(picklefile) | 586afdea80dde4fd1c79528ee8691ea72b1c9037 | 689,934 |
from typing import Iterator
from typing import ByteString
from typing import Any
from typing import Union
def hash_a_byte_str_iterator(
bytes_iterator: Iterator[ByteString], hasher: Any, as_hex_str: bool = False
) -> Union[ByteString, str]:
"""
Get the hash digest of a binary string iterator.
https:/... | d1e9814d30e78b4c89484a2c11296c233a3c6d92 | 689,935 |
import inspect
def get_var_name(var):
"""Get the name of a variable.
"""
for fi in reversed(inspect.stack()):
names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var]
if len(names) > 0:
return names[0] | 8df506ebd82e0fff5fb5b70047f9c62ba50f0938 | 689,936 |
def create_sequential_uppaal_xml(synchronizations):
"""
Create the Uppaal model based on the synchronization input.
Args:
synchronizations -- list of synchronization tuples (sync name, {arguments}) in temporal order, for example: [("robot_0_goto", {'mode': 2, 'waypoint': 3}), ...]
"""
xml = []
... | 16ec18f38a1715804e4e0cfef77af8d38ceb1fb5 | 689,937 |
def get_db_url_mysql(config):
"""
Format the configuration parameters to build the connection string
"""
if 'DB_URL_TESTING' in config:
return config['DB_URL_TESTING']
return 'mysql+mysqlconnector://{}:{}@{}/{}' \
.format(config['DB_USER'],
config['DB_PASS'],
... | 36c2a1c5a63a8f863dd40a0572b6cc04205a7d16 | 689,938 |
def recursive_config_join(config1: dict, config2: dict) -> dict:
"""Recursively join 2 config objects, where config1 values override config2 values"""
for key, value in config2.items():
if key not in config1:
config1[key] = value
elif isinstance(config1[key], dict) and isinstance(val... | 64dc0bbcebcf20ba913828d05e2004f461909b8f | 689,939 |
def is_project(project):
"""
Checks if a project meets the minimum step standards
"""
for step in project.steps:
if step.type in ("make","package"): # at least one make or package step
return True
return False | 610648d7d8645008d5b49d4a20b29c9692021b86 | 689,940 |
def iterativeFactorial(num):
"""assumes num is a positive int
returns an int, num! (the factorial of n)
"""
factorial = 1
while num > 0:
factorial = factorial*num
num -= 1
return factorial | 415234f726443a385b4d65e68fb36e7c52e9b042 | 689,941 |
def remove_code_parameter_from_uri(url):
"""
This removes the "code" parameter added by the first ORCID call if it is there,
and trims off the trailing '/?' if it is there.
"""
return url.split("code")[0].strip("&").strip("/?") | da9dc972ead23886b7f20d6d04ff4afa0a2dce99 | 689,942 |
import argparse
def create_argument_parser() -> argparse.ArgumentParser:
"""Return the command-line parser."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("package")
parser.add_argument("--cache", action="store_true", default=False)
parser.add_argument("--token")
... | 0910ff37ee3928df34cf2a0468d51dd9ff701405 | 689,943 |
def MakeJavascriptObject(attributes):
"""Generates a javascript object from the provided list of attributes.
Args:
attributes: A list of attribute strings.
Returns:
javascript code for the object.
"""
return '{ ' + ', '.join(attributes) + ' }' | a7da207989db5ac0d4e752f78cd7577bf739b660 | 689,944 |
import json
def read_json(json_path):
"""
读取JSON
"""
json_path = json_path
try:
with open(json_path, 'r', encoding='utf-8') as load_f:
res = json.load(load_f)
except Exception as e:
print(e)
res = {}
return res | 14eebf0e6a3f10a68e0c64e36d35b039bae8d4d6 | 689,946 |
from pathlib import Path
from typing import List
from typing import Dict
import time
def get_dir_data(path: Path) -> List[Dict[str, str]]:
"""Returns list of files and folders in given directory sorted by type and by name.
Parameters
----------
path : Path
Path to directory which will be expl... | e1f37b8e968c1b04668c830c0385a10d9513fc2a | 689,947 |
def decide_compiler(config):
"""确定使用的编译器
如果设置中使用的是clang,则使用设置中的编译器
否则使用默认的clang++
"""
if 'clang'in config:
return config
else:
return 'clang++' | 19510e4c646c1c392d6a66f2638cbc1fa8242735 | 689,949 |
import copy
def fill_data_by_name(project, json_data):
"""
Fills json information by name.
Used when filling in demonstration data and not user selection.
"""
json_data = copy.deepcopy(json_data)
# A mapping of data by name
for field, item in json_data.items():
# If the field is ... | 6850e689535c47bc8209408517118b789e857aa0 | 689,950 |
import subprocess
def _command(command):
"""
Return result of a subprocess call.
Doesn't set timeout for the call, so the process can hang.
Potentially for a very long time.
:return: stdout and stderr from Popen.communicate()
:rtype: tuple
"""
process = subprocess.Popen(
comman... | eb2645b567bcd8837b0423ac084d667cf3c1be33 | 689,951 |
def map_to_45(x):
"""
(y-y1)/(x-x1) = (y2-y1)/(x2-x1) ---> x1 = 1, x2 = 5, y1 = 1, y2 = 4.5
output = output_start + ((output_end - output_start) / (input_end - input_start)) * (input - input_start)
"""
input_start = 1
input_end = 5
output_start = 1
output_end = 4.5
if x >= 5:
... | 0b3c62dfb99d24ee8a85e9ff7c621676db530e57 | 689,952 |
import os
import sys
def get_script_directory():
"""
This function returns the directory of the script in scrip mode
In interactive mode returns interpreter name.
"""
path = os.path.realpath(sys.argv[0])
if os.path.isdir(path):
return path
else:
return os.path.dirname(path) | 7b039d2ef2a0854dd451ad2458b6c7e1c36b5007 | 689,953 |
def _sumLists(a, b):
"""
Algorithm to check validity of NBI and NIF.
Receives string with a umber to validate.
"""
val = 0
for i in map(lambda a, b: a * b, a, b):
val += i
return val | 590d584b74176e9744ec369537cb38fafffc8d17 | 689,954 |
import os
def separator(path):
"""Return the local path separator (always / in the contents manager)"""
if os.path.sep == "\\" and "\\" in path:
return "\\"
return "/" | 58a6903a9cb0d4e2c708f354c622bca4e55cd4cb | 689,955 |
def degtimemap(reshist):
""" Makes a heatmap dictionary of degraded time for functions given a result history"""
len_time = len(reshist['time'])
degtimemap={}
for fxnname in reshist['functions'].keys():
degtimemap[fxnname]=1.0-sum(reshist['functions'][fxnname]['status'])/len_time
for flownam... | a0be63c802c79e61d6f1d35ec31e725c38713c74 | 689,956 |
import struct
def read_unsigned_var_int(file_obj):
"""Read a value using the unsigned, variable int encoding."""
result = 0
shift = 0
while True:
byte = struct.unpack(b"<B", file_obj.read(1))[0]
result |= ((byte & 0x7F) << shift)
if (byte & 0x80) == 0:
break
... | a69ccd69907803109a98672bac4f26a738fe00aa | 689,957 |
def phrase(term: str) -> str:
"""
Format words to query results containing the desired phrase.
:param term: A phrase that appears in that exact form. (e.q. phrase "Chicago Bulls" vs. words "Chicago" "Bulls")
:return: String in the format google understands
"""
return '"{}"'.format(term) | 8a327ca9dc9b223e4ba9adbba8d7f4ed85d7db68 | 689,958 |
def mskWshape(W, cri):
"""Get internal shape for a data fidelity term mask array.
Get appropriate internal shape (see
:class:`CSC_ConvRepIndexing` and :class:`CDU_ConvRepIndexing`) for
data fidelity term mask array `W`. The external shape of `W`
depends on the external shape of input data array `S`... | 125f3d7804a71dc65ac9127fdd1e79e11d161928 | 689,959 |
import os
def searchForFileAtPath(deepestPath, fileName):
"""Search for file at path. Used mainly to find config file at highest level (shortest path)
:param str deepestPath: path to start search at
:param str fileName: file name to be searched for
:return: tupple (found, fullFileName)
:rtype: t... | 4cb63b995a5bc909922b600c65414d4fe23e5744 | 689,961 |
def tet_coord(p1, p2, p3, p4): # pragma: no cover
"""doesn't compute the elemental for a tet element"""
## R vector joins midpoints of edges G1-G2 and G3-G4.
p12 = (p1 + p2) / 2.
p34 = (p3 + p4) / 2.
r = p34 - p12
## S vector joins midpoints of edges G1-G3 and G2-G4.
p13 = (p1 + p3) / 2.
... | 1d6ffd136c8edf65d72b09f519376a2065747f32 | 689,962 |
def convert_to_numeric(num):
"""
Converte strings que representam valores monetários em Reais (R$) para
o padrão americano.
"""
num = num.strip()
if num != "":
num = num.replace(',', '.')
count_dot = num.count('.')
if count_dot >= 2:
while count_dot >= 2:
... | 170c2dd36998e03f7e1763020d26d49a2aea6aa9 | 689,963 |
from os import getlogin
import subprocess as sp
def scancel_all_matching_jobs(name=None):
""" Cancel all of the user's jobs.
Keyword arguments:
name (str): optional name to pass to scancel
Returns:
str: output from scancel.
"""
user = getlogin()
if name is None:
retu... | 31a485d76727d190e1f1d62b76c5facd4dbb5704 | 689,964 |
def clear_tier_dropdown(_):
"""
whenever a new cluster is in focus reset
the tier dropdown to empty again
Parameters
----------
_ : str
reactive trigger for the process
Returns
-------
str
empty string
"""
return '' | 07fd797d646e00b3712764bddf414b946c0b8365 | 689,967 |
import os
def findCurrentRunDirs(dirPrefix = ""):
""" Finds all of the dirs in the specified directory dir with "Run" in the name.
Args:
dirPrefix (str): Path to where all of the run directories are stored. Default: current working directory.
Returns:
list: List of runs.
"""
if di... | 3e4d62fefb3bff18b4603a20fd377e5e5b0db881 | 689,968 |
import json
def format_report(jsn):
""" Given a JSON report, return a nicely formatted (i.e. with indentation) string.
This should handle invalid JSON (as the JSON comes from the browser/user).
We trust that Python's json library is secure, but if the JSON is invalid then we still
want to ... | 811c1d0a490ff48463abd40800330dafeffd9fcd | 689,969 |
import json
def readfile(filename):
""" Read JSON from file and return dict """
try:
with open(filename, 'r') as f:
return json.load(f)
except IOError:
print('Error while reading from file') | 00fbfe4b302c1ee94000dfae100b8ce1d5a6acd2 | 689,970 |
def signed_leb128_encode(value: int) -> bytes:
"""Encode the given number as signed leb128
.. doctest::
>>> from ppci.utils.leb128 import signed_leb128_encode
>>> signed_leb128_encode(-1337)
b'\xc7u'
"""
data = []
while True:
byte = value & 0x7F
value >>= ... | 155eb5e6b9507dacfb7ca0381512f703819b8f15 | 689,971 |
def output(message):
""" Output result for IsValid
:param message: If message is not empty, object is not valid
:type message: str
"""
result = {'valid': 'no', 'message': ''}
if message != '':
result['message'] = message
return result
result['valid'] = 'yes'
return resul... | e851c78af946a931d465f9d915bdf56a7172ebef | 689,972 |
import hashlib
def generage_sha1(text: str) -> str:
"""Generate a sha1 hash string
Args:
text (str): Text to generate hash
Returns:
str: sha1 hash
"""
hash_object = hashlib.sha1(text.encode('utf-8'))
hash_str = hash_object.hexdigest()
return hash_str | 3df62f7607db571b45e82d18e756861c84699513 | 689,973 |
def flatten_list(nested_list, list_types=(list, tuple), return_type=list):
"""Flatten `nested_list`.
All the nested lists in `nested_list` will be flatten, and the elements
in all these lists will be gathered together into one new list.
Parameters
----------
nested_list : list | tuple
... | d5198fd51b9dedb0dcdf4c9fdb39f7b10288b898 | 689,975 |
def insertionSort02(nums):
"""插入排序法"""
for i in range(len(nums)):
for j in range(i, 0, -1):
if nums[j] < nums[j - 1]:
nums[j - 1], nums[j] = nums[j], nums[j - 1]
return nums | d69a704fe7524c53b450bbe6a6308343f99aa04b | 689,976 |
import json
def jsonify(obj):
"""
Takes any object and returns the json representation of the object.
"""
return json.dumps(obj, default=lambda o: getattr(o, '__dict__', o)) | 515f8a691616dafd1caafa505d080cc7bdfc92a8 | 689,977 |
def encrypt(msg, a, b, k):
""" encrypts message according to the formula l' = a * l + b mod k """
encrypted_message = ""
for letter in msg:
if letter == " ":
encrypted_message += " "
else:
encrypted_letter_index = (a * (ord(letter) - ord('a')) + b) % k
enc... | 73e1610162286704b696cc1a3fc4fd1e21f04e19 | 689,978 |
from typing import Union
import pathlib
import sys
import hashlib
def hash_path(path: Union[str, pathlib.Path]) -> str:
"""Hash the path with SHA1.
.. important::
This is not a security function, it's just to avoid name collisions in.
Args:
path: A path to hash.
Returns:
The... | fb5b36cb0cbf363575f57337bf2ec0a09e39f6b1 | 689,979 |
def decimal_to_base(n, base):
"""Convert decimal number to any base (2-16)"""
chars = "0123456789ABCDEF"
stack = []
is_negative = False
if n < 0:
n = abs(n)
is_negative = True
while n > 0:
remainder = n % base
stack.append(remainder)
n = n // base
... | 5d94af3d37eaa3d18e3e6f56e0c278668ce118e1 | 689,980 |
def split_output(cmd_output):
"""Function splits the output based on the presence of newline characters"""
# Windows
if '\r\n' in cmd_output:
return cmd_output.strip('\r\n').split('\r\n')
# Mac
elif '\r' in cmd_output:
return cmd_output.strip('\r').split('\r')
# Unix
elif ... | 174ccb65aee8e9225672f2d0d84661624c77c875 | 689,981 |
import argparse
def configure_argument_parser():
""" Configures options for our argument parser,
returns parsed arguments
"""
default_profile = 'default'
default_region = 'us-east-1'
parser = argparse.ArgumentParser()
# Help strings from ACM.Client Boto 3 docs
parser.add_argument... | a225750d10e38c553a577edbc062c8e1fce3aeb2 | 689,982 |
import os
def get_checkpoint_tracker_filename(checkpoints_path):
"""Tracker file rescords the latest chckpoint during
training to restart from."""
return os.path.join(checkpoints_path, 'latest_checkpointed_iteration.txt') | dc659675c3c34ff8ba3b5e1dfd9ae507469ae4bd | 689,983 |
import requests
def lxd_remote_get():
"""
Get function for get LXD API to remote
:return: response:
"""
r = requests.get('https://uk.images.linuxcontainers.org' + '/1.0/images/aliases?recursion=1', timeout=10)
#print(r.text)
return r | cb9b8a70595e83f165af73224a04b6f4caf8016d | 689,984 |
def _get_nodes_depth_first(all_nodes):
"""
Return all_nodes, placing parent nodes earlier in the list than their children.
"""
all_nodes = set(all_nodes)
node_parents = {node: node.getParent() for node in all_nodes}
result = []
def add_starting_at(node):
# Make sure the node's paren... | e1647ab7c2ff6da5336040be4727fded28bb18b3 | 689,985 |
def get_comment_init(request, obj):
"""
Возвращает словарь для инициализации начальных значений модели комментария
:param request: запрос
:param obj: объект к которому добавляется комментарий
:return:
"""
if request.user.is_authenticated():
init = {'obj': obj, 'username': request.use... | bc3319a9780b4b7c427c4ee1ef7d90663c7585d7 | 689,986 |
def _parse_bool(value):
"""Parse a boolean string "True" or "False".
Example::
>>> _parse_bool("True")
True
>>> _parse_bool("False")
False
>>> _parse_bool("glorp")
Traceback (most recent call last):
ValueError: Expected 'True' or 'False' but got 'glorp'
... | 80a424834b4b2abf338cdc4e4ee6a9028cb460bf | 689,987 |
def GetTweepyConfig(config_filename):
"""Returns dictionary with auth details for building a Tweepy API object."""
with open(config_filename, "r") as infile:
config = {}
for line in infile:
spline = line.split(" = ")
config[spline[0]] = spline[1].strip()
return config | 8078ce1c3fcc11d3da6220704d98a45c285972b5 | 689,988 |
import struct
def one_byte_array(value):
"""
Convert Int to a one byte bytearray
:param value: value 0-255
"""
return bytearray(struct.pack(">B", value)) | e49ca6d85bfddb85f9132eb7fbaf3e2f1709bd2e | 689,989 |
def get_column_widths(columns):
"""Get the width of each column in a list of lists.
"""
widths = []
for column in columns:
widths.append(max([len(str(i)) for i in column]))
return widths | 8c6a86f58d214b4270adefeb2e2d942c787fc2c0 | 689,990 |
def filter_arglist(args, defaults, bound_argnames):
"""
Filters a list of function argument nodes (``ast.arg``)
and corresponding defaults to exclude all arguments with the names
present in ``bound_arguments``.
Returns a pair of new arguments and defaults.
"""
new_args = []
new_defaults ... | d6346cfdc7a8579411223f11fcfc946dc4ac4a10 | 689,991 |
import string
def clean_string(s):
"""Function that "cleans" a string by first stripping leading and trailing
whitespace and then substituting an underscore for all other whitepace
and punctuation. After that substitution is made, any consecutive occurrences
of the underscore character are reduced to ... | 5f8b9e470c40682da16218e7fa075efb296044c3 | 689,992 |
import sys
import os
def get_prog() -> str:
"""Determine the program name if invoked directly or as a module"""
name = (
sys.argv[0]
if globals().get("__spec__") is None
else __spec__.name.partition(".")[0]
)
try:
prog = os.path.basename(sys.argv[0])
if prog in... | 28783503152d4f74c7b674710f1e3e8563680e37 | 689,993 |
def error_dict(error_message: str):
"""Return an error dictionary containing the error message"""
return {"status": "error", "error": error_message} | d13f21b5620f4eeebf59fef03ee493472f5cf3e5 | 689,995 |
import zipfile
def listing(zip_path):
"""Get list of all the filepaths in a ZIP.
Args:
zip_path: path to the ZIP file
Returns: a list of strings, the ZIP member filepaths
Raises:
any file i/o exceptions
"""
with zipfile.ZipFile(zip_path, "r") as zipf:
return zipf.na... | 702efd93a2ba6cd462678e493eccbea6829cb28f | 689,996 |
def ptest_add_ingredients(ingredients):
"""Here the caller expects us to return a list"""
if "egg" in ingredients:
spam = ["lovely spam", "wonderous spam"]
else:
spam = ["spendiferous spam", "magnificent spam"]
return spam | ee170ba96221c67e6620ee5242074c1012aec4cb | 689,997 |
import __main__ as main_mod
def getname(var):
"""
Attempt to find the name of a variable from the main module namespace
Parameters
----------
var
The variable in question
Returns
-------
name : str
Name of the variable
"""
for name in dir(main_mod):
va... | 1ae865b8f707c499bb0ba27be3f5f3843fd7365e | 689,998 |
def find_k_4(n):
"""Exact solution for k = 4."""
if n == 1:
return 1
cycle, rem = divmod(n - 1, 4)
adjustment = cycle * 3 - 1
result = pow(2, n - 2) + pow(2, adjustment + rem)
return result | b666998d6cfd392f69d97715747a6b252af83de6 | 689,999 |
def notfound(context, request):
""" File not found view """
return {} | 68395547e220b050eb3997830fae0ac5f80e76ef | 690,000 |
import math
def all_possible_combinations_counter(subset_size,
set_size):
"""
Return a number (int) of all possible combinations of elements in size
of a subset of a set.
Parameters
-------
subset_size: int
Size of the subset.
set_size: int
... | f16760658ac5dc43096cf824a9a77bad38946f77 | 690,001 |
def read_weights(nnf_path):
"""
Format: c weights PW_1 NW_1 ... PW_n NW_n
:param nnf_path: Path to NNF file
:return: list of weights
"""
weight_str = None
with open(nnf_path, "r") as ifile:
for line in ifile.readlines():
if "c weights " in line:
weight_str... | fa1ba187bb8b2d9055610640f794ee3d9d09554f | 690,002 |
def valid_arguments(valip, valch, valc, valii, valid):
"""
Valid the arguments
"""
bvalid = True
# Type converssion
valch = int(valch)
valii = int(valii)
# Valid the parameters
# Valid - IP
if valip == "":
print("IP is invalid.")
bvalid = False
# Valid - C... | a228cd86732265605153b3fac4f70dbb8b2c8058 | 690,003 |
def perform_iteration(ring, length, pos):
"""
Solve the Day 10 puzzle.
"""
if pos + length < len(ring):
ring[pos: pos+length] = ring[pos: pos+length][::-1]
else:
seq = ring[pos:] + ring[:pos + length - len(ring)]
len_new_left = pos + length - len(ring)
len_new_right =... | 0b69396c07bc25ed5640dd3a2eb1c7dcae3103b3 | 690,004 |
import uuid
def validate_id_is_uuid(input_id, version=4):
"""Validates provided id is uuid4 format value.
Returns true when provided id is a valid version 4 uuid otherwise
returns False.
This validation is to be used only for ids which are generated by barbican
(e.g. not for keystone project_id)
... | fbc8678ed2c326cce56e905ca9e6f9728f1571c8 | 690,005 |
import copy
def with_base_config(base_config, extra_config):
"""Returns the given config dict merged with a base agent conf."""
config = copy.deepcopy(base_config)
config.update(extra_config)
return config | 5101b143d459ea127e1cef14849199236a99006a | 690,006 |
import ftplib
def _is_ftp_dir(ftp_handle, name, guess_by_extension=True):
""" simply determines if an item listed on the ftp server is a valid directory or not """
# if the name has a "." in the fourth to last position, its probably a file extension
# this is MUCH faster than trying to set every file to ... | 5cbd8ec1714385653bed830364ff7fb71a2b05ce | 690,007 |
def action_parser(*args):
"""
<action> ::= <behaviour> <m-conf>
<behaviour> ::= {<task>}
<m-conf> ::= <id>
<task> ::= {"L" | "R" | "P" <id> | "E" | "PNone"}
The "P" (for the printing task) isn't separated from the <id> by the
tokenizer.
"""
return args[:-1], args[-1] | d9b56fcf0cab05b5ebc9c412ec3f2fb631df3473 | 690,008 |
def get_subtext(soup):
"""Gets the subtext links from the given hacker news soup."""
subtext = soup.select(".subtext")
return subtext | f4b34e0a24f47f3332906ba8b69b07593becca04 | 690,009 |
def calculate_federal_income_tax(taxable_income):
"""Returns the federal income tax"""
fed_tax = 0
if taxable_income <= 9700:
fed_tax = taxable_income*0.1
elif taxable_income > 9700 and taxable_income <= 39475:
fed_tax = 9700*0.1 + (taxable_income-9700)*.12
elif taxable_income > 39475 and taxable_income <= 842... | 34ac21e3f7873ce3585c4e390932d05c2d59fec6 | 690,010 |
def players_in_tournament(t_body):
"""Get number of players in a tournament
Args:
t_body (element.tag) : tourn table body. Child of ResponsiveTable
Returns:
number of players
"""
players = t_body.find_all("tr", class_="Table__TR Table__even")
if players is not None:
... | 5a8918a317b30aaf8523364ef28b7771d60e2fb9 | 690,011 |
def PyEval_GetBuiltins(space):
"""Return a dictionary of the builtins in the current execution
frame, or the interpreter of the thread state if no frame is
currently executing."""
caller = space.getexecutioncontext().gettopframe_nohidden()
if caller is not None:
w_globals = caller.get_w_glob... | 1f2cf2f807c3ed6a73183481bb08452f84c92bdc | 690,012 |
def map_hostname_info(hostname, nmap_store):
"""Map hostname if there is one to the database record."""
if hostname is not None:
nmap_store["hostname"] = hostname.get('name')
return nmap_store
nmap_store["hostname"] = None
return nmap_store | ecab1c241f1785dbc52f1dbc9ad6a3a8fddf618b | 690,013 |
def _optional(*args):
"""Return *args if no element is the empty string or None.
Otherwise, return an empty string.
:param args:
:return: *args or ''
"""
for a in args:
if a == '' or a is None:
return ''
return args | 3ec551c908ce1e0ca9c9f3c824fef6b969b0563a | 690,014 |
def sum_ascii_values(text: str) -> int:
"""Sum the ASCII values of the given text `text`."""
return sum(ord(character) for character in text) | 7a45396e528c6e2d6c54b611f18d0cf648e418c8 | 690,015 |
def scientific_label(obj, precision):
""" Creates a scientific label approximating a real number in LaTex style
Parameters
----------
obj : float
Number that must be represented
precision : int
Number of decimal digits in the resulting label
Return... | 6f17cda209f8b84a6381a2927184829c1d5e3307 | 690,016 |
def _find_channels(ch_names, ch_type='EOG'):
"""Find EOG channel."""
substrings = (ch_type,)
substrings = [s.upper() for s in substrings]
if ch_type == 'EOG':
substrings = ('EOG', 'EYE')
eog_idx = [idx for idx, ch in enumerate(ch_names) if
any(substring in ch.upper() for subst... | 39e3f5d7473950b6e6fbf9cb8d6e1e97cdd32ffb | 690,017 |
from typing import MutableMapping
from typing import Any
def get_dict_item_with_dot(data: MutableMapping, name: str) -> Any:
"""Get a dict item using dot notation
>>> get_dict_item_with_dot({'a': {'b': 42}}, 'a')
{'b': 42}
>>> get_dict_item_with_dot({'a': {'b': 42}}, 'a.b')
42
"""
if not ... | 5822837ee608ecb2244ae0205aeeb0e4b92cc194 | 690,018 |
import click
def _merge_dj_config(path, existing_dj_config, new_dj_config, verbose):
"""
Merges an existing config dictionary (including the commands) with a new config.
"""
dj_config = existing_dj_config
commands = []
existing_commands = dj_config.get("commands", [])
existing_command_nam... | 7710284db6a22be78fb34a89a59bec675c6231c5 | 690,019 |
import os
def get_version():
"""
Get version info from version module dict.
"""
vi = {}
vf = os.path.join("oval", "version.py")
with open(vf, 'r') as mod:
code = compile(mod.read(), "version.py", "exec")
exec(code, vi)
return vi | d2e0920ec2565739abd818ae777c36a359fdf7b4 | 690,020 |
def pytest_report_header(config):
"""Thank tester for running tests."""
if config.getoption("nice"):
return "Thanks for running the tests." | 3ac2bb01da72e1027f24c07fa51ecd4b0ec22975 | 690,021 |
def _has_exclude_patterns(name, exclude_patterns):
"""Checks if a string contains substrings that match patterns to exclude."""
for p in exclude_patterns:
if p in name:
return True
return False | 72c0401e1e7073a2ca42e1f99b98e4a1ab834bd3 | 690,023 |
def max_multiple(divisor, bound):
"""
Finds the largest dividable integer that is lower than bound.
:param divisor: positive integer.
:param bound: positive integer.
:return: the largest integer N, such that, N is divisible by divisor, N is less
than or equal to bound, and N is greater ... | 269bae35cee1d0e3fa0199cc430e6c6f4eb3d3e3 | 690,024 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.