content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def TENSOES_NORMAIS(P_I, A_C, E_P, W_INF, W_SUP, DELTA_P, DELTA_G1, DELTA_G2, DELTA_G3, DELTA_Q1, DELTA_Q2, PSI_Q1, M_G1, M_G2, M_G3, M_Q1, M_Q2):
"""
Esta função determina a tensão normal nos bordos inferior e superior da peça.
Entrada:
P_I | Carga de protensão considerando as perdas ... | bbb4d91ba6a827e79394deaccd4c254a983e188e | 638,110 |
def sanitize(string):
""" sanitize a string before JSON-ize it """
return string.strip().replace("\\", "") # slash replace is only needed on Windows | 618617a29342da284a98b855ac46b20bc2269870 | 638,111 |
import yaml
def parse_config(config_file):
"""
Helper function to parse the Yaml config file.
Args:
config_file (str): yml configuration file
Returns:
dict: parsed dictionary object
"""
with open(config_file, "rb") as f:
config = yaml.safe_load(f)
return config | d3e66bb120aee5f39a6b90e8965c82ab9612abde | 638,112 |
import re
def clean_text(txt):
"""Clean up and encode text to utf-8"""
txt = re.sub(' |\u00A0', ' ', txt)
txt = re.sub('\n\* ', '\n\\* ', txt)
return txt | 59d5df85914a3ef1d31eb3efe61b031cf8869bf8 | 638,113 |
import math
def rotate_ccw(g, r):
""" Punkte imt Pfad/Glyph g um r (Radians) gegen den Uhrzeigersinn rotieren"""
return [(x * math.cos(r) - y * math.sin(r), y * math.cos(r) + x * math.sin(r))
for (x, y) in g] | cec1a8b7bdceb958f8b774b177e5ae7b89518d1e | 638,114 |
from typing import Iterable
def precision(pred: Iterable, ref: Iterable) -> float:
"""% of predictions are correct:
P = TP / (TP + FP)
"""
# True Positive = the number of (unignored) prediction mappings that are True
tp = len(set(pred).intersection(set(ref)))
# False Positive = the number ... | 0b13e49368eb4f4a9d85f803accfe37e1af7a8cb | 638,115 |
def convert_index_to_lab(batch, ind2lab):
"""Convert a batch of integer IDs to string labels.
Arguments
---------
batch : list
List of lists, a batch of sequences.
ind2lab : dict
Mapping from integer IDs to labels.
Returns
-------
list
List of lists, same size a... | b1ed85eee7d0c72bb6b6fdb61ad99147ba0c1abf | 638,116 |
def get_time_field(da):
"""Get name of time coordinate."""
default_time_names = ['time', 'initial_time0_hours']
for d in default_time_names:
if d in da.dims:
return d
raise RuntimeError('Could not deduce time coordinate for given data') | aa5e2dc1ef7ca5f9d9adb5e1e41cf7f81cf7c213 | 638,117 |
def _unique_ids(pairs_list, used_ids):
"""Return pairs_list that does not contain previously used ids"""
pairs_list_f = [x for x in pairs_list
if ((used_ids[x[0][0]] == 0) and
(used_ids[x[1][0]] == 0))]
return pairs_list_f | 4aaf4d7dc41110e2890d730500f6fa86b39d4929 | 638,118 |
import requests
def getSunriseSunsetDataLatLong(latitude: str, longitude: str, daysFromNow: int = 0):
"""Fetches data from sunrise-sunset API.
Args:
latitude: Latitude in degrees.
longitude: Longitude in degrees.
daysFromNow: Specify fetching data for a date N days in the future... | 47bb10e14151b8e3ba7ced03b025918c9acd93ab | 638,119 |
def of_type(ts):
"""
>>> of_type({'kind': 'OBJECT', 'name': 'User', 'ofType': None})
'User'
>>> of_type({'kind': 'NON_NULL', 'name': None, 'ofType': {'kind': 'SCALAR', 'name': 'String', 'ofType': None}})
'String'
>>> of_type({"kind": "ENUM", "name": "ProjectState"})
'ProjectState'
"""
... | 40464c0f0d985fde7c3cb939958ea1bb349bcbfd | 638,120 |
def get_position_from_periods(iteration, cumulative_period):
"""Get the position from a period list.
It will return the index of the right-closest number in the period list.
For example, the cumulative_period = [100, 200, 300, 400],
if iteration == 50, return 0;
if iteration == 210, return 2;
i... | f103be219adba611e2aee4985116d64c1995a090 | 638,121 |
import math
def calc_deviation(values, average):
"""
Calculate the standard deviation of a list of values
@param values: list(float)
@param average:
@return:
"""
size = len(values)
if size < 2:
return 0
calc_sum = 0.0
for number in range(0, size):
calc_sum += m... | b6283de9b34a99f71994789ba7a2559e9f69674a | 638,122 |
def timeStamp(list_time):
"""
Format time stam into `00h00m00s` into the dictionary
:param list_time: float list of time stamp in second
:return format_time: dictionary of format time
"""
format_time = dict()
i = 0
for time in list_time:
m, s = divmod(time, 60)
h, m = div... | bbb777c43667922582725e60720a13408d27682b | 638,123 |
import os
import csv
def get_words_for_questions(path):
"""reads the word list in path and returns a list of question words"""
assert os.path.exists(path), "list of question words not found!"
with open(path) as f:
reader = csv.reader(f)
question_words = [ a[0].replace(" ", "") for a in lis... | 8c6f6813906ce2e352210a04de354077b713ff99 | 638,124 |
import torch
def bloom_gelu_forward(x):
"""
Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to
make the model jitable.
Args:
x (`torch.tensor`, *required*):
input hidden states
"""
return x * 0.5 * (1.0 + tor... | 6808c15488d19b65035a1209174f573ca21a5290 | 638,125 |
def calc_p_ratio(hps, nhps, total_hps, total_nhps):
"""
Returns a ratio between the proportion hps/nhps to the proportion nhps/hps. The larger proportion will be the
numerator and the lower proportion will be the denominator (and thus the p-ratio>=1).
This corrects for the total_hps/total_nhps imbalance... | c39727d485e94ce57ec56ff0d8bab9d85aceb241 | 638,126 |
def dichotomic_search(f, a, b, thresh=0, n_max =50):
"""Implementation of dichotomic search of minimum solution for an increasing function
Args:
-f: decreasing function
-a: lower bound of search spaceq
-b: upper bound of search space
-thresh: threshold such th... | ef08eb2aac272c6ed5cb4de529d5f5fe558eb6b3 | 638,127 |
def getInput(prompt, default):
"""getInput(prompt, default) -> str
Pops up a dialog box with a text field for an arbitrary string.
@param prompt: Present the user with this message.
@param default: Default value for the input text field.
@return: String from text field or None if dialog is cancelled."""
retur... | 4253d766459822752ef5a0a6bf3a159c9347987c | 638,128 |
import uuid
import string
def activate(key: str):
"""
encrypts key
key: activation key
"""
uid = str(uuid.getnode())
alphabet = string.ascii_uppercase
activated_key = ""
for i in range(len(key)):
if key[i] in alphabet:
activated_key += alphabet[i + int(uid[i % len(... | 6bdaf4fb0bd286321ceddebe6c6a2afe2d0d1a02 | 638,129 |
def state2dict(Primes, State):
"""
Converts the string representation of a state into the dictionary representation of a state.
If *State* is already of type *dict* it is simply returned.
**arguments**
* *Primes*: prime implicants or a list of names
* *State* (str): string representatio... | 4207b1e018cb503898aa0aaf840a551a06ab7f8f | 638,130 |
def cat(*args):
""" concatenate args """
out = ""
for arg in args:
if not arg:
pass
elif len(arg) > 0:
if len(out) == 0:
out = arg
else:
out = out + " " + arg
return out | ffd6e0525d896dcd2a3281c61e21aa538c9bcd27 | 638,131 |
def _get_name(soup) -> str:
"""Get the work name."""
return soup.find(id='work_name').a.contents[-1].strip() | 3114445dedc91802a7a23c42ddf77e1d3e7bf3c7 | 638,132 |
def extract_mg_h(sai):
"""
Given an SAI, this find the most general pattern that will generate a
match.
E.g., ('sai', ('name', '?foa0'), 'UpdateTable', ('value', '?foa1'))
will yield: {('name', '?foa0'), ('value', '?foa1')}
"""
return frozenset({tuple(list(elem) + ['?constraint-val%i' % i])... | 0a1dd85f5fde1c3aeda4762483cfb87cbbc3d58e | 638,133 |
import locale
import sys
def getpreferredencoding() -> str:
"""Get the user's preferred encoding."""
return locale.getpreferredencoding() or sys.getdefaultencoding() | 6681482a8d19540e44a8cacc6ac120bb5affaecf | 638,134 |
def getstack(repo, rev=None):
"""return a sorted smartrev of the stack containing either rev if it is
not None or the current working directory parent.
The stack will always contain all drafts changesets which are ancestors to
the revision and are not merges.
"""
if rev is None:
rev = b... | 9fe094f28f076f475393790fb38b243c57d859d4 | 638,135 |
import time
import os
def face_location(instance, filename):
"""
Rename image name to a timestamp and saves to uploads/citizenship_number/face/timestamp directory .
"""
timestr = time.strftime("%Y%m%d-%H%M%S")
name, extension = os.path.splitext(filename)
return os.path.join('uploads', str(inst... | e160c9403939e3bb1efec5bce4502cab85701765 | 638,136 |
def stopFunCombined(t, s, lst, events, out=[]):
""" Universal event detection function that handles multiple events.
Intended for scipy.integrate.ode solout application. Provides
termination of integration process when first terminate event occur.
This happens when independent variable as... | 07a7d8df2fae57954e7b1d11de0d3efe9caf906d | 638,137 |
def bool_flag(s):
"""Helper function to make argparse work with the input True and False.
Otherwise it reads it as a string and is always set to True.
:param s: string input
:return: the boolean equivalent of the string s
"""
if s == '1' or s == 'True':
return True
elif s == '0' or s ... | 89603008f3daa0411ca3c9dc537e5032bd52bc95 | 638,138 |
def falseid_to_trueid(false_id_list, map_filename):
"""
False id to real id.
Args:
false_id_list:
map_filename: map filename. In this map file, the first column is true id and the second column is false id.
Returns:
true id list
"""
map_file = open(map_filename, 'r')
... | 97db5ed43d6bde68272b59a964650465f3c9fd97 | 638,140 |
import copy
def optimize_traversal_order(params):
"""
An optimization that reduces generation time by better amortizing
setup costs. With this rendering state changes (cheap) are late
and in particular camera (~free) is the innermost loop.
It also makes generation easier to watch. With camera inn... | 3abb47c4066ab502e6b61834928264fffd0d8719 | 638,141 |
def statistics(prediction, ground_truth, beta=1):
"""Computes performance statistics for classifiers.
Parameters
----------
prediction : set
Set of objects predicted to be labeled positive.
ground_truth : set
Set of objects actually labeled positive.
beta : float, optional
... | 4b937a98a76431b979f7be33e732de82a46320bf | 638,143 |
def IsNodeOSL(node):
"""
Determines if the given node has an OSL source type.
"""
return node.GetSourceType() == "OSL" | cbda361dfb0c244f7f2baa52af6992c84509c290 | 638,144 |
import pkg_resources
def package_version():
"""
Determine the version of this package.
:return: String representing known version
"""
version = ""
try:
version = pkg_resources.get_distribution('instana').version
except pkg_resources.DistributionNotFound:
version = 'unknown... | 2fc9f380d4e41795814863608f9a6645b5947389 | 638,145 |
def join_tagblock(tagblock, nmea):
"""
Join a tagblock to an AIVDM message that does not already have a tagblock
"""
if tagblock and nmea:
return "\\{}\\{}".format(tagblock.lstrip('\\'), nmea.lstrip('\\'))
else:
return "{}{}".format(tagblock, nmea) | 011dc58a3a4342ea048f1f97e8fb5c5c47027c6d | 638,146 |
import socket
def hostname(ip, reverse=False):
"""hostname(ip) -> 'hostname'
`ip` may be a string or ipaddr.IPAddress instance.
If no hostname known, returns None."""
try:
result = socket.gethostbyaddr(str(ip))
return result[0] if not reverse else result[2][0]
except socket.error:... | 3b20c93366c037d4d669e7e9d1f89c7d79facff0 | 638,147 |
import re
def _parse_minimap_log(log_filename):
"""Parses minimap log file and returns
i string) version, float ii) peak RAM"""
version = ""
RAM = 0.0
try:
logfile = open(log_filename)
except OSError as error:
print("# ERROR: cannot open/read file:", log_filename, error)
... | 3b932a0fef7c3dad7c26db0d1bc28c21e3a634fc | 638,148 |
def string_to_number(s):
"""
Convert a bytes string into a single number.
Example:
>>> string_to_number('foo bar baz')
147948829660780569073512294
"""
return int.from_bytes(s.encode(), "little") | a27236100fc4faa940654fd93b434360e3f52fa3 | 638,149 |
def get_broadcast_shape(x_shape, y_shape, prim_name):
"""
Doing broadcast between tensor x and tensor y.
Args:
x_shape (list): The shape of tensor x.
y_shape (list): The shape of tensor y.
prim_name (str): Primitive name.
Returns:
List, the shape that broadcast between ... | 583f7f8e626d6cc9fa6941071b887b39e588aa13 | 638,151 |
import os
def readlinkabs(l):
"""
Return an absolute path for the destination
of a symlink
"""
if not (os.path.islink(l)):
return None
p = os.readlink(l)
if os.path.isabs(p):
return p
return os.path.join(os.path.dirname(l), p) | bed1e5f0f679eea3e66bd293ad7e06bb6da5988a | 638,152 |
def select_warning(conn, id):
"""Query all rows in the tasks table.
Args:
conn: the Connection object
id: id
"""
cur = conn.cursor()
cur.execute("SELECT * FROM warnings WHERE key == {}".format(id))
rows = cur.fetchall()
for item in rows:
key, warning = item
... | c76e5a5d4d084190209d3d906fefa6ba551226bc | 638,153 |
def wn2wl(wavenumber):
"""Convert wavenumber (cm-1) to wavelength (um)."""
return 10000 / wavenumber | 55aeee52dca6b36e0ddee6a7176d0deaaeb7c552 | 638,154 |
def tracer_features_importance(dataframe, df_features_importance, jeu, methode):
"""
Affiche l'étape puis nombre de lignes et de variables pour le dataframe transmis
Parameters
----------
@param IN : dataframe : DataFrame, obligatoire
df_features_importance : dataframe de suivi des d... | 6e9c75ea296c76f7ffb308788e7210e8ca7dedb0 | 638,155 |
def selectSome(strings, requiredsubstrings=[], requireAll=True):
""" Filter the list of strings to only contain those that have at least
one of the required substrings. """
if len(requiredsubstrings) == 0:
return strings
res = []
for s in strings:
if requireAll:
bad ... | 29f6d08850c38bcd989501da8588e3c68a62e246 | 638,156 |
def get_char_of_category(source, category):
""" Read category?. """
result = ""
c = source.char()
if c in category:
result = c
source.consume(len(result))
return result if result else None | 8c45b76d0c467da3bde529fbf0bfa52b5944ed6d | 638,158 |
def Define_request(req_config, url_hub):
""" Defines a search request """
url_str = url_hub + "/search?q="
if req_config["download_options"]["satellite"] != "":
url_str += "%s"%(req_config["download_options"]["satellite"]+"*")
for key in req_config["search"].keys():
if req_config["sear... | 4125cc54fce630b710fc08f65975bbcbdeaab6da | 638,159 |
def get_unique_sublist(inlist):
"""return a copy of inlist, but where elements are unique"""
newlist = []
for val in inlist:
if not val in newlist: newlist.append(val)
return newlist | bc45dda0fd87d0c1b72f05db4fe72e3b312fe40c | 638,160 |
def sig_indicator(pvalue):
"""Return a significance indicator string for the result of a t-test.
Parameters
----------
pvalue: float
the p-value
Returns
-------
str
`***` if p<0.001, `**` if p<0.01, `*` if p<0.05, `ns` otherwise.
"""
return (
'***' if p... | 51798d74afc6284c633d65a5ca89a9a421cab76b | 638,162 |
def is_left_censored(frange):
""" Returns true if the light curve is cutoff on the left. """
return 0 in frange | f34bee833fd2de57cd88504ded7c6791afe21503 | 638,163 |
import socket
def hostname_to_ip(servers):
""" Given (hostname, port) return (ip_address, port)
"""
reply = []
for server, port in servers:
ip_address = socket.gethostbyname(server)
reply.append((ip_address, port))
return reply | b9630d08e3f8daca280831230d65d2b5ec03d98c | 638,165 |
import argparse
import os
def parse_args():
"""
Use the inspector script indicating the config fil, path, format,
gpus to use and (optional) the output file name
python inspector_script.py -c config_file.json -d dataset_path -f parquet
-g "0,1,2,3,4" -o dataset_info.jso... | 212de3ed633338594986a6c9d313f214bf596ae0 | 638,166 |
def pop_key(data):
"""
Pop an item from the graph that has the fewest dependencies in the case of a tie
The winners will be sorted alphabetically
"""
items = sorted(data.items(), key=lambda item: (len(item[1]), item[0]))
key = items[0][0]
data.pop(key)
for dep in data.values():
... | cc0ce7fc97e4a2c4d6e22340110ca5ae6f90cdc6 | 638,167 |
import os
import json
def parse(version, endpoint_path):
"""Map an HTTP endpoint path to an API path"""
# Get possible paths
with open(os.path.join(os.path.dirname(__file__), '..', 'api', '{}', 'paths.json').format(version)) as paths_file:
paths = json.load(paths_file)
# Find API path that m... | c0477b26f446a66ceffca03aa76a39a2bbcc8a8c | 638,168 |
def local_node(conn):
"""Node environment context"""
return conn.prefix(
'export MANPATH=":." && source ~/.nvm/nvm.sh && nvm use'
) | d415d85a7e63cc217ed98c8888c06ffa0bb9df47 | 638,169 |
def tears(l, b, i):
""" Ỏ̷͖͈̞̩͎̻̫̫̜͉̠̫͕̭̭̫̫̹̗̹͈̼̠̖͍͚̥͈̮̼͕̠̤̯̻̥̬̗̼̳̤̳̬̪̹͚̞̼̠͕̼̠̦͚̫͔̯̹͉͉̘͎͕̼̣̝͙̱̟̹̩̟̳̦̭͉̮̖̭̣̣̞̙̗̜̺̭̻̥͚͙̝̦̲̱͉͖͉̰̦͎̫̣̼͎͍̠̮͓̹̹͉̤̰̗̙͕͇͔̱͕̭͈̳̗̭͔̘̖̺̮̜̠͖̘͓̳͕̟̠̱̫̤͓͔̘̰̲͙͍͇̙͎̣̼̗̖͙̯͉̠̟͈͍͕̪͓̝̩̦̖̹̼̠̘̮͚̟͉̺̜͍͓̯̳̱̻͕̣̳͉̻̭̭̱͍̪̩̭̺͕̺̼̥̪͖̦̟͎̻̰_á»"""
b.l_say(tears.__doc__, i)
return True | 6525e0100825ab22a187e9cc535e9e3724f74ebe | 638,170 |
def compact(sequence):
"""
Returns list of objects in sequence sans duplicates, where
s1 = (1, 1, (1,), (1,), [1], [1], None, '', 0)
compact(s1) == [[1], 1, 0, (1,), None, '']
"""
result = []
dict_ = {}
result_append = result.append
for i in sequence:
try:
dict_[i] = 1
... | 84be9004badbae5ceb9515e4f884ae878e610261 | 638,171 |
def next_exon(variant_position, coding_exon_starts):
"""
get location of next coding exon after variant
:param coding_exon_starts: coding exon start positions, Pandas Series.
:param variant_position: chromosomal position, int
:return: chromosomal position of start of next coding exon, int
"""
... | 92d875d90852491ccab66a503543d996aa90d48f | 638,173 |
def transpose(G):
"""Transpose graph."""
V, E = G; ET = {}
for u in V: ET[u] = []
for u, vs in E.items():
for v in vs: ET[v].append(u)
return (V, ET) | 2a7d3768569778275e4e64d62ae2eda02d5c080c | 638,174 |
from datetime import datetime
def get_week_of_month(year, month, day):
"""
获取指定的某天是某个月中的第几周
周一作为一周的开始
"""
end = int(datetime(year, month, day).strftime("%W"))
begin = int(datetime(year, month, 1).strftime("%W"))
star_date = end - begin + 1
if star_date == 1:
week_of = '# 第一周'
... | b119ab45bf08bea17e2ecfafa88db3438de64e94 | 638,176 |
import math
def numberOfDigits(tickSpacing):
"""Returns the number of digits to display for text label.
:param float tickSpacing: Step between ticks in data space.
:return: Number of digits to show for labels.
:rtype: int
"""
nfrac = int(-math.floor(math.log10(tickSpacing)))
if nfrac < 0:... | 95b2c16342b45616194a0c799cc02b5259093b18 | 638,177 |
def get_instance(Model, *lookups):
"""Helper function to search for model instance by a cascade of lookups"""
for kwargs in lookups:
qs = Model.objects.filter(**kwargs)
try:
return qs.get()
except Model.MultipleObjectsReturned:
return qs.last()
except Mode... | a68ab2a7d0c51f677468953f55697f84e06abcf8 | 638,178 |
def IsNumeric(value):
"""
* Determine if string is numeric.
"""
if not isinstance(value, str):
raise Exception('value must be a string.')
try:
valtxt = value
value = int(valtxt)
value = float(valtxt)
return True
except:
return False | 64e20550a237e60413d91ae25f22246a70035ef8 | 638,179 |
def get_cohypernyms(synset):
""" Cohypernyms are for exmaple:
A Legal Document and a Testimony are cohypernyms, because what is a Legal Document is possibly not a Testimony and
vice versa, but also that may possibly be the case.
Dog, Fish, Insect are no cohypernyms, because there is no entity, that is a... | 58045539a18aef3312ac6327829c63bf1dbed103 | 638,180 |
def get_A_sp_sh_JIS_A_4111(A):
"""太陽熱集熱部の有効集熱面積(IS A 4111)
Args:
A(float): 太陽熱集熱部総面積
Returns:
float: 太陽熱集熱部の有効集熱面積
"""
return A * 0.85 | c6bf8d615a4a3b838e012d79543fb5a7f33aad81 | 638,181 |
import torch
import math
def relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
"""
Adapted from Mesh Tensorflow:
https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
Tran... | 0b339513421c572d82d3ae4d8e06a1aed9d6bae3 | 638,182 |
def get_screen_name_to_player(players_dict):
"""Based on player-account assigments this function returns 'screen_name' -> schedule player name mapping."""
screen_name_to_player = {}
for player in players_dict:
for screen_name in players_dict[player]:
if screen_name in screen_name_to_play... | f3f6d1b1fd11cfc4d017c0812576903750445942 | 638,183 |
def data_context_path_computation_context_path_comp_serviceuuid_pathpath_uuid_get(uuid, path_uuid): # noqa: E501
"""data_context_path_computation_context_path_comp_serviceuuid_pathpath_uuid_get
returns tapi.path.computation.PathRef # noqa: E501
:param uuid: Id of path-comp-service
:type uuid: str
... | b61ca42e49cb137389f7c8981d7c55ebdf120756 | 638,184 |
def add_group(inventory, groupname, hostname=None):
"""Add a group to inventory, optionally add it with hostname."""
all_group = inventory["all"]
group = {}
if hostname:
group["hosts"] = {hostname: {}}
all_group["children"][groupname] = group
return group | 0332462667621dc4850eca045965d2ec9e7d587b | 638,185 |
def get_user_choice():
""" Gets and returns user input (user choice) from the user. """
return input("Please enter choice: ").upper() | 044ef5c20481a9a9365a4a8a06cb0536576d0937 | 638,186 |
def fmt_trace(val, missing, trace, _tzinfo):
"""Format precip."""
if val is None:
return missing
# careful with this comparison
if val < 0.009999 and val > 0:
return trace
return "%.2f" % (val, ) | 55d6210a6ca3dc66545058b489aa4103bb184278 | 638,187 |
import re
def alphanum_sort(l):
"""Sort the given list in ascending order the way that humans expect.
i.e For a list l containing `["5", "24", "10"]`, the function sorts it as
`["5", "10", "24"]` instead of `["10", "24", "5"]` as would Python List
sort() method.
"""
# key to use for the sort
... | 15b0c5dc44d841538896b4ec841c33ce54d7fdcb | 638,188 |
def get_function_zero(func, interval, accuracy):
"""计算函数的零点, 即一元方程f(x) = 0的近似解
依据和方法: 零点定理和二分法
Args:
func: 函数本身, 类型: python函数, 可以直接被调用, 相当于f(x), 传入x返回函数值
interval: 零点所在区间, 类型: 元组 假设为: (3, 6) 则首先保证: f(3) * f(6) < 0
accuracy: 精度, 当区间范围缩小至|a - b| < accuracy时, 即返回求解结果
Returns:
... | ac805efb6a809d9868e9c6b6e4df43ed24495682 | 638,189 |
def _format_optname(value):
"""Format the name of an option in the configuration file to a more
readable option in the command-line."""
return value.replace('_', '-').replace(' ', '-') | e12d0d27ed744d45d789f3e9e0207f04be9f5024 | 638,190 |
import ast
def safe_eval(source):
"""
Protected string evaluation.
Evaluate a string containing a Python literal expression without
allowing the execution of arbitrary non-literal code.
Parameters
----------
source : str
The string to evaluate.
Returns
-------
obj : ... | 023724d73c725286e9f632d5d2425a906dbda452 | 638,191 |
def lock_7(soup):
"""
<style>
.instructions { font-family: 'U2N9FUQA', 'Beth Ellen', cursive; }
</style>
"""
style_inner_html = soup.find('style').decode_contents()
# This returns something like ".instructions { font-family: 'VFYFYI08', 'Beth Ellen', cursive; }"
return style_inner_html.s... | e6060eb8395f2d175a10d852a0a206eaa2e3e527 | 638,192 |
def check_sentence_ending(sentence: str) -> bool:
"""Check if the sentence ends with a full stop.
:param sentence: str - a sentence to check.
:return: bool - True if punctuated correctly with period, False otherwise.
"""
return sentence.endswith(".") | 7350ea9e9a6ff9c9760ef1e200134771d33a3e32 | 638,193 |
def html_escape(t):
"""Convert special HTML characters ('&', '<', '>', '"', "'") in string to HTML-safe sequences.
>>> html_escape('<>"&')
'<>"&'
>>>
"""
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "&... | 1a4409b8bb68364400819bcdbf7d05626be0a297 | 638,194 |
def vote(neighbors):
"""Returns dictionary of the proportion of each instance in form
(instance, distance) tuples."""
total = 0
count = dict()
# Count all instances
for (instance, distance) in neighbors:
total += 1
if (instance in count):
count[instance] += 1
... | 8b36657e61641eb84fe7a15a831c06ee9a68db92 | 638,195 |
import os
def normalize(config, path):
"""Normalizes config inserting input and output parameters in FFmpeg command line.
Resolves relative paths in mask file.
:param config: config object
:param path: path to the file, where config was loaded from
:return: normalized config object
"""
f... | 182a5674dfe1fb6ada6d97c261479816eec45cf1 | 638,196 |
import io
def is_file_obj(filename: str) -> bool:
"""does this object behave like a file object?"""
return (
(hasattr(filename, 'read') and hasattr(filename, 'write'))
or isinstance(filename, (io.IOBase, io.StringIO))
) | 25554638a2bfee8fadf50961ea7f0debd3bcc6f0 | 638,197 |
def sort_index(list):
"""
Return the *indices* of the elements in an array in order from smallest
element to largest, e.g sort_index([3, -1, 1]) gives [1, 2, 0].
"""
x = zip(list, range(0, len(list)))
x = sorted(x, key=lambda x: x[0])
return map(lambda x: x[1], x) | 1ab35611dc0808602966fe4f33f06f9652c32762 | 638,198 |
def c_to_f(c):
"""
Convert celcius to fahrenheit
"""
return c * 1.8 + 32.0 | d96ee54e50b8fa8da348a6895e7da0b5b35e7c5f | 638,199 |
def find_prefix_suffix(text, start, end, inside):
"""Find the prefix and suffix separated by comment block."""
s = text.find(start)
if s == -1:
return None
e = text.find(end, s + len(start))
i = text.find(inside, s + len(start))
while e > 0 and (i == -1 or i > e):
s = text.find(s... | 5cfa5f1a448eebd11c2e245fbd261cde3eb65857 | 638,200 |
def format_locations(location : str):
"""
Takes string describing location and returns nicely formatted tuple
:param location: location string in the format 123..1234
:return: location tuple (123, 1234)
"""
return location.split("..") | 5fe299d68eddcd51ba5fc70b39d6b03c290928fd | 638,201 |
def query_member_presence_in_multiple_locations(d_map_macaddress_member_asns, s_macaddress, i_ingress_asn):
"""
Query the count of presence of a given macaddress and IXP member.
Goal to validate potential situations of IP Transport.
d_map_macaddress_member_asns { macaddress: [[asn_id, cf, ixp_id, prese... | 4f531c5d4bb4aca94536863387ce6299b37ca205 | 638,202 |
def login_required(func):
"""Decorator that redirects to the login page if you're not logged in."""
def login_wrapper(request, *args, **kwds):
""" login disabled till anonymous user is handled well
if users.get_current_user() is None:
return HttpResponseRedirect(
users.create_login_url(reque... | e4f875206112549f1b12c03f54eb334ec98bca8f | 638,203 |
def parm_is_time_dependent(parm):
"""Checks if parm is time-dependent.
"""
return parm.isTimeDependent() | 3166ad8ea301f208a8255e0658c091af102e1dc4 | 638,204 |
def num_swaps(A):
"""Given an array of integers from 0 to N-1, return number of swaps to sort."""
N = len(A)
seen = [False] * N
ct = 0
for i in range(N):
if not seen[i]:
idx = i
num = 0
while not seen[idx]:
num += 1
seen[id... | 8d83e12408b957fdd706b8217043937160614df8 | 638,205 |
from typing import Optional
from typing import Callable
from typing import Dict
def get_on_fit_config_fn(
lr_initial: float, timeout: Optional[int], partial_updates: bool
) -> Callable[[int], Dict[str, str]]:
"""Return a function which returns training configurations."""
def fit_config(rnd: int) -> Dict[... | f8e12b3bb3fb0eba56910a15d1778c113111f5fa | 638,206 |
def validate_rule(rule):
""" Validator for checking rules """
if rule not in ('simple', 'strict'):
return {'error': 'check_rule in not present in Post data'} | d735c73bd9c898508913dad568e379e144a54108 | 638,207 |
def detect_malicious_cells(formulae_cells):
"""
argument: output from detect_formulae()
returns: a list of formulae cells that are malicious
"""
danger_words = ['cmd','powershell','www','http','hyperlink','shell','bash','.exe','.sh','.bat','zsh','dash','ksh']
return [x for x in formulae_cells if... | 85d779d42cc5f3c5bddcff736bc8271486784d94 | 638,209 |
def extract_attr_val(attr_obj):
"""Return attribute value in the proper python format
INTERNAL, don't use directly
Use the class definition instead
Args:
attr_obj:
Returns:
"""
if not attr_obj.type in ("string", "int", "expr"):
raise RuntimeError("Wrong attribute type '%s... | 582aa50a076df528cccfc82138d5005f6090ad82 | 638,210 |
def insertion_sort(list):
"""
Complexity: Worst case O(N^2) when sorted backwards
Best Case O(N) when sorted
"""
for i in range(1,len(list)):
tmp = list[i]
j = i - 1
while j >= 0 and list[j] > tmp:
list[j+1] = list[j]
j -= 1
list[j+1] = tmp... | 3dd660146964020eda75d4446bd5b377c5ad7da8 | 638,211 |
import torch
def jvp(y, x, v, create_graph=False):
"""Jacobian-vector product dy/dx @ v.
Pass `create_graph=True` to allow backprop on output.
"""
return torch.autograd.grad(y.flatten(), x, v.flatten(),
retain_graph=True,
create_graph=create_graph,
only_inputs =True)[0] | 72268f65d450c389fcc5e78f2d9a8e3b84e45044 | 638,212 |
def extract_weeks_offset(tokens, end=None, key_tokens=(
'next', 'previous', 'last', 'upcoming', 'past', 'prev')):
"""Extract the number of week offsets needed.
>>> extract_weeks_offset(['next', 'next', 'week'])
(0, ['week'], 2)
>>> extract_weeks_offset(['upcoming', 'Monday'])
(0, ['Monday']... | 3bab6f12ec8ad94da6556e974694d0ca3335a6c5 | 638,213 |
from typing import OrderedDict
def bytes_as_dict(msg):
"""Parse CAM message to OrderedDict based on format /key:val.
Parameters
----------
msg : bytes
Sequence of /key:val.
Returns
-------
collections.OrderedDict
With /key:val => dict[key] = val.
"""
# decode byte... | 9ec86c892fcb8ae3078bca30b3e20e515d630f94 | 638,214 |
def extend(s, var, val):
"""
Given a dictionary s and a variable and value, this returns a new dict with
var:val added to the original dictionary.
>>> extend({'a': 'b'}, 'c', 'd')
{'a': 'b', 'c': 'd'}
"""
s2 = {a: s[a] for a in s}
s2[var] = val
return s2 | edeb7e151c50916c0b5e1a543a30a2b01cc6c5ab | 638,215 |
def sort_keys(keys):
"""
Specially designed for alignment datas
"""
ref = []
bi_align = []
hard = []
weight = []
for k in keys:
if 'ref' in k:
ref.append(k)
elif 'bi_align' in k:
bi_align.append(k)
elif '.hard' in k:
hard.append... | acc6360e1e71135b3d85d4c52d2858057689c980 | 638,216 |
def get_index(comparison, _not):
"""
:param comparison: diccionario con la comparación
:param _not: operación de la comparación asociada al not
:return: indice que indica en que posición se sitúa el número a comparar
"""
return 1 if _not is None and (
isinstance(comparison.get("args")[1... | e9649d0bc28910a0dc8cf3e81c95530344d2870f | 638,217 |
def metric_get_log(phase, epoch, epoch_loss, meter, start):
"""logging the metrics at the end of an epoch
Args:
phase:
epoch:
epoch_loss:
meter:
start:
Returns:
"""
dices, iou = meter.get_metrics()
dice, dice_neg, dice_pos = dices
print(
"Loss: %... | 4666bb32d841a91e9bb744a691428aafca8413d5 | 638,218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.