content
stringlengths
22
815k
id
int64
0
4.91M
def negate(condition): """ Returns a CPP conditional that is the opposite of the conditional passed in. """ if condition.startswith('!'): return condition[1:] return "!" + condition
5,315,000
def __worker(func): """ thread runner Args: func: Returns: """ if env.Maya(): import maya.utils as utils utils.executeDeferred(func) # https://forums.odforce.net/topic/22570-execute-in-main-thread-with-results/ elif env.Houdini(): import hdefereval ...
5,315,001
def _compute_n50_and_n95_np(readlengths): """ Numpy implementation of N50/N95 calculation. """ if isinstance(readlengths, list): readlengths = np.array(readlengths) readlengths[::-1].sort() # = np.sort(readlengths) total_length = np.sum(readlengths) csum = np.cumsum(readlengths) ...
5,315,002
def get_dominant_horizontal_line_colour(ip): """ >>> get_dominant_horizontal_line_colour(np.array([[0,0,0], [1,1,1], [1,0,0], [2,2,2],[0,0,0]])) {1, 2} """ #get unique list of colours per row row_info = ([np.unique(row) for row in ip]) # identify the whole colour lines, we do this if th...
5,315,003
def _filter_out_disabled(d): """ Helper to remove Nones (actually any false-like type) from the scrubbers. This is needed so we can disable global scrubbers in a per-model basis. """ return {k: v for k, v in d.items() if v}
5,315,004
def main(): """See fplutil/disttools/push_package.py. Returns: 0 if successful, non-zero otherwise. """ return disttools.push_package.main(disttools.push_package.parse_arguments( project_dir=PROJECT_DIR, config_json=CONFIG_JSON))
5,315,005
def test_mongod_url(monkeypatch: MonkeyPatch, platform_name: str, distro_name: str, distro_version: str, true_url: str) -> None: """Test mongo version based on platform system.""" monkeypatch.setattr("platform.system", lambda: platform_name) monkeypatch.setattr("distro.id", lambda: distr...
5,315,006
def extractRotationInteractively(input_dir,zmax_identifier): """ Rotation based on zmax image. Loads zmax image, then asks user to draw a line along the long axis. Rotation is the angle of the line. """ # find & open image with zmax projection try: fn_zmax=glob.glob(input_dir+os.sep+"*" +zmax_identifier+"*")[0...
5,315,007
def _check_supports_private_deps(repository_ctx, swiftc_path, temp_dir): """Returns True if `swiftc` supports implementation-only imports.""" source_file = _scratch_file( repository_ctx, temp_dir, "main.swift", """\ @_implementationOnly import Foundation print("Hello") """, )...
5,315,008
def can_reuse(fpath, cmp_f, silent=False): """Check if a file `fpath` exists, is non-empty and is more recent than `cmp_f` """ do_reuse = os.environ.get('REUSE', '1') if do_reuse == '0': return False if not fpath or not isfile(fpath): return False elif verify_file(fpath, cmp_f=cm...
5,315,009
def createNullOperator(context, domain, range, dualToRange, label=None): """ Create and return a null (zero-valued) operator. *Parameters:* - context (Context) A Context object to control the assembly of the weak form of the newly constructed operator. - domain (Space)...
5,315,010
def stsb(dataset): """Convert STSB examples to text2text format. STSB maps two sentences to a floating point number between 1 and 5 representing their semantic similarity. Since we are treating all tasks as text-to-text tasks we need to convert this floating point number to a string. The vast majority of the...
5,315,011
def getString(data: dict = None, separater: str = " ") -> str: """Debug message when debug is enabled. :param data: The value in either str or list. :type data: str,list :param separater: The separater between the words. :type separater: str :rtype: str :return: The message in string. "...
5,315,012
def train(generator, discriminator, combined, steps, batch_size): """ Train the GAN system :param generator: generator :param discriminator: discriminator :param combined: stacked generator and discriminator we'll use the combined network when we train the generator :param steps: number of a...
5,315,013
def make_spectrograms_old(spectros=None, overwrite=False, cmap='magma', subdirs=['no_sax', 'sax_sec', 'sax_solo'] ): """ *** VERSION 1, USES OLD FILE FORMAT *** Makes spectrograms for all audio files, or...
5,315,014
def test_overrides(session_obj): """ Override an experiment decision for a user Override a experiment or feature test decision used in future user based decisions. This override is only stored locally in memory for debugging and testing purposes and should not be used for production overrides. ...
5,315,015
def scatter_matrix(df,theme=None,bins=10,color='grey',size=2): """ Displays a matrix with scatter plot for each pair of Series in the DataFrame. The diagonal shows a histogram for each of the Series Parameters: ----------- df : DataFrame Pandas DataFrame theme : string Theme to be used (if not the defa...
5,315,016
def _gr1_sorted_ ( graph , reverse = False ) : """Make sorted graph >>> graph = ... >>> s = graph.sorted() """ oitems = ( i for i in graph.iteritems() ) sitems = sorted ( oitems , key = lambda s :s[1].value() , reverse = reverse ) new_graph = ROOT.TGraphErrors ( len( g...
5,315,017
def compute_features_paa(filename, with_timebase=False, verbose=False): """compute_features_paa Compute a bag of standard audio features to be used for some downstream task. """ if verbose: print('compute_features_paa loading from {0}'.format(filename)) [Fs, x_] = audioBasicIO.read_audi...
5,315,018
def download_datasets(destination, *datasets, server=None, api_key=None, galaxy_client=None): """ download datasets from galaxy server """ gi = galaxy_client if not gi: gi = galaxy_client(server=server, api_key=api_key) dataset_cli = galaxy.datasets.DatasetClient(gi) ...
5,315,019
def str_match_end(name, strip): """ :param name: :param strip: :return: """ if name is None: return False if name[len(name)-len(strip):len(name)] == strip: return True return False
5,315,020
def run_post_script(logger, post_script, vm, mac_ip, custom_mac): """ Runs a post script for a vm """ if mac_ip: logger.info('Running post-script command: %s %s %s %s' % (post_script, vm.config.name, mac_ip[0], mac_ip[1])) retcode = subprocess.call([post_script, vm.config.name, mac_ip[0]...
5,315,021
def points(start, end): """ Bresenham's Line Drawing Algorithm in 2D """ l = [] x0, y0 = start x1, y1 = end dx = abs(x1 - x0) dy = abs(y1 - y0) if x0 < x1: sx = 1 else: sx = -1 if y0 < y1: sy = 1 else: sy = -1 err = dx - dy whil...
5,315,022
async def test_create_phylo_run( async_session: AsyncSession, http_client: AsyncClient, ): """ Test phylo tree creation, local-only samples. """ group = group_factory() user = user_factory(group) location = location_factory( "North America", "USA", "California", "Santa Barbara Co...
5,315,023
def add_previous_and_future_tiles(dfs: Iterable[DataFrame]) -> Iterator[DataFrame]: """Used to create a `route_hash`""" for df in dfs: df["prevprevious_tile"] = df.tile_id.shift(2, fill_value=RUN_START) df["previous_tile"] = df.tile_id.shift(1, fill_value=RUN_START) df["next_tile"] = df....
5,315,024
def ExtractIconReps(icon_file_name): """Reads the contents of the given icon file and returns a dictionary of icon sizes to vector commands for different icon representations stored in that file. Args: icon_file_name: The file path of the icon file to read. """ with open(icon_file_name, "r") as...
5,315,025
def _is_device_list_local(devices): """Checks whether the devices list is for local or multi-worker. Args: devices: a list of device strings, either local for remote devices. Returns: a boolean indicating whether these device strings are for local or for remote. Raises: ValueError: if device ...
5,315,026
def ab_from_mv(m, v): """ estimate beta parameters (a,b) from given mean and variance; return (a,b). Note, for uniform distribution on [0,1], (m,v)=(0.5,1/12) """ phi = m*(1-m)/v - 1 # z = 2 for uniform distribution return (phi*m, phi*(1-m))
5,315,027
def get_credentials(): """Get the Google credentials needed to access our services.""" credentials = GoogleCredentials.get_application_default() if credentials.create_scoped_required(): credentials = credentials.create_scoped(SCOPES) return credentials
5,315,028
def mtrax_mat_to_big_arrays(data): """translation of code sent to me by alice""" if np.any(~np.isfinite(data['identity'])): # make sure no funny numbers raise ValueError('cannot handle non-finite data on identity') identity = np.array( data['identity'], dtype=int ) # cast to int assert np.allclo...
5,315,029
def on_ne_sort_pas_de_la_carte(carte,joueur,etat_du_jeu) : """ Fonction qui interdit le mouvement si le joueur depasse les bords de la carte. Pour MODELISER CECI, on restaure le joueur précédent """ X,Y = joueur.position() Max_X, Max_Y = carte.dimensions() on_depasse_sur_X = (X < 0) or (X ...
5,315,030
def normalize_class(c:Union[str,int], ensure_scored:bool=False) -> str: """ finished, checked, normalize the class name to its abbr., facilitating the computation of the `load_weights` function Parameters ---------- c: str or int, abbr. or SNOMEDCTCode of the class ensure_scored: b...
5,315,031
def appearance_kernel(x_1: int, y_1: int, p_1: np.ndarray, x_2: int, y_2: int, p_2: np.ndarray, theta_alpha: float, theta_beta: float) -> float: """Compute appearance kernel. Args: x_1: X coordinate of first pixel. y_1: Y coordinate of first pixel. ...
5,315,032
def dataset(data: utils.URLPath, meta: utils.URLPath): """Print information on the given dataset.""" try: dataset = io_functions.load_case_collection(data, meta) except TypeError: dataset = io_functions.load_case_collection_from_caseinfo(data, meta) print(f"Loaded dataset from {meta}", ...
5,315,033
def update_game_log_tables(player_id, season): """ Loads player's game for specific season as pandas DataFrame :param player_id: string, :param season: int :return: column names, table data for 'games-table' object and table title for text object """ global df_reg_games, df_po_games, df_ids ...
5,315,034
async def cmd_settings_get_prefix(ctx: commands.Context): """ Retrieve the prefix setting for this server. You need the 'Manage Server' permission to use this command. This command can only be used on Discord servers/guilds. Usage: /settings prefix Examples: /settings prefix - Pri...
5,315,035
def print_imageset_table(ibs, **kwargs): """ Dumps imageset table to stdout Kwargs: exclude_columns (list): """ print('\n') print(ibs.db.get_table_csv(const.IMAGESET_TABLE, **kwargs))
5,315,036
def main(): """Usage: newest-id.py filename.json Assumes filename.json is a JSON GroupMe transcript in chronological order. """ if len(sys.argv) < 2: print(main.__doc__) sys.exit(1) transcriptFile = open(sys.argv[1]) transcript = json.load(transcriptFile) transcriptFile.close(...
5,315,037
def download_certbot_config(config_bucket: str, config_key: str, certbot_config_dir: str, certbot_work_dir: str) -> None: """ Download the configuration tar file from S3 and extract it to the certbot config directory. """ with TemporaryFile(prefix="config", suffix=".tar.gz", dir=certbot_work_dir) as fd:...
5,315,038
def _convert_relative_time(relative_time): """ Convert a Cb Response relative time boundary (i.e., start:-1440m) to a device_timestamp: device_timestamp:[2019-06-02T00:00:00Z TO 2019-06-03T23:59:00Z] """ time_format = "%Y-%m-%dT%H:%M:%SZ" minus_minutes = relative_time.split(':')[1].split('m')[0]...
5,315,039
def test_partition_first_items(xs): """retrieving the first item of each grouping recovers the original list.""" rt = list(map(lambda pair: pair[0], u.partition(xs, 1))) assert rt == xs
5,315,040
def test_customer_soft_delete(): """ Verifies the CustomSoftDelete test model has the "custom_active" flag set to false """ soft_delete = ddf.G(models.CustomSoftDelete, custom_active=True) soft_delete.delete() assert not models.CustomSoftDelete.objects.get().custom_active
5,315,041
def NTFSolve_conv(M, Mmis, Mt0, Mw0, Mb0, nc, tolerance, LogIter, Status0, MaxIterations, NMFFixUserLHE, NMFFixUserRHE, NMFFixUserBHE, NMFSparseLevel, NTFUnimodal, NTFSmooth, NTFLeftComponents, NTFRightComponents, NTFBlockComponents, NBlocks, NTFNConv, NMFPriors, myStatusBox): """Estimate NTF matrices ...
5,315,042
def fds_remove_crc_gaps(rom): """Remove each block's CRC padding so it can be played by FDS https://wiki.nesdev.org/w/index.php/FDS_disk_format """ offset = 0x0 def get_block(size, crc_gap=2): nonlocal offset block = rom[offset : offset + size] offset += size + crc_gap ...
5,315,043
def _apply_categorical_projection_naive(y, y_probs, z): """Naively implemented categorical projection for checking results. See (7) in https://arxiv.org/abs/1802.08163. """ batch_size, n_atoms = y.shape assert z.shape == (n_atoms,) assert y_probs.shape == (batch_size, n_atoms) v_min = z[0] ...
5,315,044
def startPcap(raw_file_path, pcap_name): """ Run tcpdump to capture all network traffic. Capture full-size packets and DON'T apply snaplen, because there might be short header frames that are combined with other frames in the same packet (e.g., upon startup) and we would in those cases lose the initial valu...
5,315,045
def calculate_xdf( arr, method="truncate", methodparam="adaptive", truncate_extrema=True, ): """Calculate xDF-corrected statistics for correlation coefficients. Parameters ---------- arr : numpy.ndarray of shape (S, T) S is features, T is time points method : {"truncate", "t...
5,315,046
def truncatewords(base, length, ellipsis="..."): """Truncate a string by words""" # do we need to preserve the whitespaces? baselist = base.split() lenbase = len(baselist) if length >= lenbase: return base # instead of collapsing them into just a single space? return " ".join(baseli...
5,315,047
def normalising_general(data,scoreMAX=[20,27,100,21],scoreMIN=[0,0,0,0],cumsum=True): """Normalises the data of the patient with missing count. Parameters ---------- data : numpy data, [number of observations, number of features] scoreMAX: max scores for asrm and qids scoreMIN: min scores for a...
5,315,048
def extract_csv_from_t2out(json_output=False): """It writes the parameter for every block from the last output file of TOUGH2 simulation on csv or json Parameters ---------- json_output : bool If True a json file is save on ../output/PT/json/ Returns ------- file PT.csv: on ../output/PT/csv/ Attention ...
5,315,049
def fix_lazy_json(in_text): """ This function modifies JS-contained JSON to be valid. Posted in http://stackoverflow.com/questions/4033633/handling-lazy-json-\ in-python-expecting-property-name by Pau Sánchez (codigomanso.com) """ tokengen = tokenize.generate_tokens(io.StringIO(in_text)...
5,315,050
def get_project_family(repo, namespace=None, username=None): """Return the family of projects for the specified project { code: 'OK', family: [ ] } """ allows_pr = flask.request.form.get("allows_pr", "").lower().strip() in [ "1", "true", ] allows_iss...
5,315,051
def get_job_output(name: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetJobResult]: """ Resource schema for AWS::DataBrew::Job. :param str name: Job name """ ...
5,315,052
def transform( f, apply_rng=False, state=False, ) -> Transformed: """Transforms a function using Haiku modules into a pair of pure functions. The first thing to do is to define a `Module`. A module encapsulates some parameters and a computation on those parameters: >>> class MyModule(hk.Module): ...
5,315,053
def test_experiment_same_name_wout_exv_w_child_w_name( clean_db, three_experiments_family_same_name, capsys ): """Test status name with two experiments having the same name and one with a child.""" orion.core.cli.main(["status", "--name", "test_single_exp"]) captured = capsys.readouterr().out expe...
5,315,054
def direct_to_waypoint(aircraft_id, waypoint_name): """ Request aircraft to change heading toward a waypoint. Parameters ---------- aircraft_id : str A string aircraft identifier. For the BlueSky simulator, this has to be at least three characters. waypoint_name : str ...
5,315,055
def plot_cdf(lines, line_labels, xlabel, title, location, out_pathname, figsize = None, fontsize = 'small'): """Saves cdf for given lines in out_name.""" fig = matplotlib.pyplot.figure(figsize = figsize) line_styles = ['-v', '-o', '-s', '-*', '-x', '-D', '-+'] num_markers = 10 # histogram #...
5,315,056
def username_allowed(username): """Returns True if the given username is not a blatent bad word.""" if not username: return False blacklist = cache.get(USERNAME_CACHE_KEY) if blacklist is None: f = open(settings.USERNAME_BLACKLIST, "r") blacklist = [w.strip() for w in f.readline...
5,315,057
def satisfiability(p=5, ratio=2.0, pr_edge=0.5, pr_exo=0.3, dsp_scm=True): """ Count the number of attempts to generate a linear P-SCM that can be uniquely recovered (i.e., satisfies the derived conditions). :param p: Number of observed nodes :param ratio: Source to observed node ratio. (Num...
5,315,058
def test_parse_raw_input_node_names_C(): """ `parse_raw_input_node_names` Feature C: raising exception when node names are not a list. """ raw_input_node_names = ' - A\n - B' with pytest.raises(ValueError): parse_raw_input_node_names(raw_input_node_names)
5,315,059
def get_uri(env_var='DATABASE_URL'): """Grab and parse the url from the environment.""" parsed_result = urlparse( # Trick python3's urlparse into raising when env var is missing os.environ.get(env_var, 1337) ) meta = { 'scheme': parsed_result.scheme, 'username': unquote(p...
5,315,060
def next_update_time(m): """Return the next update time. If the UpdateFrequency or Modified """ last_mod = m.doc['Root'].find_first_value('Root.Modified') if last_mod: last_mod = parse(last_mod) else: return False uf = m.doc['Root'].find_first_value('Root.UpdateFrequency') ...
5,315,061
def random_permutation(iterable, r=None): """Random selection from itertools.permutations(iterable, r)""" pool = tuple(iterable) if r is None: r = len(pool) return list(random.sample(pool, r))
5,315,062
async def shutdown(signal, loop, bridge): """Cleanup tasks tied to the service's shutdown.""" logger.info(f"Received exit signal {signal.name}...") await bridge.stop() tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()] for task in tasks: if task.done(): ...
5,315,063
def _restore_desired_size(cfn_params, stack_name, scheduler): """ Make the ASG desired capacity to be restored to its current value after the update operation. This is done by providing the current value to CloudFormation with the DesiredSize parameter so that the ASG will be updated with that capacity...
5,315,064
def set_admin_secret(admin_secret): """ Sets the admin secret for k8s. """ global ADMIN_SECRET ADMIN_SECRET = admin_secret
5,315,065
def interact_model( model_name='117M', seed=None, nsamples=1, batch_size=1, length=None, temperature=1, top_k=0, top_p=0.0, filename='', overwrite=False, tag = '', max_document = None ): """ Interactively run the model :model_name=117M : String, which model to...
5,315,066
def rabin_karp_pattern_set(test_file_text, k): """ Given a document to detect matches for, creates a set of for the "rolling" hashcodes of each shingle. Runtime: O(len(test_file_text)) with a very small constant factor @param test_file_text: string of file to detect matchse for @param k: length of shingles @re...
5,315,067
def subs_reroll(subs, prefix): """ Subcommand parsing for rerolls """ desc = """Search youtube for songs to play. {prefix}reroll Reroll the last roll you issued. {prefix}reroll -1 Reroll the last roll you issued. {prefix}reroll -2 Reroll a roll made two rolls ago. {prefix}reroll --menu...
5,315,068
def test_set_available_nodes_call_order(kusama_manager): """Test `_set_available_nodes_call_order()` sets the available nodes sorted by preference; currently own node first and then by the highest 'weight_block'. """ # Due to `available_node_attributes_map` is a dict we must fake a key for # testing...
5,315,069
def get_hms(t_sec): """Converts time in seconds to hours, minutes, and seconds. :param t_sec: time in seconds :return: time in hours, minutes, and seconds :rtype: list """ h = t_sec//3600 m = (t_sec - h*3600)//60 s = t_sec%60 return h,m,s
5,315,070
def check_model_version_name(model_name: Text, model_version: Dict) -> bool: """Check model version name. Args: model_name {Text}: model name model_version {Dict}: model version dictionary Returns: True if model names are matches, otherwise false """ model_version = model_ve...
5,315,071
def current_page_name(webdriver: webdriver, valid_url: str = "tricount.com") -> str: """ Checks current page for content, determines name. Returns: page name, according to names in PAGE_NAV_ORDER Raises: AssertionError - webdriver.current_url doesn't match expected valid_url Ind...
5,315,072
def task_jshat_app_watch(): """JsHat application - build all on change""" return {'actions': ['yarn run --silent watch ' '--config webpack.app.config.js'], 'task_dep': ['jshat_deps']}
5,315,073
def write_suite(stedef, stefile): """ Write suite definition to file """ stedef.check_job_creation() # .ecf -> job0 stedef.check() # check trigger expressions stedef.save_as_defs(stefile)
5,315,074
def get_realm(request): """ Currently not setting realm in session, so using user to get realm Expect tenant attribute to be set on request in Workspace in use, if user not set or user is superuser, then no tenant """ from etools_permissions.models import Realm realm = None if request.u...
5,315,075
def _marked_merging(A, criterion_fn, node_weights=None): """ Method of paper 'Weighted Graph Cuts without Eigenvectors: A Multilevel Approach' """ if node_weights is None: node_weights = np.ones(A.shape[0]) unmarked_vertices = list(np.arange(A.shape[0])) edges_to_merge = np.zeros_like(A) whi...
5,315,076
def fast_aggregate(X, Y): """If X has dims (T, ...) and Y has dims (T, ...), do dot product for each T to get length-T vector. Identical to np.sum(X*Y, axis=(1,...,X.ndim-1)) but avoids costly creation of intermediates, useful for speeding up aggregation in td by factor of 4 to 5.""" T = X.shape[0] ...
5,315,077
def GroupConv2D(filters, kernel_size, strides=(1, 1), groups=32, kernel_initializer='he_uniform', use_bias=True, activation='linear', padding='valid', **kwargs): """ Grouped Convolutio...
5,315,078
def shift(seq: Sequent) -> Sequent: """ The :math:`\\textbf{Opt${}^?$}` :math:`\\texttt{shift}` rule. From an :math:`n`-opetope :math:`\\omega`, creates the globular :math:`(n+1)`-opetope :math:`\\lbrace []: \\omega`. """ n = seq.source.dimension ctx = Context(n + 1) for a in seq.sou...
5,315,079
def vgg_11(batch_norm=True, pretrained=False, fixed_feature=True): """ VGG 11-layer model from torchvision's vgg model. :param batch_norm: train model with batch normalization :param pretrained: if true, return a model pretrained on ImageNet :param fixed_feature: if true and pretrained is true, model features are ...
5,315,080
def __searchTzolkinDates( cmd_line_parser: argparse.ArgumentParser, cmdline_args: argparse.Namespace, date_str: str, tzolkin_date: TzolkinDate, ) -> None: """Search for gregorian dates with the same Tzolkin date as the given one. Args: cmd_line_parser (argparse.ArgumentParser): The comm...
5,315,081
def main(): """ Main """ parser = ctg_parseargs() args = parser.parse_args() # set up logger level = logging.WARNING if args.quiet: level = logging.ERROR if args.verbose: level = logging.INFO if args.debug: level = logging.DEBUG logging.basicConfig...
5,315,082
def det(value): """ det(m) --> float Returns the determinant of m, 0 if m is a singular MatrixN, m must be convertible to MatrixN. Related : see MatrixN.det(self) method. """ pass
5,315,083
def clean_graph(graph: Graph) -> None: """ Given graph, return a form of graph with minimal hallway nodes while still preserving connectivity and total edge weight between any two room nodes. """ cur_edge = find_removable_edge(graph) while cur_edge is not None: remove_edge(graph, cur_edg...
5,315,084
def Wavelet_hardSoft(s, jN, wname, alpha=0.5): """ 小波折中阈值滤波 :param s: :param jN: :param wname: :param alpha: :return: """ ca, cd = wavedec(s, jN, wname) for i in range(len(ca)): thr = np.median(cd[i] * np.sqrt(2 * np.log((i + 2) / (i + 1)))) / 0.6745 d...
5,315,085
def handle_actor_replicate(self, handle, connection, match, data, hdr): """ POST /actor/{replication-id}/replicate Will replicate an actor having manual_scaling requirement applied Currently must be sent to the runtime having the elected replication manager for the replication id Response status cod...
5,315,086
def compute_vad(log_energy, energy_mean_scale=0.5, energy_threshold=0.5, frames_context=0, proportion_threshold=0.6): """ Apply voice activity detection :param log_energy: Log mel energy. :param energy_mean_scale: If this is set to s, to get the actual threshold we let m be the mean log-energy of the file,...
5,315,087
def current_velocity(x_new, x_prev, h): """ returns current velocity of a particle from next position at timestep. """ """ parameters ---------- x_new : array new x-position of particle x_prev : array previous x-position of particle h : float simulation timestep ...
5,315,088
def csvReadCallback(inputFile, **kw): """Read callback for CSV data""" inputFile.readline() # skip header reader = csv.reader(inputFile, lineterminator='\n', **kw) return [row for row in reader]
5,315,089
def get_interface_config_commands(interface, intf, existing): """Generates list of commands to configure on device Args: interface (str): k/v pairs in the form of a set that should be configured on the device intf (str): full name of interface, i.e. Ethernet1/1 Returns: lis...
5,315,090
def load_word(): """ return the sql and values of the insert queuery.""" sql = """ INSERT INTO Spanglish_Test.Word ( `word`, `language_id`, `category_id` ) VALUES (%s, %s, %s) """ values = [ ( 'Ir', 2, 1 ), ...
5,315,091
def AttenLogitsRPE(query, key, abs_pos_emb, is_causal): """Attention logits from ... https://arxiv.org/pdf/1803.02155.pdf with trainable rel position emb. Notice padding is supposed to be masked by the caller of this function. B: batch size T: sequence length N: num of attention heads. H: per-head atte...
5,315,092
def test_pre_order_method(bst_2): """Test the pre order method.""" a = bst_2.pre_order(bst_2.root) result = [] for _ in range(7): result.append(next(a)) assert result == [10, 8, 7, 9, 12, 11, 13]
5,315,093
def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re_art.sub(' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): return re_punc.sub(' ', text) # convert punctu...
5,315,094
def qso_template_uv(wa, z): """ Return a composite UV QSO spectrum at redshift z. Wavelengths must be in Angstroms. This is a smoothed version of the HST/COS EUV+FUV AGN composite spectrum shown in Figure 5 of Shull, Stevans, and Danforth 2012. Only good between 550 and 1730 Angstroms (rest frame...
5,315,095
def encode_multipart_formdata(fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (headers, body) ready for httplib.HTTP instance based on http://code.activest...
5,315,096
def lanefinder_pipeline(img, video=False, debug=False): """ The pipeline for laneline finding based on all the techniques used so far :param img: The image to find lanelines on :return: An image with laneline boundaries drawn on """ # Undistort undst = cv2.undistort(img, mtx, dist, None, mtx...
5,315,097
def get_ppl_experience(log_entries: QuerySet) -> dict: """ https://www.easa.europa.eu/sites/default/files/dfu/Part-FCL.pdf (a) Applicants for a PPL(A) shall have completed at least 45 hours of flight instruction in aeroplanes or TMGs, 5 of which may have been completed in an FSTD, including at leas...
5,315,098
def fields(basekey: str, tablename: str, apikey: str): """Print the fields of the table""" table = airtable.Airtable(basekey, tablename, apikey) for row in table.get_all(maxRecords=1): click.echo(list(row['fields'].keys()))
5,315,099