content
stringlengths
22
815k
id
int64
0
4.91M
def create_tables_command(schema_file): """create one table for existing database :param number_of_companies: number_of_companies :type number_of_companies: int :param schema_file: schema file :type schema_file: json """ command_list = [] for table_name in TABLE_LIST: schema = g...
5,307,200
def _conf(): """Try load local conf.json """ fname = os.path.join(os.path.dirname(__file__), "conf.json") if os.path.exists(fname): with open(fname) as f: return json.load(f)
5,307,201
def main(): """SMPTE ST 2084 EOTF test""" print('m1', m1) print('m2', m2) print('c1', c1) print('c2', c2) print('c3', c3) for i in range(11): i = i / 10 print('L * 10000', i, L(i) * 10000)
5,307,202
def get_key(key): """ Get key :param: key - Color key """ return key.replace('-', '')
5,307,203
def readPlumes(filename, logger=None): """ read plumes from filename that contains plume time and lat lon """ if logger is not None: logger.info("reading {}".format(filename)) with open(filename,'rt') as fin: plumes = list(csv.DictReader(fin, skipinitialspace=True)) return plumes
5,307,204
def __dense_p(name, x, w=None, output_dim=128, initializer=tf.contrib.layers.xavier_initializer(), l2_strength=0.0, bias=0.0): """ Fully connected layer :param name: (string) The name scope provided by the upper tf.name_scope('name') as scope. :param x: (tf.tensor) The input to the layer (...
5,307,205
def test_itemids_in_outputevents_are_shifted(mimic_con, mimic_schema): """ Number of ITEMIDs which were erroneously left as original value """ query = f""" SELECT COUNT(*) FROM {mimic_schema}.outputevents WHERE itemid < 30000; """ queryresult = pd.read_sql_query(query, mimic_con) as...
5,307,206
def test_restart_all(mocker, pusher, puller): """ The method tests that the 'RestartAll' request is sent and received correctly. """ pusher.send_restart_all('10.0.0.1') request = puller.receive() assert request == (DeferredRequestHeaders.RESTART_ALL.value, ('10.0.0.1',)) # test that the pusher socke...
5,307,207
def _autoscan_group(addresses): """This is the function that actually gets queued during autoscanning.""" for address in addresses: _autoscan_address(address)
5,307,208
def cli(): """CLI command with no arguments. Does nothing.""" pass
5,307,209
def get_sm_tag_from_alignedseg(aln): """Get 'sm' tag from AlignedSegment.""" try: return aln.get_tag('sm') except Exception as e: raise ValueError("Could not get 'sm' tag from {aln}".format(aln=aln))
5,307,210
def get_image_info(url): """Returns the content-type, image size (kb), height and width of an image without fully downloading it. :param url: The URL of the image. """ try: r = requests.get(url, stream=True) except requests.ConnectionError: return None image_size = r.heade...
5,307,211
def limdrift(g, tau, acyrus=0.25): """ Use Cyrus Umrigar's algorithm to limit the drift near nodes. :parameter g: a [nconf,ndim] vector :parameter tau: time step :parameter acyrus: the maximum magnitude :returns: The vector with the cut off applied and multiplied by tau. """ tot = np.li...
5,307,212
def test_covariant_game(strategies, _): """Test covariant game""" game = gamegen.covariant_game(strategies) assert game.is_complete(), "didn't generate a full game" assert game.is_asymmetric(), \ "didn't generate an asymmetric game" assert np.all(strategies == game.num_role_strats), \ ...
5,307,213
def service2(backends_mapping, custom_service, service_settings2, service_proxy_settings, lifecycle_hooks): """ We need second service to test with because we want to test deletion of active docs and that needs to be tested on separate service. """ return custom_service(service_settings2, service_pr...
5,307,214
def parse_arguments(args_to_parse): """ Parse the command line arguments. Arguments: args_to_parse: CLI arguments to parse """ parser = argparse.ArgumentParser( description='Split the two CTM files (*.stm) (alignment files) into the respective lattice file directories' ) ...
5,307,215
def random_noise_image(img, new_dims, new_scale, interp_order=1 ): """ Add noise to an image Args: im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. new_scale : (min, max) tuple of new scale. interp_order : interpolation order, default is l...
5,307,216
def get_fixed_length_string(string: str, length=20) -> str: """ Add spacing to the end of the string so it's a fixed length. """ if len(string) > length: return f"{string[: length - 3]}..." spacing = "".join(" " for _ in range(length - len(string))) return f"{string}{spacing}"
5,307,217
def V3(meanFalse, meanTrue, sample): """ This NMC distance metric scores samples by considering a point that is halfway {meanFalse, meanTrue}, then calculating the cosine of the angle {sample, halfway, meanTrue}. Points towards meanTrue get a score of close to +1, while points towards meanFalse get a sc...
5,307,218
def choicelist_choices(): """Return a list of all choicelists defined for this application.""" l = [] for k, v in CHOICELISTS.items(): if v.verbose_name_plural is None: text = v.__name__ else: text = v.verbose_name_plural l.append((k, text)) l.sort(key=la...
5,307,219
def store_inspection_outputs(annotation_iterators, return_value) -> BackendResult: """ Stores the inspection annotations for the rows in the dataframe and the inspection annotations for the DAG operators in a map """ annotations_df = build_annotation_df_from_iters(singleton.inspections, annotation_i...
5,307,220
def pairwise_iou(boxes1: RotatedBoxes, boxes2: RotatedBoxes) -> None: """ Given two lists of rotated boxes of size N and M, compute the IoU (intersection over union) between __all__ N x M pairs of boxes. The box order must be (x_center, y_center, width, height, angle). Args: boxes1, box...
5,307,221
def add_one(): """{"questionId":1} """ try: __id: int = request.json.get('questionId') Question.update(click_count=Question.click_count + 1).where(Question.question_id == __id) except: pass
5,307,222
def train(): """Train CIFAR-10 for a number of steps.""" g1 = tf.Graph() with g1.as_default(): global_step = tf.contrib.framework.get_or_create_global_step() # Get images and labels for CIFAR-10. images, labels = cifar10.distorted_inputs() # Build a Graph that computes the logits predictions fr...
5,307,223
def specific_gravity(temp, salinity, pressure): """Compute seawater specific gravity. sg = C(p) + β(p)S − α(T, p)T − γ(T, p)(35 − S)T units: p in “km”, S in psu, T in ◦C C = 999.83 + 5.053p − .048p^2 β = .808 − .0085p α = .0708(1 + .351p + .068(1 − .0683p)T) γ = .003(1 − .059p − .012(1 − ....
5,307,224
def test_atomic_float_white_space_nistxml_sv_iv_atomic_float_white_space_1_8(mode, save_output, output_format): """ Type atomic/float is restricted by facet whiteSpace with value collapse. """ assert_bindings( schema="nistData/atomic/float/Schema+Instance/NISTSchema-SV-IV-atomic-float-whiteS...
5,307,225
def rollaxis(tensor, axis, start=0): """ Roll the specified axis backwards, until it lies in a given position. This function continues to be supported for backward compatibility, but you should prefer `moveaxis`. Parameters ---------- a : Tensor Input tensor. axis : int ...
5,307,226
def snapshot_download( repo_id: str, *, revision: Optional[str] = None, repo_type: Optional[str] = None, cache_dir: Union[str, Path, None] = None, library_name: Optional[str] = None, library_version: Optional[str] = None, user_agent: Optional[Union[Dict, str]] = None, proxies: Option...
5,307,227
def LoadBuffer(SerialPort, Log, OnBufferA, Data, IsNativePort): """ Writes SXXXXXXXX,XXXXXXXX# command then Xmodem. """ Log.Log("LoadBuffer():") ArduinoFlashSerial.Write(SerialPort, Log, ArduinoFlashHardValues.pageBufferA if OnBufferA else ArduinoFlashHardValues.pageBufferB, Data, ArduinoFlashHardVa...
5,307,228
def cdc_long_spec( topic:str, key_schema_name:str, key_schema_version:str, value_schema_name:str, value_schema_version:str, ): """ Create a CdcSpec opaque object (necessary for one argument in a call to consume*ToTable) via explicitly specifying all configuration opti...
5,307,229
def record(MyRecord, db): """Create a record instance of MyRecord.""" return MyRecord.create({'title': 'test'})
5,307,230
def test_can_t_preload_with_ns(namespace): """Test using a namespace as an initial value.""" with pytest.raises(ValueError, message='Bad values: {}'): print(namespace(namespace_=namespace()))
5,307,231
def send_email(kwargs): """ Wrap email sending based on SSL/TLS. :param server: SMTP email server. :type server: str :param port: Port to use. :type port: int :param username: Email address. :type username: str :param password: Email password, optional. :type password: str ...
5,307,232
def reciprocal_mod(input_x, input_m): """ # Based on a simplification of the extended Euclidean algorithm :param input_x: :param input_m: :return: """ assert 0 <= input_x < input_m intermediate_y = input_x input_x = input_m intermediate_a = 0 intermediate_b = 1 while in...
5,307,233
def clip_audio(source_file, target_file, start_time, stop_time): """ 利用pydub进行音频剪切。pydub支持源文件为 mp4格式,因此这里的输入可以与视频剪切源文件一致 :param source_file: 原视频的路径,mp4格式 :param target_file: 生成的目标视频路径,mp4格式 :param start_time: 剪切的起始时间点(第start_time秒) :param stop_time: 剪切的结束时间点(第stop_time秒) :return: """ ...
5,307,234
def sort_by_expl_var(u, z, v, hrf_rois): # pragma: no cover """ Sorted the temporal the spatial maps and the associated activation by explained variance. Parameters ---------- u : array, shape (n_atoms, n_voxels), spatial maps z : array, shape (n_atoms, n_times_valid), temporal components ...
5,307,235
def get_set_attribute() -> None: """Demonstrates how to set attributes.""" device = stc.project.ports["Port 1"].devices["Device 1"] # Get all attributes print(device.get_attributes()) # Get group of attributes print(device.get_attributes("RouterId", "RouterIdStep")) # Get specific attrib...
5,307,236
def np(self): """ Returns numpy array of the object. It returns coordinates,(and ids for line and polygon) XY coordinates are always place last. Note ---- x:x-coordinate y:y-coordinate lid: line id pid: polygon id cid: collection id Output ------ ndarray: 2D array shape: Point, (npoi...
5,307,237
def test_model_database_type_many_to_many(engine, sessionmaker): """ GIVEN spec for a many to many relationship WHEN spec is constructed with model factory and queried THEN the referenced and back reference type is an array that is not nullable. """ # Defining specification spec = { ...
5,307,238
def _common_gpipe_transformer_fprop_meta(p, inputs, *args): """GPipe FPropMeta function.""" # TODO(huangyp): return accurate estimate of flops. py_utils.CheckShapes((inputs,)) flops_per_element = 5 src_time, source_batch, dim = inputs flops = flops_per_element * src_time * src_time * source_batch * dim ar...
5,307,239
def random_closure(a, N=1000): """Sample a random fiber orientation and compute fourth order tensor. Parameters ---------- a : 3x3 numpy array Second order fiber orientation tensor. Returns ------- 3x3x3x3 numpy array Fourth order fiber orientation tensor. """ orie...
5,307,240
def get_tt_data(df): """ Returns training and test for given workload X_train, X_test are pandas dataframes y_* are 1d numpy array :param workload: :return: X_train, X_test, y_train, y_test """ # Drop fields df = df.drop('CPUTime', axis=1) df = df.drop('UsedMEM', axis=1) ...
5,307,241
def test_compare_checksum(first_read): """Test to compare a file with a checksum""" # GIVEN the path to a gzipped file, a checksum and a cli runner checksum = get_checksum(first_read) runner = CliRunner() # WHEN running the compare command result = runner.invoke( base_command, ["compare"...
5,307,242
def recomposite_from_log_components(log_reflectance, log_shading): """Combines log_reflectance and log_shading to produce an rgb image. I = R x S = e^(log_reflectance + log_shading) Args: log_reflectance: [B, H, W, 3] Log-reflectance image log_shading: [B, H, W, 1 or 3] Log-shading image Returns: ...
5,307,243
def downgrade(): """Downgrade database.""" op.drop_table('pidstore_redirect') op.drop_table('pidstore_recid') op.drop_index('uidx_type_pid', table_name='pidstore_pid') op.drop_index('idx_status', table_name='pidstore_pid') op.drop_index('idx_object', table_name='pidstore_pid') op.drop_table(...
5,307,244
def nrepeat(ts): """ Return the length of consecutive runs of repeated values Parameters ---------- ts: DataFrame or series Returns ------- Like-indexed series with lengths of runs. Nans will be mapped to 0 """ if isinstance(ts,pd.Series): return _nrepeat(ts) ...
5,307,245
def main(): """ Loads MODIS data files for the specified geographic region, timeframe, and time stamps. The user can then process these images and extract smoke plumes. """ viirs_plume_df = load_df(fp.plume_polygon_path) with open(fp.analysis_filelist_path, 'rU') as f: for viir...
5,307,246
def check_transform_series(X_list, y): """Returns X, y that have been transformed into numpy arrays. This mirrors the sktime implementation. Args: X_list: pandas DataFrame The array is presented by pandas. y: pandas DataFrame The array is presented by pandas. Re...
5,307,247
def ensure_cpu_count(use_threads: bool = True) -> int: """Get the number of cpu cores to be used. Note ---- In case of `use_threads=True` the number of threads that could be spawned will be get from os.cpu_count(). Parameters ---------- use_threads : bool True to enable multi-c...
5,307,248
def scale_all(dat, scl_prms, min_out, max_out, standardize): """ Uses the provided scaling parameters to scale the columns of dat. If standardize is False, then the values are rescaled to the range [min_out, max_out]. """ dat_dtype = dat.dtype fets = dat_dtype.names num_scl_prms = len(sc...
5,307,249
def ard_netcdf_encoding(ard_ds, metadata, **encoding_kwds): """ Return encoding for ARD NetCDF4 files Parameters ---------- ard_ds : xr.Dataset ARD as a XArray Dataset metadata : dict Metadata about ARD Returns ------- dict NetCDF encoding to use with :py:meth:`...
5,307,250
def recommendation_response(agent, resource_id, recency_limit, scale, logger): """ Giving back the direct XP as the recommendation on other agent in the point of view from agent. :param agent: The agent which calculates the popularity. :type agent: str :param resource_id: The URI of the evaluated r...
5,307,251
def _fill_page(pg, page, nsmap, book): """Fill Page data from XML tree. """ for fr in pg.findall("frame", namespaces=nsmap): frame = libacbf.body.Frame(helpers.pts_to_vec(fr.attrib["points"])) if "bgcolor" in fr.keys(): frame.bgcolor = fr.attrib["bgcolor"] page.frames.app...
5,307,252
def get_input_files(input_dirpath, pattern): """Returns the names of the files in input_dirpath that matches pattern.""" all_files = os.listdir(input_dirpath) for filename in all_files: if re.match(pattern, filename) and os.path.isfile(os.path.join( input_dirpath, filename)): ...
5,307,253
def md5hash(door: str, index: int) -> str: """ Calculate the md5 hash for the given Door ID and integer index. """ return md5((door + str(index)).encode("utf-8")).hexdigest()
5,307,254
def rename(src: str, dst: str) -> None: """Renames the file from ``src`` to ``dst`` Call the corresponding :func:`IO.rename` upon the default handler. Note the ``src`` and ``dst`` SHOULD be in the same filesystem. The ``src`` and ``dst`` can be either POSIX paths or URIs. """ global _DEFAULT_...
5,307,255
def select_layer(input, name, slice_point, axis=1): """ build a layer of type 'Slice' using fluid Args: @input (variable): input fluid variable for this layer @name (str): name for this layer @slice_point (list): parameter from caffe's Slice layer @axis (int): parameter from caf...
5,307,256
def find_dom_root(parent_dom_node, dom_node): """ .. seealso:: :meth:`find_placeable_dom_tree_roots` """ if dom_node is None or parent_dom_node is None: return None if dom_node.getparent() == parent_dom_node: return dom_node elif dom_node.getparent() is None: return None ...
5,307,257
def size_subtrees(tree: dict, root: str, tokenizer=get_tokenizer(), extra_tokens: int = 1): """ Args: tree: The tree in full_tree format of dict_to_full_tree. root: The node whose sub-trees sizes are to be measured up. ...
5,307,258
def write_run_script(run_config: RunConfig, src: TextIO, dst: TextIO) -> None: """Writes run script from src to dst""" for line in src: if line.startswith("IDE_BIN_HOME"): line = f'IDE_BIN_HOME={quote(join(run_config.path_to_app, "bin"))}\n' elif line.find("classpath") != -1: ...
5,307,259
def remove_tags( input: Optional[str] = 'dagmc.h5m', output: Optional[Union[str, List[str]]] = 'dagmc_removed_tag.vtk', tags: Optional[Union[str, List[str]]] = 'graveyard', verbose: Optional[bool] = False, ): # -> List[List[str], List[str], List[str]]: """Removes a specific tag from a dagmc h5m ...
5,307,260
def burst(wait=-1, rounds=-1, repeat=-1, req=-1, res=-1): """Creates a burst specification. Works only when netperf is compiled with --enable-intervals. For example, burst(wait=1, rounds=2, repeat=10, req=2000, res=1) will: 1) send 10 back to back 2KB requests and wait to get all 1B reponses. ...
5,307,261
def new_color(wks_id,r,g,b): """ Adds the given color to the end of the color map of the given workstation and returns the integer index of the the new color. index = Ngl.new_color(wks, red, green, blue) wks -- The identifier returned from calling Ngl.open_wks. red, green, blue -- Floating point values between 0....
5,307,262
def pathCorrectCase(path): """ return a normalized file path to the given path. Fixes any potential case errors. """ if os.path.exists(path): return path parts = path.replace("\\", "/").split('/'); if parts[0] == '~': newpath = os.path.expanduser('~') elif part...
5,307,263
def _safe_call(cmd_list): """Makes a subprocess check_call and outputs a clear error message on failure and then exits""" try: subprocess.check_output(cmd_list) return True except subprocess.CalledProcessError as err_thrown: print('Error while calling "%s"', err_thrown.cmd) r...
5,307,264
def extract_pages( dump: Iterable[mwxml.Page], language: str, stats: Mapping, only_last_revision: bool) -> Iterator[Page]: """Extract revisions from a page.""" for mw_page in dump: utils.log("Processing", mw_page.title) # Skip non-articles if mw_page.name...
5,307,265
def assert_array_equal(x: numpy.matrix, y: numpy.matrix, err_msg: Literal["(0, 1)"]): """ usage.scipy: 1 """ ...
5,307,266
def reverse_bits(num): """ reverses the bits representing the number :param num: a number treated as being 32 bits long :return: the reversed number """ result = 0 for i in range(32): result <<= 1 result |= num & 1 num >>= 1 return result
5,307,267
def generate_ODGD_spec_chirped(F1, F2, Fs, lengthOdgd=2048, Nfft=2048, \ Ot=0.5, t0=0.0, \ analysisWindowType='sinebell'): """ generateODGDspecChirped: generates a waveform ODGD and the corresponding spectrum, using as analysis window th...
5,307,268
def batch_norm(inputs, scope=None, is_training=None): """BN for the first input""" assert inputs.get_shape().ndims == 4 with tf.variable_scope(scope): output = tf.layers.batch_normalization(inputs, training=is_training) return output
5,307,269
def prepare_rf_acp( normaliser_model, ntrees, n_folds_acp, random_state=None, smoothing=False ): """ Prepare an acp with a random forest for continuous calibration Parameters ---------- normaliser_model ntrees n_folds_acp random_state smoothing Returns ------- """ ...
5,307,270
def main(input_filename, output_filename): """Creates both the _ebnf_out.py file and the second _out.py file for the given EBNF grammar. """ if not input_filename.endswith('.ebnf'): raise ValueError(input_filename) if not output_filename.endswith('.py'): raise ValueError(output_filename) grako...
5,307,271
def apply_mask(features, mask): """ Parameters ---------- features : torch.tensor mask : torch.tensor """ features[mask] = float('nan')
5,307,272
def calculate_total_profit(df): """ 1. Считает итоговую прибыль :param df: - датафрейм с колонкой '<DEAL_RESULT>' :return: - итог применения стратегии """ return df.dropna()['<PERFORMANCE>'].values[-1]
5,307,273
def memoize(a, b): """ 测试函数缓存 的装饰器 :param a: :param b: :return: """ return json_resp(str(_add(a, b)))
5,307,274
def assert_structure(yaml_loader, path, code_only=True): """Check that a parsed sql file matches the yaml file with the same name.""" lntr = Linter(config=FluffConfig()) p = list(lntr.parse_path(path + '.sql')) parsed = p[0][0] if parsed is None: print(p) raise RuntimeError(p[0][1]) ...
5,307,275
def test_directory_origin_configuration_trim_stack_trace_to_length(sdc_builder, sdc_executor, data_format, log_format, on_parse_error, trim_stack_trace_to_length, shell_executor, ...
5,307,276
def before_emit(message, data, level, **options): """ this method will call `before_emit` method of all registered hooks. :param str message: the log message that must be emitted. :param dict | object data: data that is passed to logging method. :param int level: log level. """ return get_...
5,307,277
def get_ranges(data): """ Returns a generator object that yields lists of consequtive integers from a list of integers. """ for _k, group in groupby(data, lambda t, c=count(): int(t) - next(c)): yield list(group)
5,307,278
def upload(data, filename, key): """ bucket_create :param data: dict :param filename: str :param key: str """ _s3_ = boto3.resource("s3", endpoint_url=data["ep"], aws_access_key_id=data["access_key"], aws_secret_access_...
5,307,279
def find_save_mean_stay_time_table(traj_data_df=None, bin_to_coord_df=None): """Find and save the mean stay time of each bin.""" mean_stay_time_df = traj_data_df.groupby( ["no_bin", "boat_id"])["time_array"].sum().reset_index() mean_stay_time_df.rename({"time_array":"total_stay_time"}, axis=1, inpla...
5,307,280
def getMatrixListFromPoint(point): """ Args: point (MPoint) Returns: list """ return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, point.x, point.y, point.z, 1]
5,307,281
def p_constraintOpt_check(t): """ constraintOpt : constrName R_CHECK S_PARIZQ booleanCheck S_PARDER """ t[0] = [t[2], t[1], t[4]] repGrammar.append(t.slice)
5,307,282
def test(carousels: List[element.Tag], testroot: str): """Test.""" indicators = carousels[0].find_all("div", ["scbs-carousel-indicators"])[0] control_prev = carousels[0].find_all("button", ["scbs-carousel-control-prev"])[0] control_next = carousels[0].find_all("button", ["scbs-carousel-control-next"])[0...
5,307,283
def show_progress(fun, msg, args = (), rate = 0.3): """Displays a spinner while the given function is running.""" q = Queue() def new_fun(q, a): q.put(fun(*a)) t = threading.Thread(target = new_fun, args = (q, args)) t.start() loading = ['|', '/', '-', '\\'] i = 0 while t.isAliv...
5,307,284
def test_warp_reproject_multi_bounds_fail(runner, tmpdir): """Mixing --bounds and --x-dst-bounds fails.""" srcname = 'tests/data/shade.tif' outputname = str(tmpdir.join('test.tif')) out_bounds = [-11850000, 4810000, -11849000, 4812000] result = runner.invoke(warp.warp, [srcname, outputname, ...
5,307,285
def receberInt(msg = '\tDigite um número inteiro: '): """ -> Valida a entrada de um número inteiro pelo teclado*Caso a entrada seja inválida será exigidauma nova entrada. :param msg:mensagem a ser impressa :return:número inteiro recebido """ while True: resp = input(msg).stri...
5,307,286
def convert_using_api(from_currency, to_currency): """ convert from from_currency to to_currency by requesting API """ convert_str = from_currency + '_' + to_currency options = {'compact': 'ultra', 'q': convert_str} api_url = 'https://free.currencyconverterapi.com/api/v5/convert' result = requests.get(api_url, par...
5,307,287
def show_command(args, command): """ :param args: The args variable generated by parse_parameters :param command: The command being run """ if args.show_build_commands: print("$ %s" % " ".join([str(element) for element in command]))
5,307,288
def sha224(msg): """ :return: BitString of the hash """ return hashlib.sha224(msg).digest()
5,307,289
def recipe_transparency(config, recipe_slug, recipe_name, dcm_account, dcm_advertisers): """Reports the percentage of CM impressions that can be attributed to a specific domain or application. Allows diagnostic of which domains and apps are misconfigured by publisher resulting in underreporting. Args...
5,307,290
def test_crypt(secret, hash): """check if :func:`crypt.crypt` supports specific hash :arg secret: password to test :arg hash: known hash of password to use as reference :returns: True or False """ assert secret and hash return safe_crypt(secret, hash) == hash
5,307,291
def config_error(error_message, num_parameters=1): """ # Show the root user the error message for the configuration file. # Show other users a generic message. Exit in either case. :param error_message: :param num_parameters: :return: """ message = "" if is_root: # If 2 para...
5,307,292
def download_data_archive(path: str = None, url: str = 'http://116.203.189.3/data.zip', DOI: str = None, if_exists: str = 'error'): """Download the data archive and extract into the data folder. If the path is None, the default path inside the repo itself is used. Then, you also need to change the datapa...
5,307,293
def get_two_numbers(numbers): """Give a list of items pick 2 random ones, if both are not ints raise a ValueError """ chosen = random.sample(numbers, 2) if not all(type(i) == int for i in chosen): raise ValueError('not all ints')
5,307,294
def plotc(ax,x,y,z,yerr=None,xr=None,yr=None,zr=None,size=5,cmap='rainbow',colorbar=False,xt=None,yt=None,zt=None,label=None,linewidth=0,marker='o',draw=True,orientation='vertical',labelcolor='k',tit=None,nxtick=None,nytick=None,rasterized=None,alpha=None) : """ Plots a scatter plot with point color-coded by z ...
5,307,295
def database_notification(self): """ Create tasks for database notification by team if threshold_database_notification <= 0, the notification is disabled. """ # get all teams and for each one create a new task LOG.info("retrieving all teams and sending database notification") teams = Team.ob...
5,307,296
def test_get_mesh_grid_as_point_cloud_single_pt(): """ Sample a regular grid and return the (x,y) coordinates of the sampled points. """ min_x = -3 # integer, minimum x-coordinate of 2D grid max_x = -3 # integer, maximum x-coordinate of 2D grid min_y = 2 # integer, minimum y-coordinate of...
5,307,297
def get_backend_manager(backend): """Get an instance of the `BackendManager` for the current backend. :param backend: the type of the database backend :return: `BackendManager` """ if backend == BACKEND_DJANGO: from aiida.backends.djsite.manager import DjangoBackendManager return Dj...
5,307,298
def register_extensions(modules): """ Import the modules and register their respective extensions """ if isinstance(modules, str): # Catch supplying just a string arg modules = [modules] for ext in modules: # Get the package prefix and final module name segments = ext.split('.') ...
5,307,299