content
stringlengths
22
815k
id
int64
0
4.91M
def concat_combining_function(a, b): """ Combines the tensor `a` and `b` by concatenating them. :param a: the tensor a :type a: tf.Tensor :param b: the tensor b :type b: tf.Tensor :return: a combination of the tensors :rtype: tf.Tensor """ if a.shape.rank == 2: a = tf.ex...
5,315,300
def insert(session, name, description, website_url, facebook_url, instagram_url, twitter_url): """Insert a new club into the Clubs table.""" club = Club( name=name, description=description, website_url=website_url, facebook_url=facebook_url, instagram_url=insta...
5,315,301
def filter_list_zones(auth_context, cloud_id, zones=None, perm='read', cached=False): """Filter the zones of the specific cloud based on the RBAC policy""" if zones is None: zones = list_zones(auth_context.owner, cloud_id, cached=cached) if auth_context.is_owner(): retu...
5,315,302
def pixel_weighted_categorical_crossentropy(weights,target, output, from_logits=False, axis=-1): """ pixel weighted version of tf.keras.backend.categorical_crossentropy copy of https://github.com/tensorflow/tensorflow/blob/v2.3.1/tensorflow/python/keras/backend.py#L4640-L4708 except for last line where wei...
5,315,303
def auth_required(f): """ Decorator for aiohttp web handlers with primitive auth check """ @wraps(f) async def _wrapper(request): if 'auth' not in request: raise HTTPUnauthorized() return await f(request) return _wrapper
5,315,304
def p_to_stars(p, thres=(0.1, 0.05, 0.01)): """Return stars for significance values.""" stars = [] for t in thres: if p < t: stars.append("*") return "".join(stars)
5,315,305
def permuteToBlocks(arr, blockshape): """Permute an array so that it consists of linearized blocks. Example: A two-dimensional array of the form 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 would be turned into an array like this with (2, 2) blocks: ...
5,315,306
def test_Chunkify_123_chunk_size_two(): """Test chunkify with single element returns.""" assert list(labtypes.Chunkify([1, 2, 3], 2)) == [[1, 2], [3]]
5,315,307
def do_cluster_refresh(cs, args): """Refreshes cluster status.""" if args.really_refresh: try: cs.clusters.refresh() print("Succeed to refresh cluster status.") except: raise exceptions.CommandError("Failed to refresh cluster status.") else: print(...
5,315,308
def test_smartsleep_from_unknown(protocol_version, wake_msg): """Test smartsleep message from unknown node.""" gateway = get_gateway(protocol_version=protocol_version) gateway.logic(wake_msg) ret = gateway.run_job() assert ret == '1;255;3;0;19;\n'
5,315,309
def _polygonise_splits( arr: np.ndarray, named_slices: Iterable[Dict[str, Tuple]] ) -> Dict[str, gpd.GeoDataFrame]: """ Create polygons from multiple sub-arrays of the given array. Note: Indices for `named_slices` must be given in x-y convention. x-y indexing is used for convenience wit...
5,315,310
def getPointInTheMiddle(start_point, end_point, time_diff, point_idx): """ Calculates a new point between two points depending of the time difference between them and the point index. Parameters ---------- start_point: DataFrame end_point: DataFrame time_diff: float point_idx: int ...
5,315,311
def get_style_dependencies(style_name=None, base_url=DEFAULT_BASE_URL): """Get the values of dependencies in a style. Args: style_name (str): Name of style; default is "default" style base_url (str): Ignore unless you need to specify a custom domain, port or version to connect to th...
5,315,312
def commit_version(file, remote_name): """ Commit version files and add git tag to the commit """ commit_version_func(get_version(file[0]), file, remote_name) click.echo('Version commit change was successfully created')
5,315,313
def bpt_nii(maps, ax = None, snr_min = None, deredden = False, return_figure = True, plot_map = False, plot_kde = False, radial_bin = None, return_data = None, overplot_dk_bpt = False, dk_bpt_kwargs = {}, ...
5,315,314
def correct_dcm(dcm): """ Correct DCM image which were actually signed data, but were treated as unsigned """ x = dcm.pixel_array + 1000 px_mode = 4096 x[x>=px_mode] = x[x>=px_mode] - px_mode dcm.PixelData = x.tobytes() dcm.RescaleIntercept = -1000 return dcm.pixel_array, dcm.RescaleIntercep...
5,315,315
def multiaz_subnets( name_prefix: str, cidr_block: str, region: str, vpc: object = None, vpc_id: str = None, no_of_subnets: int = 4, network_acl: object = None, network_acl_id: str = None, route_table: object = None, route_table_id: str = None, ) -> list: """Split given CIDR ...
5,315,316
def EPdiv(a, da, b, db, covar=0): """ C = A / B """ return ( a / b, np.sqrt( ((da / b) ** 2 + ((a ** 2) * (db ** 2) / (b ** 4))) - (2 * covar * a / (b ** 3)) ), )
5,315,317
def test_is_instance_false_and_set_exception(): """ Тест НЕ успешной работы метода self.is_instance() (возвращает False) в случае возникновения исключения при передаче в метод некорректных аргументов. Если передать в метод некорректные аргументы, то возниктнет исключение, ко...
5,315,318
def factorial_r(number): """ Calculates the factorial of a number, using a recursive process. :param number: The number. :return: n! """ # Check to make sure the argument is valid. if number < 0: raise ValueError # This is the recursive part of the function. if number == 0...
5,315,319
def run(): """Requirements for Task 1B""" station_list = build_station_list() station_list = stations_by_distance(station_list, (52.2053, 0.1218)) stations1 = station_list[:10] stations1 = [(x[0].name, x[0].town, x[1]) for x in stations1] stations2 = station_list[-10:] stations2 = [(x[0].na...
5,315,320
def obstacles_to_grid(obstacles): """ Transforms a list of obstacles into an m x n grid where 1 represents the cell is covered by an obstacle and 0 represents no obstacle. m and n are derived by the canvas height/width and grid width. The assumption is that the obstacles fall precisely on grid lines. ...
5,315,321
def get_gps_data(filename, traversal_id): """ Gets GPS time series gathered from a traversal :param filename: <String> csv file from GPS team in format |date|time|name|latitude|longitude|heading :return: <pandas DataFrame> time_stamp|latitude|longitude """ delimiter = r"\s+" # some of the column...
5,315,322
def get_formatted_weibo_tweets_by_name(name: str, with_comments: bool = False, pages: int = None) -> _TweetsResponse: """ Get formatted weibo tweets by nick name without any authorization >>> from weibo_scraper import get_formatt...
5,315,323
def infection_rate_symptomatic_30x60(): """ Real Name: b'infection rate symptomatic 30x60' Original Eqn: b'Susceptible 60*Infected symptomatic 30x60*contact infectivity symptomatic 30x60*(self quarantine policy SWITCH self 60\\\\ *self quarantine policy 60+(1-self quarantine policy SWITCH self 60))/non cont...
5,315,324
def compute_rewards(rl_batch, batch_actions, episode_lengths, batch_size=None): """Compute rewards for each episode in the batch. Args: rl_batch: A data.RLBatch instance. This holds information about the task each episode is solving, and a reward function for each episode. batch_actions: ...
5,315,325
def _translate_args(t=tuple(), d=dict(), unfreeze=False): """ _make_wrapper_argsでラッパー関数を作成する際の補助関数。 関数呼び出しを行うS式の引数部分に埋め込む文字列を作成する。 e.g.) (func)なるS式を送り込む場合 ""を生成することを担当する。 (func args)なるS式を送り込む場合 " args"を生成することを担当する。(冒頭のスペースに留意) 文字列を埋め込む際変数は適切に評価を行ってから埋め込む。 Euslispにはハッシュのリテラル表現はな...
5,315,326
def merge_date_time2(data, date_column, time_column=None): """This method merges columns date and time .. note: If time is missing default is 00:00. .. note: Also convert date using dt.apply(str). import datetime datetime.time.fromisoformat() Parameters ---------- Returns -------...
5,315,327
def logistic(x): """ A function that returns a value between 0 and 1 for x in the range [0, infinity] and -1 to 1 for x in the range [-infinity, infinity]. Useful for cost functions. """ return 2.0 / (1 + exp(-x)) - 1.0
5,315,328
def make_perturbed_cmtsolution(py, src_frechet_directory, cmtsolution_directory, output_directory): """ make the pertured cmtsolution based on src_frechet. """ script = f"ibrun -n 1 {py} -m seisflow.scripts.source_inversion.make_perturbed_cmtsolution --src_frechet_directory {src_frechet_directory} --cmt...
5,315,329
def weight_correct_incorrect(rslt): """Return a pair of floating-point numbers denoting the weight of (correct, incorrect) instances in EvaluationResult rslt. >>> listInstCorrect = [Instance([],True,0.25)] >>> listInstIncorrect = [Instance([],False,0.50)] >>> rslt = EvaluationResult(listInstCorrect, listInstIncor...
5,315,330
def test_actual_results_quantile_transformer_uniform(): """Test that the actual results are the expected ones.""" transformer = QuantileTransformer(n_quantiles=11) arr_actual = transformer.fit_transform(X) arr_desired = [np.linspace(0, 1, 11) for _ in range(3)] np.testing.assert_allclose(arr_actual,...
5,315,331
def test_dot_linear(x: Vector, y: Vector, z: Vector, scalar: float): """Test that x · (λ y + z) = λ x·y + x·z""" inner, outer = x * (scalar * y + z), scalar * x * y + x * z note(f"inner: {inner}") note(f"outer: {outer}") assert isclose(inner, outer, rel_to=(x, scalar, y, z), rel_exp=2)
5,315,332
def artAttrSkinPaintCtx(*args, **kwargs): """ This is a context command to set the flags on the artAttrContext, which is the base context for attribute painting operations. All commands require the name of the context as the last argument as this provides the name of the context to create, edit or query...
5,315,333
def get_data_info(path): """ Get metadata of the iamges. """ samples = [] # the data is in subfolders parent = pathlib.Path(path) for csv_file in parent.glob('**/*.csv'): with open(str(csv_file), 'r') as f: reader = csv.reader(f) for line in reader: ...
5,315,334
def BmatPRV(q): """ BmatPRV(Q) B = BmatPRV(Q) returns the 3x3 matrix which relates the body angular velocity vector w to the derivative of principal rotation vector Q. dQ/dt = [B(Q)] w """ p = np.linalg.norm(q) c = 1 / p / p * (1 - p / 2 / math.tan(p / 2)) B = np.zeros([3...
5,315,335
def test_empty_graph(): ## 8 """[summary] An empty graph properly returns null """ g = Graph() expected = 'Graph is empty' actual = g.size() assert actual == expected
5,315,336
def shuffle(x, y): """ Shuffle the datasets. """ for n in range(len(x) - 1): rnd = random.randint(0, (len(x) - 1)) x1 = x[rnd] x2 = x[rnd - 1] y1 = y[rnd] y2 = y[rnd - 1] x[rnd - 1] = x1 x[rnd] = x2 y[rnd - 1] = y1 y[rnd] = y2 retu...
5,315,337
def induced_subgraph(G: Graph, S: FrozenSet[Ind]) -> Graph: """ Generate the subgraph of G induced by the set of nodes S. See Also -------- https://en.wikipedia.org/wiki/Induced_subgraph Parameters ---------- G : Graph S : Set of nodes Returns ------- out : Graph ...
5,315,338
def showError(msg): """Shows an error message to the user in an appropriate form. In interactive mode, this shows a message box; otherwise, it reaises a ValueError. """ if not nuke.INTERACTIVE: raise ValueError(msg) nuke.message(msg)
5,315,339
def getKey(key, namespace=None): """Returns a key.""" app_id = os.environ.get('APPLICATION_ID', '') if app_id: app_id += '.' if namespace: key = '%(namespace)s.%(key)s' % locals() key = '%(app_id)s%(key)s' % locals() return base64.b64encode(key)
5,315,340
def _flatten(iterable): """ Given an iterable with nested iterables, generate a flat iterable """ for i in iterable: if isinstance(i, Iterable) and not isinstance(i, str): for sub_i in _flatten(i): yield sub_i else: yield i
5,315,341
def make_peptide_bond(mol, res = None, start = "N", end = "C", delete = "OXT"): """Performs one condesation rxn between a molecule and residue/itself default creates peptide bond Parameters ---------- mol : rdkmol Main molecule on which reaction is performed res : rdkmol ...
5,315,342
def get_data_names(data, data_names): """ Get default names for data fields if none are given based on the data. Examples -------- >>> import numpy as np >>> east, north, up = [np.arange(10)]*3 >>> get_data_names((east,), data_names=None) ('scalars',) >>> get_data_names((east, nort...
5,315,343
def train_func( max_epocs=20, learning_rate=1.8, learning_rate_schedule="time-based", enum_param0: SampleEnum = "Enum0", ): """train component""" print("hello training world...") lines = [ f"Max epocs: {max_epocs}", f"Learning rate: {learning_rate}", ...
5,315,344
def get_labels_from_file(filename): """Get labels on the last column from file. Args: filename: file name Returns: List[str]: label list """ data_frame = pandas.read_csv(filename) labels = data_frame['summary'].tolist() return labels
5,315,345
def css3_lists(): """Return a list of all css3 color names, and a corresponding list of the colors' RGB values.""" css3_db = CSS3_HEX_TO_NAMES names = [] rgb_values = [] for color_hex, color_name in css3_db.items(): names.append(color_name) rgb_values.append(hex_to_rgb(color_hex)) ...
5,315,346
def kmeans( embedding: np.ndarray, n_clusters: int = 1, init: Union[str, np.ndarray] = 'k-means++', n_init: int = 10, max_iter: int = 300, tolerance: float = 0.0001, precompute_distances='auto', verbose: int = 0, random_state: int = None, c...
5,315,347
def get_json_struct(jsonobj, template=None): """ :param jsonobj: Object to parse and adjust so could be loaded into big query :param template: An input object to use as abasis as a template defaullt no template provided :return: A json object that is a template object. This can be used as input to ...
5,315,348
def pin_to_cpu(op): """Returns a CPU device for the given node.""" device = op.device if op.device is not None else "" dev = pydev.from_string(device) if not dev.device_type: return set_cpu0(device) if dev.device_type == "CPU": return device logging.info("Operation %s has been assigned to a non-CP...
5,315,349
def build_df(data): """ Creates and returns a pandas DataFrame from the given pandas Series with the original index as a column. It also extracts and returns the original column and index name to restore the DataFrame to its original column and index name. :param data: pandas Series :return: tu...
5,315,350
def _map_spectrum_weight(map, spectrum=None): """Weight a map with a spectrum. This requires map to have an "energy" axis. The weights are normalised so that they sum to 1. The mean and unit of the output image is the same as of the input cube. At the moment this is used to get a weighted exposure...
5,315,351
def sex_chromosome(sex): """ This function will draw sex chromosomes. If the sex is male, it will draw XY. If the sex is female, it will draw XX. """ y_axis1 = 580 x_axis1 = 920 x_axis2 = 1120 chromosome_length = y_axis1 + 80 label_sex(x_axis1, x_axis2, sex) for j in range(y_...
5,315,352
def test_get_set_qos(participant): """ This test checks: - DomainParticipant::get_qos - DomainParticipant::set_qos """ qos = fastdds.DomainParticipantQos() assert(fastdds.ReturnCode_t.RETCODE_OK == participant.get_qos(qos)) qos.user_data().push_back(1) qos.user_data().push_back(2) ...
5,315,353
def STLLR(cpu_context: ProcessorContext, instruction: Instruction): """StoreLORelease register""" logger.debug("%s instruction not currently implemented.", instruction.mnem)
5,315,354
def clean_date_metadata(df): """Clean the collection and submission date metadata """ df.loc[:, "collection_date"] = df["covv_collection_date"].astype(str).str.strip() df.loc[:, "submission_date"] = df["covv_subm_date"].astype(str).str.strip() # Filter out really unspecific collection dates # ...
5,315,355
def countries_reaction(t, react_time, top_countries): """ Computes how long a country takes to react once the deceased limit is exceeded. Parameters ---------- t : int Simulation instant. react_time : int Parameter of the exponential distribution. top_countries : list ...
5,315,356
def binaryread_struct(file, vartype, shape=(1), charlen=16): """ Read text, a scalar value, or an array of values from a binary file. file is an open file object vartype is the return variable type: str, numpy.int32, numpy.float32, or numpy.float64 shape is the shape of...
5,315,357
def flatten_and_structure_dimensions(op, parameters, number_of_dimensions=None): """ Unrolls nested lists into one flat lists, applies the operation and rolls the resulting flat list back into nested lists. ---------- op : Operation to apply to the tuple of flat lists, resulting in one flat list. parame...
5,315,358
def create_result_scalar(name: str, item_type: str, value: Any) -> dict: """ Create a scalar result for posting to EMPAIA App API. :param name: Name of the result :param item_type: Type of result :param value: Value of the result """ result = {"name": name, "type": item_type, "value": value...
5,315,359
def create_edge(source_id, target_id, relationship_type, vitrage_is_deleted=False, update_timestamp=None, metadata=None): """A builder to create an edge :param update_timestamp: :param source_id: :type source_id: str :p...
5,315,360
def auto_delete_file_on_delete(sender, instance, **kwargs): """ Deletes file from filesystem when corresponding `Worksheet` object is deleted. """ if instance.worksheet_file: instance.worksheet_file.delete(save=False) if instance.solution_file: instance.solution_file.delete(save=...
5,315,361
def start(machine_name): """Starts the specified machine using vagrant""" v = vagrant.Vagrant() v.up(vm_name=machine_name) with settings(host_string= v.user_hostname_port(vm_name=machine_name), key_filename = v.keyfile(vm_name=machine_name), disable_known_hosts = True): ...
5,315,362
def hg_ui_with_checkers(hg_ui, checkers): """Get test mercurial ui with checkers config set up.""" for key, value in checkers.items(): hg_ui.setconfig('hg_commit_sanity', key, value) hg_commit_sanity.reposetup(hg_ui, hg_repo) return hg_ui
5,315,363
def no_heroku_connect_write_restrictions(): """ Allow writing to read-only Heroku Connect tables. Can be used to create test data, e.g.:: def get_test_data(): with no_heroku_connect_write_restrictions(): return MyReadOnlyModel.objects.create() """ from ..conf i...
5,315,364
def swap_values(d, updates, default=_DEFAULT_SENTINEL): """Updates a dictionary (or other mapping) with values from another mapping, and then restores the original mapping when the context is exited. """ old = {k: d.get(k, default) for k in updates} d.update(updates) yield for k, v in old.it...
5,315,365
def jtf_algo(text): """ Jump The Five Algorithm """ for char in text: print(jtf_dict.get(char, char), end="") print()
5,315,366
def get_inbox_status(): """Return current inbox status""" emails = get_inbox_emails(EMAIL) new = get_new_emails(emails) (direct, cced) = get_direct_emails(emails, MY_EMAILS) nb_total = len(emails) nb_direct = len(direct) nb_cced = len(cced) nb_total_new = get_nb_new(new) nb_direct...
5,315,367
def fill_correlation_matrix(c_vec): """ Create a Theano tensor object representing a correlation matrix of a multivariate normal distribution. :param c_vec: PyMC3 model variable corresponding to the `LKJCorr` prior on elements of the correlation matrix :return: correlation matrix...
5,315,368
def find_isomorphism(G1, G2): """Search for isomorphism between two graphs Args: G1 (networkx.Graph) G2 (networkx.Graph) Returns: If no isomorphism is found, returns None. Otherwise, returns dict with keys as nodes from graph 1 and values as corresponding nodes fro...
5,315,369
def list_bancos(request): """ Lista Bancos""" usuario = request.user dados = {} try: funcionario = Funcionario.objects.get(usuario_fun=usuario) except Exception: raise Http404() if funcionario: #id pesquisa termo_pesquisa = request.GET.get('pesquisa', None) ...
5,315,370
def do_rating_threshold_rule_update(cc, args={}): """Update a threshold rule.""" arg_to_field_mapping = { 'id': 'id', 'cost': 'cost', 'level': 'level', 'type': 'type', 'valid_since': 'valid_since', 'valid_until': 'valid_until', 'providers': 'providers', ...
5,315,371
def list_lights(value: bool) -> None: """Display a list of BlyncLights currently available and exit. Typer option callback. """ if value: typer.secho(f"{'BlyncLights':19s}:", nl=False) lights = BlyncLight.available_lights() nlights = len(lights) typer.secho(f"{nlights}",...
5,315,372
def encode_jwt_token(data, api_secret_code=None): """ Encode Python dictionary as JWT token. :param data: Dictionary with payload. :param api_secret_code: optional string, application secret key is used by default. :return: JWT token string with encoded and signed data. """ if api_secret_cod...
5,315,373
def map_mpi( run_fn: Callable[[BsuiteId], BsuiteId], bsuite_ids: Sequence[BsuiteId], num_processes: int = None, ): """Maps `run_fn` over `bsuite_ids`, using `num_processes` in parallel.""" num_processes = num_processes or multiprocessing.cpu_count() num_experiments = len(bsuite_ids) message = """ ...
5,315,374
def setup(): """Performs setup tasks for the program. Creates and configures a logger, creates and configures a webdriver and creates and configures a sqlite database connection. Returns: A Chromium based Selenium webdriver. """ logger_helper() db_helper() result = webdrive...
5,315,375
def handwrite( text: str, template: Union[Template, Sequence[Template]], seed: Hashable = None, mapper: Callable[[Callable, Iterable], Iterable] = map, ) -> Iterable[PIL.Image.Image]: """Handwrite `text` with the configurations in `template`, and return an Iterable of Pillow's Im...
5,315,376
def printMathExp(btree: BinaryTree) -> str: """Print the whole math expression""" s = '' if btree is not None: if btree.left is not None: s += '(' s += printMathExp(btree.left) s += str(btree.key) s += printMathExp(btree.right) if btree.right is not None: ...
5,315,377
def download_from_url(url: str, file_path='', attempts=28): """Downloads a URL content into a file (with large file support by streaming) :param url: URL to download :param file_path: Local file name to contain the data downloaded :param attempts: Number of attempts :return: New file path. Empty st...
5,315,378
def create_presigned_url(bucket_name, bucket_key, expiration=3600, signature_version=s3_signature['v4']): """Generate a presigned URL for the S3 object :param bucket_name: string :param bucket_key: string :param expiration: Time in seconds for the presigned URL to remain valid :param signature_versi...
5,315,379
def setup(): """Load all resources.""" quote_files = ['./_data/DogQuotes/DogQuotesTXT.txt', './_data/DogQuotes/DogQuotesDOCX.docx', './_data/DogQuotes/DogQuotesPDF.pdf', './_data/DogQuotes/DogQuotesCSV.csv'] quotes = [] for in_file in quote_files...
5,315,380
def softmax_op(node, ctx=None): """ This function computes its softmax along an axis. Parameters: ---- node : Node Input variable. Returns: ---- A new Node instance created by Op. """ return SoftmaxOp(node, ctx=ctx)
5,315,381
def circle_fit(coords): """ Find the least squares circle fitting a set of 2D points ``(x,y)``. Parameters ---------- coords : (N, 2) ndarray Set of ``x`` and ``y`` coordinates. Returns ------- centre_i : (2,) The 2D coordinates of the centre of the circle. r_i : do...
5,315,382
def bdd_common_after_scenario(context_or_world, scenario, status): """Clean method that will be executed after each scenario in behave or lettuce :param context_or_world: behave context or lettuce world :param scenario: running scenario :param status: scenario status (passed, failed or skipped) """...
5,315,383
def dispatcher(request, slug, view_name, *args, **kwargs): """Dispatcher that loads configuration corresponding to `slug` and dispatches view corresponding to `view_name` on said configuration. The configuration will be added to the `extra_context` attribute of all dispatched views. """ tr...
5,315,384
def LayerSet_toLayers(ifc_file): """ Returns a dictionary where keys are the Id of the IfcMaterialLayerSet and where the values are a list (ListOfLayers) with an element per material layer. The material layer information is stored at the same time within a list containing Id (number), material and t...
5,315,385
def conv2d_annotate_fn(expr): # pylint: disable=unused-variable """Check if nn.conv2d is supported by TensorRT.""" attrs, args = expr.attrs, expr.args if not is_supported_trt_dtype(args): return False if not isinstance(args[1], Constant): logger.info("nn.conv2d: kernel argument must be...
5,315,386
def create_bq_view_of_joined_features_and_entities( source: BigQuerySource, entity_source: BigQuerySource, entity_names: List[str] ) -> BigQuerySource: """ Creates BQ view that joins tables from `source` and `entity_source` with join key derived from `entity_names`. Returns BigQuerySource with reference to ...
5,315,387
def get_db(): """Connect to the application's configured database. The connection is unique for each request and will be reused if this is called again. """ if "db" not in g: g.db = sqlite3.connect( current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPES ) ...
5,315,388
def _go_test_impl(ctx): """go_test_impl implements go testing. It emits an action to run the test generator, and then compiles the test into a binary.""" go = go_context(ctx) # Compile the library to test with internal white box tests internal_library = go.new_library(go, testfilter = "exclud...
5,315,389
def _map_windows( df, time, method="between", periodvar="Shift Date", byvars=["PERMNO", "Date"] ): """ Returns the dataframe with an additional column __map_window__ containing the index of the window in which the observation resides. For example, if the windows are [[1],[2,3]], and the periods are ...
5,315,390
def unpack_context(msg): """Unpack context from msg.""" context_dict = {} for key in list(msg.keys()): key = str(key) if key.startswith('_context_'): value = msg.pop(key) context_dict[key[9:]] = value context_dict['msg_id'] = msg.pop('_msg_id', None) context_d...
5,315,391
def concat_cols(*args): """ takes some col vectors and aggregetes them to a matrix """ col_list = [] for a in args: if isinstance(a, list): # convenience: interpret a list as a column Matrix: a = sp.Matrix(a) if not a.is_Matrix: # convenience: al...
5,315,392
def accuracy_analogy(wv, questions, most_similar, evalVocab, topn=10, case_insensitive=True,usePhrase=True, sample=0): """ Compute accuracy of the model. `questions` is a filename where lines are 4-tuples of words, split into sections by ": SECTION NAME" lines. See questions-words.txt in https://sto...
5,315,393
def gen_connected_locations(shape, count, separation, margin=0): """ Generates `count` number of positions within `shape` that are touching. If a `margin` is given, positions will be inside this margin. Margin may be tuple-valued. """ margin = validate_tuple(margin, len(shape)) center_pos = margin ...
5,315,394
def transp(): """ Instantiates the Transp() class, and shows the widget. Runs only in Jupyter notebook or JupyterLab. Requires bqplot. """ warnings.simplefilter(action='ignore', category=FutureWarning) return Transp().widget
5,315,395
def oidc_supported(transfer_hop: DirectTransferDefinition) -> bool: """ checking OIDC AuthN/Z support per destination and source RSEs; for oidc_support to be activated, all sources and the destination must explicitly support it """ # assumes use of boolean 'oidc_support' RSE attribute if not tr...
5,315,396
def find_jest_configuration_file(file_name, folders): """ Find the first Jest configuration file. Jest's configuration can be defined in the package.json file of your project, or through a jest.config.js, or jest.config.ts, we only search the last two files. """ debug_message('find configuratio...
5,315,397
def test_str(): """Test __str__ pass-through for different variants.""" for endpoint in ["endpoint.io", "endpoint:port", None]: for image in ["image", "namespace/image"]: for tag in ["tag", None]: image_name = ImageName(endpoint, image, tag) string = str(image...
5,315,398
def test_create_list_raise_error(): """Test that TypeError is raised when you init with noniterable.""" with pytest.raises(TypeError): new_dll = DoubleLink(iterable=123456)
5,315,399