content
stringlengths
22
815k
id
int64
0
4.91M
def test_double_min_inclusive004_1096_double_min_inclusive004_1096_v(mode, save_output, output_format): """ TEST :Facet Schemas for string : (facet=minInclusive and value=1.1 and facet=maxInclusive and value=7.7) and document value=5.55 """ assert_bindings( schema="msData/datatypes/Facets/do...
17,200
def read_keys(): """ read aws credentials from file, then stick into global variables... """ with open('%s/.aws/credentials' % os.getenv('HOME'), 'rt') as infile: for line in infile: if 'aws_access_key_id' in line: aws_access_key_id = line.split('=')[-1].strip() i...
17,201
def RecalculatedEdgeDegreeAttack(G, remove_fraction = 1.0): """ Recalculated Edge Degree Attack """ n = G.number_of_nodes() m = int(G.number_of_edges() * (remove_fraction+0.0) ) tot_ND = [0] * (m + 1) tot_T = [0] * (m + 1) ND, ND_lambda = ECT.get_number_of_driver_nodes(G) tot_ND[0] = ND...
17,202
def test_strip_text(): """ Remove test text. Args: """ assert helpers.strip_text(" text ", []) == "text" # I can't interpret the rest of the code well enough yet
17,203
def add_role(rolename, roleinfo, require_parent=True): """ <Purpose> Add to the role database the 'roleinfo' associated with 'rolename'. <Arguments> rolename: An object representing the role's name, conformant to 'ROLENAME_SCHEMA' (e.g., 'root', 'snapshot', 'timestamp'). roleinfo: ...
17,204
def get(url, params=None, headers=None): """Return the contents from a URL Params: - url (str): Target website URL - params (dict, optional): Param payload to add to the GET request - headers (dict, optional): Headers to add to the GET request Example: ``` get('https://httpbin.org/an...
17,205
def main(extn='pdf', fig_mult=1.0): """Load and combine multiple jet runs into one DataFrame, plot info.""" # File called runinfo.yml stores information about each JetFindRun # with a label and file location with open('runinfo.yml', 'r') as cfg: data = yaml.safe_load(cfg.read()) dsets = ['E...
17,206
def get_param_num(model): """ get the number of parameters Args: model: Returns: """ return sum(p.numel() for p in model.parameters())
17,207
def aggregate_results(jade_runtime_output, fmt, verbose): """Aggregate results on a directory of upgrade cost analysis simulations.""" level = logging.DEBUG if verbose else logging.INFO log_file = jade_runtime_output / "upgrade_cost_analysis_aggregation.log" setup_logging(__name__, log_file, console_lev...
17,208
def get_branch_name(): """Get the name of the current branch returns: The name of the current branch """ HEAD = data.get_ref('HEAD', deref=False) if not HEAD.symbolic: return None HEAD = HEAD.value assert HEAD.startswith('refs/heads/') return os.path.relpath(HEAD, 'refs/h...
17,209
def format_tensor_to_ndarray(x: Union[ms.Tensor, np.ndarray]) -> np.ndarray: """Unify `mindspore.Tensor` and `np.ndarray` to `np.ndarray`. """ if isinstance(x, ms.Tensor): x = x.asnumpy() if not isinstance(x, np.ndarray): raise TypeError('input should be one of [ms.Tensor or np.ndarray],' ...
17,210
def hunt_csv(regex: Pattern, body: str) -> list: """ finds chunk of csv in a larger string defined as regex, splits it, and returns as list. really useful only for single lines. worse than StringIO -> numpy or pandas csv reader in other cases. """ csv_string = re.search(regex, body)[0] if r"...
17,211
def time_key(file_name): """ provides a time-based sorting key """ splits = file_name.split('/') [date] = re.findall(r'(\d{4}_\d{2}_\d{2})', splits[-2]) date_id = [int(token) for token in date.split('_')] recording_id = natural_key(splits[-1]) session_id = session_key(splits[-2]) return dat...
17,212
def silent_popen(args, **kwargs): """Wrapper for subprocess.Popen with suppressed output. STERR is redirected to STDOUT which is piped back to the calling process and returned as the result. """ return subprocess.Popen(args, stderr=subprocess.STDOUT, ...
17,213
def sizeRange(contourList, low, high): """Only keeps contours that are in range for size""" newList = [] for i in contourList: if (low <= cv2.contourArea(i) <= high): newList.append(i) return newList
17,214
def test_estim_v_3_basis(seed): """ Test the estimation of the HRF with the scaled HRF model without noise in the observed data. """ rng = check_random_state(seed) t_r = 1.0 n_atoms = 2 n_voxels = 1000 n_times_valid = 100 n_times_atom = 30 indices = np.arange(n_voxels) n_hrf_rois...
17,215
def set_persistent_cache(path_to_cache): """ Set a persistent cache. If the file does not yet exist, it is created. :param path_to_cache: The place where the cache is stored or needs to be created """ net.server_cache.set_persistent_location(path_to_cache)
17,216
def test_parse_annotations() -> None: """Test the parse annotations function.""" filepath = get_test_file("motchallenge_labels.txt") result = parse_annotations(filepath) assert list(result.keys()) == [0, 1, 3] for frame_idx, labels in result.items(): for label in labels: assert...
17,217
def release(): """Create a tag release for an revision""" print yellow(">>> Creating a tag release") local("git tag") tagname = prompt("Enter a new tagname as according as above: ") print red('.... updating tag release at hstore_flattenfields') _replace_in_file("__version__ = '.*'", "__version_...
17,218
def test_unique(exec): """ Only a single event is accepted at a given position""" rec = EventCollectRecorder("./test.txt") exec.call_except(lambda: rec.register_event_source("SRC1", 1, "test1"), None) exec.call_except(lambda: rec.register_event_source("SRC2", 1, "test2"), Exception) exec.call_except...
17,219
def number_field_choices(field): """ Given a field, returns the number of choices. """ try: return len(field.get_flat_choices()) except AttributeError: return 0
17,220
def _is_an_unambiguous_user_argument(argument: str) -> bool: """Check if the provided argument is a user mention, user id, or username (name#discrim).""" has_id_or_mention = bool(commands.IDConverter()._get_id_match(argument) or RE_USER_MENTION.match(argument)) # Check to see if the author passed a usernam...
17,221
def resize_image(image, size): """ Resize the image to fit in the specified size. :param image: Original image. :param size: Tuple of (width, height). :return: Resized image. :rtype: :py:class: `~PIL.Image.Image` """ image.thumbnail(size) return image
17,222
def one_hot_vector(val, lst): """Converts a value to a one-hot vector based on options in lst""" if val not in lst: val = lst[-1] return map(lambda x: x == val, lst)
17,223
def follow(request, username): """ Add user with username to current user's following list """ request.user.followers.add(User.objects.get(username=username)) return redirect('accounts:followers')
17,224
def sesteva_stolpce(seznam_seznamov_stolpcev): """sešteje vse 'stolpce' v posameznem podseznamu """ matrika_stolpcev = [] for i in range(len(seznam_seznamov_stolpcev)): sez = seznam_seznamov_stolpcev[i] stolpec11 = sez[0] while len(sez) > 1: i = 0 stolpec22 = ...
17,225
def create_response(data={}, status=200, message=''): """ Wraps response in a consistent format throughout the API Format inspired by https://medium.com/@shazow/how-i-design-json-api-responses-71900f00f2db Modifications included: - make success a boolean since there's only 2 values - make messag...
17,226
async def test_reschedule_action_1(startup_and_shutdown_uvicorn, base_url, tmp_path): """ schedule action, run it, change it, re-run it """ await reset_dispatcher(base_url, str(tmp_path)) action1 = file_x.FileAppend( relative_to_output_dir=False, file=str(tmp_path / "output1.txt"), ...
17,227
def add_to_worklist(worklist, item): """assures that each item is only once in the list""" if item in worklist: return worklist.append(item)
17,228
def do_sizes_match(imgs): """Returns if sizes match for all images in list.""" return len([*filter(lambda x: x.size != x.size[0], imgs)]) > 0
17,229
def gaussian_sampling(len_x, len_y, num_samples, spread_factor=5, origin_ball=1): """ Create a gaussian sampling pattern where each point is sampled from a bivariate, concatenated normal distribution. Args: len_x (int): Size of output mask in x direction (width) len_y (int): ...
17,230
def add_shares(parent): """allows you to add share""" def save(): if(manage_db.check_if_valid_name(name.get()) and manage_db.check_for_real_numbers(entry_price.get()) and manage_db.check_date_format(date.get())): share = {"Name": name.get(), "Quanti...
17,231
def from_cx_jsons(graph_json_str: str) -> BELGraph: """Read a BEL graph from a CX JSON string.""" return from_cx(json.loads(graph_json_str))
17,232
def _calculate_dimensions(image: Image) -> Tuple[int, int]: """ Returns the width and height of the given pixel data. The height of the image is the number of rows in the list, while the width of the image is determined by the number of pixels on the first row. It is assumed that each row contains ...
17,233
def cli(ctx, invocation_id): """Get a summary of an invocation, stating the number of jobs which succeed, which are paused and which have errored. Output: The invocation summary. For example:: {'states': {'paused': 4, 'error': 2, 'ok': 2}, 'model': 'WorkflowInvocation', ...
17,234
def test_local_plugin_can_add_option(local_config): """A local plugin can add a CLI option.""" argv = ["--config", local_config, "--anopt", "foo"] stage1_parser = stage1_arg_parser() stage1_args, rest = stage1_parser.parse_known_args(argv) cfg, cfg_dir = config.load_config( config=stage1_...
17,235
def test_compute_delta_cchalf_returned_results(): """Test that delta cchalf return necessary values for scale_and_filter.""" # Check for correct recording of # results_summary['per_dataset_delta_cc_half_values']['delta_cc_half_values'] summary = {} delta_cc = {0: -4, 1: 2, 2: -3, 3: -5, 4: 1} s...
17,236
def test_missing_classes(): """Test that empty tuple is returned if data of embedded representation don't have 'class' key. 1. Create an embedded representation parser for a dictionary without classes. 2. Parse classes. 3. Check that empty tuple is returned. """ actual_classes = EmbeddedReprese...
17,237
def union_categoricals(to_union: List[pandas.core.series.Series]): """ usage.dask: 8 """ ...
17,238
def remove_observations_mean(data,data_obs,lats,lons): """ Removes observations to calculate model biases """ ### Import modules import numpy as np ### Remove observational data databias = data - data_obs[np.newaxis,np.newaxis,:,:,:] return databias
17,239
def test_field_multi_instance(frozen: bool): """Each instance has a separate state.""" @dataclasses.dataclass(frozen=frozen) class A: x: Any = edc.field(validate=str) # pytype: disable=annotation-type-mismatch a0 = A(123) assert a0.x == '123' a1 = A(456) assert a0.x == '123' assert a1.x == '456' ...
17,240
def joint_extraction_model_fn(features, labels, mode, params): """Runs the node-level sequence labeling model.""" logging.info("joint_extraction_model_fn") inputs = features # Arg "features" is the overall inputs. # Read vocabs and inputs. dropout = params["dropout"] if params["circle_features"]: nnod...
17,241
def use_rbg(): """ Swaps the Green and Blue channels on the LED backlight Use if you have a first batch Display-o-Tron 3K """ global LED_R_G, LED_R_B global LED_M_G, LED_M_B global LED_L_G, LED_L_B (LED_R_G, LED_R_B) = (LED_R_B, LED_R_G) (LED_M_G, LED_M_B) = (LED_M_B, LED_M_G) ...
17,242
def convert( input, ply, bb, direction="z", inverse=False, ignoreAlpha=True, wSamples=0, hSamples=0, maintainAspectRatio=True ): """ Read the input directory and find all of the images of the supported file extensions. This list is sorted and will then have its pixels processed and store...
17,243
def jp2yy (sent): """take a Japanese sentence in UTF8 convert to YY-mode using mecab""" ### (id, start, end, [link,] path+, form [surface], ipos, lrule+[, {pos p}+]) ### set ipos as lemma (just for fun) ### fixme: do the full lattice yid = 0 start = 0 cfrom = 0 cto = 0 yy = list() ...
17,244
def save(data,filename): """This creates a FreeMind file based on a SUAVE data structure. Assumptions: None Source: N/A Inputs: data SUAVE data structure filename <string> name of the output file Outputs: FreeMind file with name as specified by filename Prope...
17,245
def test_multi_headed_mat_attention(): """Test invoking MultiHeadedMATAttention.""" feat = dc.feat.MATFeaturizer() input_smile = "CC" out = feat.featurize(input_smile) node = torch.tensor(out[0].node_features).float().unsqueeze(0) adj = torch.tensor(out[0].adjacency_matrix).float().unsqueeze(0) dist = tor...
17,246
def make_ss_matrices(sigma_x, dt): """ To make Q full-rank for inversion (so the mle makes sense), use: Q = [ dt**2 dt/2 dt/2 1 ] to approximate Q = (dt 1)(dt 1)' System: x = [p_x p_y v_x v_y] y = [p_x' p_y'] :param sigma_x: :param dt: :return: sigma_0:...
17,247
def get_icp_val(tmr): """Read input capture value""" return peek(tmr + ICRx) | (peek(tmr + ICRx + 1) << 8)
17,248
def main(epochs: int, lr: float, min_accuracy: float, stop_service: bool): """Run the MLflow example pipeline""" if stop_service: service = load_last_service_from_step( pipeline_name="continuous_deployment_pipeline", step_name="model_deployer", running=True, ...
17,249
def dmp_to_mdiff(diffs): """Convert from diff_match_patch format to _mdiff format. This is sadly necessary to use the HtmlDiff module. """ def yield_buffer(lineno_left, lineno_right): while left_buffer or right_buffer: if left_buffer: left = lineno_left, '\0-{0}\1'....
17,250
def validate(segmenter, val_loader, epoch, num_classes=-1): """Validate segmenter Args: segmenter (nn.Module) : segmentation network val_loader (DataLoader) : training data iterator epoch (int) : current epoch num_classes (int) : number of classes to consider Returns: Mean Io...
17,251
def test_determine_type_unsupported(): """ GIVEN artifacts with an unsupported type WHEN _determine_type is called with the artifacts THEN FeatureNotImplementedError is raised. """ artifacts = types.ColumnArtifacts("unsupported") with pytest.raises(exceptions.FeatureNotImplementedError): ...
17,252
def detect_forward(CoreStateMachine, PostConditionStateMachine): """A 'forward ambiguity' denotes a case where the post condition implementation fails. This happens if an iteration in the core pattern is a valid path in the post- condition pattern. In this case no decision can be made about where to res...
17,253
def price_sensitivity(results): """ Calculate the price sensitivity of a strategy results results dataframe or any dataframe with the columns open, high, low, close, profit returns the percentage of returns sensitive to open price Note ----- Price sensitivity is calc...
17,254
def wrap_zone(tz, key=KEY_SENTINEL, _cache={}): """Wrap an existing time zone object in a shim class. This is likely to be useful if you would like to work internally with non-``pytz`` zones, but you expose an interface to callers relying on ``pytz``'s interface. It may also be useful for passing non-`...
17,255
async def async_browse_media( hass, media_content_type, media_content_id, *, can_play_artist=True ): """Browse Spotify media.""" info = list(hass.data[DOMAIN].values())[0] return await async_browse_media_internal( hass, info[DATA_SPOTIFY_CLIENT], info[DATA_SPOTIFY_ME], me...
17,256
def bounds(url: str) -> Tuple[str, str, str]: """Handle bounds requests.""" info = main.bounds(url) return ("OK", "application/json", json.dumps(info))
17,257
def ldplotdb(xaxis, yaxis, center_freq=0, plotnum="", peaks=[]): """This function loads a matplotlib.pyplot figure with xaxis and yaxis data which can later be plotted""" yaxis=10*np.log10(yaxis) if(len(peaks)!=0): plt.plot(xaxis[peaks], yaxis[peaks], 'ro') plt.plot(xaxis, yaxis) plt.title("FFT "+plotnum+...
17,258
def make_message_id(): """ Generates rfc message id. The returned message id includes the angle brackets. """ return email.utils.make_msgid('sndlatr')
17,259
def _understand_err_col(colnames): """Get which column names are error columns Examples -------- >>> colnames = ['a', 'a_err', 'b', 'b_perr', 'b_nerr'] >>> serr, terr = _understand_err_col(colnames) >>> np.allclose(serr, [1]) True >>> np.allclose(terr, [2]) True >>> serr, terr =...
17,260
def clear_folder(folder: str): """create temporary empty folder. If it already exists, all containing files will be removed. Arguments: folder {[str]} -- Path to the empty folder """ if not os.path.exists(os.path.dirname(folder)): os.makedirs(os.path.dirname(folder)) ...
17,261
def unpivot(frame): """ Example: >>> df date variable value 0 2000-01-03 A 0.895557 1 2000-01-04 A 0.779718 2 2000-01-05 A 0.738892 3 2000-01-03 B -1.513487 4 2000-01-04 B -0.543134 5 2000-01-05 B 0.902733 6 20...
17,262
def find_viable_generators_aux (target_type, prop_set): """ Returns generators which can be used to construct target of specified type with specified properties. Uses the following algorithm: - iterates over requested target_type and all it's bases (in the order returned bt type.all-bases....
17,263
async def test_initialized_finished(): """When the polling method is initialized as finished, it shouldn't invoke the command or sleep""" command = raise_exception("polling method shouldn't invoke the command") polling_method = AsyncDeleteRecoverPollingMethod(command, final_resource=None, finished=True) ...
17,264
def analyze(model, Y, print_to_console=True): """ Perform variance-based sensitivty analysis for each process. Parameters ---------- model : object The model defined in the sammpy Y : numpy.array A NumPy array containing the model outputs print_to_console : bool ...
17,265
def generate_parity_fixture(destination_dir): """ The parity fixture generation strategy is to start a ghuc client with existing fixtures copied into a temp datadir. Then a parity client is started is peered with the ghuc client. """ with contextlib.ExitStack() as stack: ghuc_datadir =...
17,266
def GetMorganFingerprint(mol, atomId=-1, radius=2, fpType='bv', nBits=2048, useFeatures=False, **kwargs): """ Calculates the Morgan fingerprint with the environments of atomId removed. Parameters: mol -- the molecule of interest radius -- the maximum radius fpType -...
17,267
def _rgb2lab(rgb): """Convert an RGB integer to Lab tuple""" def xyzHelper(value): """Helper function for XYZ colourspace conversion""" c = value / 255 if c > 0.0445: c = (c + 0.055) / 1.055 c = math.pow(c, 2.4) else: c /= 12.92 c *= 10...
17,268
def _resolve_dir(env_name, dflt_dir): """Resolve a directory given the override env var and its default directory. And if '~' is used to indicate the home directory, then expand that.""" folder = os.environ.get(env_name, dflt_dir) if folder is not None: return os.path.expanduser(folder) ...
17,269
def test_start_r(): """ tests the restful endpoint: start """ # get web app test_app = start_web_app() # create some container d = docker.from_env() d.images.pull('alpine') test_cont = d.containers.create('alpine') # test start r = test_app.post('/start', params={}) assert r.st...
17,270
def biband_mask(n: int, kernel_size: int, device: torch.device, v=-1e9): """compute mask for local attention with kernel size. Args: n (torch.Tensor): the input length. kernel_size (int): The local attention kernel size. device (torch.device): transformer mask to the device. Return...
17,271
def URDFBoundingObject(proto, link, level, boxCollision): """Write a bounding object (collision). Args: proto (file): proto file to write the information in. link (Link): link object. level (int): level in the tree. boxCollision (bool): If True, the bounding objects are approxim...
17,272
def test_define_x(arterynetwork_def, param): """Test correct value for x. :param arterynetwork_def: Artery network object :param param: Config parameters """ an = arterynetwork_def order, rc, qc, Ru, Rd, L, k1, k2, k3, rho, Re, nu, p0, R1, R2, CT,\ Nt, Nx, T, N_cycles, output_location, t...
17,273
def containsIfElse(node): """ Checks whether the given node contains another if-else-statement """ if node.type == "if" and hasattr(node, "elsePart"): return True for child in node: if child is None: pass # Blocks reset this if-else problem so we ignore them # ...
17,274
def main(): """this is test function""" os.chdir( opt.outDir ) rdir = opt.tophatdir rfile = opt.tophatsummary d,report = readTophatMapResult(rdir,rfile) # print(d) w = open(opt.outfile,"w") w.writelines(report) # print(report)
17,275
def lstm_create_dataset(data_home, batch_size, repeat_num=1, training=True): """Data operations.""" ds.config.set_seed(1) data_dir = os.path.join(data_home, "aclImdb_train.mindrecord0") if not training: data_dir = os.path.join(data_home, "aclImdb_test.mindrecord0") data_set = ds.MindDataset...
17,276
def get_gitlab_scripts(data): """GitLab is nice, as far as I can tell its files have a flat hierarchy with many small job entities""" def flatten_nested_string_lists(data): """helper function""" if isinstance(data, str): return data elif isinstance(data, list): ...
17,277
def method(cls): """Adds the function as a method to the given class.""" import new def _wrap(f): cls.__dict__[f.func_name] = new.instancemethod(f,None,cls) return None return _wrap
17,278
def maps_from_echse(conf): """Produces time series of rainfall maps from ECHSE input data and catchment shapefiles. """ # Read sub-catchment rainfall from file fromfile = np.loadtxt(conf["f_data"], dtype="string", delimiter="\t") if len(fromfile)==2: rowix = 1 elif len(fromfile)>2: ...
17,279
def utility_assn(tfr_dfs): """Harvest a Utility-Date-State Association Table.""" # These aren't really "data" tables, and should not be searched for associations non_data_dfs = [ "balancing_authority_eia861", "service_territory_eia861", ] # The dataframes from which to compile BA-Uti...
17,280
def is_smtp_enabled(backend=None): """ Check if the current backend is SMTP based. """ if backend is None: backend = get_mail_backend() return backend not in settings.SENTRY_SMTP_DISABLED_BACKENDS
17,281
def validate_isotypes(form, field): """ Validates that isotypes are resolved. """ try: df = form.trait_data.processed_data except AttributeError: return try: unknown_strains = df.STRAIN[df.ISOTYPE.isnull()] if unknown_strains.any(): unknown_strains...
17,282
def test_th_ch(): """ Run `python -m pytest ./day-02/part-1/th-ch.py` to test the submission. """ assert ( ThChSubmission().run( """ forward 5 down 5 forward 8 up 3 down 8 forward 2 """.strip() ) == 150 )
17,283
def get_presentation_requests_received(tenant: str, state: str = ''): """ state: must be in ['propsal-sent', 'proposal-received', 'request-sent', 'request-received', 'presentation-sent', 'presentation-received', 'done', 'abondoned'] """ possible_states = ['', 'propsal-sent', 'proposal-received', 'reques...
17,284
def generate_round(): """ Генерируем раунд. Returns: question: Вопрос пользователю result: Правильный ответ на вопрос """ total_num, random_num = generate_numbers() question = " ".join(total_num) answer = str(random_num) return question, answer
17,285
def get_basic_activity(): """ A basic set of activity records for a 'Cohort 1' and CoreParticipant participant. """ return [ {'timestamp': datetime(2018, 3, 6, 0, 0), 'group': 'Profile', 'group_id': 1, 'event': p_event.EHRFirstReceived}, {'timestamp': datetime(2018, 3, 6, 20, 20...
17,286
def bad_multi_examples_per_input_estimator_misaligned_input_refs( export_path, eval_export_path): """Like the above (good) estimator, but the input_refs is misaligned.""" estimator = tf.estimator.Estimator(model_fn=_model_fn) estimator.train(input_fn=_train_input_fn, steps=1) return util.export_model_and_e...
17,287
def page_is_dir(path) -> bool: """ Tests whether a path corresponds to a directory arguments: path -- a path to a file returns: True if the path represents a directory else False """ return os.path.isdir(path)
17,288
def read_configuration(dirname_f: str) -> dict: """ :param dirname_f: path to the project ending with .../cameras_robonomics :type dirname_f: str :return: dictionary containing all the configurations :rtype: dict Reading config, containing all the required data, such as filepath, robonomics par...
17,289
def caption_example(image): """Convert image caption data into an Example proto. Args: image: A ImageMetadata instance. Returns: example: An Example proto with serialized tensor data. """ # Collect image object information from metadata. image_features, positions = read_object(image.objects, image...
17,290
def test_env_vars(): """test if the critical env variables are available in the environment""" CELERY_BROKER_URL = get_env_var('CELERY_BROKER_URL') DB_URL = get_env_var('SQLALCHEMY_DATABASE_URI') DB_URL_TEST = get_env_var('SQLALCHEMY_DATABASE_URI_TEST') SECRET_KEY = get_env_var('MPORTER_SECRET') ...
17,291
def GetAttributeTableByFid(fileshp, layername=0, fid=0): """ GetAttributeTableByFid """ res = {} dataset = ogr.OpenShared(fileshp) if dataset: layer = dataset.GetLayer(layername) feature = layer.GetFeature(fid) geom = feature.GetGeometryRef() res["geometry"] = geo...
17,292
def get_root_folder_id(db, tree_identifier, linked_to, link_id): """Get id of the root folder for given data category and profile or user group Args: db (object): The db object tree_identifier (str): The identifier of the tree linked_to (str): ['profile'|'group'] link_id (int): ...
17,293
def check_normalized_names(id_series, season_number, episode_number): """Check normalized names. Print the difference between IMDb and transcripts Parameters ---------- id_series : `str` Id of the series. season_number : `str` The desired season number. If None, all seasons are proc...
17,294
def str_cell(cell): """Get a nice string of given Cell statistics.""" result = f"-----Cell ({cell.x}, {cell.y})-----\n" result += f"sugar: {cell.sugar}\n" result += f"max sugar: {cell.capacity}\n" result += f"height/level: {cell.level}\n" result += f"Occupied by Agent {cell.agent.id if cell.agen...
17,295
def get_idx_pair(mu): """get perturbation position""" idx = np.where(mu != 0)[0] idx = [idx[0], idx[-1]] return idx
17,296
def zeeman_transitions(ju, jl, type): """ Find possible mu and ml for valid ju and jl for a given transistion polarization Parameters: ju (scalar): Upper level J jl (scalar): Lower level J type (string): "Pi", "S+", or "S-" for relevant polarization type Returns: tu...
17,297
def get_reachable_nodes(node): """ returns a list with all the nodes from the tree with root *node* """ ret = [] stack = [node] while len(stack) > 0: cur = stack.pop() ret.append(cur) for c in cur.get_children(): stack.append(c) return ret
17,298
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc(): """separate rgb embeddings.""" hparams = imagetransformer_sep_channels_12l_16h_imagenet_large() hparams.num_hidden_layers = 16 hparams.local_attention = True hparams.batch_size = 1 hparams.block_length = 256 return hparams
17,299