content
stringlengths
22
815k
id
int64
0
4.91M
def print_version(): """Print version.""" print(get_version_string())
5,323,100
def pandas_pivot(filename): """Used to import a csv file to a pandas data frame, so the data can be pivoted and aggregated by date""" if filename == None: raise FileNotFoundError("File is not found.") else: logging.info("Reading .csv and writing to .xlsx file...") cols_to_use = [...
5,323,101
def add_user_session(username): """Generates a token for a user and adds that token and username to the sesssions.""" token = b64encode(uuid4().bytes).decode() con, cur = create_con() cur.execute('INSERT INTO sessions(username, token) VALUES (?, ?);', (username, token)) con.commit() cur.cl...
5,323,102
def array_input(f): """ decorator to provide the __call__ methods with an array """ @wraps(f) def wrapped(self, t): t = np.atleast_1d(t) r = f(self, t) return r return wrapped
5,323,103
def get_own_ip(): """ returns own ip original from: https://stackoverflow.com/a/25850698/3990615 """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 1)) # connect() for UDP doesn't send packets local_ip_address = s.getsockname()[0] return local_ip_address
5,323,104
def get_sle_after_datetime(self): """get Stock Ledger Entries after a particular datetime, for reposting""" return get_stock_ledger_entries(self.previous_sle or frappe._dict({ "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse")}), ">", "asc", for_update=True, check_s...
5,323,105
def test_default_config_used_when_file_is_invalid_json(config_path): """ When: `init_configuration` called with a path to invalid JSON file Expect: 1. The default config is used. 2. The file is created with the default config. 3. INVALID_CONFIGURATION_FILE Alert is recorded ...
5,323,106
def chaperone(method): """ Wraps all write, read and query methods of the adapters; monitors and handles communication issues :param method: (callable) method to be wrapped :return: (callable) wrapped method """ def wrapped_method(self, *args, validator=None, **kwargs): if not self.co...
5,323,107
def mc_wheeny_purification(p,s): """ The McWheeny Prurification for an idempotent matrix p in a basis with overlaps S """ return (3 * np.dot(np.dot(p, s), p) - np.dot(np.dot(np.dot(np.dot(p, s), p), s), p)) / 2
5,323,108
def shutdown(): """ Shuts down the Pi """ auth = auth_active() if auth["status"] and "username" not in session: flash(auth["msg"], "error") return redirect(url_for("index")) shutdown_pi() return redirect(url_for("index"))
5,323,109
def gzip_decompress(source_file,dest_file = None): """Create unzipped file from existing gzip file (https://docs.python.org/2/library/gzip.html). Note: this does not delete the source file. Args: source_file: source path for the file to unzip dest_file: path to write the unzipped version of...
5,323,110
def _set_up_model_thermo_rxns(base_df: pd.DataFrame, rxns_order: list, rxn_list: list, use_equilibrator:bool, file_bigg_kegg_ids: str = None, pH: float = 7.0, ionic_strength: float = 0.1) \ -> pd.DataFrame: """ Fills in the thermoRxns sheet on the excel GRASP input file. ...
5,323,111
def load_ref_system(): """ Returns cyclopentane as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C -0.8201 -1.0104 -0.1068 C -1.2133 0.4696 0.0650 C 0.0767 1.2934 -0...
5,323,112
def load_audio_channel(delay, attenuation, pytorch=True): """ Return an art LFilter object for a simple delay (multipath) channel If attenuation == 0 or delay == 0, return an identity channel Otherwise, return a channel with length equal to delay + 1 NOTE: lfilter truncates the end of the echo...
5,323,113
def slices(img, shape=[3, 4]): """ create tiled image with multiple slices :param img: :param shape: :return: """ sh = np.asarray(shape) i_max = np.prod(sh) allimg = np.zeros(img.shape[-2:] * sh) for i in range(0, i_max): # i = 0 islice = round((img.shape[0] / fl...
5,323,114
async def test_api_host_info_error(oppio_handler, aioclient_mock): """Test setup with API Open Peer Power info error.""" aioclient_mock.get( "http://127.0.0.1/host/info", json={"result": "error", "message": None} ) with pytest.raises(OppioAPIError): await oppio_handler.get_host_info() ...
5,323,115
def getRawInput(display): """ Wrapper around raw_input; put into separate function so that it can be easily mocked for tests. """ return raw_input(display)
5,323,116
def path_completer(text, state): """ Completer method for system paths. """ return [x if os.path.isfile(x) else (x + os.sep) for x in sorted_glob(text + '*')][state]
5,323,117
def add_variables_summaries(grads_and_vars, step): """Add summaries for variables. Args: grads_and_vars: A list of (gradient, variable) pairs. step: Variable to use for summaries. """ with tf.name_scope('summarize_vars'): for grad, var in grads_and_vars: if grad is not None: if isinst...
5,323,118
def prepare_input_image(img_fpath): """Read and prepare input image as AlexNet input.""" # Read input image as 3-channel 8-bit values pil_img = PIL.Image.open(img_fpath) # Resize to AlexNet input size res_img = pil_img.resize((IMG_SIZE, IMG_SIZE), PIL.Image.LANCZOS) # Convert to NumPy array a...
5,323,119
def sparse_spectral_matrix(c, ell, em, ess=-2): """ Combine functions to create the sparse matrix to be solved. Inputs: c (float): a * omega ell (int): swsh mode number em (int): mode number ess (int) [-2]: spin number Returns: band_matrix (sparse<float>): spars...
5,323,120
def preprocess_text(text, lower=True): """ Prepsocess text. """ text = text.replace("ä", "äe").replace("ö", "oe").replace("ü", "ue").replace("ß", "ss") # Remove punctuations and numbers text = re.sub("[^a-zA-Z]+", " ", text) # Single character removal text = re.sub(r"\b[a-zA-Z]\b", "", text)...
5,323,121
def decode_aes256_base64_auto(data, encryption_key): """Guesses AES cipher (EBC or CBD) from the length of the base64 encoded data.""" assert isinstance(data, bytes) length = len(data) if length == 0: return b'' if data[0] == b'!'[0]: return decode_aes256_cbc_base64(data, encryption...
5,323,122
def get_TS( norm_sh, mass, # Msh, # csh, bsh, vsh, spec_sh_interp, # bsh_range, N_samples, n_nu, nthetas, ext_bool, ext_unc, # N_track_bins, spec_halo_interp, spec_1a, spec_neutrons, spec_nu, indep_index, wimp_masses, Gaussian_likelihoo...
5,323,123
def add_verbosity_action_argument(parser, default=0): """Add a verbosity argument to parser. Parameters ---------- parser : :class:`argparse.ArgumentParser` The parser to which to add a verbosity argument. default : The default level, defaults to 0. Notes ----- The argu...
5,323,124
def rotate(start): """Rotate the orientation clockwise one increment from the starting orientation. Args: start: The starting orientation. Returns: The orientation one increment clockwise from the start. """ orientations = collections.deque([NE, NW, W, SW, SE, E]) if start ...
5,323,125
def test_assign_toangle(): """Assign to Angle3 works""" node = cmdx.createNode("transform") node["Limits"] = cmdx.Angle3() node["Limits"] = (0, 0, 0) node["Limits"] = 0
5,323,126
def make_wcs(shape, galactic=False): """ Create a simple celestial `~astropy.wcs.WCS` object in either the ICRS or Galactic coordinate frame. Parameters ---------- shape : 2-tuple of int The shape of the 2D array to be used with the output `~astropy.wcs.WCS` object. galacti...
5,323,127
def _is_shape(expected_shape, actual_tensor, actual_shape=None): """Returns whether actual_tensor's shape is expected_shape. Note that -1 in `expected_shape` is recognized as unknown dimension. Args: expected_shape: Integer list defining the expected shape, or tensor of same. actual_tensor: Tenso...
5,323,128
def separate_last_day(df_): """ takes a dataset which has the target and features built and separates it into the last day """ # take the last period last_period = df_.iloc[-1] # the last period is now a series, so it's name will be the timestamp training_data = df_.loc[df_.i...
5,323,129
def KDEbounded(x_d,x,bandwidth=np.nan,lowbnd=np.nan,uppbnd=np.nan,kernel = 'gaussian'): """Estimate the probability by Kernel Density Estimation If bandwidth is np.nan, calculate the optimal kernel width, aka bandwidth. Be careful, this can take a while. Mirrors the data at either or both of the edg...
5,323,130
def update(movie_id, **options): """ updates the info of given movie. it returns a value indicating that update is done. :param uuid.UUID movie_id: movie id. :keyword bool content_rate: update content rate. defaults to True if not provided. :keyword bool count...
5,323,131
def validate_sig_integrity(signer_info: cms.SignedData, cert: x509.Certificate, expected_content_type: str, actual_digest: bytes) -> Tuple[bool, bool]: """ Validate the integrity of a signature for a particular signerInfo object ...
5,323,132
def get_c_header_path(*args): """get_c_header_path(char buf) -> ssize_t""" return _idaapi.get_c_header_path(*args)
5,323,133
def str_to_datetime(str_datetime: str) -> datetime.datetime: """ WebAPIがサポートしているISO8601の文字列をdatetime objectに変換します。 datetime objectはawareです。 Args: str_datetime (str): ISO8601の文字列(例: ``2021-04-01T01:23:45.678Z`` ) Returns: datetime object """ # 末尾がZだと、datetime.fromisoformatが利...
5,323,134
def run_regr(sess, analyspar, stimpar, logregpar, quantpar, extrapar, techpar): """ Does runs of a logistic regressions on the specified comparison on a session. Required args: - sess (Session) : Session on which to run logistic regression - analyspar (AnalysPar): named tuple con...
5,323,135
def uncertainty_separation_variance(predicted_distribution, true_labels): """Total, epistemic and aleatoric uncertainty based on a variance measure B = batch size, N = num predictions Note: if a batch with B samples is given, then the output is a tensor with B values The true targets argument is si...
5,323,136
def cubic_spline_breaksToknots(bvec): """ Given breakpoints generated from _cubic_spline_breaks, [x0, x0, x0, x0, x1, x2, ..., xN-2, xf, xf, xf, xf], return the spline knots [x0, x1, ..., xN-1=xf]. This function ``undoes" _cubic_spline_breaks: knot_vec = _cubic_spline_breaks2knots(_cubic_spline_breaks(knot_vec)) ...
5,323,137
def test_append_with_strings(): """Append strings.""" context = Context({ 'arblist': [1, 2], 'append': { 'list': PyString('arblist'), 'addMe': 'three' }}) append.run_step(context) context['append']['addMe'] = 'four' append.run_step(context) ass...
5,323,138
def randtest(): """ organize random test """ for rept in 100, 1000, 10000, 100000, 1000000, 10000000: #~ for rept in 100, 1000, 10000, 100000, 1000000: estim(rept)
5,323,139
def set_seed(seed: int) -> None: """Set seed""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) # type: ignore if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) # type: ignore # Module has no attribute "manual_seed_all" [attr-defined] os.environ["PY...
5,323,140
def as_iso_date(wx_date): """ Convert a QDate object into and iso date string. """ day = wx_date.GetDay() month = wx_date.GetMonth() + 1 # wx peculiarity! year = wx_date.GetYear() return datetime.date(year, month, day).isoformat()
5,323,141
def should_certificate_be_visible( certificates_display_behavior, certificates_show_before_end, has_ended, certificate_available_date, self_paced ): """ Returns whether it is acceptable to show the student a certificate download link for a course, based on provided attributes of the cour...
5,323,142
def svn_repos_invoke_freeze_func(*args): """svn_repos_invoke_freeze_func(svn_repos_freeze_func_t _obj, void * baton, apr_pool_t pool) -> svn_error_t""" return _repos.svn_repos_invoke_freeze_func(*args)
5,323,143
def load_results( files_or_dir: Union[str, list, Path], scoring_key: str = "balanced_accuracy", average_results: bool = True, ) -> pd.DataFrame: """Load prediction results from *results.csv""" # Create Dataframes from Files files_or_dir = _handle_files_or_dir( files_or_dir=files_or_dir, ...
5,323,144
def _tflite_convert_verify_op(tflite_convert_function, *args, **kwargs): """Verifies that the result of the conversion contains Gelu op.""" result = tflite_convert_function(*args, **kwargs) tflite_model_binary = result[0] if not result[0]: tf.compat.v1.logging.error(result[1]) # stderr from running tflite_...
5,323,145
def store_index(config, archiver, index): """ Store an archiver's index record for faster search :param archiver: The name of the archiver type (e.g. 'git') :type archiver: ``str`` :param index: The archiver index record :type index: ``dict`` """ root = pathlib.Path(config.ca...
5,323,146
def tamper_nt_response(data, vars): """The connection is sometimes terminated if NTLM is successful, this prevents that""" print("Tamper with NTLM response") nt_response = vars["nt_response"] fake_response = bytes([(nt_response[0] + 1 ) % 0xFF]) + nt_response[1:] return data.replace(nt_response, fak...
5,323,147
def get_banned_per_category(cat: int, w_id: int) -> bool: """ Determine if a weapon is banned. :param cat: Category of the weapon. :param w_id: Id of the weapon. :return: True if the weapon is banned, False if not. """ d = dict() # Edit this function to change the ruleset: # To ban ...
5,323,148
def pascal_classes(): """Get Pascal VOC classes :return: mapping from class name to an integer """ return { 'aeroplane': 1, 'bicycle' : 2, 'bird' : 3, 'boat' : 4, 'bottle' : 5, 'bus' : 6, 'car' : 7, 'cat' : 8, 'chair' : 9, 'cow' ...
5,323,149
def get_duty_cate_score(chosen_duty_list: list) -> pmag.MagicDict: """ Get duty score of each category. We don't calculate each post score, we think what a man like can be described on category level. Parameters ---------- chosen_duty_list: list Duty list chosen by user, each word w...
5,323,150
def offset(xs: Optional[ColumnSize] = None, sm: Optional[ColumnSize] = None, md: Optional[ColumnSize] = None, lg: Optional[ColumnSize] = None, xl: Optional[ColumnSize] = None) -> Optional[str]: """ Arguments: xs: Offset (in column count) size for extra small s...
5,323,151
def process_runner(job_queue, internal_storage): """ Listens the job_queue and executes the jobs """ while True: event = job_queue.get(block=True) if isinstance(event, ShutdownSentinel): break task, task_id, data = event task.id = task_id task.data = ...
5,323,152
def play_sound(data): """ Parameters ---------- data: dict Returns ------- """ if 'sound_name' in data: clientUtils.sound(data.get('sound_name')) return "" return "Je ne trouve pas le son demandé"
5,323,153
async def async_setup(hass, config): """Start the Fortigate component.""" conf = config[DOMAIN] host = conf[CONF_HOST] user = conf[CONF_USERNAME] api_key = conf[CONF_API_KEY] devices = conf[CONF_DEVICES] is_success = await async_setup_fortigate(hass, config, host, user, api_key, devices) ...
5,323,154
def get_snapshot_usages_project(meta, project_id): """Return the snapshot resource usages of a project""" snapshots_t = Table('snapshots', meta, autoload=True) snapshots_q = select(columns=[snapshots_t.c.id, snapshots_t.c.volume_size, sna...
5,323,155
def compute_patch_embeddings( samples, model, patches_field, embeddings_field=None, force_square=False, alpha=None, handle_missing="skip", batch_size=None, num_workers=None, skip_failures=True, ): """Computes embeddings for the image patches defined by ``patches_field`` o...
5,323,156
def get_exact_file_name(file_name, file_path): """ :param file_name: :param file_path: :return: """ for root, dirs, files in os.walk(file_path): for name in files: logging.debug("Checking {0}".format(name)) if str(name).startswith(file_name): retu...
5,323,157
def getRetRange( rets, naLower, naUpper, naExpected = "False", s_type = "long"): """ @summary Returns the range of possible returns with upper and lower bounds on the portfolio participation @param rets: Expected returns @param naLower: List of lower percentages by stock @param naUpper: List of uppe...
5,323,158
def cos(a): """cosine of a"""
5,323,159
def landing(): """ Landing page - either shows login/sign-up or redirects to dashboard """ if g.uid: return redirect("/dashboard") else: return render_template("landing.html", menu_item="login")
5,323,160
def pi_estimator(iterations: int): """An implementation of the Monte Carlo method used to find pi. 1. Draw a 2x2 square centred at (0,0). 2. Inscribe a circle within the square. 3. For each iteration, place a dot anywhere in the square. 3.1 Record the number of dots within the circle. 4. After a...
5,323,161
def get_projects(filters: Optional[Sequence[pulumi.InputType['GetProjectsFilterArgs']]] = None, sorts: Optional[Sequence[pulumi.InputType['GetProjectsSortArgs']]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetProjectsResult: """ Retrieve information about ...
5,323,162
def get_market_impact( portfolio_name, start_date, end_date, denominator="reference_equity", model_id=DEFAULT_MODEL_ID, ): """Get market impact for each daily change of a portfolio in terms of dollars and percent of a denominator, either reference_equity or gmv. Note that this ignores change...
5,323,163
def importH5(name, df): """ """ f = h5py.File(name,'r') data = f.get(df) data = np.array(data) oldShape = data.shape data = np.swapaxes(data, 1, 2) print 'convert shape %s to %s' % (oldShape, data.shape) return data
5,323,164
def svc_longi_u_polar(vr,vpsi,vz,gamma_l=-1,R=1,m=0,ntheta=180,polar_out=False): """ Raw function, not intended to be exported. Induced velocity from a skewed semi infinite cylinder of longitudinal vorticity. Takes polar coordinates as inputs, returns velocity either in Cartesian (default) or polar. Th...
5,323,165
def main(): """ Parse Lighthouse JSON for failing elements and capture images of those elements """ args = get_args() input_file = args.input_file assets_dir = args.assets_dir output_dir = os.path.dirname(args.input_file) sleep = args.sleep initialize_logger('capture', output_dir) loggin...
5,323,166
def _unremediate_email_o365_EWS(emails): """Remediates the given emails specified by a list of tuples of (message-id, recipient email address).""" assert emails assert all([len(e) == 2 for e in emails]) result = [] # tuple(message_id, recipient, result_code, result_text) # get the hostname and...
5,323,167
def compute_feedback_score(user_search, result): """ Compute the feedback score Input: user_search: keyword entered by the user result: proposed result to the user Output: Feedback score, default value to 0.4 if no feedbacks available """ # This old version take into account when ...
5,323,168
def filenames_per_batch (gen): """ arg = name of the data generator (datagen.flow_from_dataframe) """ img_paths_per_batch=[] batches_per_epoch = gen.samples // gen.batch_size + (gen.samples % gen.batch_size > 0) for i in range(batches_per_epoch): batch = next(gen) current_inde...
5,323,169
def coarsemask_head_generator(params): """Generator function for ShapeMask coarse mask head architecture.""" head_params = params.shapemask_head return heads.ShapemaskCoarsemaskHead( head_params.num_classes, head_params.num_downsample_channels, head_params.mask_crop_size, head_params.use_c...
5,323,170
def ethtype_to_int_priv_pubv(priv, pubv): """ 将 priv 和 pubv 转换为 weidentity 支持的格式(十进制) :param priv: type: bytes :param pubv: type: hex :return: priv int, pubv int """ private_key = int.from_bytes(priv, byteorder='big', signed=False) public_key = eval(pubv) return {"priv": str(private...
5,323,171
def printlet(flatten=False, **kwargs): """ Print chunks of data from a chain :param flatten: whether to flatten data chunks :param kwargs: keyword arguments as for :py:func:`print` If ``flatten`` is :py:const:`True`, every chunk received is unpacked. This is useful when passing around connecte...
5,323,172
def test_parametrize_fail_second_call_with_uut(uut, params, executed_tests): """ test parametrize with uut fail on second call """ executed_tests.append(0) assert executed_tests.count(0) == 1
5,323,173
def build_arg_parse() -> argparse.ArgumentParser: """Builds the arguments parser.""" parser = argparse.ArgumentParser( description="This script updates the python extension micro version based on the release or pre-release channel." ) parser.add_argument( "--release", action="sto...
5,323,174
def solver(I, a, L, Nx, F, T, theta=0.5, u_L=0, u_R=0, user_action=None): """ Solve the diffusion equation u_t = a*u_xx on (0,L) with boundary conditions u(0,t) = u_L and u(L,t) = u_R, for t in (0,T]. Initial condition: u(x,0) = I(x). Method: (implicit) theta-rule in time. Nx is the...
5,323,175
def create_clean_df_from_cloud_json(js): """ Given a json downloaded on the cloud from get_datasource_data or get_location_data, returns a corrected df""" df = json_to_df(js) df_data = set_timestamp_df_index(df) for col in df_data.columns: if col[:6] == 'values': df_data[col] = __pd....
5,323,176
def run(ctx): """ Continuously run the bot """ bot = BotInfrastructure(ctx.config) bot.run()
5,323,177
def print_options(): """Prints all the usage options""" print( """Options:\n -v: verbosity indicator. "full" or "minimal"\n -d: maximum recursion depth for traversing the directory.\n -tok: Output tokens\n -tree: Output xml tree\n -novm: Do not output vm code\n ...
5,323,178
def tfidf_corpus(docs=CORPUS): """ Count the words in a corpus and return a TfidfVectorizer() as well as all the TFIDF vecgtors for the corpus Args: docs (iterable of strs): a sequence of documents (strings) Returns: (TfidfVectorizer, tfidf_vectors) """ vectorizer = TfidfVectorizer() ...
5,323,179
def svn_utf_cstring_from_utf8_string(*args): """svn_utf_cstring_from_utf8_string(svn_string_t const * src, apr_pool_t pool) -> svn_error_t""" return _core.svn_utf_cstring_from_utf8_string(*args)
5,323,180
def squint(t, r, orbit, attitude, side, angle=0.0, dem=None, **kw): """Find squint angle given imaging time and range to target. """ assert orbit.reference_epoch == attitude.reference_epoch p, v = orbit.interpolate(t) R = attitude.interpolate(t).to_rotation_matrix() axis = R[:,1] # In NISAR ...
5,323,181
def get_cmfgenNoRot_atmosphere(metallicity=0, temperature=30000, gravity=4.14): """ metallicity = [M/H] (def = 0) temperature = Kelvin (def = 30000) gravity = log gravity (def = 4.14) """ sp = pysynphot.Icat('cmfgenF15_noRot', temperature, metallicity, gravity) # Do some error checking ...
5,323,182
def _SanitizeDoc(doc, leader): """Cleanup the doc string in several ways: * Convert None to empty string * Replace new line chars with doxygen comments * Strip leading white space per line """ if doc is None: return '' return leader.join([line.lstrip() for line in doc.spli...
5,323,183
def load_file(file_path: str): """Loads a file using a serializer which guesses based on the file extension""" if file_path.lower().endswith('.json'): with open(file_path) as input_file: return json.load(input_file) elif file_path.lower().endswith('.yaml') or file_path.lower().endswith('...
5,323,184
def _init(args, workflows_dir, config_path): """ Initialise a config.yaml and samples.tsv from the relevant workflow. """ for file in ["samples.tsv", "config.yaml"]: src = os.path.join(workflows_dir, args.workflow.replace("-", "_"), file) dest = os.path.join(os.path.dirname(config_path),...
5,323,185
def list_assets(event, context): """ Get a list of assets of the given type. Query string parameters ----------------------- asset_type (required): The type of asset to get. Allowed values are found in the ``asset_map`` dict. """ query_params = event.get('queryStringParamete...
5,323,186
def pop_execute_query_kwargs(keyword_arguments): """ pop the optional execute query arguments from arbitrary kwargs; return non-None query kwargs in a dict """ query_kwargs = {} for key in ('transaction', 'isolate', 'pool'): val = keyword_arguments.pop(key, None) if val is not No...
5,323,187
def chunks(l, n): """ Divides L into N many chunks, each containing approximately the same number of elements Refrence: http://stackoverflow.com/a/9873935 >>> [len(x) for x in chunks(range(45), 13)] [4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 3] >>> [len(x) for x in chunks(range(253), 13)] [20, 19,...
5,323,188
def decompress(target_file): """This is the decompression section""" # extract binary string from a file start_decompress = float(time.process_time()) # start measure time in this line to check processing time binary_file_name = target_file filename = target_file with open(binary_file...
5,323,189
def resize(img, new_shape, interpolation=1): """ img: [H, W, D, C] or [H, W, D] new_shape: [H, W, D] """ type = 1 if type == 0: new_img = skt.resize(img, new_shape, order=interpolation, mode='constant', cval=0, clip=True, anti_aliasing=False) else: shp = tuple(np.array(new_s...
5,323,190
def get_oneview_client(session_id=None, is_service_root=False): """Establishes a OneView connection to be used in the module Establishes a OV connection if one does not exists. If one exists, do a single OV access to check if its sill valid. If not tries to establish a new connection. ...
5,323,191
def test_delete_document_returns_response(): """Test if the API responds. When we try to create a content library document. """ assert _heartbeat(client.delete_document(fixtures['document']))
5,323,192
def test_multi_file_ignore_name(hera_uvh5_split, future_shapes): """ Verify that if phased two objects to the same position with different names, we can successfully use the "ignore_name" switch in the add operation to allow the two objects to be combined. """ uv1, uv2, uvfull = hera_uvh5_split ...
5,323,193
def SegmentByPeaks(data, peaks, weights=None): """Average the values of the probes within each segment. Parameters ---------- data : array the probe array values peaks : array Positions of copy number breakpoints in the original array Source: SegmentByPeaks.R """ segs =...
5,323,194
def get_cnt_sw(g_sc, g_sa, g_wn, g_wc, g_wo, g_wvi, pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi, mode): """ usalbe only when g_wc was used to find pr_wv """ cnt_sc = get_cnt_sc(g_sc, pr_sc) cnt_sa = get_cnt_sa(g_sa, pr_sa) cnt_wn = get_cnt_wn(g_wn, pr_wn) cnt_wc = get_cnt_wc(g_wc, pr_wc) cnt_w...
5,323,195
def _get_memcache_client(): """Return memcache client if it's enabled, otherwise return None""" if not cache_utils.has_memcache(): return None return cache_utils.get_cache_manager().cache_object.memcache_client
5,323,196
def get_long_description(readme_file='README.md'): """Returns the long description of the package. @return str -- Long description """ return "".join(open(readme_file, 'r').readlines()[2:])
5,323,197
def extract_dem( bounds, out_raster="dem.tif" ): """Get 25m DEM for area of interest from BC WCS, write to GeoTIFF """ bbox = ",".join([str(b) for b in bounds]) # build request payload = { "service": "WCS", "version": "1.0.0", "request": "GetCoverage", "covera...
5,323,198
def G1DListGetEdgesComposite(mom, dad): """ Get the edges and the merge between the edges of two G1DList individuals :param mom: the mom G1DList individual :param dad: the dad G1DList individual :rtype: a tuple (mom edges, dad edges, merge) """ mom_edges = G1DListGetEdges(mom) dad_edges = G1DListG...
5,323,199