content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import uuid
def is_uuid_like(val):
"""
Check if value looks like a valid UUID.
"""
try:
uuid.UUID(val)
except (TypeError, ValueError, AttributeError):
return False
else:
return True | 0f5113f9fe6e04e2377a0921257030b7c116aa25 | 34,665 |
def rev_dict(l):
""" Reverse dict or list """
return {k: i for i, k in enumerate(l)} | 0fead05ee47e66bc0fc7f20bfa95309bcf810717 | 34,666 |
def get_summary_of_old_data(old_data):
"""Return a string summarizing the OLD resources that will be created.
"""
summary = [u'\nOLD resources to be created.']
for resource_name in sorted(old_data.keys()):
resource_list = old_data[resource_name]
summary.append(u' %s: %d' % (resource_name, len(resource_list)))
return u'\n'.join(summary) | 7af2b605ccc2d131b6841d586f0c7f9a49728481 | 34,667 |
def shares(shares):
"""Returns integer with comma notation"""
try:
shares = int(shares)
except (ValueError, TypeError, UnicodeEncodeError):
return ''
return '{0:,}'.format(shares) | 89b2dcc444b32c642c53967f445f6cab94cd50eb | 34,668 |
def strToList(text):
""" 将Permutation的密钥转换为list形式 """
try:
listKey = list(map(int, text.split()))
except ValueError:
return -1
else:
for i in range(1, len(listKey)):
if i in listKey:
pass
else:
return -1
return listKey | afb02b6ff0783b995827abdcebe72debf198005e | 34,669 |
def averageGuessesFromGuessMap(guessMap: dict[int, int]) -> float:
"""Return average guesses from map using weighed sum in form <guesses: words>,
e.g <1:20, 3:5> returns 1.75"""
weighedSum = 0
wordsCount = 0
for key,item in guessMap.items():
weighedSum = weighedSum + key*item
wordsCount = wordsCount + item
return weighedSum/wordsCount | 58d494133386915f7c7c7bc3a75becc129c7ff41 | 34,670 |
import time
def epoch_to_local_date(timestamp: float):
"""Epoch timestamp to `day/month/year - time` representation."""
return time.strftime("%d/%b/%Y - %X", time.localtime(int(timestamp))) | cd4036abb4095fcc56cfaf667408ac4befec1766 | 34,671 |
def read_folds(fname):
""" Reads a list of fold index lists.
Format: let the training set indices range from 0... n_samples-1. Each line
in a fold file should contain a subset of these indices corresponding to a
single fold. For example, let n_samples = 11, then:
0 3 4 8
1 5 9 10
2 6 7
would correspond to a fold-file with three folds, with first and second fold
containing 4, and last one 3 instances. The reader would return the list
[[0,3,4,8],[1,5,9,10],[2,6,7]]
Parameters
----------
fname : string
input file name
Returns
-------
folds : a list of lists, each containing the indices corresponding to a single fold
"""
f = open(fname)
folds = []
for i, line in enumerate(f):
#We allow comments starting with #
cstart = line.find("#")
if cstart != -1:
line = line[:cstart]
fold = []
foldset = set([])
line = line.strip().split()
for x in line:
try:
index = int(x)
except ValueError:
raise Exception("Error when reading in fold file: malformed index on line %d in the fold file: %s" % (i + 1, x))
if index < 0:
raise Exception("Error when reading in fold file: negative index on line %d in the fold file: %d" % (i + 1, index))
if index in foldset:
raise Exception("Error when reading in fold file: duplicate index on line %d in the fold file: %d" % (i + 1, index + 1))
fold.append(index)
foldset.add(index)
folds.append(fold)
f.close()
return folds | 9146f332dc6da9d212f1dbec95e8a9ff229c6220 | 34,673 |
def combinations_list(max_length):
"""
returns list of combinations of ACGT of all lengths possible
"""
letters = ["0", "A", "C", "G", "T"]
# max_length = 4
b = len(letters) - 1
# base to convert to
n = 0
k = 0
while k < max_length:
n = (n * b) + b
k += 1
# number of combinations
i = 1
l = []
while i <= n:
current = i
# m and q_n in the formula
combination = ""
while True:
remainder = current % b
if remainder == 0:
combination += letters[b]
current = int(current / b) - 1
else:
combination += letters[remainder]
current = int(current / b)
if (current > 0) == False:
break
l.append(combination)
i += 1
return l | 692158d3f9f73a5ccaf0729fd8811d95f3f6cbf3 | 34,675 |
from typing import Callable
from typing import Any
import math
def equal_or_close(rel_tol=1e-6, abs_tol=1e-6) -> Callable[[Any, Any], bool]:
"""Return a function that decides if a ~= b"""
def comparator(a, b) -> bool:
try:
v = math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol)
except Exception:
v = a == b
return v
return comparator | ad6723302d6470bcb36a65f92929dafa94a96146 | 34,676 |
def get_lang_abbr_from_resp(http_resp):
"""
This function takes a requests object containing a response from
detectlanguage.com, parses it, and returns the abbreviation of
the language detected.
"""
return http_resp.json()["data"]["detections"][0]["language"] | 6635b88306fbc4f149307133c0a118542a8709a9 | 34,677 |
def _reindex_values(new_index, values, initial_value):
"""
Conform values to new index
Parameters
----------
new_index : pandas.Index
values : pandas.Series
initial_value : float
Returns
-------
pandas.Series
"""
first_step = values.index[0]
new_values = values.reindex(new_index, method="ffill")
new_values.loc[new_values.index < first_step] = initial_value
return new_values | 31b1c197ebb47e2d641db21ea5ea1763e0bddb18 | 34,679 |
import os
def check_exist(filename, status):
"""
check_exist(filename, status)
checks to see if filename exists
if status==r, must exist, otherwise prints error + returns False
if status==w, if exists and clobber=no then prints error + returns False
else deletes + returns True
"""
if (status == "r"):
# check to see if it exists for reading
# (i.e. must be present)
if (not (os.path.exists(filename))):
print(f"Couldn't open input file: {filename}.")
return False
else:
# check to see if it exists for writing
# (i.e. must not exist or clobber=yes)
if (os.path.exists(filename)):
if (status == "w"):
return True
else:
return False
return True | 0ca0bfa0af4de6f21e017f9a1efd225e6ffce2ce | 34,683 |
def map_blocks_adresses(raw, column):
"""
Maps the adresses of the individual blocks from a given raw and column identifier of the 4x8 matrix to the corresponding mosaic identifier (1 to 32) given the following convention
|32|31|30|29|16|15|14|13|
|28|27|26|25|12|11|10| 9|
|24|23|22|21| 8| 7| 6| 5|
|20|19|18|17| 4| 3| 2| 1|
Parameters
----------
raw : [int]
column : [int]
Return
----------
[int] address of the block in the mosaic given the raw and column identifier
"""
raw_colomn_id = '(%i,%i)' % (raw, column)
if raw_colomn_id == '(3,0)':
return 0
if raw_colomn_id == '(3,1)':
return 1
if raw_colomn_id == '(3,2)':
return 2
if raw_colomn_id == '(3,3)':
return 3
if raw_colomn_id == '(2,0)':
return 4
if raw_colomn_id == '(2,1)':
return 5
if raw_colomn_id == '(2,2)':
return 6
if raw_colomn_id == '(2,3)':
return 7
if raw_colomn_id == '(1,0)':
return 8
if raw_colomn_id == '(1,1)':
return 9
if raw_colomn_id == '(1,2)':
return 10
if raw_colomn_id == '(1,3)':
return 11
if raw_colomn_id == '(0,0)':
return 12
if raw_colomn_id == '(0,1)':
return 13
if raw_colomn_id == '(0,2)':
return 14
if raw_colomn_id == '(0,3)':
return 15
if raw_colomn_id == '(3,4)':
return 16
if raw_colomn_id == '(3,5)':
return 17
if raw_colomn_id == '(3,6)':
return 18
if raw_colomn_id == '(3,7)':
return 19
if raw_colomn_id == '(2,4)':
return 20
if raw_colomn_id == '(2,5)':
return 21
if raw_colomn_id == '(2,6)':
return 22
if raw_colomn_id == '(2,7)':
return 23
if raw_colomn_id == '(1,4)':
return 24
if raw_colomn_id == '(1,5)':
return 25
if raw_colomn_id == '(1,6)':
return 26
if raw_colomn_id == '(1,7)':
return 27
if raw_colomn_id == '(0,4)':
return 28
if raw_colomn_id == '(0,5)':
return 29
if raw_colomn_id == '(0,6)':
return 30
if raw_colomn_id == '(0,7)':
return 31 | ce256a7d41e332e6bd47e38033b0dfa9df235895 | 34,684 |
def attn_weight_core_fetch(attn_weight, peptide):
"""Accoding to attn_weight to fetch max 9 position
Note: we don consider padded sequenc after valid
"""
max_weight = -float('Inf')
core_bind = ''
for start_i in range(0, len(peptide) - 9 + 1):
sum_weight = sum(attn_weight[start_i: start_i + 9])
if sum_weight > max_weight:
max_weight = sum_weight
core_bind = peptide[start_i: start_i + 9]
return core_bind | 2f23db753497cd0db13a341a2714f25292a90ad0 | 34,685 |
def LCA(root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root or root is p or root is q:
return root
left = LCA(root.left, p, q)
right = LCA(root.right, p, q)
if left and right:
return root
return left if left else right | 1d09d5725dcbbbf3eb44d3dc9048fae1f45fca0f | 34,686 |
import math
def prime_sieve(angka: int) -> list[int]:
"""
mengembalikan daftar dengan semua bilangan prima
hingga ke n
>>> prime_sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> prime_sieve(10)
[2, 3, 5, 7]
>>> prime_sieve(2)
[2]
>>> prime_sieve(1)
[]
"""
if angka <= 0:
raise ValueError("angka harus positif atau tidak boleh 0")
sieve = [True] * (angka + 1)
prime = []
start = 2
end = int(math.sqrt(angka))
while start <= end:
if sieve[start] is True:
prime.append(start)
# atur kelipatan awal menjadi false
for i in range(start * start, angka + 1, start):
if sieve[i] is True:
sieve[i] = False
start += 1
for j in range(end + 1, angka + 1):
if sieve[j] is True:
prime.append(j)
return prime | 375a02fe2e355f538f6f967cd83d4ba9821cf36d | 34,687 |
def function_polynomial(data, a, b, c, d):
"""Function used in fitting parameter surface to reflectance-transmittance value pairs.
Used in fitting and in retrieving Blender parameter values.
"""
r = data[0]
t = data[1]
res = a*(r**b) + c*(t**d)
return res | bd1e64f94d1110ceb39bec0cc1073428462e52d3 | 34,688 |
def add_file_to_tree(tree, file_path, file_contents, is_executable=False):
"""Add a file to a tree.
Args:
tree
A list of dicts containing info about each blob in a tree.
file_path
The path of the new file in the tree.
file_contents
The (UTF-8 encoded) contents of the new file.
is_executable
If ``True``, the new file will get executable permissions (0755).
Otherwise, it will get 0644 permissions.
Returns:
The provided tree, but with the new file added.
"""
record = {
"path": file_path,
"mode": "100755" if is_executable else "100644",
"type": "blob",
"content": file_contents,
}
tree.append(record)
return tree | c1d10dca15cf25f2f638deda423a7807332d4bb0 | 34,689 |
def _is_whitespace_or_comment(directive):
"""Is this directive either a whitespace or comment directive?"""
return len(directive) == 0 or directive[0] == '#' | c11f19ca8047194f2fe35d17dc7d058f029ccab9 | 34,690 |
import re
def get_easy_apply(soup, verbose=False):
"""
Check if the ad offers "Easy Apply" (only with LinkedIn)
"""
# Usually looks like this:
# <span class="artdeco-button__text">
tag = soup.find("span", class_="artdeco-button__text", string=re.compile("Easy Apply"))
if verbose: print(tag)
if tag != None:
return True
else:
return False | b4350d6a5894a2a6fb7cd70ed96425126561bf3f | 34,691 |
def settingDicts():
""" This dicts is used to make settings form"""
dicts = [
{
"id": 1,
"name": "Bot User OAuth Access Token",
"isEncrypted": False,
"properties": {
"rules": [
{
"required": False,
"message": ""
}
],
"type": "text",
}
},
{
"id": 2,
"name": "Slack Channel ID for Anomaly Alerts",
"isEncrypted": False,
"properties": {
"rules": [
{
"required": False,
"message": ""
}
],
"type": "text",
}
},
{
"id": 3,
"name": "Slack Channel ID for App Monitoring",
"isEncrypted": False,
"properties": {
"rules": [
{
"required": False,
"message": ""
}
],
"type": "text",
}
},
{
"id": 4,
"name": "Send Email To",
"isEncrypted": False,
"properties": {
"rules": [
{
"required": False,
"message": ""
}
],
"type": "textarea",
}
},
{
"id": 5,
"name": "Webhook URL",
"isEncrypted": False,
"properties": {
"rules": [
{
"required": False,
"message": ""
}
],
"type": "text",
}
}
]
return dicts | 241f70e3915373c43612f4dd1668587987faf5b0 | 34,692 |
import six
import io
def txt_filename(f, fname_or_fh, *args, **kwargs):
"""Decorator to allow seamless use of filenames rather than
file handles for functions that operate on a text file.
Usage
-----
To use this decorator, write the function to take a file object
as the function's first argument."""
if isinstance(fname_or_fh, six.string_types):
with io.open(fname_or_fh, 'r') as fh:
return f(fh, *args, **kwargs)
else:
return f(fname_or_fh, *args, **kwargs) | a20f65ecfbba7b101132ba9f43a2918b0706fc2b | 34,693 |
def clean_data(df, primary_key=None):
""" Drops null & duplicate rows """
if primary_key:
df = df.dropna(subset=[primary_key])
df = df.drop_duplicates(subset=[primary_key], keep='first')
df = df.dropna(how='all')
return df | 62ede4fc6d72c0c1b579816339d839ffd62a0122 | 34,696 |
def get_host(request):
"""
Get host info from request META
:param request:
:return:
"""
return request.META["HTTP_HOST"].split(":")[0] | 926710583bc1a7685b6268851fea757bede560c6 | 34,698 |
import json
def parse_question_task(x):
"""Gather task valid answers"""
annotation_dict = json.loads(x)[0]
if annotation_dict["task"] == "T1":
response = annotation_dict["value"]
else:
response = None
return response == 'Yes' | e5cdaa6fd2d4e11e7689fffe791d7b162bd67003 | 34,699 |
def value_to_bool(value):
"""Return bool True/False for a given value.
If value is string and is True or 1, return True
If value is string and is False or 0, return False
Otherwise if value is numeric or None, return bool(value)
"""
if isinstance(value, bool):
return value
elif isinstance(value, str):
return value.lower() in ("true", "1")
elif isinstance(value, int) or value is not None:
return bool(value)
else:
return False | 271d0a33b09b651a7705751a51aa7eab9cc76e55 | 34,700 |
import os
def get_num_part_files():
"""Get the number of PART.html files currently saved to disk."""
num_parts = 0
for filename in os.listdir(os.getcwd()):
if filename.startswith('PART') and filename.endswith('.html'):
num_parts += 1
return num_parts | f67d003ef1922808daef4852dcad751a2e59f466 | 34,701 |
def intoBinary(num):
"""
bin() function converts decimal to binary but does not return value in 8
bits. So we need to add the remaining zeros in order to make it 8 bits, for
which the 'switcher' dictionary is created. For instance if bin() returns
3 bits data, remaining 5 zeros are concatenated.
Input:
'num' as integer.
Returns:
Corresponding binary value of 'num'
"""
val = bin(num).replace('0b', "")
switcher = {
1:"0000000",
2:"000000",
3:"00000",
4:"0000",
5:"000",
6:"00",
7:"0",
8:""
}
#returns either number of zeros as per length or the value itself
if len(val) > 8:
final_value = val
else:
final_value = switcher.get(len(val), val)+val
print("Binary value of {}: ".format(num),final_value)
return final_value | 200c13daa1d7a0bf9dd16015c2c9ac6e299869aa | 34,702 |
def _canonicalize(name, package=''):
"""
If name is in package, will strip package component.
"""
name = name.replace('/', '.')
if name.startswith('java.lang.'):
return name[len('java.lang.'):]
i = name.rfind('.')
if i != -1 and package + '.' == name[:i + 1]:
return name[i + 1:]
else:
return name | e8fa0586b2b50d63d72090f3d03f2df09721af30 | 34,703 |
from typing import List
def get_color_scheme_3_channel(color_scheme_length: int) -> List[List[int]]:
"""
Use channel 1, 2 to time_frame_length / 2 and channel 2, 3 for the other half of the time frame
:param color_scheme_length:
:return:
"""
time_frame_split_1 = int(color_scheme_length / 2)
time_frame_split_2 = color_scheme_length - time_frame_split_1
split_1_step_size = int(255 / time_frame_split_1)
split_2_step_size = int(255 / time_frame_split_2)
colors = [[255, 0, 0]]
for i in range(1, time_frame_split_1):
step_num = i * split_1_step_size
colors.append([255-step_num, 0 + step_num, 0])
colors.append([0, 255, 0])
for i in range(1, time_frame_split_2 - 1):
step_num = i * split_2_step_size
colors.append([0, 255 - step_num, 0 + step_num])
colors.append([0, 0, 255])
return colors | d786182407d6b481b679c9bdd00ee189a690bf00 | 34,704 |
def help_message():
"""
:return:
"""
help_text = """
**RERO**
*The multipurpose utility bot for Discord.*
Commands
```ruby
. ?names : List of detected name changes
?pm [on, off, 24/7] : Sends you PM if you get mentioned
?8ball question : Answers a question 8 ball style
?sr subreddit : Grab random image from the subreddit
?anime name : Grab a anime from MAL
?manga name : Grab a manga from MAL
?ud query : Urban Dictionary definition
?wiki query : Wikipedia summary of querry
?giphy query : Gif matching querry
?xkcd [number] : Random xkcd or specify a number
?weather city : Get weather information
```
For a complete list of functions (*too many to send by PM*),
Want Rero in your server too?
<https://discordapp.com/oauth2/authorize?client_id=314796406948757504&scope=bot&permissions=8>
Visit RERO's Server:
https://discord.gg/nSHt53W
"""
return help_text | 943b0b840b8f7089b2906500feb8c7b8acf7e160 | 34,705 |
def idfy(var: str, *args):
"""Append ids to the variable."""
for arg in args:
var += '_' + str(arg)
return var | 6d768e5fdc1ec916555cb35ef27d2f27ee8a15e9 | 34,706 |
from operator import eq
from operator import ne
from operator import gt
from operator import lt
from operator import ge
from operator import le
def pruneByParamCmp(dataset, param, cmpoperator, value, interpretation="auto", retrievefailresult=False, comparefailresult=False) :
"""Reduce object list according to certain parameter's values.
Go through list "dataset" and keep only objects that satisfy comparison
>>param cmpoperator value<< (eg. "speed" "<=" "45"). With "interpretation",
behaviour can be further refined with type conversion prior to comparison.
For not present parameter, comparison result is substituted by
"retrievefailresult". For type conversion failure, comparison result is
substituted by "comparefailresult".
Possible "interpretation" values:
* "none" don't convert at all, compare string with given type
(fastest but works for few type/comparison combinations)
* "auto" cast to type of "value" (DEFAULT)
* "str" cast to strings
(makes sense only for equality check)
* "num" cast to number (float)
(commas and dots resolved correctly)
* "magic" try "num", "str", "auto" and "none" until something works
(slowest but human-like, may fail weirdly)
Allowed expressions for "cmpoperator" are: < > = == != ! <= >= => =< *
Asterisk "*" is a special operator for presence, regardless of "value" -
it also overrides "retrievefailresult" by setting it to true.
"""
# The generalized "what to do now" table is 2-D, one dimension with
# operator and one with interpretation. However, operators can be
# off-sourced to a hash of functions, and * is special anyway.
# hash of functions from module "operator"
operator_table = {
"==" : eq,
"=" : eq,
"!" : ne,
"!=" : ne,
">" : gt,
"<" : lt,
">=" : ge,
"=>" : ge,
"<=" : le,
"=<" : le
}
# easiest to write as loop over another function, using RETURN
def evalParamCmpOneObj(obj) :
# needs nested scopes !!!!
objval = obj.ask(param) # defaults to None
if objval == None :
return retrievefailresult
if cmpoperator == "*" :
return True # if the first test passed, * is automatically satisfied
typedval = None
typedcmp = None
if interpretation == "none" :
typedval = objval
typedcmp = value
elif interpretation == "auto" :
try :
paramtype = type(value)
typedval = paramtype(objval)
typedcmp = paramtype(value)
return operator_table[cmpoperator](typedval, typedcmp)
except :
return comparefailresult
elif interpretation == "str" :
try :
typedval = str(objval)
typedcmp = str(value)
return operator_table[cmpoperator](typedval, typedcmp)
except :
return comparefailresult
elif interpretation == "num" :
try :
typedval = float(objval)
typedcmp = float(value)
return operator_table[cmpoperator](typedval, typedcmp)
except :
return comparefailresult
elif interpretation == "magic" :
# in this mode, life is great and errors do not concern us... pass!
# expectation: jump to EXCEPT occurs before RETURN happens
try :
typedval = float(objval)
typedcmp = float(value)
return operator_table[cmpoperator](typedval, typedcmp)
except :
pass
try :
typedval = str(objval)
typedcmp = str(value)
return operator_table[cmpoperator](typedval, typedcmp)
except :
pass
try :
paramtype = type(value)
typedval = paramtype(objval)
typedcmp = paramtype(value)
return operator_table[cmpoperator](typedval, typedcmp)
except :
pass
# all possibilities exhausted, a direct comparison is called for!
typedval = objval
typedcmp = value
return operator_table[cmpoperator](typedval, typedcmp)
if cmpoperator not in ["=", "==", "!", "!=", "<", ">", "<=", "=<", ">=", "=>", "*"] :
raise ValueError("Invalid operator specified")
if interpretation not in ["none", "auto", "str", "num", "magic"] :
raise ValueError("Invalid interpretation specification")
i = len(dataset) - 1
while i >= 0 :
if not evalParamCmpOneObj(dataset[i]) :
del(dataset[i])
i = i - 1 | 8361e817ede8f6542dca4996da1d0c1f46a7581e | 34,707 |
from typing import List
def normalize_exchange_amounts(list_act: List[dict]) -> List[dict]:
"""
In vehicle market datasets, we need to ensure that the total contribution
of single vehicle types equal 1.
:param list_act: list of transport market activities
:return: same list, with activity exchanges normalized to 1
"""
for act in list_act:
total = 0
for exc in act["exchanges"]:
if exc["type"] == "technosphere":
total += exc["amount"]
for exc in act["exchanges"]:
if exc["type"] == "technosphere":
exc["amount"] /= total
return list_act | 34f0eac421fdb2e317415a0854038e418dc1d90e | 34,709 |
def choose_number():
"""
This function returns an integer from 1 to 5 inclusive (1, 5). It will
continually ask the user for a number if they do not enter valid input until
they do.
"""
valid = range(1,6)
while True:
usr_num = int(input("Enter an integer from 1 to 5 (inclusive): "))
if usr_num in valid:
return usr_num
print("ERROR: INVALID INPUT") | 6d87c5538ad89ce91dbc27ebca6a8092aa91910f | 34,711 |
import functools
import logging
def require_column(*colnames):
"""Wrapper to coordinate the segment-filtering functions.
Verify that the given columns are in the CopyNumArray the wrapped function
takes. Also log the number of rows in the array before and after filtration.
"""
if len(colnames) == 1:
msg = "'{}' filter requires column '{}'"
else:
msg = "'{}' filter requires columns " + \
", ".join(["'{}'"] * len(colnames))
def wrap(func):
@functools.wraps(func)
def wrapped_f(segarr):
filtname = func.__name__
if any(c not in segarr for c in colnames):
raise ValueError(msg.format(filtname, *colnames))
result = func(segarr)
logging.info("Filtered by '%s' from %d to %d rows",
filtname, len(segarr), len(result))
return result
return wrapped_f
return wrap | 9f7cba8cb4fca0c7632a9a787d33d9b509573c42 | 34,712 |
import base64
def encode_from_bytes(data: bytes) -> str:
"""
Base64-encodes a sequence of bytes for transmission and storage.
:param data: The byte sequence to encode
:return: string representation of base64-encoded bytes
"""
data_encoded_bytes = base64.b64encode(data)
data_encoded_str = str(data_encoded_bytes, "utf-8")
return data_encoded_str | ddb35881394ec18be3832b1181abf0538f60146d | 34,713 |
def digest_lines(digest_input):
"""
Read the lines of the Digest file output
"""
outlines = []
with open(digest_input, 'r') as infile:
for line in infile:
outlines.append(line)
return outlines | fe2627af2a15d51f399364bcfd0c0ef68e4973df | 34,714 |
def cached_property(getter):
"""
Decorator that converts a method into memoized property.
The decorator works as expected only for classes with
attribute '__dict__' and immutable properties.
"""
def decorator(self):
key = "_cached_property_" + getter.__name__
if not hasattr(self, key):
setattr(self, key, getter(self))
return getattr(self, key)
decorator.__name__ = getter.__name__
decorator.__module__ = getter.__module__
decorator.__doc__ = getter.__doc__
return property(decorator) | 5f63f088ea02591e35ad3144bf8a71d67dbec45f | 34,715 |
import uuid
def generate_uuid(value):
"""
Create an id for this dataset earlier than normal.
"""
return str(uuid.uuid4()) | ae64159b6bbc6e6b7423cfdfac71d1d0fee27ec0 | 34,717 |
def topBranchWithSampleCount(node, sampleCount):
"""If a descendant of this node is the topmost branch with sampleCount then return the
descendant. Return self if no descendant is the topmost branch but this node has sampleCount."""
if (node['sampleCount'] < sampleCount):
return None;
if (node['kids']):
for kid in node['kids']:
topKid = topBranchWithSampleCount(kid, sampleCount)
if (topKid):
return topKid
return node | 4e7b33e77d6e00a23635593cdb0f1e67df061f20 | 34,718 |
import string
import random
def random_str(size=6, chars=string.ascii_uppercase + string.digits):
"""
Формирует строку из случайных символов
:param size: размер строки
:param chars: сприсок символов для формирования строки
:type size: int
:type chars: str
:return: случайная строка
:rtype: str
"""
return "".join(random.choice(chars) for _ in range(size)) | 79732f7aa3ecc1ea27dbb7525a3b8878e72118c9 | 34,719 |
def _match_code_type_re():
"""
匹配codetype
"""
return r'^Code\sType:\s*([a-zA-Z0-9\-]+)\s*$' | 5c3b2cb95c447b51f6e7e5f839f2d39b7b235504 | 34,720 |
def log_approx(input, order=2):
"""
Taylor expansion of log function
input - (N,C) where C = number of classes
order - number of expansions
"""
result = 0
for n in range(1, order+1):
result += (-1)**(n-1) * (input-1)**n / n
return result | 6a3e3514027146704c98d6a0f8068812469d5f12 | 34,721 |
import re
def improve_address(address):
"""
Apply some methods to make the address
clearer to the locator.
:param address: a string
:return: str with improved address
"""
if isinstance(address, dict):
return f"{address['street']}, {address['city']}"
parsed_address = re.split(r" - |, ", address)
for i in parsed_address:
if not re.search(r"\d+", i):
street = i
break
else:
return None
states = ["Acre", "Alagoas", "Amapá", "Amazonas", "Bahia", "Ceará", "Distrito Federal", "Espírito Santo", "Goiás",
"Maranhão", "Mato Grosso", "Mato Grosso do Sul", "Minas Gerais", "Pará", "Paraíba", "Paraná",
"Pernambuco", "Piauí", "Rio de Janeiro", "Rio Grande do Norte", "Rio Grande do Sul", "Rondônia",
"Roraima", "Santa Catarina", "São Paulo", "Sergipe", "Tocantins"]
for e in states:
if e in address:
return f"{street}, {e}"
else:
return None | f18b49065c3f1b4980fce0c71e9e8dec2a5314ba | 34,722 |
def GetParentDir(savename):
"""Get parent directory from path of file"""
#split individual directories
splitstring = savename.split('/')
parent = ''
#concatenate all dirs except bottommost
for string in splitstring[:-1]:
parent += string + '/'
return parent | 511aefc52fa221aecece1287e622235b26bb8024 | 34,723 |
def check_columns(df, previous_df):
"""前ページと現ページのデータフレーム比較"""
diff1 = set(df.keys()) - set(previous_df.keys())
diff2 = set(previous_df.keys()) - set(df.keys())
return (len(diff1) == 0 and len(diff2) == 0) | d4ce86b9c44e367d4d7eb33de07c0f4bb2737ccb | 34,724 |
def winToPosix(win):
"""Converts the specified windows path as a POSIX path in msysgit.
Example:
win: C:\\home\\user
posix: /c/home/user
"""
posix = win.replace('\\', '/')
return "/" + posix.replace(':', '', 1) | cbdb521cbc6128c1d96f4e73c34d051108e30c88 | 34,725 |
def removeprefix(self: str, prefix: str) -> str:
"""
Removes a prefix from a string.
Polyfills string.removeprefix(), which is introduced in Python 3.9+.
Ref https://www.python.org/dev/peps/pep-0616/#specification
"""
if self.startswith(prefix):
return self[len(prefix):]
else:
return self[:] | c26b99313e4350adf082be7c32a9e8773ba8101e | 34,727 |
def convert_dct_to_matrix(val_dct, name_mat):
""" Take the values dictionary parsed from setval.read and convert
it to a value matrix used to build Z-Matrix objects
"""
val_mat = tuple(tuple(val_dct[name] if name is not None else None
for name in name_mat_row)
for name_mat_row in name_mat)
return val_mat | c3e4febbb0f13362abfccf83ad5ed9342283884c | 34,728 |
def runner(contest):
"""Contest wrapper, needed for multiprocessing implementation"""
try:
result = contest.run()
except KeyboardInterrupt:
# need to raise a non-keyboard interrupt error here to get
# the pool to die cleanly.
# XXX Is there a better way to handle this?
raise Exception("Got Keyboard Interrupt!")
return result | 24cc4e3de9fc56fee167fa8e70047041682c6498 | 34,729 |
def integrate_trapezoidal(f, a, b, n):
"""
Approximates the definite integral of f from a to b by the composite trapezoidal rule, using n subintervals.
Input:
- f (function)
- a (float)
- b (float)
- n (int)
"""
a = float(a)
b = float(b)
h = (b - a) / n-1
s = f(a) + f(b)
for i in range(1, n-1):
s += 2 * f(a + i * h)
return s * h / 2 | 00b83bb58520f0f7c3bd736975418633861d205d | 34,731 |
def __guess_key(key, keys, default_value):
"""Attempts to retrieve a key from a set of keys. There's a somewhat insane
amount of domain specific knowledge here. The keys often change subtley,
and therefore need some tweaking to find the right keys. This is extremely
error prone and should not be trusted. The idea is to use this to determine
the value in a dict, such as foo = bar[__guess_key(...)].
Args:
key (string): A string to attempt to find. Generally speaking, this
will be one of the following, and the function will attempt to
find anything close to it:
- "source"
- "pws_project_id"
- "pws_credential_id"
- "type"
keys (List<string>): A list of strings to be searched.
default_value (string): If no match was found, return this string.
Returns:
string: Either the closest match or the value of default_value
"""
default_value = key
if "cred" in key:
key = "credential"
elif "proj" in key:
key = "project"
for k in keys:
if key in k:
return k
return default_value | 6ef66a9e343d4b18cad7aa75a17c3423a732d9b0 | 34,732 |
def asline(iterable, sep=' ', end='\n'):
"""Convert an iterable into a line."""
return sep.join(str(x) for x in iterable) + end | b3ce332d8f78089d4df191c06556f7558c48c096 | 34,733 |
def output_passes_filter(data, filter_from, filter_to):
"""
Check if the data passes the given filter.
:param data: The data tuple to check.
:param filter_to: Filter to only values starting from this value...
:param filter_from: ...Filter to only values ending with this value.
:return: True if the data passes the filter, False otherwise.
"""
if filter_from is None or filter_to is None:
return True
return data[1] == filter_from and data[2] == filter_to | b2bc203c6e56647240e1d6376a98feda3a8695e8 | 34,734 |
def format_percentage(val: float, suffix: str = ' %') -> str:
"""
Formats a percentage value (0.0 - 1.0) in the standardized way.
Returned value has a constant width and a trailing '%' sign.
Args:
val: Percentage value to be formatted.
suffix: String to be appended to the result.
Returns:
Formatted percentage value with a constant width and trailing '%' sign.
Examples:
>>> print(format_percentage(0.359))
str(' 36 %')
>>> print(format_percentage(1.1))
str('110 %')
"""
return f'{round(val * 100): >3d}{suffix}' | 682fc3ea39f3de31ace9a72d80a982aea0fe63af | 34,736 |
def hour_number(N, time):
"""
Takes the day number and time (in hours) and
converts to hour number.
Parameters
----------
N : integer
The day number
time : float
The time in hours (24-hour clock)
Returns
-------
hour : float
The hour number
"""
hour = N * 24 + time
return hour | 058c6752fe531c0a5e3fd91cf23094facb6e5277 | 34,738 |
def list_sum(num_list):
"""Returns the sum of all of the numbers in the list"""
if len(num_list) == 1:
return num_list[0]
else:
return num_list[0] + list_sum(num_list[1:]) | 2145e3b52d7df2f36b99b8d44a81141d2cb98d88 | 34,739 |
def form_field(field):
"""Render the given form field."""
return {'field': field} | 02a580d99a3a8569d0bcc820013062359f95fd7c | 34,740 |
import time
from datetime import datetime
def LeapTime(t):
"""
converts strings to datetime, considering leap seconds
"""
nofrag, frag = t.split('.')
if len(frag) < 6: # IAGA string has only millisecond resolution:
frag = frag.ljust(6, '0')
nofrag_dt = time.strptime(nofrag, "%Y-%m-%dT%H:%M:%S")
ts = datetime(*nofrag_dt[:5]+(min(nofrag_dt[5], 59),))
#ts = datetime.fromtimestamp(time.mktime(nofrag_dt))
dt = ts.replace(microsecond=int(frag))
return dt | 79d2f9be510cd2b3565a7facf47e2385db4ad25c | 34,741 |
import os
def path_to_module_name(filename):
"""Convert a path to a file to a Python module name."""
filename = os.path.relpath(filename)
dotted_path = []
while True:
filename, component = os.path.split(filename)
dotted_path.insert(0, component)
if filename == "":
break
dotted_path[-1] = os.path.splitext(dotted_path[-1])[0]
if dotted_path[-1] == "__init__":
dotted_path.pop()
return ".".join(dotted_path) | cc29d2cf518d35b41043e0cbe23cfc7138474acb | 34,742 |
import time
def retries(times=3, timeout=1):
"""对未捕获异常进行重试"""
def decorator(func):
def _wrapper(*args, **kw):
att, retry = 0, 0
while retry < times:
retry += 1
try:
return func(*args, **kw)
except:
att += timeout
if retry < times:
time.sleep(att)
return _wrapper
return decorator | 4e7622a6929dec8cdbda2b14f74f81ca81e587a5 | 34,743 |
import torch
def solarize(image, threshold=128):
"""Invert all values above the threshold."""
return torch.where(threshold <= image, image, 255 - image) | 57e414392e655058c97615ad0cd4f75b3e34bf7c | 34,744 |
def scale_model_weights(weight, scalar):
"""Function for scaling a models weights for federated averaging"""
weight_final = []
steps = len(weight)
for i in range(steps):
weight_final.append(scalar * weight[i])
return weight_final | a3bb3bf4ad31a9b646ec96a084e59b6af04355e9 | 34,745 |
import re
def strip_html_markup(html):
"""
Strip HTML tags from any string and transfrom special entities
"""
text = html
if type(text) == bytes:
text = text.decode('utf-8')
# apply rules in given order!
rules = [
{ r'\s+' : u' '}, # replace consecutive spaces
{ r'\s*<br\s*/?>\s*' : u'. '}, # newline after a <br>
{ r'</(div)\s*>\s*' : u'. '}, # newline after </p> and </div> and <h1/>...
{ r'</(p|h\d)\s*>\s*' : u'. '}, # newline after </p> and </div> and <h1/>...
{ r'<head>.*<\s*(/head|body)[^>]*>' : u'' }, # remove <head> to </head>
{ r'<a\s+href=".*"[^>]*>([^"]+)</a>' : r'\1' }, # remove links
{ r'<[^<]*?/?>' : u'' }, # remove remaining tags
{ r'^\s+' : u'' } # remove spaces at the beginning
]
for rule in rules:
for (k,v) in rule.items():
text = re.sub(k, v, text)
# replace special strings
special = {
' ' : ' ', '&' : '&', '"' : '"',
'<' : '<', '>' : '>'
}
for (k,v) in special.items():
text = text.replace (k, v)
return text | f1d34027ee4e9408e3f2e5a1e9fce3314c6a6ed1 | 34,746 |
def extract_column_from_header(row):
"""
This function returns the landing status from the HTML table cell
Input: the element of a table data cell extracts extra row
"""
if (row.br):
row.br.extract()
if row.a:
row.a.extract()
if row.sup:
row.sup.extract()
colunm_name = ' '.join(row.contents)
# Filter the digit and empty names
if not(colunm_name.strip().isdigit()):
colunm_name = colunm_name.strip()
return colunm_name | b8d4e6a2c9c6b276bb67edcddede372948485d93 | 34,747 |
from typing import List
def build_branches(program: List[dict],
branches_end_nodes: List[int]) -> List[List[int]]:
"""
Build branches (currently only 2 branches are possible) by iterating through
the program. Stop once all branches_end_nodes are reached.
Parameters
---
program (List[dict])
Functional program
branches_end_nodes (List[int])
Indices of the last nodes in branches before the merge into a single node
Result
---
List[List[int]]
List of branches (only 2) containing indices of nodes.
"""
# not really important since we know it's only 2, but in case
# this changes in the future
num_branches = len(branches_end_nodes)
branches = [[] for i in range(num_branches)]
for branch_idx, end_node_idx in enumerate(branches_end_nodes):
branches[branch_idx].append(end_node_idx)
inputs = program[end_node_idx]["inputs"]
# stop when we reach empty inputs (i.e. scene program)
while inputs:
# there shouldn't be anymore branches
assert len(inputs) == 1
prev_node = inputs[0]
# append current branch with previous node
branches[branch_idx].append(prev_node)
inputs = program[prev_node]["inputs"]
return branches | 45983c9e0204acdc76dec8572b5f1a74cbc8147f | 34,748 |
def listify(x):
"""Turn argument into a list.
This is a convenience function that allows strings
to be used as a shorthand for [string] in some arguments.
Returns None for None.
Returns a list for a list or tuple.
Returns [x] for anything else.
:param x: value to be listified.
"""
if x is None:
return None
elif isinstance(x, (list, tuple)):
return x
else:
return [x] | d295f85eb6a37fd869c493ffd5da2fdc54927bf4 | 34,749 |
def split_channels(data):
"""
Splits a stereo signal into two mono signals (left and right respectively).
Example:
>>> data_left, data_right = split_channels(data)
"""
if len(data[0]) == 2:
data_l = data[:, 0]
data_r = data[:, 1]
return data_l, data_r
else:
print("Signal should be stereo.")
return data | 75561b8f4afa7aed727a536dcf0e60c31902f532 | 34,750 |
def fwhm_expr(model):
"""Return constraint expression for fwhm."""
fmt = "{factor:.7f}*{prefix:s}sigma"
return fmt.format(factor=model.fwhm_factor, prefix=model.prefix) | 7c7b8872904b94c7ac6b67b87ecfbc197cec520a | 34,751 |
from jinja2 import Environment, FileSystemLoader
import os
from io import StringIO
def upload_template(c, filename, destination, context=None, template_dir=None):
"""
Render and upload a template text file to a remote host.
"""
text = None
template_dir = template_dir or os.getcwd()
jenv = Environment(loader=FileSystemLoader(template_dir))
context = context if context is not None else {}
text = jenv.get_template(filename).render(**context)
# Force to a byte representation of Unicode, or str()ification
# within Paramiko's SFTP machinery may cause decode issues for
# truly non-ASCII characters.
# text = text.encode('utf-8')
# Upload the file.
return c.put(
StringIO(text),
destination,
) | 9f64a5acde061d2e20acfe5b8b31395a36e328fe | 34,752 |
import math
def acos(value):
"""Returns the arc cosinus in radians"""
return math.acos(value) | c3c793cb712d17a0da545300ffae7e521ec5ab64 | 34,753 |
import json
def _parse_default(version: int, data: memoryview) -> str:
"""
Default parser for user data sections that are not currently supported.
"""
return json.dumps(None) | 68d86c5757d5684e6383ff3355bdc2c6528310f9 | 34,754 |
import torch
def speye(n, dtype=torch.float):
"""identity matrix of dimension n as sparse_coo_tensor."""
return torch.sparse_coo_tensor(torch.tile(torch.arange(n, dtype=torch.long), (2, 1)),
torch.ones(n, dtype=dtype),
(n, n)) | b8fb388ebfd1c3f28fea02345d905cd9e43bc131 | 34,755 |
def exists(array, previous_arrays):
"""Tests if the array has been seen before"""
for i in previous_arrays:
if array == i:
return True
return False | 1329da3bacb6ff42e836efc4f056ea48fdfb4fc3 | 34,756 |
from typing import List
import requests
def option_sina_sse_list(symbol: str = "50ETF", exchange: str = "null") -> List[str]:
"""
新浪财经-期权-上交所-50ETF-合约到期月份列表
https://stock.finance.sina.com.cn/option/quotes.html
:param symbol: 50ETF or 300ETF
:type symbol: str
:param exchange: null
:type exchange: str
:return: 合约到期时间
:rtype: list
"""
url = "http://stock.finance.sina.com.cn/futures/api/openapi.php/StockOptionService.getStockName"
params = {"exchange": f"{exchange}", "cate": f"{symbol}"}
r = requests.get(url, params=params)
data_json = r.json()
date_list = data_json["result"]["data"]["contractMonth"]
return ["".join(i.split("-")) for i in date_list][1:] | 3f6254d28be8ae03fd2654edcd49b895e8bcbb86 | 34,757 |
import functools
import importlib
def served_by(service, attribute_name=None):
""" Decorator that connects a service to a service consumer.
"""
def f_wrapper(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if isinstance(service, str):
service_x = service.split('.')
service_module = importlib.import_module(
'.'.join(service_x[:-1]))
service_class = getattr(service_module, service_x[-1])
service_name = service_x[-1]
else:
service_class = service
service_name = service.__name__
service_attribute = ''
if attribute_name is None:
first = True
for s in service_name:
if s.isupper():
if first:
service_attribute = ''.join([
service_attribute, s.lower()])
else:
service_attribute = ''.join([
service_attribute, '_', s.lower()])
else:
service_attribute = ''.join([service_attribute, s])
first = False
else:
service_attribute = attribute_name
must_set_service = False
if not hasattr(self, service_attribute):
must_set_service = True
else:
if getattr(self, service_attribute) is None:
must_set_service = True
if must_set_service:
setattr(self, service_attribute, service_class(self))
return method(self, *args, **kwargs)
return wrapper
return f_wrapper | 3835562dcef6ba3dae1fc570b794e0d9696b333c | 34,758 |
def post_data(logged_in_apiclient):
"""Fixture for testing collection creation using valid post data"""
_, user = logged_in_apiclient
input_data = {
"owner": user.id,
"title": "foo title",
"view_lists": [],
"admin_lists": [],
}
return input_data | c8bd2b702f8bca1b33ca0b01e37f6ae83becbe55 | 34,759 |
from typing import List
def index_modules(a_dict: object, keys: List[str]) -> object:
"""Recursively find a syft module from its path
This is the recursive inner function of index_syft_by_module_name.
See that method for a full description.
Args:
a_dict: a module we're traversing
keys: the list of string attributes we're using to traverse the module
Returns:
a reference to the final object
"""
if len(keys) == 0:
return a_dict
return index_modules(a_dict=a_dict.__dict__[keys[0]], keys=keys[1:]) | f28247fc00eb7ea0514be1e54b7f77a995779ad1 | 34,761 |
import subprocess
def _q_tx_events(msg):
"""
takes in the msg to say withdraw_validator commission and fill the rest of the flags and commands and pass it into the CLI
"""
# fxcored query txs --events 'message.sender=fxvaloper1c4glwxgvs5vjx9j2w4ef7r4480cfs2dkv7h8u2&message.action=withdraw_validator_commission' --node https://fx-json.functionx.io:26657
raw_data=subprocess.run(["fxcored","q","txs","--events",msg,"--node=https://fx-json.functionx.io:26657"],stdout=subprocess.PIPE)
return raw_data | 5dc463659d8fbe5566dfdb7217f7b92f994fd40b | 34,762 |
def seconds_to_str(seconds):
""" converts a number of seconds to hours, minutes, seconds.ms
"""
(hours, remainder) = divmod(seconds, 3600)
(minutes, seconds) = divmod(remainder, 60)
return "h{}m{}s{}".format(int(hours), int(minutes), float(seconds)) | edaa063c1d5423c0404a41e83f1a1419891e685a | 34,763 |
import os
import re
def recipe_to_append(recipefile, config, wildcard=False):
"""
Convert a recipe file to a bbappend file path within the workspace.
NOTE: if the bbappend already exists, you should be using
workspace[args.recipename]['bbappend'] instead of calling this
function.
"""
appendname = os.path.splitext(os.path.basename(recipefile))[0]
if wildcard:
appendname = re.sub(r'_.*', '_%', appendname)
appendpath = os.path.join(config.workspace_path, 'appends')
appendfile = os.path.join(appendpath, appendname + '.bbappend')
return appendfile | e5570f626ab400266560316970c3c680dee1a1f3 | 34,764 |
def normalize(img, mean, std):
"""
Normalize image with mean and standard deviation.
Parameters
----------
img : array(float)
The image to normalize
mean : float
The mean used for normalization.
std : float
The standard deviation used for normalization.
Returns
-------
array(float)
The normalized image.
"""
return (img - mean) / std | 9d85497ef251a98d7630bcea694e6f12ba8ab608 | 34,765 |
def sum(a, b):
"""Returns the sum of a, b"""
print("Calculating the sum of %d, %d" % (a, b))
return a + b | 114242f453074eeb687f6b895f594c1c7ae358f7 | 34,766 |
def update_process(process, stock, time=1):
"""
Check if process ended
if so, adding it's output to the stock and setting busy to false.
"""
process.update(time)
if (process.done()):
stock.new(process)
process.end()
return process, stock | 7897ab759cdb2b68239961e11c287f17a8c99687 | 34,769 |
def color_str_green(s):
"""Color string GREEN for writing to STDIN."""
return "\033[1m\033[92m{}\033[00m".format(s) | 4d1a74d4f7b4af27e51076cf04d51031b007773a | 34,771 |
def diffa(dist, alpha, r):
"""
Compute the derivative of local-local BDeu score.
"""
res = 0.0
for n in dist:
for i in range(n):
res += 1.0/(i*r+alpha)
for i in range(sum(dist)):
res -= 1.0/(i+alpha)
return res | 9f5b14da7940eec4a91077b000770f55485cdc45 | 34,773 |
def _qr_R(qr):
"""Extract the R matrix from a QR decomposition"""
min_dim = min(qr.shape)
return qr[:min_dim + 1, :] | 5d3270cf3b1430e81dc933cec72e9d38d91b1653 | 34,775 |
import sys
def lazyf(template):
"""Do a f-string formating."""
frame = sys._getframe(1)
result = eval('f"""' + template + '"""', frame.f_globals, frame.f_locals)
return result | 6382fbc9d2d9eaaaa049fd45336f5d9fa05b192d | 34,776 |
import math
def calculate_parameters(latency, jitter, bandwidth, packetloss, current_parameters):
""" From the network Q4S parameters generats the coder options."""
#pylint: disable=unused-argument
if math.isnan(packetloss):
frame_skipping = 0
elif packetloss == 0:
frame_skipping = 0
elif packetloss < 0.05:
frame_skipping = 2
elif packetloss < 0.1:
frame_skipping = 4
elif packetloss < 0.15:
frame_skipping = 6
elif packetloss < 0.2:
frame_skipping = 8
elif packetloss < 0.25:
frame_skipping = 10
elif packetloss < 0.30:
frame_skipping = 12
elif packetloss < 0.35:
frame_skipping = 14
elif packetloss < 0.4:
frame_skipping = 16
elif packetloss < 0.45:
frame_skipping = 18
elif packetloss < 0.5:
frame_skipping = 20
else:
frame_skipping = 25
return (frame_skipping, ) | e7ce1c21b8f97b86e59eefa716e8675c45167584 | 34,777 |
def get_action_key(action, category):
"""
Return a key for indexing an action.
"""
return (action, category) | bc4343e4a00913dd289c1df28602df4410a9b7e4 | 34,781 |
import os
def create_file_names_and_files(number_of_files, begin=""):
"""Creates multiple files if they not exists"""
counter = 0
filenames = []
for i in range(number_of_files):
while True:
filename = begin + str(counter)
if not os.path.isfile(filename):
open(filename, 'a').close()
filenames.append(filename)
counter += 1
break
counter += 1
return filenames | aa2ba7d2aea37326a70ee51d759c48a3c5dc3a27 | 34,782 |
import sys
import traceback
def redact_exception(ex: Exception) -> str:
"""Log an exception in a redacted way. Logs the traceback code line and function name but not the message.
Args:
ex (Exception): The exception to log.
Returns:
str: The redacted exception message.
"""
msg = ""
name = ex.__class__.__name__ if hasattr(ex, "__class__") else "Exception"
_, _, e_traceback = sys.exc_info()
msg += "Traceback (most recent call last):\n"
for filename, linenum, funname, line in traceback.extract_tb(e_traceback):
msg += f' File "{filename}", line {linenum}, in {funname}\n {line}\n'
msg += f"{name}: [MESSAGE REDACTED]"
return msg | 11aa76907f7a8490b029f354ad58438d72bb4d79 | 34,783 |
def fields(format_mapping):
"""
Create a formatter that performs specific formatting based on field names.
:type format_mapping: ``Dict[text_type, Callable[[Any, text_type], Any]]``
"""
def _format_field_value(value, field_name=None):
f = format_mapping.get(field_name, None)
if f is None:
return None
return f(value, field_name)
return _format_field_value | b199e6955eb53354bf6a111277afe619626fc713 | 34,787 |
import os
import torch
def load_network(filename, model, optimizer=None, **kwargs):
"""
Loads state_dicts to model and optimizer
Parameters
----------
filename: string
file to load from
model: torch.nn.Module
modle to load state_dict to
optimizer: torch.optim.Optimizer or None
if not None: optimizer to load state_dict to
kwargs:
additional keyword arguments (directly passed to torch.load)
Returns
-------
model, optimizer and start epoch
"""
if os.path.isfile(filename):
print("=> loading checkpoint '{}'".format(filename))
checkpoint = torch.load(filename, **kwargs)
start_epoch = checkpoint['epoch']
model.load_state_dict(checkpoint['state_dict'])
if optimizer is not None:
optimizer.load_state_dict(checkpoint['optimizer'])
print("=> loaded checkpoint '{}' (epoch {})"
.format(filename, checkpoint['epoch']+1))
return model, optimizer, start_epoch
else:
print("=> no checkpoint found at '{}'".format(filename))
raise FileNotFoundError("Checkpoint File not found") | 71c17f0c6bafac567ba9c4c51cbc717f69584854 | 34,789 |
from typing import Iterable
from typing import List
def split(chars: Iterable[str], maxlen: int) -> List[List[str]]:
"""Returns char groups with a fixed number of elements"""
result = []
shatter: List[str] = []
for i in chars:
if len(shatter) < maxlen:
shatter.append(i)
else:
result.append(shatter)
shatter = [i]
if shatter:
while len(shatter) < maxlen:
shatter.append('')
result.append(shatter)
return result | cc320baf00ac67aef8a1bfa919b84e687ead46d5 | 34,790 |
def recuperer_valeur_tag(elem,cle_valeur):
"""
Dans OSM, les attributs d'une relation sont dans les objets tag de l'objet XML de la relation.
Récupérer la valeur associée à la clé cle_valeur
:param elem:
:param cle_valeur:
:return:
"""
# Recherche de tous les éléments tag de l'objet elem
for item in elem.findall('tag'):
if item.get("k") == cle_valeur:
return item.get("v")
return None | 5b600ce792aeda98b73de879685caa73ef3fd5e3 | 34,793 |
def convert_name(cs):
"""Convert the name of prototype to formal name
"""
def convert_single(_cs):
if isinstance(_cs, str): # convert string name
_cs = cs.lower()
if _cs[0] == "z":
return "zincblende"
elif _cs[0] == "w":
return "wurtzite"
elif _cs[0] in ("n", "r"):
return "rocksalt"
elif _cs[0] == "c":
return "cesiumchloride"
elif _cs[0] == "d":
return "diamond"
elif _cs[0] == "p":
return "perovskite"
else:
return "other"
else:
return ""
if isinstance(cs, str):
return ([convert_single(cs)])
elif isinstance(cs, list):
return tuple([convert_single(c) for c in cs]) | 196b0d95435a77c640bbb8e2392d0735f9fe63e6 | 34,794 |
import os
def get_file_name_pieces(file_path):
"""
Split input file path into the path, the file name without extension, and the extension, and return as a tuple.
Example:
Inputting "/Users/Me/python/src/my_file.py" returns ("/Users/Me/python/src", "my_file", ".py").
Args:
file_path (str): A file name, either with or without a path. Examples: my_file.py, ./src/my_file.py,
/Users/Me/python/src/my_file.py .
Returns:
tuple(str, str, str): A tuple containing first the path to the input file, then the file name without
extension, then the extension.
"""
file_dir, filename = os.path.split(file_path)
file_base, file_ext = os.path.splitext(filename)
return file_dir, file_base, file_ext | 3470abb4247256bb9fe321c9e210437458f677cb | 34,795 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.