content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_user_message(message):
"""Check if the message is a message from the user"""
return (message.get('message') and
message['message'].get('text') and
not message['message'].get("is_echo")) | d3af3638857650b2da4196818e4800d04c969ae2 | 682,264 |
def _ToString(rules):
"""Formats a sequence of Rule objects into a string."""
return '[\n%s\n]' % '\n'.join('%s' % rule for rule in rules) | 927c6eb8d8dce8161ec9fb5db52da64837567b58 | 682,265 |
import requests
def gateway(self, IPFS_path: str, **kwargs):
"""
Retrieve an object from the IFPS gateway (useful if you do not want to rely on a public gateway, such as ipfs.blockfrost.dev).
https://docs.blockfrost.io/#tag/IPFS-Gateway
:param IPFS_path: Path to the IPFS object.
:type IPFS_path:... | 79597b1ea6699febeb93ceb216466aa3a3d358b2 | 682,266 |
def get_deep_value(key, params, default=None, deep=True):
""" Extract value from complex structure with deep search
:param key: special key, use '.' to separate different depth
:param params: origin data
:param default: default value if special key is not exists
:param deep: extract deep value
... | bb88eb5fd6a43dae5b65f3d5b5d62dbe1d060289 | 682,267 |
def select_best_model_from_results_df(results_df):
"""
Aggregates the result df extracted from a fitted grid search to return
the best parameters.
"""
first_agg_dict = {"params": "first", "perf": "mean"}
second_agg_dict = {"params": "first", "perf": "min"}
results_df = results_df.groupby([... | dd9f8dd571c621dc49b22d3ac94b62f854257a9d | 682,268 |
def get_lr(config, base_step):
"""dynamic learning rate generator"""
base_lr = config.lr
lr = []
now_lr = base_lr
for i in range(config.epoch_size):
if i % config.epoch_change == 0 and i != 0:
now_lr = now_lr / 10
for _ in range(base_step):
lr.append(now_lr)
... | 50105639f0c1cbdb351ed230c14d1f1c948af988 | 682,269 |
import json
def ipynb2markdown(ipynb):
"""
Extract Markdown cells from iPython Notebook
Args:
ipynb (str):
iPython notebook JSON file
Returns:
str: Markdown
"""
j = json.loads(ipynb)
markdown = ""
for cell in j["cells"]:
if cell["cell_type"] == "ma... | 3e9a8a74440bc261653a1093dedd5f28e82831be | 682,270 |
import torch
def torch_hamm_dist(A, B):
"""
Assuming that A and B have patterns as vectors when input.
The columns of what is returned will be A compared with everything in B.
Therefore the order of what comes first is important!
"""
assert len(A.shape) == len(B.shape), "Need for A and B to ... | ff7c3fda5f1d6c60664c065495b27f84d8f57e05 | 682,271 |
def ConvertWindowState(state):
"""Map a string representation of an activity window to a code for the
Cytoscape heat map
"""
stateMap = {"ambiguous": "", "inactive": "0",
"activation": "1", "inhibition": "-1"}
return stateMap[state] | 0f0f5f3b14f077336b447d30d81db42bf72192eb | 682,272 |
def get_target_shape(shape, size_factor):
"""
Given an shape tuple and size_factor, return a new shape tuple such that each of its dimensions
is a multiple of size_factor
:param shape: tuple of integers
:param size_factor: integer
:return: tuple of integers
"""
target_shape = []
fo... | 83c60a72e19cca5606995c9cdf324017156012ac | 682,273 |
def obj_to_str(obj):
""" get class string from object
Examples
--------
>>> print(obj_to_str([1,2,3]).split('.')[-1])
list
>>> import numpy as np
>>> print(obj_to_str(np.array([1,2,3])))
numpy.ndarray
"""
mod_str = obj.__class__.__module__
name_str = o... | 791a07e032bf1d7a24d664293ad42d9963c4d708 | 682,274 |
def format_row(row: list) -> list:
"""Format a row of scraped data into correct type
All elements are scraped as strings and should be converted to the proper format to be used. This converts the
following types:
- Percentages become floats (Ex: '21.5%' --> 0.215)
- Numbers become ints (Ex: '2020'... | eb4de7f8760ac706409e5f32de9427cb78fcc3db | 682,275 |
def count_in_progress(state, event):
"""
Count in-progress actions.
Returns current state as each new produced event,
so we can see state change over time
"""
action = event['action']
phase = event['phase']
if phase == 'start':
state[action] = state.get(action, 0) + 1
elif ... | 2b8badb80e7f6897945770f8271b550b4c1b6218 | 682,277 |
import json
def read_json(file):
"""read json file
"""
if isinstance(file, str):
file = open(file)
with file as f:
res = json.load(f)
return res | 44bc4a6881bc0afba8acf97856b0c430fe699a48 | 682,278 |
def is_draft(record, ctx):
"""Shortcut for links to determine if record is a draft."""
return record.is_draft | 246ed4e954daa693f6d128278fbeb89c914b5f1a | 682,279 |
def approx_equal(a_value: float, b_value: float, tolerance: float = 1e-4) -> float:
"""
Approximate equality.
Checks if values are within a given tolerance
of each other.
@param a_value: a value
@param b_value: b value
@param tolerance:
@return: boolean indicating values are with in gi... | e081bdd07c18a3163035028303e9707284f5a75a | 682,280 |
def create_zero_matrix(rows: int, columns: int) -> list:
"""
Creates a matrix rows * columns where each element is zero
:param rows: a number of rows
:param columns: a number of columns
:return: a matrix with 0s
e.g. rows = 2, columns = 2
--> [[0, 0], [0, 0]]
"""
if not isinstance(ro... | 4e4a759d318f33f962a1d924c4893d5af7043b94 | 682,281 |
def _fix_attribute_names(attrs, change_map):
"""
Change attribute names as per values in change_map dictionary.
Parameters
----------
:param attrs : dict Dict of operator attributes
:param change_map : dict Dict of onnx attribute name to mxnet attribute names.
Returns
-------
:retur... | 857c8e2eaf4652bb6a5f6207dd0a332ad43971cf | 682,282 |
import sys
def strand2int(row):
"""
returns 1 for positive strand, -1 for negative strand, 0 for ambiguous (anything else).
"""
if row['strand'] == '+':
return 1
elif row['strand'] == '-':
return -1
else:
print("Strand error: [{}], [{}]".format(row['ref_name'], row['str... | f86828fba472022a6b3fb439e86ffe87b18c51c8 | 682,283 |
def combine_result(par_result):
"""Combine results from each core.
Take the parallel resulting list and combine the entries so that a single
dictionary with the beginning/end indices and travel times for all
particles is returned as opposed to a list with one dictionary per
parallel process
**... | 5475ee3a2ba643b17fc1fd3f85678f882d8966d6 | 682,284 |
def build_table(
x,
perceiver,
tokenize,
indices,
indices_data,
device,
knn,
y=None,
ctx=None,
is_image=True,
return_images=False,
):
"""im2txt table."""
table = [" || "] * len(x)
x = perceiver.encode_image(x).float()
x /= x.norm(dim=-1, keepdim=True)
for ... | 86a099fb6b08e3cd003cd6424901aa6716198471 | 682,285 |
def _get_string_from_list(list_of_strings):
"""Takes a list of strings and returns a single concatenated string.
:param list_of_strings: A list of strings to be concatenated
:returns: Single string representing the concatenated list
"""
return b"".join(list_of_strings) | a2337dd0ba55d90c7659669af83528b347488a56 | 682,286 |
def strip_token(token) -> str:
"""
Strip off suffix substring
:param token: token string
:return: stripped token if a suffix found, the same token otherwise
"""
if token.startswith(".") or token.startswith("["):
return token
pos = token.find("[")
# If "." is not found
if po... | d8fe892b51f08b52a3de43acef7b636f553adc13 | 682,287 |
def str_to_tile_index(s, index_of_a = 0xe6, index_of_zero = 0xdb, special_cases = None):
"""
Convert a string to a series of tile indexes.
Params:
s: the string to convert
index_of_a: begining of alphabetical tiles
index_of_zero: begining of numerical tiles
special_cases: what to if a character is not alpha... | 2835743b026beb78edc561758bcffc19a87ff67e | 682,288 |
import numpy
def mix_x_and_y_and_call_f_with_float_inputs(func, x, y):
"""Create an upper function to test `func`, with inputs which are forced to be floats"""
z = numpy.abs(10 * func(x + 0.1))
z = z.astype(numpy.int32) + y
return z | 88511291dccb328ecbe26e1eec51aa80a7d25ce8 | 682,289 |
def _get_valid_string(section, option, provided):
"""Validates a string type configuration option.
Returns None by default if the option is unset.
"""
if provided is None:
return None
if not isinstance(provided, str):
error = "Value provided for '{0}: {1}' is not a valid string".f... | 4a71ea5bce59710c3eba7a4ff8b76550a4e85710 | 682,290 |
import argparse
def mk_arg_pars():
"""Create a comand line arg parse.
Returns:
dict: Argparse argument dictionary.
"""
parser = argparse.ArgumentParser(
description="Create Random Forest predictions from superpixel image and labelled training points"
)
parser.add_argument(
... | 34eef626631ae85e805cae006bf71e37772e9662 | 682,291 |
def num_of_words(line, context):
"""
a temporary feature to test the design
"""
return [('num_of_word', len(line.txt.split()))] | 95ece1c838a7e215691f33a852f2e04799160e6e | 682,292 |
def curl(U, V, pm, pn):
"""2D curl from C-grid velocity
rho-points have shape (jmax, imax)
U : U-component, velocity [m/s], shape[-2:] = (jmax, imax-1)
V : V-component, velocity [m/s], shape[-2:] = (jmax-1, imax)
pm : invers metric term X-direction [1/m], shape = (jmax, imax)
pn : invers metric... | 40f238eeb7836ccb5f92ed81ebb742900526ff69 | 682,293 |
import csv
def load_data(filename):
"""
Load shopping data from a CSV file `filename` and convert into a list of
evidence lists and a list of labels. Return a tuple (evidence, labels).
evidence should be a list of lists, where each list contains the
following values, in order:
- Administr... | 535072672faceda545f46793154b807f18fdd490 | 682,294 |
def edges_from_matchings(matching):
"""
Identify all edges within a matching.
Parameters
----------
matching : list
of all matchings returned by matching api
Returns
-------
edges : list
of all edge tuples
"""
edges = []
nodes = []
# only address highest... | 14932530bdb1f5e0796d8c7f33449bd830d3b129 | 682,295 |
def count_images(root):
"""estimate image number in the lif file"""
image_list = [x for x in root.iter('{http://www.openmicroscopy.org/Schemas/OME/2016-06}Image')]
return (len(image_list)) | 852f90ad02d1b02edd2afef19600e76df7ceb1d5 | 682,296 |
def find_faces_with_vertex(index, faces):
"""
For a given vertex, find all faces containing this vertex.
Note: faces do not have to be triangles.
Parameters
----------
index : integer
index to a vertex
faces : list of lists of three integers
the integers for each face are in... | e48f203aa27a38f118d7f7135f9f67166f451e0e | 682,297 |
def definitions_match(definition_objects, expected_descriptor):
"""
Return whether Definition objects have expected properties.
The order of the definitions, and their sources, may appear in any order.
expected_descriptor is a shorthand format, consisting of a list or tuple
`(definition_string, so... | 0ed29ae0666b78a0b99bf8295b64cad5ec4bfcb9 | 682,298 |
def punto_en_poligono(x, y, poligono):
"""Comprueba si un punto se encuentra dentro de un polígono
poligono - Lista de tuplas con los puntos que forman los vértices [(x1, x2), (x2, y2), ..., (xn, yn)]
"""
# print("x=", x)
# print("y=", y)
i = 0
j = len(poligono) - 1
# print("... | f2811689a04027b5cda7820d5014975d88405496 | 682,299 |
import re
def split_title(title):
"""Splits a title, or title and author, into individual words, probably."""
return re.split(r'[-\s,:;\(\)]', title) | b849f5ae60a31ac08f028fa174e8089058e4ca96 | 682,300 |
from typing import Pattern
import re
import fnmatch
def _glob_to_re(glob: str) -> Pattern[str]:
"""Translate and compile glob string into pattern."""
return re.compile(fnmatch.translate(glob)) | 663e78d54d8dd34a38f0919a190c2041db648e7e | 682,301 |
import socket
def get_my_ip():
"""
returns ip / hostname of current host
"""
return socket.gethostbyname(socket.gethostname()) | 4d0678a5f19439e256e22009de2bfeda41e84d1b | 682,302 |
import os
def delete_file(path):
"""
Deletes the specified file if it exists.
:param path: Path of the file to delete.
:return: True if the path was a file and was deleted.
"""
if os.path.isfile(path):
os.remove(path)
return True
return False | 172f27841a823a3ea4e157cfdcb8e161ba1d0133 | 682,304 |
def run_dir_name(run_num):
"""
Returns the formatted directory name for a specific run number
"""
return "run{:03d}".format(run_num) | ae70f534b0c62912956ac81d2d35751b1d78d176 | 682,305 |
def _and(x,y):
"""Return: x and y (used for reduce)"""
return x and y | 7255241213594425c9f7efcf5b7edaec56000deb | 682,306 |
import re
def as_24hr(time, include_separator=False):
"""Converts the time to a 24hr label.
Args:
time: (string) The time of day in HH:MM:SS format.
Returns:
Returns the PST label.
"""
if include_separator:
return time[:5]
return re.sub(r"[^\d]", "", time)[:4] | 155d7b7bcecfc9130c0695d75b1c34d0d26c320c | 682,307 |
import json
def update_sources(file):
"""Callback method for updating the sources options."""
with open(file) as f:
j = json.load(f)
return [[{'label' : jj['name'], 'value': jj['name']} for jj in j],
j[0]['name']] | 6339bc9500ac66abbda119212d9a612889a96f36 | 682,308 |
from typing import List
import os
def gen_sls_config_files(stage: str, region: str) -> List[str]:
"""Generate possible SLS config files names."""
names: List[str] = []
for ext in ["yml", "json"]:
# Give preference to explicit stage-region files
names.append(os.path.join("env", f"{stage}-{r... | a05d1783c225a3c247be9b70883d94a034467cd6 | 682,310 |
def compute_float(computer, name, value):
"""Compute the ``float`` property.
See http://www.w3.org/TR/CSS21/visuren.html#dis-pos-flo
"""
if computer['specified']['position'] in ('absolute', 'fixed'):
return 'none'
else:
return value | e4018f5370c967e11c253b8d9a7b5ef6629bde67 | 682,311 |
import argparse
def parse_forex_symbol(input_symbol):
"""Parses potential forex symbols"""
for potential_split in ["-", "/"]:
if potential_split in input_symbol:
symbol = input_symbol.replace(potential_split, "")
return symbol
if len(input_symbol) != 6:
raise argpar... | 37c596a62c7089477979b8b1f0b97ad5d735251e | 682,312 |
def get_policy(observations, hparams):
"""Get a policy network.
Args:
observations: Tensor with observations
hparams: parameters
Returns:
Tensor with policy and value function output
"""
policy_network_lambda = hparams.policy_network
action_space = hparams.environment_spec.action_space
retur... | b965235a3719eb946aff3a9877a8a12f7509b163 | 682,313 |
def get_description(desc_file_path):
"""read description from README.md"""
with open(desc_file_path, 'r', encoding='utf-8') as fstream:
description = fstream.read()
return description | 12ca88547e3314bb2d40867104742a70b14f69ea | 682,315 |
def get_columns(filters):
"""return columns based on filters"""
columns = [
{
"fieldname":"item",
"fieldtype":"Data",
"label":"Month",
"width":200
},
{
"fieldname":"in_qty",
"fieldtype":"Float",
"label":"In Qty",
... | 2ffe13cc03392342341e30b6a1cf8f1794b173a6 | 682,316 |
def extract_urls_metadata(urls_metadata_results):
"""
These columns are placed back into the urls_metadata dict for returning
in order to preserve backward compatibility. It's modular enough to be
easily changed in the future
"""
urls_metadata = {}
for url in urls_metadata_results:
t... | b1852be8673374953b0836bfd63e06dfbabe41f9 | 682,317 |
def qubit_init_check(function):
"""Decorator to check the arguments of initialization function in qubit class.
Arguments:
function {} -- The tested function
"""
def wrapper(self, alpha, beta):
"""Method to initialize an instance of the qubit class. The squared sum of alpha and beta... | 92d9ccdcfc8e668f7e28efda79039d1add63c496 | 682,319 |
from typing import Counter
def column_checker(chat_df, message_df, attachment_df, handle_df):
"""
Checks the columns of the major tables for any conflicting column names
:param chat_df: the chat table dataframe
:param message_df: the message table dataframe
:param attachment_df: the attachment tab... | 2ed34b903aeab58d0868ad3e067bf05ce5ed7634 | 682,320 |
def _IsMacro(command):
"""Checks whether a command is a macro."""
if len(command) >= 4 and command[0] == "MACRO" and command[2] == "=":
return True
return False | cbe72b9c0c3cbe5dcc85ddb0834a59a7020fc510 | 682,321 |
import json
from collections import defaultdict
def read_config_filters(file_config):
"""
Parse json file to build the filtering configuration
Args:
file_config (Path): absolute path of the configuration file
Returns:
combine (str):
filter_param (dict): {key:list o... | ed1b6dcad3cce6beaf3e7c5cf309afc1380b8f88 | 682,322 |
import warnings
def _split_sketch(text):
"""
Splits the model file between the main section and the sketch
Parameters
----------
text : string
Full model as a string.
Returns
-------
text: string
Model file without sketch.
sketch: string
Model sketch.
... | ab9b30e0873f70357a21b3491abd9eb68dd8c9cb | 682,323 |
import os
def walk(rootdir):
"""
Perform a directory walk
:param rootdir: Root directory of search
:returns: List of files
"""
flist = []
for root, dirs, files in os.walk(rootdir):
flist = flist + [os.path.join(root, x) for x in files]
return flist | d3291290c6ee6dcb95336bf02dab812ff706621c | 682,325 |
def simplify_fasta_keys(dictionary, how=('|',1)):
"""
In the fasta dictionary, change keys with split / selection
"""
new_dict = {}
for key in dictionary:
value = dictionary[key]
simpler_key = key.split(how[0])[how[1]]
new_dict[simpler_key] = value
return new_dict | ff6fbbd101590e834ec83e40f448563587f70c8a | 682,326 |
import pathlib
import re
def check_row_files():
"""Check for the existence of rows in the rows directory.
The files in this directory are serialized lists of aggregated movie reviews.
Returns the position of the user list to pick back up at."""
# If rows folder is empty, then return 0 (start at the be... | b17d30d4d4321062efea978475669db6efa9c709 | 682,327 |
def negate_conf(c):
"""Negate a line of configuration."""
return "no %s" % c | 8c57b2a464c14f36fc21f7b7b0b52ba9f09b633a | 682,328 |
import re
def check_spotify_link(link: str, patterns_list: list) -> bool:
"""
Handles all checks needed to vet user-entered Spotify links.
"""
is_match = False
# patterns_list contains a list of regex patterns for Spotify URLs
for pattern in patterns_list:
if re.search(pattern=patter... | 89a4f5b0aad728973cab17df236125183b5b982c | 682,329 |
def get_pts_desc_from_agent(val_agent, img, subpixel, patch_size, device="cpu"):
"""
pts: list [numpy (3, N)]
desc: list [numpy (256, N)]
"""
heatmap_batch = val_agent.run(img.to(device)) # heatmap: numpy [batch, 1, H, W]
# heatmap to pts
pts = val_agent.heatmap_to_pts()
# print("pts fr... | 406c08a23d1b4a105f68c3a5c4d895f4348bb538 | 682,330 |
from typing import Type
from enum import Enum
def _make_form_enum(enum_cls: Type[Enum]):
"""
Modify an :class:`Enum` class that uses int value to accept string value member.
Args:
enum_cls (Type[Enum]): An enum class.
Returns:
Type[Enum]: the modified enum class.
"""
def _m... | 023c1426f1e780ab8d33b43300a8cf1b0a81a6ee | 682,331 |
def input_s(prompt: str = "", interrupt: str = "", eof: str = "logout") -> str:
"""
Like Python's built-in ``input()``, but it will give a string instead of
raising an error when a user cancel(^C) or an end-of-file(^D on Unix-like
or Ctrl-Z+Return on Windows) is received.
prompt
The promp... | 13c648f3ed3c6c7e11c07d8bb0d42bce68fda24d | 682,332 |
import re
def instruction_decoder_name(instruction):
"""
Given an instruction with the format specified in ARMv7DecodingSpec.py
output a unique name that represents that particular instruction decoder.
"""
# Replace all the bad chars.
name = re.sub('[\s\(\)\-\,\/\#]', '_', instruction["name"])... | 237c036ed844fab8f4185f850faa7da3c1e513cb | 682,333 |
def fast_relpath_optional(path, start):
"""A prefix-based relpath, with no normalization or support for returning `..`.
Returns None if `start` is not a directory-aware prefix of `path`.
"""
if len(start) == 0:
# Empty prefix.
return path
# Determine where the matchable prefix ends.
pref_end = len... | c067cac0bf7b8a870f1984cf7c907dd4a5d49eb7 | 682,334 |
from typing import Optional
import requests
def get_def_tenant_id(sub_id: str) -> Optional[str]:
"""
Get the tenant ID for a subscription.
Parameters
----------
sub_id : str
Subscription ID
Returns
-------
Optional[str]
TenantID or None if it could not be found.
... | 2d21fb31bf71424b1fbb15771e4cfafe551871b5 | 682,335 |
import argparse
def setup_parser() -> argparse.ArgumentParser:
"""Return the parser of the CLI arguments"""
parser = argparse.ArgumentParser(
prog="battery_handyman",
description=(
"Checks battery status periodically"
" and react to it according to the provided configur... | 585e489031715c6cd5a133d5ecd99ff9c220b1e9 | 682,336 |
import asyncio
async def subprocess_run_async(*args, shell=False):
"""Runs a command asynchronously.
If ``shell=True`` the command will be executed through the shell. In that case
the argument must be a single string with the full command. Otherwise, must receive
a list of program arguments. Returns ... | c5d6d1e4f0a12062272ef45d230bd3f4e47180de | 682,337 |
from functools import reduce
def djb2(L):
"""
h = 5381
for c in L:
h = ((h << 5) + h) + ord(c) # h * 33 + c
return h
"""
return reduce(lambda h, c: ord(c) + ((h << 5) + h), L, 5381) | fef0331e6b7ca3b3f7b2cac097714cfcfc2b0a78 | 682,338 |
import argparse
def parse_args():
"""
Parse input positional arguments from command line
:return: args - parsed arguments
"""
parser = argparse.ArgumentParser('Sentiment Polarity Analyzer - Binary Logistic Regression')
parser.add_argument('formatted_train_input',help='path to the formatted tra... | 57c2b212d2961190c2c93971019b4d6f2991f9f5 | 682,340 |
def create_user(ssh_fn, name):
"""Create a user on an instance using the ssh_fn and name.
The ssh_fn is a function that takes a command and runs it on the remote
system. It must be sudo capable so that a user can be created and the
remote directory for the user be determined. The directory for the us... | 79fca1b6b49d46a231c9f7179b5e034f3722cbca | 682,341 |
def index():
"""
Index page of server, returns index.html.
"""
with open("index.html", "r") as f_obj:
return f_obj.read() | da72ce20218dd7cf3c24bfae31efd767b785246f | 682,342 |
def if_json_contain(left_json, right_json, op='strict'):
"""
判断一个 json 是否包含另外一个 json 的 key,并且 value 相等;
:param:
* left_json: (dict) 需要判断的 json,我们称之为 left
* right_json: (dict) 需要判断的 json,我们称之为 right,目前是判断 left 是否包含在 right 中
* op: (string) 判断操作符,目前只有一种,默认为 strict,向后兼容
:return:
... | 8b506318e6105ad484499ddb644088eb93aae843 | 682,343 |
import json
def events_post(body=None):
"""Creates a new event and returns it."""
result = {}
return json.dumps(result), 201 | c9177728bfe5991c253a2085772cc53cc19a684e | 682,344 |
import torch
def dot(f_lookup, f):
"""
Dot product kernel, essentially a cosine distance kernel without normalization.
Args:
f_lookup (FloatTensor): features of the lookup keys
f (FloatTensor): features of the value keys
Returns:
FloatTensor: the attention mask for each looku... | 20acac53e6b84f89ec6950710c2f4d95d2333ed5 | 682,345 |
from random import shuffle
def randomize_ietimes(times, ids = []):
"""
Randomize the times of the point events of all the ids that are given.
This randomization keeps the starting time of each individual and reshuffles
its own interevent times.
Parameters
----------
times : dictionary of l... | 29347060cf738ab82d8a6cfe24d22e5426c3dfa7 | 682,347 |
def write_csv_string(data):
"""
Takes a data object (created by one of the read_*_string functions).
Returns a string in the CSV format.
"""
data_return = ""
row_num = 0
#Building the string to return
#print('data',data)
for row in data:
data_return += ','.join(str(v) for v in data[row_num].values())
data_... | c26cc186dfd9232e5e83d56468d11481f0412500 | 682,348 |
def longest_sub_seq(text1, text2):
"""
Return longest sub sequence
:param text1: str
:param text2: str
:return: int
"""
_m = len(text1)
_n = len(text2)
_l = [[0 for _ in range(_n+1)] for _ in range(_m+1)]
for i in range(_m+1):
for j in range(_n+1):
if i == 0 o... | 7dd6f769d18db786e067f9a03f5717e12c0d0a54 | 682,349 |
def convert_list_to_string(input_list):
"""
Converts a list to a string with each value separated with a new paragraph
Parameters
----------
input_list : list
List of values
Returns
-------
output : str
String output with each value in `input_list` recorded
"""
... | fa2749d7738418244c1d09309adf7cc39cd3fbfb | 682,350 |
import pathlib
import hashlib
def get_hash(file_path):
"""Return sha256 hash of file_path."""
text = b""
if (path := pathlib.Path(file_path)).is_file():
text = path.read_bytes()
return hashlib.sha256(text).hexdigest() | 0afecdb34812dad7ad25509d9430235649a40e1f | 682,351 |
def pos_pow(self, p):
"""
Approximates self ** p by computing: :math:`x^p = exp(p * log(x))`
Note that this requires that the base `self` contain only positive values
since log can only be computed on positive numbers.
Note that the value of `p` can be an integer, float, public tensor, or
encr... | eda63d990f7f7cc008e2d15d29f4ce66b4c45ac2 | 682,352 |
def create_turbine(turbine_params):
""" create turbine object """
t = None
return t | aa0a0e7a06bdf6c5a8714605f54e3d94ede23fed | 682,353 |
import winreg
import os
def find_directory(filepath: str) -> str:
"""
Finds the downloads directory for active user if filepath is not set.
:param filepath: Filepath specified by the configuration file.
:type filepath: str
:raises FileNotFoundError: Error raised if the filepath is invalid.
:r... | 130ad1b03c13802a0025ebadd63e7d195fa96663 | 682,355 |
def format_3(value):
"""Round a number to 3 digits after the dot."""
return "{:.3f}".format(value) | 4d27bc15afe130444126e2f3a1149d1726a292f3 | 682,357 |
def get_only_first_stacktrace(lines):
"""Get the first stacktrace because multiple stacktraces would make stacktrace
parsing wrong."""
new_lines = []
for line in lines:
line = line.rstrip()
if line.startswith('+----') and new_lines:
break
# We don't add the empty lines in the beginning.
... | 2b7c0e126bddbad3008f2825a829d5d59df3e1f7 | 682,358 |
def get_match_length(almnt):
"""
Gets length of perfect matches from cigar string
"""
if almnt.cigar is None:
return 0
return sum(length for cigar, length in almnt.cigar if cigar == 0) | 6ff616afe398b57117245aec4e3987c9a57a74bb | 682,359 |
def bande_est_noire(nv):
"""
Determine si une bande est noire ou blanche a partir de
son numero
"""
return nv % 2 == 1 | 9fbde2bdc09d9f85f8aad0dd94fb6d06b8172627 | 682,360 |
import argparse
def arg_parse():
"""
Parse arguments to the detect module
"""
parser = argparse.ArgumentParser(description='Farsi digit Detection Network')
parser.add_argument("--cfg", dest='cfgfile', help=
"Config file",
default="cfg/architecture.cfg", type=str)
... | fa2b7ead131ac4766903674c13ccff713c483144 | 682,361 |
def updateBoundaryCond(presDomain,tempDomain,uVelDomain,vVelDomain):
"""
Inflow and top BC's do not change
Wall u, v and T do not change but pressure does
Outflow all values float
"""
# Wall
presDomain[1:,0] = 2*presDomain[1:,1] - presDomain[1:,2]
presDomain[1:,-1] = 2*presDomain[1:,-2] - presDomain[1:,-3]
# ... | c96cc47a53e0ad5557b55784fb1bd92414163138 | 682,362 |
import numpy
def _numpy_hook(obj):
"""If an object is a ufunc, return '<ufunc>'"""
if isinstance(obj, numpy.ufunc):
return '<ufunc>'
return None | 475db911efd822d195301526c812eee3e911312f | 682,363 |
def fmt(obj):
"""Value formatter replaces numpy types with base python types."""
if isinstance(obj, (str, int, float, complex, tuple, list, dict, set)):
out = obj
else: # else, assume numpy
try:
out = obj.item() # try to get value
except:
... | 1f655ca2c8a862368c8e826006074175599e0c16 | 682,364 |
def parse_charge(dL):
""" There are two options:
1) call FcM(**kwargs,fcs=[c1,c2,--cn]) with a list of length equal to the number of atoms
2) FcM(**kwargs,fcs=[[aidx1,aidx2,..,aidxn],[c1,c2,..cn]]) with a list of two sublist for atoms' indexes and fract charges
"""
a=[[],[]]
parsed=False
if... | 2af2af2d3993eda8b49ec2c3f8a7b42ab93b4548 | 682,365 |
def get_first_aligned_bp_index(alignment_seq):
"""
Given an alignment string, return the index of the first aligned,
i.e. non-gap position (0-indexed!).
Args:
alignment_seq (string): String of aligned sequence, consisting of
gaps ('-') and non-gap characters, such as "HA-LO" or "---... | d16331cb0cf6e94cfcb8aa04730520aeec915480 | 682,367 |
def check_hash(file_path, expected_hash, hasher):
"""
Checks a expected_hash of a file
:param file_path:
:param expected_hash:
:param hash_type:
:return:
"""
a_file = open(file_path, 'rb')
block_size = 65536
buf = a_file.read(block_size)
while len(buf) > 0:
hasher.upd... | a6e7480c91cec09478d94ac9b796c2647c1b1d00 | 682,368 |
def risingfactorial(n, m):
"""
Return the rising factorial; n to the m rising, i.e. n(n+1)..(n+m-1).
For example:
>>> risingfactorial(7, 3)
504
"""
r = 1
for i in range(n, n+m):
r *= i
return r | 7fef55ede604d8b5f576608c505edae56822857d | 682,369 |
def get_adoc_title(title: str, level: int) -> str:
"""Returns a string to generate a ascidoc title with the given title, and level"""
return " ".join(["="*level, title, '\n']) | 6d59042961df96d4d62ef9228c93a0023f67786d | 682,370 |
def _normalize_typos(typos, replacement_rules):
"""
Applies all character replacement rules to the typos and returns a new
dictionary of typos of all non-empty elements from normalized 'typos'.
"""
if len(replacement_rules) > 0:
typos_new = dict()
for key, values i... | fc47995303b00bc4d612a6a161dfad4c0bcd8e02 | 682,371 |
import csv
def create_idf_dict() -> dict:
"""Returns the idf_dict from tstar_idf.txt"""
with open("climate_keywords/tstar_idf.txt", "r", encoding='utf-8', errors='ignore') as f:
reader = csv.reader(f)
idf_dict = {}
for term, idf in reader:
idf_dict[term] = float(idf)
re... | 57a7d207d27159767de775720c520db09790a83c | 682,372 |
def is_bound(self):
"""
Determine if all the pointers are fully bound.
"""
for key in self._pointers_:
if getattr(self, key, None)==None:
return False
return True | 03d67cb5b01c39564f874942c6c6aaff1baf8dcf | 682,373 |
import re
def sanitize_json_string(string):
"""
Cleans up extraneous whitespace from the provided string so it may be
written to a JSON file. Extraneous whitespace include any before or after
the provided string, as well as between words.
Parameters
----------
string : str
The str... | 1c62bfc176674f378de3ecc42db629b8b71ccf7b | 682,374 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.