content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def run_hyperband(project_name,X_ros, y_ros, test, actual): """Set up and run the Keras Tuner Hyperband which creates a bracket of many different neural network models with different hyperparameters and trains, tests and evaluates them to determine the best one and stores the values in best_hps.""" MET...
6974edb467faacdad215994932d393a7b9238b2c
64,900
import pandas as pd import os def dm(path): """DM Dollar Exchange Rate weekly observations from 1975 to 1989 *number of observations* : 778 *observation* : country *country* : Germany A dataframe containing : date the date of the observation (19850104 is January, 4, 1985) s the ask ...
022e0ad5434ad2dafb364534a308cff80edb7205
64,901
def all_images(request, profile_id): """ function gets and displays all images uploaded by a user """ current_user = request.user.profile user = current_user images = Image.objects.filter(profile_id=profile_id) return render(request, 'profile_templates/user_posts.html', {'images':images})
3133e121da93b28646d925cf7ea1d0d6048cb076
64,902
import time def overloaded_abstract_retrieval(identifier, view='FULL', refresh=True, id_type='eid'): """ The only thing this extra layer does is swap api-keys on error 429 Any multi-threading etc is done elsewhere (and may need its own testing as always) """ try: res = AbstractRetrieval(id...
acc13ab14b77cbdcead83ff826153f72c55a20c9
64,903
import json import logging def api_station_create(): """ This function creates a new station """ # execute and return result result_data = json.loads(request.data) logging.info('Create station %s', result_data["item"]["name"]) result = station_set( result_data["item"]["name"], ...
7d7d4485cfb78719f8829dea21a854552bd075d5
64,904
def select_edges(edges, by_col='SUID', preserve_current_selection=True, network=None, base_url=DEFAULT_BASE_URL): """Select edges in the network by SUID, name or other column values. Args: edges (list): List of edge SUIDs, names or other column values by.col (str): Edge table column to lookup u...
1a7d88ad86a7f5978d30de68c395d9952f238dfb
64,905
import requests import json def _login(email: str, password: str, login_url: str = LOGIN_URL) -> requests.Response: """ Login to Shipped Brain :param email: shipped brain account email :param password: shipped brain account password :param login_url: login url :return: requests.Response with aut...
15f5a66127daf7ff9532d91d60d87140ee25d4bc
64,906
import scipy def simpson(dataset, *args, **kwargs): """ Integrate using the composite Simpson's rule. Wrapper of scpy.integrate.trapezoid. Performs the integration along the last or given dimension. If there are an even number of samples, N, then there are an odd number of intervals (N-1), ...
eb6162fbdecadaf51588d528197cb13f2d72a1aa
64,907
import sys def get_curr_sha(repo_path): """ Gets the latest SHA for the specified repo. :param repo_path: Path to a git repository. :return: Last commit SHA. """ cmd = ['git', '-C', repo_path, 'log', '--pretty=format:%h', '-n', '1'] _, _sha = run_cmd_with_output(cmd, exit_on_failure=True...
7bd1819899718337f92192da5aa33f338410ff00
64,908
from pathlib import Path def get_cache_dict(db_instance): """Return a dictionary `{identifier: path}` keys and values. Args: db_instance: Connected Database file with `DBConnect()`. Returns: dict: dictionary `{identifier: path}` keys and values """ table = get_files_table(db_ins...
687e766dfc04e911131fb361a72cf6ac2743d84b
64,909
from pathlib import Path def build_raw_ben_s2_parquet( ben_path: Path, output_path: Path = Path() / "raw_ben_s2_gdf.parquet", n_workers: int = 8, target_proj: str = "epsg:3035", verbose: bool = True, ) -> Path: """ Create a fresh BigEarthNet-S2-style parquet file from all the image pat...
fb58ca6eb5e7e1095789e7d978a029585850fe8c
64,910
def _validate_belongs(*options): """ Return a validator ensuring the item belongs in the list. """ def _validate_belongs(value): # noqa: E306 for opt in options: if isinstance(value, str) and isinstance(opt, str): if value.lower() == opt.lower(): # noqa: E501 ...
9284b6ff4f55138a3606cc530891f8d1c206ece3
64,911
import re def mw(formula): """ Tokenize a molecular formula to determine total molecular weight. Calculation is based on atomic weight values from IUPAC [1]_. Parameters ---------- formula : str Molecular formula or element. Returns ------- mw : float Molecular wei...
e9e59e8010eee227351ad7fdc21d3171ee0dac9d
64,912
def get_credentials(url, token): """ Get the credentials list Returns requests object """ r_endpoint = "credentials" r = api_get(url, r_endpoint, token) return r
79c9ba149a70485e0f851c781989f78a0a0b718f
64,913
def sorted_ext_names(config, ext_names): """Sort extensions if `EXT_ORDER` is specified. Extensions not listed in `EXT_ORDER` will be appended to the end of the list in an arbitrary order. """ ext_order = [e.strip() for e in config['EXT_ORDER'].split(',')] def sort_key(ext_name): try: ...
6265b6c6ea21915b148648d9adeb800f6d9a8a95
64,914
import functools def of_int_to_int(real_simplex_result, d): """convert all of_int terms to integer terms""" pt1 = real_simplex_result # a ⋈ x, ..., c ⋈ z ⊢ false for hyp in pt1.hyps: pt1 = pt1.implies_intr(hyp) dd = [pt.on_lhs(top_conv(real.real_eval_conv()), bottom_conv(rewr_conv('real_mul_li...
26a492463b26080095729d1447b4d5f60bb8a140
64,915
def _deal_with_axis(obj, axis): """Handle the `axis` parameter Parameters ---------- obj: DimArray object axis: `int` or `str` or `tuple` or None Returns ------- newobj: reshaped obj if axis is tuple otherwise obj idx : axis index name : axis name """ # before apply...
ae0eec4bdf7f172f9617e9f9d1330d75b08f8e97
64,916
def build_optimizer(model, opts): """ Re linear may get larger learning rate """ no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] param_optimizer = [(n, p) for n, p in model.named_parameters() if 're_output' not in n] param_top = [(n, p) for n, p in model.named_parameters...
df373cd0df51efa625200a02260bedcae13da7cd
64,917
def do_train(dataset_dict): """provide dict in train mode""" # USER: Modify this if you want to keep them for some reason. dataset_dict.pop("annotations", None) dataset_dict.pop("sem_seg_file_name", None) return dataset_dict
d6a2bc73baa41218c24282695f7b2a2c57d086d4
64,918
def load_data(time,info): """docstring for load_data""" sfc = load_sfc(time, info) atm = load_atm(time, info) return Bunch(sfc=sfc, atm=atm)
d7f8bd9a83e090c24a591fa124742fa4d687a4fc
64,919
import pytz from datetime import datetime def daily_forecast_embed(obs, loc): """ Accepts pyowm OneCall and geopy Location. Returns Embed for 7-day forecast. """ # forecast details forecasts = obs.forecast_daily loc_str = loc.raw['address']['formattedAddress'] tz = pytz.timezone(obs.ti...
f0a8d67a8a0a4b574f46d6fe38167618191aaf53
64,920
import bisect def calc_precision_recall(ground_truths_list, predictions_list, match_labels): """Adjust threshold to get mutiple precision recall sample.""" true_positive_list, false_positive_list = get_confidence_list( ground_truths_list, predictions_list, match_labels) true_positive_list = sorted...
0507f350c83597eb0ace3fc1fa6a22aa0b019a7d
64,921
from typing import Optional import scipy def solve_regularized_weighted_lstsq( coefs: np.ndarray, result: np.ndarray, *, weights: Optional[np.ndarray] = None, penalty_matrix: Optional[np.ndarray] = None, lstsq_method: LstsqMethod = lstsq_svd, ) -> np.ndarray: """ Solve a regularized an...
408c3e6dbc5723cebbd7b1afc3edeb2802edd1cf
64,922
def checkSum(n, cType, errMsg): """do chksum for card is real card or not Args: n (str): card # cType (str): card type errMsg (str): error msg Returns: bool: true if valid chksum or false otherwise """ errorMsg = errMsg or "Not a Valid Card!" tracker = int(n) ...
5b2087bb7c4d051300ed4079adc66a3d86aaab27
64,923
def clear_noise(image, size): """利用自定义矩形框清除噪点 :param image: 二值图 :param size: 自定义矩形框的大小 type: tuple :return: image """ image = image.convert('L') for y in range(image.size[1] - size[1]): for x in range(image.size[0] - size[0]): white = True for xx in range(x...
e9b5a00e724eb6c2d464d02e1041c59c128e490d
64,924
def create_mclp_model(coverage_dict, num_fac, model_file=None, delineator="$", use_serviceable_demand=False): """ Creates an MCLP model using the provided coverage and parameters Writes a .lp file which can be solved with Gurobi Church, Richard, and Charles R Velle. 1974. The maximal covering location...
d6b818207ff575a1206415d6a1f6c499a5901182
64,925
def simple_bet(pressure, n_monolayer, c_const): """A simple BET equation returning loading at a pressure.""" return (n_monolayer * c_const * pressure / (1 - pressure) / (1 - pressure + c_const * pressure))
601701b608a48fe634d028023068fcadc636499b
64,926
def generate_refval_attribute( desc, stems, ctree_name, preferred_attr, prototypes, ubunch, default_attr = None, ): """ For use inside of a dproperty_adv_group """ desc.stems(*stems) prototypes = frozenset(prototypes) if preferred_attr is None: preferred_attr...
8f37a87aee09c90e22752464d1dd0a1f2ccdfd44
64,927
def _select_identifier(identifiers, dict_to_identify): """Select the right field identifier. Args: identifiers (list): List of identifiers. dict_to_identify (dict): Dictionary to identify. Returns: str: Identifier. """ for identifier in identifiers: if identifier i...
647be77f4f87b6d6cba1d979882ac78741134484
64,928
def setup_fab_data(clay_bullets): """Check for placed bullets in JSON. Parameters ---------- clay_bullets : list of :class:`compas_rcf.fabrication.clay_objs.ClayBullet` Original list of ClayBullets. Returns ------- list of :class:`compas_rcf.fabrication.clay_objs.ClayBullet` ...
9df151634186cb693539e10f31366b08d97db41e
64,929
def filter_permission_names(permissions): """ Generate a Permission model query filtered by names, e.g.: ['<app_label>.<codename>', ...] """ permission_pks = [] for permission in permissions: assert '.' in permission, f'Wrong format: {permission!r}' app_label, codename = permission.s...
f4907537efbb58d9b4289733d516518e71092f96
64,930
def positions_func(inputs, pad=0): """ A layer filling i-th column of a 2D tensor with 1+ln(1+i) when it contains a meaningful symbol and with 0 when it contains PAD """ position_inputs = K.cumsum(K.ones_like(inputs, dtype="float32"), axis=1) position_inputs *= K.cast(K.not_equal(inputs, pad...
4db34c8c9fc0dee07ba4017793caff95fbff40c1
64,931
from typing import List def create_contact( create_contact_input: contacts.Create, db: DbSession = Depends(get_db_session), user: User = Depends(require_user), principals: List[str] = Depends(get_active_user_principals), ): """Creates a new contact. Raises an exception if the user is not logged in...
64ed02d1b8d57dbd4d39784c54772cb7c5ea4ea7
64,932
def get_uvw_segment(d, segment=-1): """ Calculates uvw for each baseline at mid time of a given segment. d defines pipeline state. assumes segmenttimes defined by RT.set_pipeline. """ # define times to read if segment != -1: assert 'segmenttimes' in d, 'd must have segmenttimes defined' ...
eb06e5651d4b9a7bcda8967912c27b7a78e6b980
64,933
import os def _process_tag(tmpdir: str) -> pd.DataFrame: """Concatenate all TAG tables in dataset zipfiles found in tmpdir along index (axis=0). Removes duplicate tags. The TAG (Tags) table contains all standard taxonomy tags and custom tags found in the downloaded tables. Sets multindex with ta...
9aa679cb3b49859af4076b98e970628dd24ae1ae
64,934
from typing import AnyStr from typing import List from typing import Dict def get_pods_metrics_rating(start: AnyStr, end: AnyStr, tenant_id: AnyStr, namespaces: List[AnyStr]) -> List[Dict]: """ Get the rating by pods and names...
fc58a63905da19eb57494dc7622c035b38ceb350
64,935
def parsing_rule(f): """ Wrap a parsing function to memoize its calls :param f: the function to wrap :return: the wrapped function """ def wrapped_func(self: BaseParser, *args): self.reader.consume_non_significant() pos = self.mark() ...
412f64d954b59dc66fa16f68b1f5a594741db362
64,936
import os import re import argparse def is_file_type(arg, type): """ Validate file path and check if the file is of the specified type. Parameters ---------- arg : :obj:`str` File path. type : {'dataset', 'task', 'model'} Possible file types. Returns -...
f3f1adeb113fd1f610e0ffae695a79c951068dfe
64,937
import os def get_user_ids(path): """ Get all user ids based on name of folders under "public_dataset/" :return: a list of user ids """ file_name = os.listdir(path) user_id = [i for i in file_name if '.pdf' not in i and '.DS_Store' not in i] return user_id
bc018eb494acc5a586383beb1eef2f9ccf7eff8d
64,938
def dot_product(a, b): """ >>> dot_product({'a': 1, 'b': 2, 'c': 3}, {'b': 4, 'c': -1, 'd': 'whatever'}) 5 """ return sum(ak * bk for _, ak, bk in _aligned_items(a, b))
f6e8d5a39667faf4b4d1e2f576b98a3ab445cf9a
64,939
def get_group_summary(conn, group_name): """Return the summary of the group results""" cur = conn.execute(''' select t.path, t.filename, cast(substr(reverse(group_concat(cast(result as char))), 1, 1) as integer), duration, t.lines from results inner join tests t on resu...
806b6a34f379aa2b7c74edc43d523fa9ee169602
64,940
def char_floats(floats): """Pretty printing of floats. Args: floats (list or float): if float it gets converted to a list with one entry. Returns: line (list): list of strings. """ if isinstance(floats, float): floats = [floats] line = [] for value in ...
b1cb0eaa7408e3b040504cf115159a4115ed240b
64,941
def create_matrix(PBC=[1, 1, 1], omit=False): """ Used for calculating distances in lattices with periodic boundary conditions. When multiplied with a set of points, generates additional points in cells adjacent to and diagonal to the original cell Args: PBC: A periodic boundary condition l...
66ed835fbf7a35b4056b5c3eaa2e1d4322a44c84
64,942
def h5py_read_dataset(dset, index=tuple(), decode_ascii=False): """Read data from dataset object. UTF-8 strings will be decoded while ASCII strings will only be decoded when `decode_ascii=True`. :param h5py.Dataset dset: :param index: slicing (all by default) :param bool decode_ascii: """ ...
4d96386cf96487fdc0775c1a0a92594e27790984
64,943
def sample(data, labels, sizes, seed=None, verbose=0): """ Sample from the dataset. Model a generative algorithm over each of the desired labelled data to sample more data from the resulting distributions. Parameters ---------- data : array-like, shape=(n_samples, n_features) Data. labels : array-like, sh...
831683df272082808cf4d988fc85f17be3d50c3c
64,944
def eidas_crypto_hash_hex(hex_data: str) -> str: """ Generates a 256-hash hex string from a given hex string data (using cryptography module) """ return eidas_crypto_hash_byte(bytes.fromhex(hex_data))
45296ad57fe26cf1ba8e7fcc5c400dc97e320ec7
64,945
from io import StringIO def truncateToMultiLine(line, length = 60, prefix = '', indentPrefix = None): """ Parse a one line message into multiple lines of the specified length """ multiLine = StringIO() numLines = ((len(line) - 1) / length) + 1 offset = 0 for i in range(numLines): if indent...
0d88406974b77a109f0082d28a3a4070a9a8e082
64,946
def _shift_and_fix_registers(registers, offset, addresses, min_address): """Shift register contents.""" sregisters = [] for register in registers: register = register.copy() if not register.name.startswith("GPR"): # Do not shift not GPR registers sregisters.append(reg...
c1d13a72ae77073ed0837d681bbdcca0435c3d17
64,947
from bcbio.variation import validate import copy import os def combine_calls(data): """Combine multiple callsets into a final set of merged calls. """ if _has_ensemble(data): logger.info("Ensemble consensus calls for {0}: {1}".format( ",".join(x["variantcaller"] for x in data["variants...
a0834549ca554f05c727becb49e1c3eff1c91e33
64,948
def pandas2markdown(dataframe: pd.DataFrame) -> str: """ translate the Dataframe in pandas into Markdown table :type dataframe: object """ if not hasattr(pandas2markdown,'writer'): pandas2markdown.writer: MarkdownTableWriter = MarkdownTableWriter() pandas2markdown.writer.from_dataframe( ...
763b0be9feb64ce3259254bf85b35ed5141566b2
64,949
def image_preprocessing(image, train, crop_size, im_size=None, thread_id=0, bbox=None): """Decode and preprocess one image for evaluation or training. Args: image_buffer: JPEG encoded string Tensor bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate ...
2e77a32c363a667d64258b0a81d9a03311914b2d
64,950
from typing import Container from typing import Iterable def match_tags(search: Container[str], tags: Iterable[str]): """Check if the search constraints satisfy tags. The search tags should be uppercased. All !tags or -tags cannot be present, all +tags must be present, and at lest one normal tag mus...
0a6ee5f233900eb50ad72613aa73f227a836b4dd
64,951
def view_2dmol(option, maps=None, out_put=None, target_id=None, legends=None, extra=None): """Function to render a mol image from a smiles. The input (option) could be 1) a list of smiles 2) a smiles 3) pdb_code Returns a molecule image as data""" option = str(option) print option try: o...
d609d38b36058627551397902d070ee8594a9ead
64,952
def time_parse(s, format='%H:%M:%S'): """ Parse a time string in a IIS extended log format file. :param str s: The string containing the time to parse (HH:MM:SS format) :param str format: The optional strftime(3) format string :returns: A :class:`~lars.datatypes.Time` object representing the time ...
c947631730108339e10d8cda8c79dbdb92b1cd12
64,953
import os def find_netmiko_dir(): """Check environment first, then default dir""" try: netmiko_base_dir = os.environ['NETMIKO_DIR'] except KeyError: netmiko_base_dir = NETMIKO_BASE_DIR netmiko_base_dir = os.path.expanduser(netmiko_base_dir) if netmiko_base_dir == '/': raise...
c9463eb50d0e93d4d05105c550282d490b980c1d
64,954
def dws_branch_k7_s2_p3(in_channels, out_channels, extra_padding=False, stem=False, data_format="channels_last", **kwargs): """ 7x7/2/3 version of the NASNet specific depthwise separable convo...
0016fa4b75a71af07339aceae1d7ae2c77e746d4
64,955
def parse_output(actual_out = "", horizontal = False, mearge_header = True): """ commmon parser for all show commands will return touple of following @param heading : first line of output @param header: Second line of output @param params: list of parameters """ data = ...
f05d3103d12a673ce3bc35f2a4e2e8beb354b935
64,956
def findVariablesInFile(filepath): """Lists variables parsed from the given file Args: filepath: A path to a file containing Python code to be parsed Returns: A set of 4-tuples describing found variables {(str file, ast.stmt function_or_class, str variable, ...
df0347dd6511836cde2ba556d3f0cf5cae4ef4e9
64,957
def _switch_on_off_(kat, timestamp, switch=0): """Switch noise-source on or off. Parameters ---------- kat : session kat container-like object Container for accessing KATCP resources allocated to schedule block. timestamp : float, optional Tim...
37b00231630b52d1b84fcb8c7225d6b04de9d02d
64,958
def correct_slopes(X: np.array, vivo=False) -> np.array: """ Change Learning data to shape of series instead of series """ if not vivo: for i in range(0, X.shape[1], 3): X[:, i + 2] = X[:, i + 2] - X[:, i + 1] X[:, i + 1] = X[:, i + 1] - X[:, i + 0] else: for i in ran...
b92c21099d4b4aadf92392a157d6f6d23b471680
64,959
def tensor_to_ndarray(tensor): """ Convert float tensor into numpy image :param tensor: input tensor :type tensor: torch.Tensor :return: numpy image :rtype: np.ndarray """ tensor_np = tensor.permute(1, 2, 0).cpu().numpy() tensor_np = tensor_np.astype(np.float32) tensor_np = (ten...
b2c173f55b24c0bb998e447c80a8df7787b0b127
64,960
from typing import Tuple from typing import cast def ks_2samp(data1: np.ndarray, data2: np.ndarray) -> Tuple[float, float]: """Delayed version of scipy ks_2samp.""" return cast(Tuple[float, float], ks_2samp_(data1, data2))
7e745848c90a375a6c34dcba7817aa7e86c8fa79
64,961
import os def get_fa_from_scratch(scratch_dir): """ Careful... May not work in the Future Inputs: scratch_dir: (str) Path to work dir/ tmp etc.. Outputs: FNA fp: (str) Automatic download through GenbankToGenome """ fna_fp = None scratch_files = os.listdir(scratch_dir) ...
cd673c4abb2ecfdf5d6def9a41185b6d60f46f2e
64,962
def parse_indicators_command(sh, area): """ :param sh: :param area: :return: """ some_error = False issues = [] """ self._name = name self._formula = formula self._from_indicator = from_indicator self._benchmark = benchmark self._indicator_catego...
2a98272bfb06fb09328d3b1bad6163946b1e0cc7
64,963
def _rpc_state_string(class_name, rpc_state): """Calculates error string for RPC.""" with rpc_state.condition: if rpc_state.code is None: return '<{} object>'.format(class_name) elif rpc_state.code is grpc.StatusCode.OK: return _OK_RENDEZVOUS_REPR_FORMAT.format(class_name...
d75203f7dbd92d2a2fcf8b5b3fb8247a021cf081
64,964
def coordinate_generator(): """Return a generator which returns `count` randomly-generated coordinates in the range [-1000, 1000], in a mixture of floats and ints""" def wrapped(count=COUNT, seed=SEED): twister = Random(seed) def rand(is_int=False): n = (twister.random() - 0.5)...
7b4a250a5724d327cb308d0a25960d922b86f027
64,965
def get_data_path(data_path): """Return Blender data path.""" index = data_path.rfind('.') if index == -1: return data_path return data_path[(index + 1):]
b32b32cb624e87e278f72490e23fe5ccb7ae1206
64,966
from typing import Union from typing import List from typing import Tuple def get_members_from_args(guild: discord.Guild, potential_members: Union[List[str], Tuple[str]]) -> List[discord.Member]: """ Iterate over list and try :param guild: guild to search in :param potential_members: tuple or list wit...
3bc8c0ebb9c2797f4f9989ee8bcb37ccd8d66d73
64,967
def de2bi(decimals, n=None): """ Parameters ---------- decimals : ndarray vector of decimals n : int number of binary digits """ decimals = np.array(decimals) try: nd = np.ceil(np.log2(np.max(decimals))) except RuntimeWarning: print('{0}:{1}'.format(de...
25a07a2b86792f250fc86114d8a182a4586094d2
64,968
def text_node_for(context, text): """Outputs the text node with the forloop.counter incremented""" return ('<text id="%d">%s</text>' %(context["forloop"]["counter"]+1, text))
4fbf40884ed19e326ce7e1fdc6a9773ed14a40fc
64,969
def check_created_resource(db_output, resource_type): """Validation Checks for values and existence and responses """ if 'Invalid Data' in db_output: return make_response(jsonify({"status": 400, "error": "Check Input Values"}), 400) elif 'party' not in resource_type and 'Office Exists' in db_output:...
1726d7f7a4704c3f640379ddc68a1b5a9d6f9d40
64,970
import requests def get_base_info_single(bond_code: str) -> pd.Series: """ 获取单只债券基本信息 Parameters ---------- bond_code : str 债券代码 Returns ------- Series 债券的一些基本信息 """ columns = EASTMONEY_BOND_BASE_INFO_FIELDS params = ( ('reportName', 'RPT_BOND_CB_L...
7010b3ea4ac871ff2b370192f951f0b964b0e8bb
64,971
import aiohttp import async_timeout async def get_html(url): """ Retrieves HTML of a webpage """ async with aiohttp.ClientSession() as session: async with async_timeout.timeout(10): async with session.get(url) as response: return await response.text()
5a27c417b5ff1cbd0561fc38504f12e0ea4a5418
64,972
def GUI_Safe(func): """ Decorator to execute func into the GUI thread """ S = SignalCaller(func) return S.run
d23b21e973c3ac176ac1f540bc5b3fc261c2994d
64,973
def marg_dist(msgs, i, use_log=True): """ Calculate the marginal distribution of a variable node from the messages of a factor graph :param msgs: messages :param i: :param use_log: True if operations should be done in log space, False otherwise :return: marginal distribution of variable node i ...
bc2ae58728e69a8ed1e9745524d25c7e4a498492
64,974
def install_openssh_server(instance, args, verbose=True): """ Install and launch ssh server. Returns: int: Return 1 if the function works successfully, otherwise 0. """ install(instance, {"module":"openssh-server"}, verbose=False) instance.execute(["systemctl","start","ssh"]) return 0
4089e289fa2e2c70e6f2afffbe1579745c182b71
64,975
from typing import Dict from typing import Any from typing import Iterator from typing import Tuple def flatten(dictionary: Dict[str, Any]) -> Dict[str, Any]: """ >>> flatten({'foo':{'bar':{'baz': 0}, 'deadbeef': 1}, '42': 3}) {'foo.bar.baz': 0, 'foo.deadbeef': 1, '42': 3} """ def iterate(data: Di...
401f2f8894690a0c1171d26378ac4a5178dd705a
64,976
from typing import Optional def make_object_schema( var_schema: Optional[dict] = None, type_enum: Optional[list] = None) -> dict: """jsonschema of an encoded object. :param var_schema: Json schema of variable :param type_enum: Used to restrict a value to a fixed set of values. """ schema =...
6cd30e39f210e81f08132677637322e33631b7fd
64,977
def offline_validator_address(): """Ethereum address of the offline validator. The offline validator is the third positioned validator at the e2e_test_chain. He is meant to be not started at all and therefore becomes reported as offline. """ return "0xe7a664509027ff348d379bb5d3a8340aaecb56eb"
e89238a3a9d0bc938e60bdf8f52e0416a4a81987
64,978
import torch import os def load_and_cache_examples(args, processor, retrievers, relation_list, input_dir, evaluate=False, output_examples=False): """ :param args: arguments. Here use "local_rank", "cache_dir", "model_type", "max_seq_length", "data_dir", "train_file", "tokenizat...
4e4e63ae201b01f892bd6744034a01837f3cb2a8
64,979
def lstm_luong_attention_multi(): """Multi-head Luong attention.""" hparams = lstm_luong_attention() hparams.num_heads = 4 return hparams
d03d0f1f0aece05cfb17424579a309340a87f58b
64,980
def encode_label(dataframe, column, column_encoded, encoding_dictionary=None): """Encode ``column`` label in ``dataframe`` with ``encoding_dictionary`` provided. Parameters ---------- dataframe : pandas.DataFrame The DataFrame to read and to write to. column : str Name of the column...
223e61455493ea75247258c32ad87343ae609dbd
64,981
def effective_neighbor(G: nx.Graph, infected: int, target: list, compliance_edge_known:bool = False): """ Filters out edges of no transmission for G.neighbors """ effective_neighbors = set() for v in target: if check_edge_transmission(G, infected, v): effective_neighbors.add(v) ...
f6c12e832944663f55330a4e1ccc847364b50700
64,982
def xyz_there(s): """ Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not. xyz_there('abcxyz') → True xyz_there('abc.xyz') → False xyz_there('xyz.abc') → True """ return False
16a882ac081e7b5cc7f75d66ce7d78c1efcc92b7
64,983
def stack_obs_space(obs_space, stack_size, stack_dim=-1): """ obs_space_dict: Dictionary of observations spaces of agents stack_size: Number of frames in the observation stack Returns: New obs_space_dict """ if isinstance(obs_space, Box): dtype = obs_space.dtype # stack 1...
0182301bdb2170752b477892f1a8dfa8c437c02a
64,984
def filter_kaisord_highpass(signal, sampling_rate, cutoff=100, transitionWidth=40, rippleDB=20): """ Applies a digital high pass filter to <signal>. :param Sequence signal: sequence of floats representing the signal to be filtered :param float sampling_rate: sampling rate of <signal> in Hz :param fl...
3270d0a77766cef8a8c312db965db75452a53dbf
64,985
def get_page_format(format, k=None): """Return page width and height size in points. Throws FPDFPageFormatException `format` can be either a 2-tuple or one of 'a3', 'a4', 'a5', 'letter', or 'legal'. If format is a tuple, then the return value is the tuple's values given in the units specified...
490a1a3c189121fd58d9e74ce483726e9284795d
64,986
def fromobject(thrift, tcls, obj): """Create thrift object with type `tcls` from a Python object. """ if isinstance(obj, tcls): return obj return globals().get(tcls.__name__, tcls)(thrift, obj)
fcb868dc460db835a4ec77fc08e8ed944fb8296b
64,987
def describe_zones(): """ Describe a specific zone or all zones. @return: Response. """ args = {'command': 'listZones'} response = cloudstack.describe_item( args, 'zone', errors.invalid_zone, 'ZoneName' ) return _describe_zones_response( response )
21e85162cba67030c0a093af0a6308aa6466c1f0
64,988
def restore_codebook(codebook_filename): """ reads the cluster_centers from the codebook file and restores a kmeans model to use for prediction """ cluster_centers = np.fromfile(codebook_filename) cluster_centers = cluster_centers.reshape(-1, int(cluster_centers[0])) # do this because the first ...
e6cb18d07fde2b54498ff08d789c620b8b5197ba
64,989
def Predict_serpent_isotope_response(serpent_filename, response_filename): """This function makes a Cherenkov light intensity prediction based on the isotope contents read from a Serpent output file and a isotope response function. Parameters ---------- serpent_filename : string Path ...
66e4db08ff6cb11597f58cbb0c9feb1962e8fa07
64,990
def subdivide_stats(data): """ If a key contains a ., create a sub-dict with the first part as parent key """ ret = {} for key, value in data.items(): if '.' in key: parent, subkey = key.split('.', 2) if parent not in ret: ret[parent] = {} ...
65e47db5c75118c1939a8ecdd3ad581a053da893
64,991
def request_revisions_dialog(request): """deletes the department with the given id """ logger.debug('request_revisions_dialog is starts') came_from = request.params.get('came_from', '/') selected_task_list = get_multi_integer(request, 'task_ids', 'GET') logger.debug('selected_task_list: %s' % ...
d927933252f722dcb491ce3433b96f4faef03dcc
64,992
def delete_ip(request): """API delete_ip""" if request.method == 'POST': id = request.POST['id'] ip = get_object_or_404(IP, pk=id) ip.delete() ips = IP.objects.all() return render_to_response( 'spams/show_ips.html', { 'ips': ips, ...
0778f565e642a56d673e63498ce52b7e54f5847f
64,993
def tdig(tombfile, size, force=False): """ Dig a tomb of given size """ cmd = ['tomb', 'dig', tombfile, '-s', str(size), '--no-color'] if force: cmd += ["-f"] return execute(cmd)
3f0a5524f6554d73a0bb4c7f0af483c58eeab4bf
64,994
def cancel(f, *gens, **args): """ Cancel common factors in a rational function ``f``. **Examples** >>> from sympy import cancel >>> from sympy.abc import x >>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1)) -(2 + 2*x)/(1 - x) """ options.allowed_flags(args, ['polys']) f = sympify(f) ...
af6cc6c694a0e3e484cffbd5bfdce64a96310cc6
64,995
import collections def run_parametrised_hmc(model_config, interceptor, num_samples=2000, burnin=1000, num_leapfrog_steps=4, num_adaptation_steps=500, num_optimization_s...
f06ac8e26f63a49d0eb12b82b69551f793d0f0c8
64,996
from typing import Optional def existing_external_event(external_id, events) -> Optional[CalendarEntry]: """Return existing external event or None.""" events = tuple(e for e in events if e.external_id == external_id) if len(events): return events[0] return None
0bc38241032654a584f7588d3cc3d794880c7a33
64,997
def get_ecg_path_example() -> path_t: """Return folder path to ECG example data. Returns ------- :class:`~pathlib.Path` or str path to folder with ECG raw files """ subject_ids = ["Vp01", "Vp02"] file_path = None # ensure that folder exists and data in folder is available f...
e2b4af3fbcfbd6bd075583c5c6e79854012d4599
64,998
def complete(request): """ Complete the authentication flow for the configured authenticator. """ def handle_request(request): # The auth_complete method of the authenticator should return a token or null # depending on whether authentication was successful token = auth_settings....
05038a21dff458f0aae66c1d5413f1c159c6f3d1
64,999