content
stringlengths
22
815k
id
int64
0
4.91M
def test_directory_origin_configuration_quote_character(sdc_builder, sdc_executor, delimiter_format_type, data_format, quote_character, shell_executor, delimited_file_writer, delimiter_character): """Veri...
5,345,800
async def test_async_get_config( aiohttp_session: aiohttp.ClientSession, aiohttp_server: Any ) -> None: """Test async_get_event_summary.""" config_in = {"cameras": {"front_door": {"camera_config": "goes here"}}} config_handler = Mock(return_value=web.json_response(config_in)) server = await start_f...
5,345,801
def project(dim, states): """Qiskit wrapper of projection operator. """ ket, bra = states if ket in range(dim) and bra in range(dim): return st.basis(dim, ket) * st.basis(dim, bra).dag() else: raise Exception('States are specified on the outside of Hilbert space %s' % states)
5,345,802
def check_service_status(ssh_conn_obj, service_name, status="running", device='server'): """ Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) Function to check the service status :param ssh_conn_obj: :param service_name: :param status: :return: """ st.log("##### Checking ...
5,345,803
def _persist_block(block_node, block_map): """produce persistent binary data for a single block Children block are assumed to be already persisted and present in block_map. """ data = tuple(_to_value(v, block_map) for v in block_node) return S_BLOCK.pack(*data)
5,345,804
def get_graph_names(test_dir): """Parse test_dir/*GRAPHFILES and return basenames for all .graph files""" graph_list = [] GRAPHFILES_files = [f for f in os.listdir(test_dir) if f.endswith("GRAPHFILES")] for GRAPHFILE in GRAPHFILES_files: with open(os.path.join(test_dir, GRAPHFILE), 'r') as f: ...
5,345,805
def get_sagemaker_feature_group(feature_group_name: str): """Used to check if there is an existing feature group with a given feature_group_name.""" try: return sagemaker_client().describe_feature_group(FeatureGroupName=feature_group_name) except botocore.exceptions.ClientError as error: log...
5,345,806
def check_system(command, message, exit=0, user=None, stdin=None, shell=False, timeout=None, timeout_signal='TERM'): """Runs the command and checks its exit status code. Handles all of the common steps associated with running a system command: runs the command, checks its exit status code against the expec...
5,345,807
def get_repo_data(api_token): """Executes the GraphQL query to get repository data from one or more GitHub orgs. Parameters ---------- api_token : str The GH API token retrieved from the gh_key file. Returns ------- repo_info_df : pandas.core.frame.DataFrame """ import requ...
5,345,808
def getJson(file, filters={}): """Given a specific JSON file (string) and a set of filters (dictionary key-values pairs), will return a JSON-formatted tree of the matching data entries from that file (starting as a null-key list of objects). """ with open(file, 'r') as f: j = json.loads(f.read()) all = j[...
5,345,809
def underline_node_formatter(nodetext, optionstext, caller=None): """ Draws a node with underlines '_____' around it. """ nodetext_width_max = max(m_len(line) for line in nodetext.split("\n")) options_width_max = max(m_len(line) for line in optionstext.split("\n")) total_width = max(options_widt...
5,345,810
def compare(path_to_config, config_file): """Rules.""" # This sys.path bookended chunk is common to all entry functions. sys.path.insert(0, './') app_pipeline = importlib.import_module(path_to_config + '.app_pipeline') subproject_name = os.path.basename(os.path.dirname(__file__)) app_con...
5,345,811
def validategeojson(data_input, mode): """GeoJSON validation example >>> import StringIO >>> class FakeInput(object): ... json = open('point.geojson','w') ... json.write('''{"type":"Feature", "properties":{}, "geometry":{"type":"Point", "coordinates":[8.5781228542328, 22.87500500679]}, "crs...
5,345,812
def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes): """ Create the layers for a fully convolutional network. Build skip-layers using the vgg layers. :param vgg_layer3_out: TF Tensor for VGG Layer 3 output :param vgg_layer4_out: TF Tensor for VGG Layer 4 output :param vgg_layer7...
5,345,813
def determine_issues(project): """ Get the list of issues of a project. :rtype: list """ issues = project["Issue"] if not isinstance(issues, list): return [issues] return issues
5,345,814
def init_parser(subparsers): """ Initialize the subparser. """ parser = subparsers.add_parser(COMMAND, help="delete a task from the list.") parser.add_argument("id", type=int, nargs='?', default=-1, help="the id of the task which should be deleted.")
5,345,815
def find_image_files(path=None): """ Used to find image files. Argument: path - path to directory of 'img.image' files """ if path is None: path = os.getcwd() folders = [] for folder in os.listdir(path): if folder.endswith("img.image"): folders.append(os.path.join(path...
5,345,816
def get_media_after_date(mountpoint: str, date:str): """ Date format in EXIF yyyy:mm:dd, look for EXIF:CreateDate """ metadata = get_media_list(mountpoint) filtered_meta = list() for m in metadata: if 'File:FileModifyDate' in m: if is_after(m['File:FileModifyDate'].split(' ')...
5,345,817
def failure_message_on_plane(context): """Report an informative error message in a popup. Args: context: Blender bpy.context instance. Returns: Nothing. """ pg = context.scene.pdt_pg pg.error = f"{PDT_ERR_NOINT}" context.window_manager.popup_menu(oops, title="Error", icon...
5,345,818
def run_normal_game(): """Run a complex game, like the real thing.""" stage = create_stage() contestant_first_pick = random.randrange(3) montys_pick_algorithm(stage, contestant_first_pick) contestant_second_pick = contestants_second_pick_algorithm(stage, contestant_first_pick) wins = contesta...
5,345,819
def reformat_wolfram_entries(titles, entries): """Reformat Wolfram entries.""" output_list = [] for title, entry in zip(titles, entries): try: if ' |' in entry: entry = '\n\t{0}'.format(entry.replace(' |', ':') .replace('\n', '\n\t...
5,345,820
def project_root() -> str: """Returns path to root directory of a project""" return os.path.join(_file_directory_path(__file__), '..')
5,345,821
def GetAndValidateRowId(row_dict): """Returns the integer ID for a new Row. This method is also responsible for validating the input fields related to making the new row ID. Args: row_dict: A dictionary obtained from the input JSON. Returns: An integer row ID. Raises: BadRequestError: The in...
5,345,822
def generate_test_cases(ukernel, channel_tile, pixel_tile, isa): """Generates all tests cases for a BILINEAR micro-kernel. Args: ukernel: C name of the micro-kernel function. channel_tile: Number of channels processed per one iteration of the inner loop of the micro-kernel. pixel_tile...
5,345,823
def string_mask(stringvalue: str): """Method to divide two divide_two_numbers ARGUMENTS: Value1: first value Value2: second value """ for char in stringvalue: print(ord(char), end=' | ')
5,345,824
def get_file_range(ase, offsets, timeout=None): # type: (blobxfer.models.azure.StorageEntity, # blobxfer.models.download.Offsets, int) -> bytes """Retrieve file range :param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity :param blobxfer.models.download.Offsets offsets: download ...
5,345,825
def parse_cli_args(): """Return parsed command-line arguments.""" parser = ArgumentParser(description='parse and summarize a GLSL file') parser.add_argument('path') shader_type_names = [member.name for member in ShaderType] parser.add_argument('shader_type', nargs='?', choice...
5,345,826
def genus_species_name(genus, species): """Return name, genus with species if present. Copes with species being None (or empty string). """ # This is a simple function, centralising it for consistency assert genus and genus == genus.strip(), repr(genus) if species: assert species == spe...
5,345,827
def _native_set_to_python_list(typ, payload, c): """ Create a Python list from a native set's items. """ nitems = payload.used listobj = c.pyapi.list_new(nitems) ok = cgutils.is_not_null(c.builder, listobj) with c.builder.if_then(ok, likely=True): index = cgutils.alloca_once_value(c....
5,345,828
def asm(code, arch='x86', mode='32'): """Assemble instructions to bytecode"" Args: code: str, eg: add eax, ebx; pop ecx arch: str, default value: 'x86' mode: str, default value: '32' """ arch = get_kt_arch(arch) if arch is None: print('Unsupported architecture') ...
5,345,829
def JointAngleCalc(frame,vsk): """ Joint Angle Calculation function. Calculates the Joint angles of plugingait and stores the data in array Stores: RPel_angle = [] LPel_angle = [] RHip_angle = [] LHip_angle = [] RKnee_angle = [] LKnee_angle = [] RAnkle_angle = [] LAnkle_angl...
5,345,830
def confidence_thresholding_2thresholds_2d( probabilities_per_model: List[np.array], ground_truths: Union[List[np.array], List[pd.Series]], metadata, threshold_output_feature_names: List[str], labels_limit: int, model_names: Union[str, List[str]] = None, output_di...
5,345,831
def var_to_str(var): """Returns a string representation of the variable of a Jax expression.""" if isinstance(var, jax.core.Literal): return str(var) elif isinstance(var, jax.core.UnitVar): return "*" elif not isinstance(var, jax.core.Var): raise ValueError(f"Idk what to do with this {type(var)}?") ...
5,345,832
def cut_reset(): """ Select the reference Plane to cut the Object from. """ global myDialog global m_cut_selectObjects del m_cut_selectObjects[:] m_text = "" # deActivate the button_cut_select_line myDialog.ui.button_cut_select_line.setEnabled(False) # deActivate the button_cut_sele...
5,345,833
def lal_binary_neutron_star( frequency_array, mass_1, mass_2, luminosity_distance, a_1, tilt_1, phi_12, a_2, tilt_2, phi_jl, theta_jn, phase, lambda_1, lambda_2, **kwargs): """ A Binary Neutron Star waveform model using lalsimulation Parameters ---------- frequency_array: array_...
5,345,834
def handledisc(tree): """Binarize discontinuous substitution sites. >>> print(handledisc(Tree('(S (X 0 2 4))'))) (S (X 0 (X|<> 2 (X|<> 4)))) >>> print(handledisc(Tree('(S (X 0 2))'))) (S (X 0 (X|<> 2))) """ for a in tree.postorder(lambda n: len(n) > 1 and isinstance(n[0], int)): binarize(a, rightmostunary=Tru...
5,345,835
def check_bounds(shape: Shape, point: Coord) -> bool: """Return ``True`` if ``point`` is valid index in ``shape``. Args: shape: Shape of two-dimensional array. point: Two-dimensional coordinate. Return: True if ``point`` is within ``shape`` else ``False``. """ return (0 <...
5,345,836
def logout(home=None): """ Logs out current session and redirects to home :param str home: URL to redirect to after logout success """ flask_login.logout_user() return redirect(request.args.get('redirect', home or url_for('public.home')))
5,345,837
def N(u,i,p,knots): """ u: point for which a spline should be evaluated i: spline knot p: spline order knots: all knots Evaluates the spline basis of order p defined by knots at knot i and point u. """ if p == 0: if knots[int(i)] < u and u <=knots[int(i+1)]: retu...
5,345,838
def infer_growth_rate(data, od_bounds=None, convert_time=True, groupby=None, cols={'time':'clock_time', 'od':'od_600nm'}, return_opts=True, print_params=True, **k...
5,345,839
def check_merge(s, idn) -> bool: """ Check whether a set of nodes is valid to merge """ found = False in_size = None out_size = None stride = None act = None nds = [idn[i] for i in state2iset(s)] if len(nds) == 1: return True for nd in nds: if not isinstance(n...
5,345,840
def _run_server(file_store_path, artifact_root, host, port, workers): """Run the MLflow server, wrapping it in gunicorn""" env_map = {} if file_store_path: env_map[FILE_STORE_ENV_VAR] = file_store_path if artifact_root: env_map[ARTIFACT_ROOT_ENV_VAR] = artifact_root bind_address = "%...
5,345,841
def typeMap(name, package=None): """ typeMap(name: str) -> Module Convert from C/C++ types into VisTrails Module type """ if package is None: package = identifier if isinstance(name, tuple): return [typeMap(x, package) for x in name] if name in typeMapDict: return ty...
5,345,842
def _rm_from_diclist(diclist, key_to_check, value_to_check): """Function that removes an entry form a list of dictionaries if a key of an entry matches a given value. If no value of the key_to_check matches the value_to_check for all of the entries in the diclist, the same diclist will be returned that ...
5,345,843
def fix_colocation_after_import(input_map, absolute_import_scope): """Fixes colocation attributes after import according to input_map. This function is meant to be called after importing a GraphDef, in order to rewrite colocate_with constrains analogous to how inputs to ops are rewritten by input_map during im...
5,345,844
def odr_linear(x, y, intercept=None, beta0=None): """ Performs orthogonal linear regression on x, y data. Parameters ---------- x: array_like x-data, 1D array. Must be the same lengths as `y`. y: array_like y-data, 1D array. Must be the same lengths as `x`. intercept: floa...
5,345,845
def get_centroid_world_coordinates(geo_trans, raster_x_size, raster_y_size, x_pixel_size, y_pixel_size): """Return the raster centroid in world coordinates :param geo_trans: geo transformation :type geo_trans: tuple with six values :param raster_x_size: number of columns :type raster_x_size: int ...
5,345,846
def save_change_item(request): """ 保存改变项 算法:在rquest_list中查找对应的uuid,找到后将数据更新其中 :param request: :return: """ if request.method != 'POST': return HttpResponse("数据异常.") str_data = request.POST.get('jsons') logger.info("change_item: " + str_data) jsons = json.load...
5,345,847
def test_starg_mroute_p0(request): """ 1. Verify (*,G) mroute detail on FRR router after BSM rp installed Topology used: b1_____ | | s1-----f1-----i1-----l1----r1 | ______| b2 b1 - BSR 1 b2 - BSR 2 s1 - Source f1 - FHR...
5,345,848
def test_authorization_received(): """Assert that authorization received validation works as expected.""" statement = copy.deepcopy(FINANCING_STATEMENT) del statement['authorizationReceived'] is_valid, errors = validate(statement, 'financingStatement', 'ppr') assert is_valid statement['authori...
5,345,849
def update_tests_if_needed(): """Updates layout tests every day.""" data_directory = environment.get_value('FUZZ_DATA') error_occured = False expected_task_duration = 60 * 60 # 1 hour. retry_limit = environment.get_value('FAIL_RETRIES') temp_archive = os.path.join(data_directory, 'temp.zip') tests_url = ...
5,345,850
def save_fig(plot, name): """Save figure. :param plot: Matplotlib's pyplot. :type plot: matplotlib.pyplot :param name: File name. :type name: str """ path = figures_dir / f'{name}.png' plot.savefig(path) log.info(f'Figure saved: {path}') path = figures_dir / f'{name}.svg' p...
5,345,851
def get_lastest_stocklist(): """ 使用pytdx从网络获取最新券商列表 :return:DF格式,股票清单 """ import pytdx.hq import pytdx.util.best_ip print(f"优选通达信行情服务器 也可直接更改为优选好的 {{'ip': '123.125.108.24', 'port': 7709}}") # ipinfo = pytdx.util.best_ip.select_best_ip() api = pytdx.hq.TdxHq_API() # with api.conne...
5,345,852
def grpc_detect_ledger_id(connection: "GRPCv1Connection") -> str: """ Return the ledger ID from the remote server when it becomes available. This method blocks until a ledger ID has been successfully retrieved, or the timeout is reached (in which case an exception is thrown). """ LOG.debug("Star...
5,345,853
def cross_mcs(input_vectors, value_fields, verbose=False, logger=None): """ Compute map comparison statistics between input vector features. MCS (Map Comparison Statistic) indicates the average difference between any pair of feature polygon values, expressed as a fraction of the highest value. MCS is c...
5,345,854
def extrapolate_trace(traces_in, spec_min_max_in, fit_frac=0.2, npoly=1, method='poly'): """ Extrapolates trace to fill in pixels that lie outside of the range spec_min, spec_max). This routine is useful for echelle spectrographs where the orders are shorter than the image by a signfiicant amount, since...
5,345,855
def getStopWords(stopWordFileName): """Reads stop-words text file which is assumed to have one word per line. Returns stopWordDict. """ stopWordDict = {} stopWordFile = open(stopWordFileName, 'r') for line in stopWordFile: word = line.strip().lower() stopWordDict[wor...
5,345,856
def metade(valor): """ -> Realiza o calculo de metade salárial :param valor: Valor do dinheiro :param view: Visualizar ou não retorno formatado :return: Retorna a metade do valor """ if not view: return moeda(valor / 2) else: return valor / 2 return valor / 2
5,345,857
def monopole(uvecs: [float, np.ndarray], order: int=3) -> [float, np.ndarray]: """ Solution for I(r) = 1. Also handles nonzero-w case. Parameters ---------- uvecs: float or ndarray of float The cartesian baselines in units of wavelengths. If a float, assumed to be the magnitude of ...
5,345,858
def get_question( numbers: OneOrManyOf(NUMBERS_AVAILABLE), cases: OneOrManyOf(CASES_AVAILABLE), num: hug.types.in_range(1, MAX_NUM + 1) = 10): """When queried for one or multiple numbers and cases, this endpoint returns a random question.""" questions = [] bag = NounCaseQuestionBag( no...
5,345,859
def delete(ctx, **_): """Deletes a Resource Group""" if ctx.node.properties.get('use_external_resource', False): return azure_config = ctx.node.properties.get('azure_config') if not azure_config.get("subscription_id"): azure_config = ctx.node.properties.get('client_config') else: ...
5,345,860
def test_dpp_proto_auth_resp_invalid_r_proto_key(dev, apdev): """DPP protocol testing - invalid R-Proto Key in Auth Resp""" run_dpp_proto_auth_resp_missing(dev, 67, "Invalid Responder Protocol Key")
5,345,861
def _print_attrs(attr, html=False): """ Given a Attr class will print out each registered attribute. Parameters ---------- attr : `sunpy.net.attr.Attr` The attr class/type to print for. html : bool Will return a html table instead. Returns ------- `str` Stri...
5,345,862
def create_wave_header(samplerate=44100, channels=2, bitspersample=16, duration=3600): """Generate a wave header from given params.""" # pylint: disable=no-member file = BytesIO() numsamples = samplerate * duration # Generate format chunk format_chunk_spec = b"<4sLHHLLHH" format_chunk = str...
5,345,863
def xslugify(value): """ Converts to ASCII. Converts spaces to hyphens. Removes characters that aren't alphanumerics, underscores, slash, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace. (I.e., does the same as slugify, but also converts slashes to dashes.) """ ...
5,345,864
def firstcond(list1, list2): """this is a fixture for testing conditions when the list is a four node list """ ll = LinkedList() ll.insert(1, 5) ll.insert(3, 9) ll.insert(2, 4) return ll
5,345,865
def read_bert_vocab(bert_model_path): """读取bert词典""" dict_path = os.path.join(bert_model_path, 'vocab.txt') token2idx = {} with open(dict_path, 'r', encoding='utf-8') as f: tokens = f.read().splitlines() for word in tokens: token2idx[word] = len(token2idx) return token2idx
5,345,866
def test_get_index(list): """ Vectors should be subscript-able in a way that mimics lists """ inf_vec = V(list) fin_vec = V[len(list)](list) for idx, val in enumerate(list): assert inf_vec[idx] == fin_vec[idx] == val
5,345,867
def _template_message(desc, descriptor_registry): # type: (Descriptor, DescriptorRegistry) -> str """ Returns cls_def string, list of fields, list of repeated fields """ this_file = desc.file desc = SimpleDescriptor(desc) if desc.full_name in WKTBASES: desc.bases.append(WKTBASES[desc...
5,345,868
def random_portfolio(n, k, mu=0., sd=0.01, corr=None, dt=1., nan_pct=0.): """ Generate asset prices assuming multivariate geometric Brownian motion. :param n: Number of time steps. :param k: Number of assets. :param mu: Drift parameter. Can be scalar or vector. Default is 0. :param sd: Volatility o...
5,345,869
def parse_command_line_arguments() -> None: """ Parse command line arguments and save their value in config.py. :return: None """ parser = argparse.ArgumentParser() parser.add_argument("-d", "--dataset", default="CBIS-DDSM", help="The dataset to us...
5,345,870
def vulnerabilities_for_image(image_obj): """ Return the list of vulnerabilities for the specified image id by recalculating the matches for the image. Ignores any persisted matches. Query only, does not update the data. Caller must add returned results to a db session and commit in order to persist. ...
5,345,871
def update_cg_itp_obj(ns, parameters_set, update_type): """Update coarse-grain ITP. ns requires: out_itp (edited inplace) opti_cycle exec_mode """ if update_type == 1: # intermediary itp_obj = ns.out_itp elif update_type == 2: # cycles optimized itp_obj = n...
5,345,872
def superpose_images(obj, metadata, skip_overlaps=False, num_frames_for_bkgd=100, every=1, color_objs=False, disp_R=False, b=1.7, d=2, false_color=False, cmap='jet', remove_positive_noise=True): """ Superposes images of an object onto one frame. ...
5,345,873
def gen_s_linear(computed_data, param ): """Generate sensitivity matrix for wavelength dependent sensitivity modeled as line""" mat=np.zeros((computed_data.shape[0],computed_data.shape[0])) #print(mat.shape) for i in range(computed_data.shape[0]): for j in range(computed_data.shape[0]): ...
5,345,874
def upsample2(x): """ Up-sample a 2D array by a factor of 2 by interpolation. Result is scaled by a factor of 4. """ n = [x.shape[0] * 2 - 1, x.shape[1] * 2 - 1] + list(x.shape[2:]) y = numpy.empty(n, x.dtype) y[0::2, 0::2] = 4 * x y[0::2, 1::2] = 2 * (x[:, :-1] + x[:, 1:]) y[1::2, 0...
5,345,875
def test_should_return_return_invalid_login_msg(db_session): """ Teste deve retornar usuário quando a senha está correta """ user = User( name="John Doe", username="jd", email="jd@example.com", ) db_session.add(user) db_session.commit() with pytest.raises(Unautho...
5,345,876
def test_surf_pipeline_cont_endpoint(): """Check: Data (Continuous Endpoint): SURF works in a sklearn pipeline""" np.random.seed(240932) clf = make_pipeline(SURF(n_features_to_select=2), RandomForestRegressor(n_estimators=100, n_jobs=-1)) assert abs(np.mean(cross_val_score(clf,...
5,345,877
def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object is appropriate. Can be called multiple times on a single string. """ if isinstance(s, SafeData): return s if isinstance(s, bytes) ...
5,345,878
def ensure_environment_directory(environment_file_directory): """Ensure directory for environment files exists and is private""" # ensure directory exists os.makedirs(environment_file_directory, mode=0o700, exist_ok=True) # validate permissions mode = os.stat(environment_file_directory).st_mode ...
5,345,879
def _unravel_plug(node, attr): """Convert Maya node/attribute combination into an MPlug. Note: Tries to break up a parent attribute into its child attributes: .t -> [tx, ty, tz] Args: node (str): Name of the Maya node attr (str): Name of the attribute on the Maya node ...
5,345,880
def index(): """ Root URL response """ return jsonify(name='Payment Demo REST API Service', version='1.0'), status.HTTP_200_OK
5,345,881
def unvoigt(A): """ Converts from 6x1 to 3x3 :param A: 6x1 Voigt vector (strain or stress) :return: 3x3 symmetric tensor (strain or stress) """ a=np.zeros(shape=(3,3)) a[0,0]=A[0] a[0,1]=A[5] a[0,2]=A[4] a[1,0]=A[5] a[1,1]=A[1] a[1,2]=A[3] a[2,0]=A[4] a[2,1]=A[3] a[2,2]=A[2] return (a)
5,345,882
def get_parser(): """ Creates a new argument parser. """ parser = argparse.ArgumentParser('niget_yyyymm.py', formatter_class=argparse.RawDescriptionHelpFormatter, description=""" help description """ ) version = '%(prog)s ' + __version__ parser.add_argument('--version', '-v', action='version', version=v...
5,345,883
def create_db(): """ Creates the db tables """ db.create_all()
5,345,884
def _calculate_rmsd(P, Q): """Calculates the root-mean-square distance between the points of P and Q. The distance is taken as the minimum over all possible matchings. It is zero if P and Q are identical and non-zero if not. """ distance_matrix = cdist(P, Q, metric='sqeuclidean') matching = lin...
5,345,885
def use_backend(backend): """Select a backend for image decoding. Args: backend (str): The image decoding backend type. Options are `cv2`, `pillow`, `turbojpeg` (see https://github.com/lilohuang/PyTurboJPEG) and `tifffile`. `turbojpeg` is faster but it only supports `.jpeg` file...
5,345,886
def initialize_parameters(): """ Initializes weight parameters to build a neural network with tensorflow. The shapes are: W1 : [4, 4, 3, 8] W2 : [2, 2, 8, 16] Note that we will hard code the shape values in the function to make the grading simpler. Normall...
5,345,887
def generate_dynamic_secret(salt: str) -> str: """Creates a new overseas dynamic secret :param salt: A ds salt """ t = int(time.time()) r = "".join(random.choices(string.ascii_letters, k=6)) h = hashlib.md5(f"salt={salt}&t={t}&r={r}".encode()).hexdigest() return f"{t},{r},{h}"
5,345,888
def upload(slot_id): """ Upload a file """ form = request.form # Is the upload using Ajax, or a direct POST by the form? is_ajax = False if form.get("__ajax", None) == "true": is_ajax = True # Target folder for these uploads. target = os.path.join(APP_ROOT, UPLOAD_ROOT, slo...
5,345,889
def is_sim_f(ts_kname): """ Returns True if the TSDist is actually a similarity and not a distance """ return ts_kname in ('linear_allpairs', 'linear_crosscor', 'cross_correlation', 'hsdotprod_autocor_truncated', ...
5,345,890
def test_coerce() -> None: """Test value coercion.""" @dataclass class _TestClass: ival: int = 0 fval: float = 0.0 # Float value present for int should never work. obj = _TestClass() # noinspection PyTypeHints obj.ival = 1.0 # type: ignore with pytest.raises(TypeError)...
5,345,891
def initialise_pika_connection( host: Text, username: Text, password: Text, port: Union[Text, int] = 5672, connection_attempts: int = 20, retry_delay_in_seconds: float = 5, ) -> "BlockingConnection": """Create a Pika `BlockingConnection`. Args: host: Pika host username: ...
5,345,892
def _validate_game_id(game_id): """ Test whether a game ID is valid. If it is not, raise a 403 Forbidden. """ try: int(str(game_id)) except ValueError: abort(403, message="Malformed game ID {}".format(game_id))
5,345,893
def units(arg_name, unit): """Decorator to define units for an input. Associates a unit of measurement with an input. Parameters ---------- arg_name : str Name of the input to attach a unit to. unit : str Unit of measurement descriptor to use (e.g. "mm"). Example -----...
5,345,894
async def to_thread_task(func: Callable, *args, **kwargs) -> Task: """Assign task to thread""" coro = to_thread(func, *args, **kwargs) return create_task(coro)
5,345,895
def setup_logging(stream_or_file=None, debug=False, name=None): """ Create a logger for communicating with the user or writing to log files. By default, creates a root logger that prints to stdout. :param stream_or_file: The destination of the log messages. If None, stdout will be used. :ty...
5,345,896
def combo2fname( combo: Dict[str, Any], folder: Optional[Union[str, Path]] = None, ext: Optional[str] = ".pickle", sig_figs: int = 8, ) -> str: """Converts a dict into a human readable filename. Improved version of `combo_to_fname`.""" name_parts = [f"{k}_{maybe_round(v, sig_figs)}" for k, ...
5,345,897
def insertTopic(datum): """Load a single topic.""" _insertSingle(datum, 'topic')
5,345,898
def cls_from_str(name_str): """ Gets class of unit type from a string Helper function for end-users entering the name of a unit type and retrieving the class that contains stats for that unit type. Args: name_str: str Returns: UnitStats """ name_str = name_str.l...
5,345,899