content
stringlengths
22
815k
id
int64
0
4.91M
def get_podcastep(podcastep_id): """ Get a podcast ep by their ID in your media server """ conn = database_connect() if(conn is None): return None cur = conn.cursor() try: ######### # TODO # ######### ##############################################...
5,290,800
def ImageMLP_Imagenet16_Relu256x256x256(): """A 3 hidden layer MLP trained on 16x16 resized imagenet.""" datasets = image.imagenet16_datasets(batch_size=128) return _MLPImageTask(datasets, [256, 256, 256])
5,290,801
def get_database_output(filter: Optional[pulumi.Input[Optional[pulumi.InputType['GetDatabaseFilterArgs']]]] = None, zone: Optional[pulumi.Input[Optional[str]]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetDatabaseResult]: """ Get inform...
5,290,802
def _ros(veos, vpos, eos, pos): """ ROG = Rate of Senescing (Days) """ return (veos - vpos) / (eos - pos)
5,290,803
def stop_container(duthost, container_name): """Stops the running container. Args: duthost: Host DUT. container_name: A string represents the container which will be stopped. Returns: None """ logger.info("Stopping the container '{}' on DuT '{}' ...".format(container_name, dutho...
5,290,804
def bollinger_lband_indicator(close, n=20, ndev=2, fillna=False): """Bollinger Low Band Indicator Returns 1, if close is lower than bollinger low band. Else, return 0. https://en.wikipedia.org/wiki/Bollinger_Bands Args: close(pandas.Series): dataset 'Close' column. n(int): n period. ...
5,290,805
def make_cython_wrapper(filenames, sources, modulename=None, target=".", config=Config(), incdirs=(), compiler_flags=("-O3",), verbose=0): """Make Cython wrapper for C++ files. Parameters ---------- filenames : list of strings or string C++ files ...
5,290,806
def _create_missing_method(name): """Create a drop-in callable for a missing role method with the given name.""" def bridge(roles, compound, *args, **kwargs): return proceed(name, roles, compound, *args, **kwargs) return bridge
5,290,807
def test_paragraph_series_m_hs_ol_nl_i3_t_nl_i3_hs(): """ Test case: Ordered list newline indent of 3 text new line indent of 3 setext heading was: test_list_blocks_256hxc """ # Arrange source_markdown = """1. foo --- """ expected_tokens = [ "[olist(1,1):.:1:3:: \n ...
5,290,808
def werCalc(s1, s2): """ Computes the Word Error Rate, defined as the edit distance between the two provided sentences after tokenizing to words. Arguments: s1 (string): space-separated sentence s2 (string): space-separated sentence """ s1 = s1.lower() s2 = s2.lower() # b...
5,290,809
def not_found_error(error): """404 Page Missing handling""" if wants_json_response(): return api_error_response(404) return render_template('errors/404.html'), 404
5,290,810
def save_union_users_v3(p): """ 新需求,看最后k条tweets, 2019-03-01 ~ 2019-10-10 """ rsts = {} all_dates = [dt.to_date_string() for dt in pendulum.Period(pendulum.Date(2019, 3, 1), pendulum.Date(2019, 10, 27))] for dt in all_dates: rsts[dt] = { ...
5,290,811
def read_general_arr(fpath, txt=True, compress=False): """ Reads general data array (txt, npy, or compressed npz) """ if txt: assert not compress return np.loadtxt(fpath, delimiter=',') else: X = np.load(fpath) if compress: return X['a'] else: ...
5,290,812
def RunTransformix(command): """Run the transfomix transformation. You must be able to call transformix from your command shell to use this. You must also have your transformation parameter files set before running (see transformix parameter files). Parameters ---------- command: string Sent to the system for ...
5,290,813
def timer(fcn): """Returns the runtime in ms of the function fcn""" def wrapper(*args, **kwargs): t0 = time.time_ns() res = fcn(*args, **kwargs) t = time.time_ns() - t0 print(f"{fcn.__name__}: {round(t * 10**-6, 1)} 'ms'") return res return wrapper
5,290,814
def read_landmarks(f_landmarks): """ Reads file containing landmarks for image list. Specifically, <image name> x1 y1 ... xK yK is expected format. :param f_landmarks: text file with image list and corresponding landmarks :return: landmarks as type dictionary. """ landmarks_lut = {} ...
5,290,815
def parse_char(ch): """ 'A' or '\x41' or '0x41' or '41' '\x00' or '0x00' or '00' """ if ch is None: return None if len(ch) == 1: return ord(ch) if ch[0:2] in ("0x", "\\x"): ch = ch[2:] if not ch: raise ValueError("Empty char") if len(ch) > 2: r...
5,290,816
def validate_parameters(self, parameters, task_id=None): """Validate parameters generated by the parameter parsing task All validation should be done here - are there data restrictions? Combinations that aren't allowed? etc. Returns: parameter dict with all keyword args required to load data. ...
5,290,817
def Get_Entry(): """ get the entry number of customers at every minute """ df['timestamp'] = df.index.time time_spent = df.groupby(['weekday','customer_no'], as_index=False).agg({'timestamp':'min'}) time_spent.head() entry = time_spent.groupby('timestamp').count() //5 entry['timestamp'] ...
5,290,818
def load_detections_into_dataset( dataset_name, dataset_dicts, det_file, top_k_per_obj=1, score_thr=0.0, train_objs=None, top_k_per_im=None, ): """Load test detections into the dataset. Args: dataset_name (str): dataset_dicts (list[dict]): annotations in Detectron2 D...
5,290,819
def revert_version(request, revision_id): """Roll back the object saved in a Version to the previous Version""" referer = request.META.get("HTTP_REFERER", "/") revision_obj = Revision.objects.get(pk=revision_id) revision_obj.revert() # revert all associated objects too msg = "Rolled back revision %...
5,290,820
def get_or_create_permission( session: Session, name: str, description: Optional[str] = None ) -> Tuple[Optional[Permission], bool]: """Get a permission or create it if it doesn't already exist. Returns: (permission, is_new) tuple """ perm = get_permission(session, name) is_new = False ...
5,290,821
def get_user_me( db: Session = Depends(deps.get_db), current_user: models.User = Depends( deps.get_current_active_user ), ) -> Any: """ Get current user. """ if current_user is None: raise exceptions.get_user_exception() role = ( None if not current_user.u...
5,290,822
def get_temp_dir(request): """ Action: If temporary directory does not exist, it is created. Then the temporary directory is returned Returns: Temporary Directory """ if request.session.get('tmp_dir', None) is None: tmp = os.path.join(gettempdir(), '{}'.format(hash(time.time()))) o...
5,290,823
def trigger_oauth_expires_test(limit): """ Test data for IFTTT trigger bunq_oauth_expires """ result = [{ "created_at": "2018-01-05T11:25:15+00:00", "expires_at": "2018-01-05T11:25:15+00:00", "meta": { "id": "1", "timestamp": "1515151515" } }, { ...
5,290,824
def translate_subset_type(subset_type): """Maps subset shortcut to full name. Args: subset_type (str): Subset shortcut. Returns: str: Subset full name. """ if subset_type == 'max': model = 'best' elif subset_type == 'random': model = 'random' elif subset_typ...
5,290,825
def mid2aud(n_mid): """Return an audio segment from a mid file and build a wav meanwhile""" m2a.FluidSynth().midi_to_audio(mid_dir + n_mid + '.mid', wav_dir + n_mid + '.wav') seg = AudioSegment.from_file(wav_dir + n_mid + '.wav') return seg
5,290,826
def lambda_handler(event, context): """ expected event: { "body-json" : {}, "params" : { "path" : {}, "querystring" : { "game" : "string" }, "header" : {} }, "stage-variables" : { } """ if type(event) is not dict: logger....
5,290,827
def open_file_on_worker(view): """Open the file on the worker process""" service = cli.get_service() if not service: return None service.open_on_worker(view.file_name(), view.substr(sublime.Region(0, view.size())))
5,290,828
def solar_offset(geom: Geometry, precision: str = "h") -> timedelta: """ Given a geometry compute offset to add to UTC timestamp to get solar day right. This only work when geometry is "local enough". :param precision: one of ``'h'`` or ``'s'``, defaults to hour precision """ lon = mid_longitud...
5,290,829
def bgr_to_y(image): """Convert a bgr image to grayscale. :param image: an image denoted by a numpy array, which is HWC, and channels are in gbr :type image: np.array :return: the grayscale image :rtype: np.array (with dtype np.float32), in range 0~255 """ image = image.astype(np.float32) /...
5,290,830
def _create_email( to_field="to_user@test1.com", from_field="from_user@test2.com", subject="This is a test email", body="Almost empty text message", attachment=None, maintype=None, subtype=None, ): """ Builds and returns an ``email.message.EmailMessage`` instance with to, from, s...
5,290,831
def by_user_recipe_id(user_id, recipe_id): """ Get Recipe owned by a user """ session = query_session.get_session() return session.query(Recipe).filter(Recipe.id == recipe_id) \ .filter(Recipe.user_id == user_id) \ .first()
5,290,832
def test_greedy_one_or_more(): """ Test greedy variant of one or more. """ grammar = r""" S: A+ A*; terminals A: "a"; """ g = Grammar.from_string(grammar) p = GLRParser(g) forest = p.parse("a a a a a a") assert len(forest) == 6 # But greedy variant has only one solu...
5,290,833
def Z_score(data): """ Z_score标准化 :param data: :return: """ x, y, z = data.shape def z_score(data): return (data - np.mean(data)) / np.maximum(np.std(data), 1 / 256) for i in range(z): data[:, :, i] = z_score(data[:, :, i]) return data
5,290,834
def torch_vad(sig, winLen=400, winSht=160, ener_thres=5.7, mean_scale=0.5, prop_thres=0.12, frm_context=2, twice_log_max_signed_int16=20.794354380710768, eps=1.19209e-07): """ Equivalent to KALDI's energy-based VAD implementation (https://github.com/kaldi-asr/kaldi/...
5,290,835
async def create_sync_payload(dc, key): """Converts dictionary to JSON, encrypts it with provided public key (PEM) and returns it as a Base64-encoded string. """ return await _run_async(_create_sync_payload, dc, key)
5,290,836
def arg_setup(): """Sets up an argument parser and returns the arguments.""" parser = argparse.ArgumentParser( description="run simulations of agents with wishful thinking") parser.add_argument('scenario', help="""the scenario to use (currently: sequence, fixed, ...
5,290,837
def graph_to_xarray(graph): """ Convert a hetnetpy.hetnet.Graph to an xarray.Dataset """ data_vars = dict() for metaedge in graph.metagraph.get_edges(exclude_inverts=True): data_array = metaedge_to_data_array(graph, metaedge) name = metaedge.get_abbrev() data_vars[name] = dat...
5,290,838
def get_shared_segments(poly1, poly2, bool_ret=False): """Returns the line segments in common to both polygons. Parameters ---------- poly1 : libpysal.cg.Polygon A Polygon. poly2 : libpysal.cg.Polygon A Polygon. bool_ret : bool Return only a ``bool``. Default is ``False`...
5,290,839
def get_latest_resources_asset(name): """ Searches through hazm's releases and find latest release that contains resources. Parameters ---------- name: str The resource name Returns ------- asset: GitReleaseAsset The resources asset """ g = Github() repo...
5,290,840
def conv1x1_1bit(in_channels, out_channels, stride=1, groups=1, bias=False, binarized=False): """ Convolution 1x1 layer with binarization. Parameters: ---------- in_channels : int Number of input channels. ...
5,290,841
def get_vec_by_query(text): """提取文本向量 """ token_ids, segment_ids = tokenizer.encode(text, max_length=maxlen) # print("token_ids={},segment_ids={}".format(token_ids, segment_ids)) vec = encoder.predict([[token_ids], [segment_ids]])[0] # print('vec size={}, element={}'.format(len(vec), vec[-1])) ...
5,290,842
def serving_input_receiver_fn(): """An input function for TensorFlow Serving.""" def _preprocess_image(image_bytes): """Preprocess a single raw image.""" image = tf.image.decode_jpeg(image_bytes, channels=IMG_CHANNEL) image.set_shape((None, None, IMG_CHANNEL)) image = tf.image.r...
5,290,843
def _process_optimization_results(results, results_arguments): """Expand the solutions back to the original problems. Args: results (list): list of dictionaries with the harmonized results objects. results_arguments (list): each element is a dictionary supplying the star...
5,290,844
def check_preprocessors(preprocessors): """Check preprocessors in recipe.""" valid_functions = set(preprocessor.DEFAULT_ORDER) for name, profile in preprocessors.items(): invalid_functions = set(profile) - {'custom_order'} - valid_functions if invalid_functions: raise RecipeError...
5,290,845
def is_valid_continuous_partition_object(partition_object): """Tests whether a given object is a valid continuous partition object. :param partition_object: The partition_object to evaluate :return: Boolean """ if (partition_object is None) or ("weights" not in partition_object) or ("bins" not in pa...
5,290,846
def get( hostname, refresh_key, authorization_host, org_id, sddc_id, tier1, nat, verify_ssl=True, cert=None, cursor=None, page_size=None, sort_by=None, sort_ascending=None, ): """ Retrieves nat rules for Given SDDC CLI Example: .. code-block:: bash ...
5,290,847
def format_add_header(txt:str): """ """ if find_str(txt, 'MNAME') < 0 : ll2 = "NAME" + "" if find_str(txt, 'HELP') < 0 : pass ### Write down and check to_file(ll2, finew) isok = os_file_compile_check(finew) if isok : os.remove(fi) os.renam...
5,290,848
def add_fiber_array( component: Component, grating_coupler: Component = grating_coupler_te, gc_port_name: str = "W0", component_name: Optional[str] = None, taper_factory: Callable = taper, taper_length: float = 10.0, get_route_factory: Callable = route_fiber_array, get_input_labels_funct...
5,290,849
def commit(message: str, branch: str): """commit changes to git repository""" # check if git repository exists if git_utils.check_git() is not True: click.echo('ERROR: git repository for current directory does not exists') return # add changes for staging git_utils.add() # pro...
5,290,850
def main(): """Program entry point""" parser = argparse.ArgumentParser( description='Generic Python program') parser.add_argument('-e', '--long-option', help='Long option', action='store_true') parser.add_argument('file', h...
5,290,851
def run_all_below(ev): """ run_all_below """ display(Javascript('IPython.notebook.select_next()')) display(Javascript('IPython.notebook.execute_cells_below()'))
5,290,852
def run(prefix, items, timestamp, delta, output_path=None, creation_dir=None, parent_dir_name="logs", silent=False, interactive=False): """ collects log items and creates an archive with all collected items. items is a list of instances of 'Item' subclasses (see the collectables submodule). timestamp and de...
5,290,853
def get_instruments(instruments, level): """Returns a list of themis instruments for L2 data""" if level == 'l1': instr_list = ['bau', 'eff', 'efp', 'efw', 'esa', 'fbk', 'fff_16', 'fff_32', 'fff_64', 'ffp_16', 'ffp_32', 'ffp_64', 'ffw_16', 'ffw_32', 'ffw_64', ...
5,290,854
def add_release( target_name, target_resource_group, remote_url=None, remote_branch=None, remote_access_token=None, vsts_account_name=None, vsts_project_name=None, registry_resource_id=None, registry_name=None): """ Creates a build definiti...
5,290,855
def connect(): """initialize a connection to a mysql db on a local host server """ try: return mysql.connect( host="127.0.0.1", port="3306", user="root", password=ROOT_PASSWORD , auth_plugin='mysql_native_password', database="sales"...
5,290,856
def scatter(x, y, z, color=default_color, size=default_size, size_selected=default_size_selected, color_selected=default_color_selected, marker="diamond", selection=None, grow_limits=True, **kwargs): """Plots many markers/symbols in 3d :param x: {x} :param y: {y} :pa...
5,290,857
def create_openapi_spec(app: falcon.API) -> APISpec: """Creates an OpenAPI Spec for the Sustainerds API""" spec = APISpec( title="Sustainerds API", version="1.0.0", openapi_version="3.0.0", plugins=[MarshmallowPlugin()], ) return spec
5,290,858
def trigger_oauth_expires_delete(identity): """ Delete a specific trigger identity for trigger bunq_oauth_expires """ # We don't store trigger identities, so this call can be ignored return ""
5,290,859
def test_file_registered( psql_fixture, # noqa: F811 s3_fixture, # noqa: F811 amqp_fixture, # noqa: F811 ): # noqa: F811 """Test `subscribe_file_registered` method""" container, config = get_cont_and_conf( sources=[psql_fixture.config, s3_fixture.config, amqp_fixture.config] ) e...
5,290,860
def get_bidirectional_path_images(coord_path, path_ref): """ get_bidirectional_path_images Iterates over all coordinate points in a series and acquires both the forward-facing and rear-facing google street view image. Input: List of lat,lon,heading tuples corresponding to a walked series of adja...
5,290,861
def p_array(p): """array : LBRACK values RBRACK""" p[0] = p[2]
5,290,862
def upload_log(): """ Upload logfile to S3 store and delete local copy """ outfilename = 'scarplet-' + datetime.now().isoformat() + '.log' save_file_to_s3('/efs/logs/scarp_reduce.log', outfilename, bucket_name='scarp-log') os.remove('/efs/logs/scarp_reduce.log')
5,290,863
def bibTex_abs_format_export_post(): """ :return: """ results, status = export_post(request, 'BibTex Abs') if status == 200: maxauthor, keyformat, authorcutoff, journalformat = export_post_extras(request, 'BibTex Abs') return return_bibTex_format_export(solr_data=results, include_ab...
5,290,864
def ligands_rmsd_calculator(pdb_target, pdb_reference, resname="GRW"): """ :param pdb_target: problem pdb file :param pdb_reference: reference pdb file :param write2report: if True export results in a file :param write2pdb: pdb file with the result of the superposition between "pdb_target" and "pdb...
5,290,865
def knn_points_idx(p1, p2, K, sorted=False, version=-1): """ K-Nearest neighbors on point clouds. Args: p1: Tensor of shape (N, P1, D) giving a batch of point clouds, each containing P1 points of dimension D. p2: Tensor of shape (N, P2, D) giving a batch of point clouds, each ...
5,290,866
def modularity_individual(individual, graph: igraph.Graph): """ Decode an individual into a community membership vector and calculates the modularity of the individual community set. """ members = decode(individual) try: return graph.modularity(members) except igraph.InternalError as...
5,290,867
def api_get_challenge_detail(challengeID: int): """ 查询挑战详情 { "name":"名称", "id":ID, "description":描述, "level":等级, "hasFinished":是否完成 "problemsetList":[ { "name":"名称", "hasFinished":"是否完成", ...
5,290,868
def superop2chi(superop: np.ndarray) -> np.ndarray: """ Converts a superoperator into a list of Kraus operators. Operators with small norm may be excluded. :param superop: a dim**2 by dim**2 superoperator :return: a dim**2 by dim**2 process matrix """ return kraus2chi(superop2kraus(superop...
5,290,869
def is_instation(stmt): """Check whether the statement is an 'instance' or 'instance-list' definition """ return is_instance(stmt) or is_instance_list(stmt)
5,290,870
def check_multigene(overlaps, min_overlap_bp=0, min_query_overlap=0, min_gene_overlap=.5): """ overlaps is a list of: (gene, overlap_bp, overlap_gene_ratio, overlap_query_ratio) """ if all(x[1]>=min_overlap_bp and x[2]>=min_gene_overlap and x[3]>=min_query_overlap for x in overlaps): new_name = ...
5,290,871
def unpickle(): """Unpickle the bot token""" with open('token.pickle', 'rb') as file: token = pik(file) return token
5,290,872
def calcInertiaTensor(coords): """"Calculate inertia tensor from coords""" coords = getCoords(coords) center = calcCenter(coords) coords = coords - center return dot(coords.transpose(), coords)
5,290,873
def clarify_coroutine_warnings(exception_cell): """ Python's default error checking will print warnings of the form: RuntimeWarning: coroutine '???' was never awaited This function will will upgrade such a warning to a fatal error, while also injecting a additional clarification message about p...
5,290,874
def run_green(token: str, org: str, assignment_title: str, all_students: bool, students: list[str] = None): """ Enable push access to assignment repositories. """ repos = [] if all_students: repos = AssignmentRepo.get_all(token, org, assignment_title) elif students: for student i...
5,290,875
def auto_eq(only: Optional[Set[str]] = None, exclude: Optional[Callable[[str], bool]] = None): """ Decorator. Auto-adds a __hash__ function by hashing its attributes. :param only: Only include these attributes :param exclude: Exclude these attributes """ @wraps(auto_eq) def dec(cls): def __eq(self, other): ...
5,290,876
async def startup_event(): """ 获取链接 :return: """ app.state.redis = await aioredis.from_url("redis://localhost")
5,290,877
def AddLoggingParent(android_manifest, logging_parent_value): """Add logging parent as an additional <meta-data> tag. Args: android_manifest: A string representing AndroidManifest.xml logging_parent_value: A string representing the logging parent value. Raises: RuntimeError: Invalid manifest ...
5,290,878
def replace_nans_binmean(d, by, aggreagation="mean"): """"Replace each NaN value in `d` by the mean in each bin when grouping by `by`.""" return d.where(~np.isnan(d), mean_per_bin(d, by, aggreagation=aggreagation))
5,290,879
def repeatAndVarySequence(seq, poss, channels, names, args, iters): """ Repeat a sequence and vary part(s) of it. Returns a new sequence. Given N specifications of M steps, N parameters are varied in M steps. Args: seq (Sequence): The sequence to be repeated. poss (Union[list, tuple...
5,290,880
def conv_bn(inp, oup, stride): """ :param inp: :param oup: :param stride: :return: """ return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False), nn.BatchNorm2d(oup), #nn.ReLU6(inplace=True), nn.ReLU(inplace=True) )
5,290,881
def normalize(x, axis=-1, mean=None, variance=None, epsilon=1e-5): """Normalizes an array by subtracting mean and dividing by sqrt(var).""" if mean is None: mean = T.mean(x, axis, keepdims=True) if variance is None: # this definition is traditionally seen as less accurate than jnp.var's ...
5,290,882
def _get_restart_standard_names(restart_properties: RestartProperties = None): """Return a list of variable names needed for a smooth restart. By default uses restart_properties from RESTART_PROPERTIES.""" if restart_properties is None: restart_properties = RESTART_PROPERTIES return_dict = {} ...
5,290,883
async def portfolio_style_report(folio_id, request, *,factor_code=""): """ :param folio_id: :param request: :return: { 'T': 290, 'rolling_reg': [[{ 'month': 7, 'day': 25, 'year': 2017 }, { 'crisk': [0.22442397676756218, 0.362866...
5,290,884
def flatten(l, types=(list, )): """ Given a list/tuple that potentially contains nested lists/tuples of arbitrary nesting, flatten into a single dimension. In other words, turn [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]] into [5, 6, 8, 3, 2, 2, 1, 3, 4] This is safe to call on something not a list/tuple -...
5,290,885
def bitwise_or(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None): """ The BitwiseOr operation The arguments for this function are as follows: :param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string :param extent_type: one ...
5,290,886
def compare_approximations( approximation_true: Tuple[float, float], approximation_test: Tuple[float, float], rel_tol: float = 0.01, abs_tol: float = 0.0, ) -> None: """A pytest-friendly check whether two tuples (mean, std) are approximately equal.""" __tracebackhide__ = True mean_true, std...
5,290,887
def Theory_Algebraic(N,Kappa,d) : """ Theoretical approximation for the algebraic connectivity of periodic RGGs Parameters ----------- N : int Network size Kappa : float Expected mean degree of the ensemble d: int Dimension of the embedding space Returns --------- Mu2 : float Approximate val...
5,290,888
def define_passes(ext_val): """ Overwrite function based depending on enum flag. :param ext_val: :return: """ if ext_val in [EXTENSIONS.CGINC, EXTENSIONS.GLSLINC, EXTENSIONS.SHADER]: return format_write_cginc_first elif ext_val in [EXTENSIONS.CS]: return format_write_cs_first...
5,290,889
def get_path_prefix(path): """ gets path_prefixe given path """ temp_path=list(filter(None, path.split("/"))) j=0 path_prefix=[] for node in temp_path: path_prefix.append([node]) return path_prefix
5,290,890
def INSAR_to_rasterio(grd_file, desc, out_file): """ Reads in the UAVSAR interferometry file and saves the real and complex value and writes them to GeoTiffs. Requires a .ann file in the same directory to describe the data. Args: grd_file: File containing the UAVsAR data desc: dicti...
5,290,891
def iter_csv(filepath_or_buffer, target_name, types=None, parse_dates=None): """Yields rows from a CSV file. Parameters: filepath_or_buffer: Either a string indicating the location of a CSV file, or a buffer object that has a ``read`` method. types (dict): The type of each feature. ...
5,290,892
def test_pull_request_exists(monkeypatch: MonkeyPatch, branch: str) -> None: """It matches the branch in the process output.""" def stub(*args: Any, **kwargs: Any) -> Any: return pretend.stub(stdout="topic") with monkeypatch.context() as m: m.setattr("subprocess.run", stub) assert ...
5,290,893
def classify_image(interpreter, image, top_k=1): """ return a sorted array of classification results """ set_input_tensor(interpreter, image) interpreter.invoke() output_details = interpreter.get_output_details()[0] output = np.squeeze(interpreter.get_tensor(output_details['index'])) # if model...
5,290,894
def occupancy_to_color(occupancy): """ Return corresponding color from blue to red spectrum """ # color = [255*(1-isoval), 255*(1-isoval), 255] # white to blue # color = [255*isoval, 0, 255*(1-isoval)] # blue to red color = "gray" + str(int(math.floor((1-occupancy)*100))).zfill(2) if(color == "gray100"): co...
5,290,895
def queue_get(): """Queue get"""
5,290,896
def _simplify_cnots_triplets( cnots: List[Tuple[int, int]], flip_control_and_target: bool ) -> Tuple[bool, List[Tuple[int, int]]]: """Simplifies CNOT pairs according to equation 11 of [4]. CNOT(i, j) @ CNOT(j, k) == CNOT(j, k) @ CNOT(i, k) @ CNOT(i, j) ───@─────── ───────@───@─── │ ...
5,290,897
def reshape(a): """Combine the last two dimensions of a numpy array""" all_head_size = a.shape[-2] * a.shape[-1] new_shape = a.shape[:-2] + (all_head_size,) return a.reshape(new_shape)
5,290,898
def load_in_autotrack(trackDirPath, SCALE_FACTOR=1.0, TRACK_FILE_EXT="json"): """Load an predicted track""" trackDict = OrderedDict() frameDict = OrderedDict() #count = 0 for x in os.listdir(trackDirPath): path = os.path.join(trackDirPath, x) # skip non file if not os.pat...
5,290,899