content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def SMLB(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
"""
Taken from Minerbo, G. N. and Levy, M. E., "Inversion of Abel’s integral equation by means of orthogonal polynomials.",
SIAM J. Numer. Anal. 6, 598-616 and swapped to satisfy SMLB(0) = 0.
"""
return (np.where((x > 0.00000000001),... | 27,000 |
def add_colon(in_str):
"""Add colon after every 4th character."""
return ':'.join([in_str[i:i+4] for i in range(0, len(in_str), 4)]) | 27,001 |
def fetch_partial_annotations():
""" Returns the partial annotations as an array
Returns:
partial_annotations: array of annotation data - [n_annotations, 5]
row format is [T, L, X, Y, Z]
"""
raw_mat = loadmat(PARTIAL_ANNOTATIONS_PATH)
annotations = raw_mat['divisionAnnotations']
#... | 27,002 |
def get_historical_tweets(query: str, start_date: str, end_date: str, top_only=True, max_tweets=1000):
"""
start_date ex: 2020-06-01
end_date ex: 2020-06-15
"""
tweetCriteria = got.manager.TweetCriteria()\
.setQuerySearch(query)\
.setTopT... | 27,003 |
async def test_download_diagnostics(hass, hass_client):
"""Test record service."""
assert await get_diagnostics_for_config_entry(
hass, hass_client, "fake_integration"
) == {"hello": "info"} | 27,004 |
def initialize_program():
""" Get REST configuration
"""
global CONFIG
data = call_responder('config', 'config/rest_services')
CONFIG = data['config'] | 27,005 |
def get_alt_pos_info(rec):
"""Returns info about the second-most-common nucleotide at a position.
This nucleotide will usually differ from the reference nucleotide, but it
may be the reference (i.e. at positions where the reference disagrees with
the alignment's "consensus").
This breaks ties arbi... | 27,006 |
def accuracy(output, target, topk=(1,)):
""" 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)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct ... | 27,007 |
def post(out):
""" Posts a request to the slack webhook. Payload can be customized
so the message in slack is customized. The variable out is the text
to be displayed.
"""
payload = {
"attachments": [
{
"title": "THANKS FOR THE RIDE!",
"te... | 27,008 |
def main():
"""Main function"""
# Parse arguments from command line
parser = argparse.ArgumentParser(description='Check value of last-modified date header for list of URLs')
args = parseCommandLine(parser)
fileIn = args.fileIn
fileOut = args.fileOut
separator = ","
# Read input file
... | 27,009 |
def grim(n, mu, prec=2, n_items=1):
"""
Test that a mean mu reported with a decimal precision prec is possible, given a number of observations n and a
number of items n_items.
:param n: The number of observations
:param mu: The mean
:param prec: The precision (i.e., number of decimal places) of... | 27,010 |
def split_dataframe(df:pd.DataFrame,split_index:np.ndarray):
"""
Split out the continuous variables from a dataframe \n
Params:
df : Pandas dataframe
split_index : Indices of continuous variables
"""
return df.loc[:,split_index].values | 27,011 |
def user_select_columns():
"""
Useful columns from the users table, omitting authentication-related
columns like password.
"""
u = orm.User.__table__
return [
u.c.id,
u.c.user_name,
u.c.email,
u.c.first_name,
u.c.last_name,
u.c.org,
u.c.cre... | 27,012 |
def remove_query_param(url, key):
"""
Given a URL and a key/val pair, remove an item in the query
parameters of the URL, and return the new URL.
"""
(scheme, netloc, path, query, fragment) = urlparse.urlsplit(url)
query_dict = urlparse.parse_qs(query)
query_dict.pop(key, None)
query = ur... | 27,013 |
def test_ap_hs20_sim(dev, apdev):
"""Hotspot 2.0 with simulated SIM and EAP-SIM"""
if not hlr_auc_gw_available():
return "skip"
hs20_simulated_sim(dev[0], apdev[0], "SIM")
dev[0].request("INTERWORKING_SELECT auto freq=2412")
ev = dev[0].wait_event(["INTERWORKING-ALREADY-CONNECTED"], timeout=... | 27,014 |
def FreshReal(prefix='b', ctx=None):
"""Return a fresh real constant in the given context using the given prefix.
>>> x = FreshReal()
>>> y = FreshReal()
>>> eq(x, y)
False
>>> x.sort()
Real
"""
ctx = _get_ctx(ctx)
return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ct... | 27,015 |
def ndim_rectangles_integral(
# main args
func,
up_limits,
low_limits,
ndim,
nsamples=10000,
args_func = {},
... | 27,016 |
def expand_inhomog_tuple_assignments(block, language_has_vectors = False):
"""
Simplify expressions in a CodeBlock by unravelling tuple assignments into multiple lines
Parameters
==========
block : CodeBlock
The expression to be modified
Examples
--------
>>> from ... | 27,017 |
def handle_readable(client):
"""
Return True: The client is re-registered to the selector object.
Return False: The server disconnects the client.
"""
data = client.recv(1028)
if data == b'':
return False
client.sendall(b'SERVER: ' + data)
print(threading.active_count())
ret... | 27,018 |
def test_referencelibrary_construction_list():
"""Check that we construct reference library where sub-props are lists."""
book = ReferenceBook("a")
library = ReferenceLibrary(books=[book])
assert library.books == [book] | 27,019 |
def fund_wallet():
"""
---
post:
summary: fund a particular wallet
description: sends funds to a particular user given the user id the amount will be
removed from the wallet with the respective currency, if not it falls to the default wallet.
if the sender is admin no money will... | 27,020 |
def create_objective(dist, abscissas):
"""Create objective function."""
abscissas_ = numpy.array(abscissas[1:-1])
def obj(absisa):
"""Local objective function."""
out = -numpy.sqrt(dist.pdf(absisa))
out *= numpy.prod(numpy.abs(abscissas_ - absisa))
return out
return obj | 27,021 |
def get_party_to_seats(year, group_id, party_to_votes):
"""Give votes by party, compute seats for party."""
eligible_party_list = get_eligible_party_list(
group_id,
party_to_votes,
)
if not eligible_party_list:
return {}
n_seats = YEAR_TO_REGION_TO_SEATS[year][group_id]
... | 27,022 |
def get_product(name, version):
"""Get info about a specific version of a product"""
product = registry.get_product(name, version)
return jsonify(product.to_dict()) | 27,023 |
def test_extract_fields() -> None:
""" Test extract_fields """
assert extract_fields([], [0]) == []
assert extract_fields(['abc', 'def'], [0]) == ['abc']
assert extract_fields(['abc', 'def'], [1, 0, 2]) == ['def', 'abc'] | 27,024 |
def _is_segment_in_block_range(segment, blocks):
"""Return whether the segment is in the range of one of the blocks."""
for block in blocks:
if block.start <= segment.start and segment.end <= block.end:
return True
return False | 27,025 |
def acrobatic(m):
"""More power and accuracy at the cost of increased complexity; can stun"""
if 'do_agility_based_dam' in m['functions'] or 'do_strength_based_dam' in m['functions']:
return None
if 'takedown' in m['features']:
return None
m = m.copy()
mult(m, 'stam_cost', 1.25)
... | 27,026 |
def systemd(config, args):
""" Build and install systemd scripts for the server """
try:
config = load_config(args.cfg_file, explicit=True)
except (OSError, configparser.ParsingError) as exc:
print(exc, file=sys.stderr)
return 1
print("Building systemd services")
using_venv... | 27,027 |
def load_graph(filename):
"""Unpersists graph from file as default graph."""
with tf.gfile.FastGFile(filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='') | 27,028 |
def compute_snes_color_score(img):
""" Returns the ratio of SNES colors to the total number of colors in the image
Parameters:
img (image) -- Pillow image
Returns:
count (float) -- ratio of SNES colors
"""
score = _get_distance_between_palettes(img, util.get_snes_color_p... | 27,029 |
def get_assignments_for_team(user, team):
""" Get openassessment XBlocks configured for the current teamset """
# Confirm access
if not has_specific_team_access(user, team):
raise Exception("User {user} is not permitted to access team info for {team}".format(
user=user.username,
... | 27,030 |
def is_flexible_uri(uri: Uri_t) -> bool:
"""Judge if specified `uri` has one or more flexible location.
Args:
uri: URI pattern to be judged.
Returns:
True if specified `uri` has one or more flexible location,
False otherwise.
"""
for loc in uri:
if isinstance(loc, F... | 27,031 |
def load_frame_gray(img_path, gray_flag=False):
"""Load image at img_path, and convert the original image to grayscale if gray_flag=True.
Return image and grayscale image if gray_flag=True; otherwise only return original image.
img_path = a string containing the path to an image file readable by cv.imread
... | 27,032 |
def read_vocab_file(path):
""" Read voc file.
This reads a .voc file, stripping out empty lines comments and expand
parentheses. It returns each line as a list of all expanded
alternatives.
Args:
path (str): path to vocab file.
Returns:
List of List... | 27,033 |
def release_cherry_pick(obj, version, dry_run, recreate):
"""
Cherry pick commits.
"""
from .release import Release, MinorRelease, PatchRelease
release = Release.from_jira(version, jira=obj['jira'], repo=obj['repo'])
if not isinstance(release, (MinorRelease, PatchRelease)):
raise click.... | 27,034 |
def natural_key(string_):
"""See http://www.codinghorror.com/blog/archives/001018.html"""
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)] | 27,035 |
def _set_wpa_supplicant_config(interface, config, opt):
"""Starts or restarts wpa_supplicant unless doing so would be a no-op.
The no-op case (i.e. wpa_supplicant is already running with an equivalent
config) can be overridden with --force-restart.
Args:
interface: The interface on which to start wpa_supp... | 27,036 |
def test_resample():
"""Tests :func:`~pomdp_belief_tracking.pf.importance_sampling.resample`"""
p = ParticleFilter([0])
pf = resample(p, 5)
assert len(pf) == 5
assert pf() == 0
p = ParticleFilter([True, False, True, False])
n = 1000
pf = resample(p, n)
assert len(pf) == n
ass... | 27,037 |
def test_workspace_permissions(app, session, default_user,
sample_yadage_workflow_in_db,
tmp_shared_volume_path):
"""Test workspace dir permissions."""
create_workflow_workspace(sample_yadage_workflow_in_db.get_workspace())
expeted_worspace_permi... | 27,038 |
def generate_episode(sim, policy, horizon=200):
"""
Generate an episode from a policy acting on an simulation.
Returns: sequence of state, action, reward.
"""
obs = sim.reset()
policy.reset() # Reset the policy too so that it knows its the beginning of the episode.
states, actions, rewards ... | 27,039 |
async def _ensure_meadowrun_vault(location: str) -> str:
"""
Gets the meadowrun key vault URI if it exists. If it doesn't exist, also creates the
meadowrun key vault, and tries to assign the Key Vault Administrator role to the
current user.
"""
subscription_id = await get_subscription_id()
... | 27,040 |
def export_postgresql_to_tmp_csv(**kwargs):
"""
export table data from mysql to csv file
"""
print(f"Entering export_postgresql_to_csv {kwargs['copy_sql']}")
#gcs_hook = GoogleCloudStorageHook(GOOGLE_CONN_ID)
pg_hook = PostgresHook.get_hook(kwargs['conn_id'])
current_dir = AIRFLOW_HOME + "... | 27,041 |
def test_upload_file(mocker):
""" Ensure a file gets properly uploaded."""
resp.status_code = SUCCESS
http_obj = HTTPTransput(PATH_UP, URL, FTYPE)
mocker.patch('requests.put', return_value=resp)
assert 0 == http_obj.upload_file() | 27,042 |
def execute_scanner(dataset_location: str, result_location_str, j, use_ml=False):
"""Execute CredSweeper as a separate process to make sure no global states is shared with training script"""
dir_path = os.path.dirname(os.path.realpath(__file__)) + "/.."
command = f"{sys.executable} -m credsweeper --path {da... | 27,043 |
def get_dataset_splits(
datasets: Iterable[HarmonicDataset],
data_dfs: Dict[str, pd.DataFrame] = None,
xml_and_csv_paths: Dict[str, List[Union[str, Path]]] = None,
splits: Iterable[float] = (0.8, 0.1, 0.1),
seed: int = None,
) -> Tuple[List[List[HarmonicDataset]], List[List[int]], List[List[Piece]]]... | 27,044 |
def put_data_es(job, jobSite, stageoutTries, files, workDir=None, activity=None):
"""
Do jobmover.stageout_outfiles or jobmover.stageout_logfiles (if log_transfer=True)
or jobmover.stageout_logfiles_os (if special_log_transfer=True)
:backward compatible return: (rc, pilotErrorDiag, rf, "", ... | 27,045 |
def floor(data):
"""
Returns element-wise largest integer not greater than x.
Args:
data (tvm.tensor.Tensor): Tensor of type float16, and float32
Returns:
tvm.tensor.Tensor, has the same shape as data and type of int32.
"""
vc_util.ops_dtype_check(data.dtype, vc_util.DtypeForDa... | 27,046 |
def pixel_link_model(inputs, config):
""" PixelLink architecture. """
if config['model_type'] == 'mobilenet_v2_ext':
backbone = mobilenet_v2(inputs, original_stride=False,
weights_decay=config['weights_decay'])
elif config['model_type'] == 'ka_resnet50':
back... | 27,047 |
def ingresar_datos():
"""Pide al usuario los datos para calcular el precio de la compra
de boletos.
:return: tipo, cantidad
:rtype: tuple
"""
text_align("Datos de la compra", width=35)
tipo: str = choice_input(tuple(TIPO.keys()))
cantidad: int = int_input("Ingrese el número de boletos: ... | 27,048 |
def trim_spectrum(freqs, power_spectra, f_range):
"""Extract a frequency range from power spectra.
Parameters
----------
freqs : 1d array
Frequency values for the power spectrum.
power_spectra : 1d or 2d array
Power spectral density values.
f_range: list of [float, float]
... | 27,049 |
def plot_neighbor_rids_of_edge(eid, df_edges_unvisted, dis_buffer=25):
"""Plot the neighbor rids of the eid.
Args:
eid ([type]): [description]
df_edges_unvisted ([type]): [description]
"""
road_mask = gpd.GeoDataFrame({'eid': eid, 'geometry': df_edges_unvisted.query(f'eid=={eid}').buffe... | 27,050 |
def _get_variable_for(v):
"""Returns the ResourceVariable responsible for v, or v if not necessary."""
if v.op.type == "VarHandleOp":
for var in ops.get_collection(ops.GraphKeys.RESOURCES):
if (isinstance(var, resource_variable_ops.ResourceVariable)
and var.handle.op is v... | 27,051 |
def append_jsonlines(dest_filename, items, encoding=__ENCODING_UTF8):
"""
append item as some lines of json string to file
:param dest_filename: destination file
:param items: items to be saved
:param encoding: file encoding
:return: None
"""
with open(dest_filename, 'a', encoding=encodi... | 27,052 |
def load_prefixes(filepath):
"""Dado um arquivo txt contendo os prefixos utilizados na SPARQL, é
devolvida uma string contendo os prefixos e uma lista de tuplas contendo
os prefixos.
Parameters
----------
filepath : str
Caminho do arquivo txt contendo o conjunto de prefixos.
Return... | 27,053 |
def messenger_database_setup(force=False):
"""Setup the database from SQL database dump files.
Repopulates the database using a SQL backup rather than the original
IDL save files. See :doc:`database_fields` for a description of the
tables and fields used by MESSENGERuvvs.
**Parameters**
... | 27,054 |
def build_convolutional_box_predictor(is_training,
num_classes,
conv_hyperparams_fn,
min_depth,
max_depth,
num_layers_before_... | 27,055 |
def _get_default_directory():
"""Returns the default directory for the Store. This is intentionally
underscored to indicate that `Store.get_default_directory` is the intended
way to get this information. This is also done so
`Store.get_default_directory` can be mocked in tests and
`_get_default_di... | 27,056 |
def parse_command_line():
"""
:return:
"""
parser = argp.ArgumentParser(prog='TEPIC/findBackground.py', add_help=True)
ag = parser.add_argument_group('Input/output parameters')
ag.add_argument('--input', '-i', type=str, dest='inputfile', required=True,
help='Path to input fi... | 27,057 |
def test_bit_integer_index_list(c_or_python):
"""Make sure sequential integers are returned for a full bitstring
"""
fqe.settings.use_accelerated_code = c_or_python
test_list = list(range(8))
start = (1 << 8) - 1
biti_list = bitstring.integer_index(start)
assert (biti_list == test_list).all(... | 27,058 |
def get_rental_data(neighborhoods):
"""This function loops through all the items in neighborhoods,
scrapes craiglist for date for that neighborhood, appends it to a list,
and uploads a json to s3.
Args:
neighborhoods: neighborhoods is a dictionary containing
the names of the neighbo... | 27,059 |
def enable_bootstrap_logging(service_name=None):
"""
Turn on the bootstrap logger, which provides basic stdout logs until the main twisted logger is online and ready.
:param name_prefix:
:return:
"""
global bootstrap_logger_enabled, bootstrap_logger, log_level
if log_level:
level =... | 27,060 |
def get_text(event=None):
"""
:param event: None
:return: None
Gets the recommendations and shows it in a text widget.
"""
pygame.mixer.music.load('music/button-3.wav')
pygame.mixer.music.play()
text_widget = Text(frame, font='Courier 13 italic', cursor='arrow', bg='yellow', heig... | 27,061 |
def disparity_to_idepth(K, T_right_in_left, left_disparity):
"""Function athat transforms general (non-rectified) disparities to inverse
depths.
"""
assert(len(T_right_in_left.shape) == 3)
# assert(T_right_in_left.shape[0] == self.batch_size)
assert(T_right_in_left.shape[1] == 4)
assert(T_ri... | 27,062 |
def resol_dijkstra():
"""Utilise l'algorithme de Djikstra pour trouver le plus cours chemin"""
# les sommets sont nommés de 0 à longueur*largeur-1 du labyrinthe
G = gen_graph()
reponse_dijkstra = G.dijkstra("0")
chemin = Trouve_chemin(reponse_dijkstra)
suis_chemin(chemin) | 27,063 |
def test_tls_client_auth( # noqa: C901 # FIXME
# FIXME: remove twisted logic, separate tests
mocker,
tls_http_server, adapter_type,
ca,
tls_certificate,
tls_certificate_chain_pem_path,
tls_certificate_private_key_pem_path,
tls_ca_certificate_pem_path,
is_trusted_cert, tls_client_id... | 27,064 |
def display_board(state: object, player_num: int, winners: Union[List[int], None] = None):
"""Render Board with graphical interface
Parameters
----------
state : object
The state to render
player_num : int
The current player whose turn it is.
winners : List[int] (optional)
... | 27,065 |
def processPhoto(photoInfo, panoramioreview=False, reviewer='',
override=u'', addCategory=u'', autonomous=False, site=None):
"""Process a single Panoramio photo."""
if not site:
site = pywikibot.Site('commons', 'commons')
if isAllowedLicense(photoInfo) or override:
# Should... | 27,066 |
def auto_apilado(datos,target,agrupacion,porcentaje=False):
"""
Esta función recibe un set de datos DataFrame,
una variable target, y la variable
sobre la que se desean agrupar los datos (eje X).
Retorna un grafico de barras apilado.
"""
total = datos[[target,agrupacion]].grou... | 27,067 |
def month_from_string(month_str: str) -> datetime.date:
"""
Accepts year-month strings with hyphens such as "%Y-%m"
"""
return datetime.datetime.strptime(month_str, "%Y-%m").date() | 27,068 |
def get_isomorphic_signature(graph: DiGraph) -> str:
"""
Generate unique isomorphic id with pynauty
"""
nauty_graph = pynauty.Graph(len(graph.nodes), directed=True, adjacency_dict=nx.to_dict_of_lists(graph))
return hashlib.md5(pynauty.certificate(nauty_graph)).hexdigest() | 27,069 |
def rebuild_cluster():
"""Signal other etcd units to rejoin new cluster."""
log('Requesting peer members to rejoin cluster')
rejoin_request = uuid4().hex
hookenv.leader_set(force_rejoin=rejoin_request) | 27,070 |
def watchdog(timeout: int | float, function: Callable, *args, **kwargs) -> Any:
"""Time-limited execution for python function. TimeoutError raised if not finished during defined time.
Args:
timeout (int | float): Max time execution in seconds.
function (Callable): Function that will be evaluate... | 27,071 |
def _encode_raw_string(str):
"""Encodes a string using the above encoding format.
Args:
str (string): The string to be encoded.
Returns:
An encoded version of the input string.
"""
return _replace_all(str, _substitutions) | 27,072 |
def char_pred(pred: Callable[[int], bool]) -> Parser:
"""Parses a single character passing a given predicate."""
def f(x):
if pred(x):
return value(x)
else:
raise Failure(f"Character '{chr(x)}' fails predicate"
" `{pred.__name__}`")
return i... | 27,073 |
def test_missing_proteins():
"""fails on bad input"""
rv, out = getstatusoutput(f'{prg} -p {proteins}')
assert rv > 0
assert re.search('the following arguments are required: -c/--cdhit', out) | 27,074 |
def convert_bound(bound, coord_max, coord_var):
"""
This function will return a converted bound which which matches the
range of the given input file.
Parameters
----------
bound : np.array
1-dimensional 2-element numpy array which represent the lower
and upper bounding box on t... | 27,075 |
def tk_window_focus():
"""Return true if focus maintenance under TkAgg on win32 is on.
This currently works only for python.exe and IPython.exe.
Both IDLE and Pythonwin.exe fail badly when tk_window_focus is on."""
if rcParams['backend'] != 'TkAgg':
return False
return rcParams['tk.window_... | 27,076 |
def multi_qubit_decay_bellstate():
"""
Test multiqubit decay
"""
program = Program().inst([RYgate(np.pi/3)(0), CNOTgate(0, 1)])
noise = NoiseModel(ro_fidelity=1.0)
qvm = QVMConnection(type_trans='density', noise_model=noise)
initial_density = np.zeros((4, 4), dtype=complex)
initial_dens... | 27,077 |
def execute_by_key_event(code):
"""
:param code: int, keyEvent
:return:
"""
adb = [PATH + 'adb', 'shell', 'input', 'keyevent', str(code)]
con = Popen(adb, env=ENV, stdout=PIPE, stderr=PIPE) | 27,078 |
def cc_filter_set_variables(operator, bk_biz_id, bk_obj_id, bk_obj_value):
"""
通过集群ID、过滤属性ID、过滤属性值,过滤集群
:param operator: 操作者
:param bk_biz_id: 业务ID
:param bk_obj_id: 过滤属性ID
:param bk_obj_value: 过滤属性值
:return:
"""
client = get_client_by_user(operator)
obj_value_list = bk_obj_value... | 27,079 |
def distance(mags, spt, spt_unc):
"""
mags is a dictionary of bright and faint mags
set a bias
"""
res={}
f110w=mags['F110W']
f140w=mags['F140W']
f160w=mags['F160W']
relations=POLYNOMIAL_RELATIONS['abs_mags']
nsample=1000
for k in mags.keys():
#take the stand... | 27,080 |
def loss_function(recon_x, x, mu, logvar, cl, target, natural):
"""
Universally calculates the loss, be it for training or testing. Hardcoded to use mse_loss. Change below to binary_cross_entropy if desired.
@param recon_x: images reconstructed by the decoder(s)
@param x: original images for comparison
@param mu: ... | 27,081 |
def foo(X):
"""The function to evaluate"""
ret = []
for x in X:
r = 2*math.sqrt(sum([n*n for n in x]));
if r == 0:
ret.append(0)
else:
ret.append(math.sin(r) / r);
return ret | 27,082 |
def measure_curv(left_fit, right_fit, plot_points, ym_per_pix, xm_per_pix):
"""
calculates the curvature using a given polynom
Args:
left_fit ([type]): [description]
right_fit ([type]): [description]
plot_points ([type]): [description]
"""
#get the max y value (start of the... | 27,083 |
def get_external_dns(result):
"""
Function to validate the ip address. Used to extract EXTERNAL_DNS server information
Args:
result(dict): Input result dictionary with all network parameters and boolean flags
Returns:
result(dict): The updated result dictionary with network parameters
... | 27,084 |
def save_json(data_coco, json_file):
"""
save COCO data in json file
:param json_file:
:return:
"""
json.dump(data_coco, open(json_file, 'w'), indent=4) # indent=4 更加美观显示
print("save file:{}".format(json_file)) | 27,085 |
def __process_agent(agent_param):
"""Get the agent id and namespace from an input param."""
if not agent_param.endswith('TEXT'):
param_parts = agent_param.split('@')
if len(param_parts) == 2:
ag, ns = param_parts
elif len(param_parts) == 1:
ag = agent_param
... | 27,086 |
def inference(predictions_op, true_labels_op, display, sess):
""" Perform inference per batch on pre-trained model.
This function performs inference and computes the CER per utterance.
Args:
predictions_op: Prediction op
true_labels_op: True Labels op
display: print sample prediction... | 27,087 |
def run_temp_dir(args):
"""Setup temporary directory and run server."""
with tempfile.TemporaryDirectory(prefix="scelvis.tmp") as tmpdir:
logger.info("Creating temporary directory %s", tmpdir)
settings.TEMP_DIR = tmpdir
run_server(args) | 27,088 |
def callback_with_answer_and_close_window(
on_change: Optional[OnQuestionChangeCallback], window: Window
) -> OnQuestionChangeCallback:
"""Create a callback that calls both the on_change and window.close methods."""
def inner(answer: Any) -> None:
if on_change is not None:
on_change(ans... | 27,089 |
def nlu_tuling(question, loc="上海"):
"""图灵 API
"""
url = 'http://www.tuling123.com/openapi/api'
data = {
'key': "fd2a2710a7e01001f97dc3a663603fa1",
'info': question,
"loc": loc,
'userid': mac_address
}
try:
r = json.loads(requests.post(url=url, data=data).... | 27,090 |
def update_hpo():
"""Update human phenotype ontology."""
url = 'http://purl.obolibrary.org/obo/hp.obo'
OboClient.update_resource(path, url, 'hp', remove_prefix=False) | 27,091 |
def test_auth_middleware(setup_user, client):
"""test middleware"""
c = Client()
res = c.post(
"/accounts/login",
{"email": "admin@domain.com", "password": "admin"},
follow=True,
)
res.status_code == 200
res = c.get("/accounts/login", follow=True)
assert res.status_co... | 27,092 |
def Lines(
apply_clip: bool = True,
close_path: bool = False,
color: ndarray = None,
colors: list = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"],
curves_subset: list = [],
display_legend: bool = False,
enable_hover: bool = Tru... | 27,093 |
def parse_currencies(row):
"""Clean up and convert currency fields to floats."""
date_columns = (
'Datum van laatste bijwerking',
'Einddatum',
'Begindatum'
)
for key in date_columns:
try:
row[key] = arrow.get(row[key], 'DD.MM.YYYY HH:mm')
except Parse... | 27,094 |
def as_tuple(item, type=None, length=None):
"""
Force item to a tuple.
Partly extracted from: https://github.com/OP2/PyOP2/.
"""
# Empty list if we get passed None
if item is None:
t = ()
elif isinstance(item, (str, sympy.Function)):
t = (item,)
else:
# Convert i... | 27,095 |
def messages(request):
"""
Return a lazy 'messages' context variable as well as
'DEFAULT_MESSAGE_LEVELS'.
"""
return {
"messages": get_messages(request=request),
"DEFAULT_MESSAGE_LEVELS": DEFAULT_LEVELS,
} | 27,096 |
def hash_graph(graph):
""" A hash value of the tupelized version of graph.
Args:
graph (NetworkX graph): A graph
Returns:
int: A hash value of a graph.
Example:
>>> g = dlib.sample(5)
>>> g.nodes
NodeView((0, 1, 2, 3, 4))
>>> g.edges
EdgeView([(... | 27,097 |
def test_get_api_url(test_dict: FullTestDict):
"""
- GIVEN a list of words
- WHEN API urls are generated
- THEN check the urls are encoded and correct
"""
word_list = convert_list_of_str_to_kaki(test_dict['input'])
sections = test_dict['jisho']['expected_sections']
for word in word_list... | 27,098 |
def deserialize(rank: str, suit: str) -> Card.Name:
"""
Convert a serialized card string to a `Card.Name`.
Parameters
----------
rank : str
A, 2, 3, ..., 10, J, Q, K
suit : str
C, D, H, S
"""
suit_map = {
'C': Suit.CLUBS,
'D': Suit.DIAMONDS,
'H': ... | 27,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.