content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def findx(mu, lnum):
"""Obtains the Hill sphere and x-coordinate for a mu-value and lnum."""
hill = (mu/3)**(1.0/3.0)
if lnum == 1: #lnum is used to request one of the collinear Lagrange points.
guess = 1 - mu - hill * (1 - (1.0/3.0) * hill - (1.0/9.0) * hill ** 2)
elif lnum == ... | 5,348,000 |
def plot_op_states(
df: pd.DataFrame,
agent0: str,
agent1: str,
state: str,
level: int = 0,
agent: int = 0,
show: bool = True,
):
"""
df (ResultsDf): an outcome from the compete() function
agent0 (str): an agent name in the agent0 column in the df
agent1 (str): an agent name ... | 5,348,001 |
def _f1_div_ ( self , other ) :
"""Operator for ``1D-function / other''"""
return _f1_op_ ( self , other , Ostap.MoreRooFit.Division , "Divide_" ) | 5,348,002 |
def test_interrupted_late_wait():
"""Test we can interrupt the wait during the timeout period.
"""
called = 0
def cond():
nonlocal called
called += 1
if called == 3:
return True
job = InstrJob(cond, 0)
assert not job.wait_for_completion(lambda: True, refresh... | 5,348,003 |
def set_prior_6(para):
"""
set prior before the first data came in
doc details to be added
"""
n_shape = para['n_shape']
log_prob = [ [] for i_shape in range(n_shape) ]
delta_mean = [ [] for i_shape in range(n_shape) ]
delta_var = [ [] for i_shape in range(n_shape) ]
time_since_last... | 5,348,004 |
def inf_set_af2(*args):
"""
inf_set_af2(_v) -> bool
"""
return _ida_ida.inf_set_af2(*args) | 5,348,005 |
def showOverlapTable(modes_x, modes_y, **kwargs):
"""Show overlap table using :func:`~matplotlib.pyplot.pcolor`. *modes_x*
and *modes_y* are sets of normal modes, and correspond to x and y axes of
the plot. Note that mode indices are incremented by **1**. List of modes
is assumed to contain a set of ... | 5,348,006 |
def initdb(ctx):
"""Initialize database, dropping all tables"""
global STORAGE
app = ctx.obj
if STORAGE:
ctx.fail("Database already initialized.")
db.create_all()
if not app.config.get('USE_SQLITE'):
from alembic import command
command.stamp(ALEMBIC_CONFIG, 'head')
... | 5,348,007 |
def json_find_matches_dataframe(df, filter_path, reverse_selectivity=False):
"""Iteratively filters a pandas.DataFrame df using the same sort of
filter_path used by json_extract.
Because of the tabular nature of pandas DataFrames, filters are treated as
being either 'down' or 'check'; a filter e... | 5,348,008 |
def contrast(arr, amount=0.2, split=0.5, normalize=True):
"""
General contrast booster or diffuser of normalized array-like data.
Parameters
----------
arr : ndarray
Input array (of floats on range [0, 1] if ``normalize=False``). If
values exist outside this range, with ``normalize=... | 5,348,009 |
def get_group(items, total_groups, group_id):
"""
Get the items from the passed in group based on group size.
"""
if not 0 < group_id <= total_groups:
raise ValueError("Invalid test-group argument")
start, size = get_group_size_and_start(len(items), total_groups, group_id)
selected = it... | 5,348,010 |
def read_nq_entry(entry, is_training):
"""
Converts a NQ entry into a list of NqExamples.
:param entry: dict
:param is_training: bool
:return: list[NqExample]
"""
def is_whitespace(c):
return c in " \t\r\n" or ord(c) == 0x202F
examples = []
contexts_id = entry["id"]
con... | 5,348,011 |
def main():
"""
Main
"""
run_module() | 5,348,012 |
def calc_atoms(psi, vol_elem=1.0):
"""Calculate the total number of atoms.
Parameters
----------
psi : :obj:`list` of 2D NumPy :obj:`array` or PyTorch :obj:`Tensor`
The input spinor wavefunction.
vol_elem : :obj:`float`
2D volume element of the space.
Returns
-------
at... | 5,348,013 |
def get_tcp_packet_payload_len(pkt: dpkt.ethernet.Ethernet) -> int:
"""
Return the length of only payload without options
:param pkt: dpkt.ethernet.Ethernet packet containing TCP header
:return: int
"""
if isinstance(pkt, dpkt.ethernet.Ethernet):
ip = pkt.data
elif isinstance(pkt... | 5,348,014 |
def overviewUsage(err=''):
""" default overview information highlighting active scripts"""
m = '%s\n' %err
m += ' The following scripts allow you to manage Team Branches (TmB) on SalesForce.\n'
m += ' Use one of the scripts below to meet your needs.\n'
m += ' \n'
m += ' 1. First link T... | 5,348,015 |
def min_distance(z_i, z_j, sc_size):
"""Calculates the minimum distance between the particle at
``z_i`` and all of the images of the particle at ``z_j``,
including this. The minimum distance is always less than
half of the size of the simulation supercell ``sc_size``.
:param z_i:
:param z_j:
... | 5,348,016 |
def prf(gold: str, pred: str, dic) -> tuple:
"""
计算P、R、F1
:param gold: 标准答案文件,比如“商品 和 服务”
:param pred: 分词结果文件,比如“商品 和服 务”
:param dic: 词典
:return: (P, R, F1, OOV_R, IV_R)
"""
A_size, B_size, A_cap_B_size, OOV, IV, OOV_R, IV_R = 0, 0, 0, 0, 0, 0, 0
with open(gold,encoding='utf8') as gd... | 5,348,017 |
def lorem():
"""Returns some sample latin text to use for prototyping."""
return """
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nis... | 5,348,018 |
def read_gene2species(* filenames):
"""
Reads a gene2species file
Returns a function that will map gene names to species names.
"""
for filename in filenames:
maps = []
for filename in filenames:
maps.extend(util.read_delim(util.skip_comments(
util.open_... | 5,348,019 |
def ingest(
token: str,
endpoint: str,
method: str = "GET",
time_zone: str = "Asia/Tokyo",
params: Dict[Any, Any] = {},
data: Dict[Any, Any] = {},
) -> Optional[Dict[Any, Any]]:
"""情報を取得する
"""
url = path.join(GRAPH_ENDPOINT, endpoint)
headers = {
"Authorization": f"Beare... | 5,348,020 |
def make_list_table(headers, data, title='', columns=None):
"""Build a list-table directive.
:param headers: List of header values.
:param data: Iterable of row data, yielding lists or tuples with rows.
:param title: Optional text to show as the table title.
:param columns: Optional widths for the ... | 5,348,021 |
def toss_unbaised():
"""
toss 2 times:
assign 0-1 = 0
assign 1-0 = 1
discard 0-0 and 1-1
"""
while True:
first, second = toss_biased(), toss_biased()
if first == 0 and second == 1:
return 0
if first == 1 and second == 0:
return 1 | 5,348,022 |
def split_val_condition(input_string):
"""
Split and return a {'value': v, 'condition': c} dict for the value and the condition.
Condition is empty if no condition was found.
@param input A string of the form XXX @ YYYY
"""
try:
(value, condition) = [x.strip() for x in input_string.s... | 5,348,023 |
def autolabel(rects,ax,labels):
"""
Attach a text label above each bar displaying its height
"""
for i,rect in enumerate(rects):
height = rect.get_height()
# pdb.set_trace()
ax.text(rect.get_x() + rect.get_width()/2., 1.01*height,
labels[i],
ha='cen... | 5,348,024 |
def while_octagon():
"""printing shape of'octagon' using while loop"""
i=0
while i<7:
j=0
while j<7:
if j in(0,6) and i in(2,3,4) or i in(0,6) and j in(2,3,4) or j in(1,5) and i in(1,5) :
print("*",end=" ")
else:
print(" ",en... | 5,348,025 |
def shap_scatterplot(
sklearn_model: BaseEstimator,
X_explain: pd.DataFrame,
feature_labels: dict,
feature: str = "bac_guess",
moderator: Sequence[str] = "episode",
output_folder: str = "/mnt/data/figures/shap"
) -> None:
"""Partial Dependence Plot for SHAP
Args:
sklearn_m... | 5,348,026 |
def shimenreservoir_operation_rule_lower_limit():
"""
Real Name: ShiMenReservoir Operation Rule Lower Limit
Original Eqn: WITH LOOKUP ( Date, ([(1,190)-(366,250)],(1,240),(32,240),(152,220),(182,220),(244,225),(335,240),(365,\ 240) ))
Units: m
Limits: (None, None)
Type: component
... | 5,348,027 |
def pre_process(dd, df, dataset_len, batch_size):
"""Partition one dataframe to multiple small dataframes based on a given batch size."""
df = dd.str2ascii(df, dataset_len)
prev_chunk_offset = 0
partitioned_dfs = []
while prev_chunk_offset < dataset_len:
curr_chunk_offset = prev_chunk_offset... | 5,348,028 |
def after_hypothesis_control(context: Hypothesis, state: Dict[str, Any], **kwargs):
"""
Finishes the span created when the steady-state hypothesis began
"""
tracer = opentracing.global_tracer()
scope = tracer.scope_manager.active
span = scope.span
try:
if not span:
return... | 5,348,029 |
def fromisoformat(s):
"""
Hacky way to recover a datetime from an isoformat() string
Python 3.7 implements datetime.fromisoformat() which is the proper way
There are many other 3rd party modules out there, but should be good enough for testing
"""
return datetime(*map(int, re.findall('\d+', s))) | 5,348,030 |
def non_repeat(a, decimals=12):
"""
Функция возвращает матрицу А с различными строками.
"""
a = np.ascontiguousarray(a)
a = np.around(a, decimals = int(decimals))
_, index = np.unique(a.view([('', a.dtype)]*a.shape[1]), return_index=True)
index = sorted(index)
return a[index] | 5,348,031 |
def softmax_with_cross_entropy(predictions, target_index):
"""
Computes softmax and cross-entropy loss for model predictions,
including the gradient
Arguments:
predictions, np array, shape is either (N) or (batch_size, N) -
classifier output
target_index: np array of int, shape is (1... | 5,348,032 |
def scraper_main_olx(url):
""" Reads pages with offers from OLX and provides URLS to said offers. """
def __create_url_olx(offs_ids, prefix="https://www.olx.pl"):
""" Method creates an olx offer link from parts read from a main page. """
return [
"/".join([
prefix,
... | 5,348,033 |
async def test_user_ignore(
hass: HomeAssistant,
vizio_connect: pytest.fixture,
vizio_bypass_setup: pytest.fixture,
) -> None:
"""Test user config flow doesn't throw an error when there's an existing ignored source."""
entry = MockConfigEntry(
domain=DOMAIN,
data=MOCK_SPEAKER_CONFIG,... | 5,348,034 |
def process_sha1(dataset_infos):
"""Computes the SHA-1 hash of the datasets. Removes the datasets for which the SHA-1 hash is already in the database.
N.B.: a dataset for which the SHA-1 hash is not in the database represents a new dataset version.
:param datasets_infos: A list of DatasetInfos containing to... | 5,348,035 |
def accuracy(
output: torch.Tensor,
target: torch.tensor,
topk: Tuple[int] = (
1,
)) -> List[float]:
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)... | 5,348,036 |
def _make_unique(key, val):
"""
Make a tuple of key, value that is guaranteed hashable and should be unique per value
:param key: Key of tuple
:param val: Value of tuple
:return: Unique key tuple
"""
if type(val).__hash__ is None:
val = str(val)
return key, val | 5,348,037 |
def replace_caps(x):
"""Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before."""
res = []
for t in x:
if t == '': continue
if t[0].isupper():
if len(t) == 1 and t[0] == 'I':
res.append(TK_MAJ)
if len(t) > 1 and (t[1:].is... | 5,348,038 |
def logout():
"""
Deletes the .pypirc file with your login info.
Requires you to login again before uploading
another package.
"""
# delete the .pypirc file for better security
home = os.path.expanduser("~")
path = os.path.join(home, ".pypirc")
os.remove(path)
print("logged out ... | 5,348,039 |
def computes_ts_coverage(k, outputs, two_symbols):
""" Computes the input coverage by Two Symbol schematas.
Args:
k (int): the number of inputs.
outpus (list): the list of transition outputs.
two_symbols (list): The final list of Two Symbol permutable schematas. This is returned by `fin... | 5,348,040 |
def parse_NETU(
header: atop_helpers.Header,
record: atop_helpers.Record,
sstat: atop_helpers.SStat,
tstats: list[atop_helpers.TStat],
) -> dict:
"""Retrieves statistics for Atop 'NET' parseable representing network usage on upper interfaces."""
values = {
'timestamp': re... | 5,348,041 |
def create_measurements(nh, nv, offset, measurement_type):
"""Creates necessary measurement details for a given type on a given lattice.
Given the lattice size, whether odd or even pairs are being measured,
and the measurement type, this function returns a namedtuple
with the pairs of qubits to be meas... | 5,348,042 |
def headline(
in_string,
surround = False,
width = 72,
nr_spaces = 2,
spacesym = ' ',
char = '=',
border = None,
uppercase = True,
):
"""return in_string capitalized, spaced and sandwiched:
============================== T E S T... | 5,348,043 |
def do_performance_metric_get_os_and_kernel(cs, args):
"""Gets os and kernel information."""
if not args.server_id:
raise exceptions.CommandError("you need specify a server_id")
performance_metric = \
cs.performance_metrics.get_os_and_kernel(args.server_id)
if isinstance(performance_metr... | 5,348,044 |
def rainbow_cmd(bot, trigger):
"""Make text colored. Options are "rainbow", "usa", "commie", and "spooky"."""
text = clean(trigger.group(2) or '')
scheme = trigger.group(1).lower()
if not text:
try:
msg = SCHEME_ERRORS[scheme]
except KeyError:
msg = "How did you ... | 5,348,045 |
def url_decode(s, charset='utf-8', decode_keys=False, include_empty=True,
errors='ignore', separator='&', cls=None):
"""Parse a querystring and return it as :class:`MultiDict`. Per default
only values are decoded into unicode strings. If `decode_keys` is set to
`True` the same will happen f... | 5,348,046 |
def special_loader(as_type: type) -> Type[FullLoader]:
"""Construct new loader class supporting current class structure"""
class TypedLoader(FullLoader): # pylint: disable=too-many-ancestors
"""Custom loader with typed resolver"""
...
_add_path_resolvers(as_type, TypedLoader) # we need t... | 5,348,047 |
def test_invalid_subsample_ratio_warning():
"""Assert that the TPOT intitializes raises a ValueError when subsample ratio is not in the range (0.0, 1.0]."""
# Invalid ratio
tpot_obj = TPOTClassifier(subsample=0.0)
assert_raises(ValueError, tpot_obj._fit_init)
# Valid ratio
TPOTClassifier(subsamp... | 5,348,048 |
def listVotes(bot, trigger):
"""Listar las propuestas hechas."""
plugins_info = bot.db.get_plugin_value(PLUGIN_INFO, "list", [])
if (plugins_info != []):
plugins_info = json.loads(plugins_info)
id = 0
for voteName in plugins_info:
id += 1
vote_info = json.loads(bot.db.get_p... | 5,348,049 |
def try_(func, *args, **kwargs):
"""Try to call a function and return `_default` if it fails
Note: be careful that in order to have a fallback, you can supply
the keyword argument `_default`. If you supply anything other
than a keyword arg, it will result in it being passed to the wrapped
function a... | 5,348,050 |
def _create_course_and_cohort_with_user_role(course_is_cohorted, user, role_name):
"""
Creates a course with the value of `course_is_cohorted`, plus `always_cohort_inline_discussions`
set to True (which is no longer the default value). Then 1) enrolls the user in that course,
2) creates a cohort that th... | 5,348,051 |
def relative_vorticity(
u, v, wrap=None, one_sided_at_boundary=False, radius=6371229.0, cyclic=None
):
"""Calculate the relative vorticity using centred finite
differences.
The relative vorticity of wind defined on a Cartesian domain (such
as a plane projection) is defined as
ζcartesian = δv... | 5,348,052 |
def coalesce(
edge_index: torch.Tensor,
edge_attr: _typing.Union[
torch.Tensor, _typing.Iterable[torch.Tensor], None
] = None,
num_nodes: _typing.Optional[int] = ...,
is_sorted: bool = False,
sort_by_row: bool = True
) -> _typing.Union[
torch.Tensor, _typi... | 5,348,053 |
def get_label_names(l_json):
"""
Get names of all the labels in given json
:param l_json: list of labels jsons
:type l_json: list
:returns: list of labels names
:rtype: list
"""
llist = []
for j in l_json:
llist.append(j['name'])
return llist | 5,348,054 |
def init_asl_derivatives_wf(
bids_root,
metadata,
output_dir,
spaces,
scorescrub=False,
basil=False,
name='asl_derivatives_wf',
):
"""
Set up a battery of datasinks to store derivatives in the right location.
Parameters
----------
bids_root : :obj:`str`
Original ... | 5,348,055 |
def makehash(w=dict):
"""autovivification like hash in perl
http://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-python
use call it on hash like h = makehash()
then directly
h[1][2]= 3
useful ONLY for a 2 level hash
"""
# return defaultdict(m... | 5,348,056 |
def sample_parameters(kmodel,
tmodel,
individual,
param_sampler,
scaling_parameters,
only_stable=True,
):
"""
Run sampling on first order model
"""
solution_raw = individu... | 5,348,057 |
def load_yaml(fpath):
""" load settings from a yaml file and return them as a dictionary """
with open(fpath, 'r') as f:
settings = yaml.load(f)
return settings | 5,348,058 |
def recommendation(agent, other_agent, resource_id, scale, logger, discovery, recency_limit):
"""
Get recommendations on other agent of third agents and average them to one recommendation value.
:param agent: The agent which calculates the popularity.
:type agent: str
:param other_agent: The other ... | 5,348,059 |
def do_predictions_mhctools(work_item_dicts, constant_data=None):
"""
Each tuple of work items consists of:
(work_item_num, peptides, alleles)
"""
# This may run on the cluster in a way that misses all top level imports,
# so we have to re-import everything here.
import time
import nu... | 5,348,060 |
def inceptionresnetv2(**kwargs):
"""
InceptionResNetV2 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for mod... | 5,348,061 |
def convertStringToSysEncoding(strng):
"""
Convert a string to the current platform file system encoding.
Returns the new encoded string.
:Args:
strng: string
String to convert.
"""
if type(strng) not in [bytes_t, unicode_t]:
strng = strng.decode("utf-8")
strn... | 5,348,062 |
def _n_pow_i(a, b, n):
"""
return (1+i)**k
"""
x = a
y = b
for i in range(1, n):
x1 = (x*a) - (y*b)
y1 = (y*a) + (x*b)
x = x1
y = y1
return x, y | 5,348,063 |
async def get_group(msg):
"""Смена этапа на изменение группы."""
await msg.edit_text(
text="*Выберите группу:*", reply_markup=kb.group_keyboard(msg.chat.id)
) | 5,348,064 |
def IsNameBased(link):
"""Finds whether the link is name based or not
:param str link:
:return:
True if link is name-based; otherwise, False.
:rtype: boolean
"""
if not link:
return False
# trimming the leading "/"
if link.startswith("/") and len(link) > 1:
lin... | 5,348,065 |
def scrape_number_of_skins(names, save=True):
"""
Scrapes number of champion skins from League of Legends Wiki and saves
them to a csv file, but returns nothing
Parameters
----------
names : pandas series
Contains the champion names as strings in alphabetical order
save : ... | 5,348,066 |
def register_submit(class_name, fire) -> None:
"""
Register on a form a handler
:param class_name: class name of the form
:param fire: function that will be fire on form submit
:return: None
"""
def submit_handler(event) -> None:
"""
Handle form submit and fire handler
... | 5,348,067 |
def compile(obj: Any) -> Definition:
"""Extract a definition from a JSON-like object representation."""
return ConcreteValue(obj) | 5,348,068 |
def policy_network(vocab_embed_variable, document_placeholder, label_placeholder):
"""Build the policy core network.
Args:
vocab_embed_variable: [vocab_size, FLAGS.wordembed_size], embeddings without PAD and UNK
document_placeholder: [None,(FLAGS.max_doc_length + FLAGS.max_title_length + FLAGS.max_image... | 5,348,069 |
def get_feature(file_path: str):
""" Read and parse given feature file"""
print('Reading feature file ', file_path)
file_obj = open(file_path, "r")
steam = file_obj.read()
parser = Parser()
return parser.parse(TokenScanner(steam)) | 5,348,070 |
def hough_lines_draw(img, outfile, peaks, rhos, thetas):
"""
Returns the image with hough lines drawn.
Args
- img: Image on which lines will be drawn
- outfile: The output file. The file will be saved.
- peaks: peaks returned by hough_peaks
- rhos: array of rhos used in Hough Sp... | 5,348,071 |
def cg_file_h(tmpdir):
"""Get render config."""
return {
'cg_file': str(tmpdir.join('muti_layer_test.hip'))
} | 5,348,072 |
def test_enabled():
"""
Test to verify that the service is enabled
"""
ret = {"changes": "saltstack", "comment": "", "name": "salt", "result": True}
mock = MagicMock(return_value={"changes": "saltstack"})
with patch.object(service, "_enable", mock):
assert service.enabled("salt") == ret
... | 5,348,073 |
def tags(ui, repo):
"""list repository tags
This lists both regular and local tags. When the -v/--verbose
switch is used, a third column "local" is printed for local tags.
"""
hexfunc = ui.debugflag and hex or short
tagtype = ""
for t, n in reversed(repo.tagslist()):
if ui.quiet:
... | 5,348,074 |
def core_profiles_currents(
ods,
time_index=None,
rho_tor_norm=None,
j_actuator='default',
j_bootstrap='default',
j_ohmic='default',
j_non_inductive='default',
j_total='default',
warn=True,
):
"""
This function sets currents in ods['core_profiles']['profiles_1d'][time_index]
... | 5,348,075 |
def group_by_until(
key_mapper: Mapper[_T, _TKey],
element_mapper: Optional[Mapper[_T, _TValue]],
duration_mapper: Callable[[GroupedObservable[_TKey, _TValue]], Observable[Any]],
subject_mapper: Optional[Callable[[], Subject[_TValue]]] = None,
) -> Callable[[Observable[_T]], Observable[GroupedObservable... | 5,348,076 |
def GetFilesystemSize(options, image_type, layout_filename, num):
"""Returns the filesystem size of a given partition for a given layout type.
If no filesystem size is specified, returns the partition size.
Args:
options: Flags passed to the script
image_type: Type of image eg base/test/dev/factory_inst... | 5,348,077 |
def match_pairs(obj_match, params):
""" Matches objects into pairs given a disparity matrix and removes
bad matches. Bad matches have a disparity greater than the maximum
threshold. """
# Create a list of sets, where the i-th set will store the objects
# from image1 that have merged with objects in... | 5,348,078 |
def test_handle_response_for_invalid_content(mock_get, response_dir):
"""If invalid content is returned, store warning log entry"""
# arrange
url = 'http://digital.bibliothek.uni-halle.de/hd/oai/?verb=GetRecord&metadataPrefix=mets&mode=xml&identifier=foo'
mock_get.return_value.status_code = 200
moc... | 5,348,079 |
def spike_train_convolution(spike_times, interval, dt, sigma):
"""
Needed for Schreiber reliability measure
"""
N = int(np.floor((interval[1]-interval[0])/dt)+1)
x = np.linspace(interval[0], interval[1], N)
s = np.zeros(N)
for spike in spike_times:
s = s + gaussian(x, spike, sigma)
... | 5,348,080 |
def part_4() -> None:
"""
Spam Classification:
- Preprocessing emails.
- Making a vocabulary list.
- Extracting features from emails.
- Training SVM for spam classification.
Returns:
None
"""
vocabulary = readers.read_vocabulary(DATA_PATH_5)
tokens = readers.read_tokens(DA... | 5,348,081 |
def p_shift_expression(p):
"""shift_expression : additive_expression
| shift_expression LEFT_OP additive_expression
| shift_expression RIGHT_OP additive_expression"""
if len(p) == 2:
p[0] = p[1]
else:
fname, entry, args = resolve_function_name_uniform_types(p[2], [p[1], p[3]])
... | 5,348,082 |
def touch(file):
"""
update a file's access/modifications times
Attempts to update the access/modifications times on a file. If the file
does not exist, it will be created. This utility call operates in the same
fashion as the ``touch`` system command.
An example when using in the context of s... | 5,348,083 |
def interpolate_peak(spectrum: list, peak: int) -> float:
""" Uses quadratic interpolation of spectral peaks to get a better estimate of the peak.
Args:
- spectrum: the frequency bin to analyze.
- peak: the location of the estimated peak in the spectrum list.
Based off: htt... | 5,348,084 |
def _check_trunk_switchport(
dut, check, expd_status: SwitchportTrunkExpectation, msrd_status: dict
) -> tr.CheckResultsCollection:
"""
This function validates a trunk switchport against the expected values.
These checks include matching on the native-vlan and trunk-allowed-vlans.
"""
results =... | 5,348,085 |
def is_valid_compressed(file):
"""Check tar gz or zip is valid."""
try:
archive = ZipFile(file, 'r')
try:
corrupt = archive.testzip()
except zlib_error:
corrupt = True
archive.close()
except BadZipfile:
corrupt = True
return not corrupt | 5,348,086 |
def Krsol_SP_pt(SP,pt):
"""
Krsol_SP_pt solubility of Kr in seawater
==========================================================================
USAGE:
Krsol = sol.Krsol_SP_pt(SP,pt)
DESCRIPTION:
Calculates the krypton, Kr, concentration expected at equil... | 5,348,087 |
def get_node_element(tree_element, tag, key=None):
"""
FIXME: This is an ugly function that should be refactored. It wqs written to create the same
function for getting either an attribute or a subelement for an element.
:param tree_element: Element object from the ElementTree package
:param tag:... | 5,348,088 |
def UseNetwork(weights_f, load_weights=False):
"""Use DenseModel.
Args:
weights_f: weight file location.
load_weights: load weights when it is True.
"""
model = QDenseModel(weights_f, load_weights)
batch_size = BATCH_SIZE
(x_train_, y_train_), (x_test_, y_test_) = mnist.load_data()
x_train_ = x... | 5,348,089 |
def find_title(item):
"""Title of the video"""
title = item['snippet']['title']
return title | 5,348,090 |
def calc_fingerprint(text):
"""Return a hex string that fingerprints `text`."""
return hashlib.sha1(text).hexdigest() | 5,348,091 |
def yolo_collate_fn(
batch: List[Any],
) -> Tuple[Tensor, Tuple[Tensor, Tensor, List[Tuple[Tensor, Tensor]]]]:
"""
Collate function to be used for creating a DataLoader with values for Yolo model
input.
:param batch: a batch of data points and annotations transformed by
bounding_box_and_lab... | 5,348,092 |
def delete_category(category_id):
"""Delete a category."""
category = session.query(Category).filter_by(id=category_id).first()
if 'username' not in login_session:
flash("Please log in to continue.")
return redirect(url_for('login'))
if not exists_category(category_id):
flash(... | 5,348,093 |
def ec2_add_priv_launch_key(argument_table, operation_model, session,
**kwargs):
"""
This handler gets called after the argument table for the
operation has been created. It's job is to add the
``priv-launch-key`` parameter.
"""
argument_table['priv-launch-key'] = La... | 5,348,094 |
def get_all_users_of(fx_module: GraphModule, index: int) -> List[int]:
"""Given the graph(fx_module) and an index, return a list of all node indexes that use this node"""
graph = fx_module.graph
current_node = graph.nodes[index]
user_indexes: List[int] = []
"""if the node A is in node B's args, then... | 5,348,095 |
def insert_from(
table_name, into_table_name, column_names=None, join_columns=None, create_if_not_exists=False, engine=None
):
"""
Inserts records from one table into another
:param table_name: the name of the table from which to insert records
:param into_table_name: the name of the table into whi... | 5,348,096 |
def format(color, style=''):
"""Return a QTextCharFormat with the given attributes.
"""
_color = QColor()
_color.setNamedColor(color)
_format = QTextCharFormat()
_format.setForeground(_color)
if 'bold' in style:
_format.setFontWeight(QFont.Bold)
if 'italic' in style:
_fo... | 5,348,097 |
def array_to_mincvolume(filename, array, like,
volumeType=None, dtype=None, labels=None,
write=True, close=False):
"""
Create a mincVolume from a data array.
Create a mincVolume from a data array, using coordinate system information from another volume.
... | 5,348,098 |
def getRandomPipe():
"""returns a randomly generated pipe"""
# y of gap between upper and lower pipe
gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE))
gapY += int(BASEY * 0.2)
pipeHeight = IMAGES['pipe'][0].get_height()
pipeX = SCREENWIDTH + 10
return [
{'x': pipeX... | 5,348,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.