content
stringlengths
22
815k
id
int64
0
4.91M
def login(): """Login user""" # Instantiate login form form = LoginForm() username = form.username.data if form.validate_on_submit(): # Query database for username and validate form submission user = User.query.filter_by(username=username).first() # if user exists i...
41,200
def serialize(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime.datetime): serial = obj.isoformat(sep='T') return serial if isinstance(obj, uuid.UUID): serial = str(obj) return serial try: return obj.__dict...
41,201
def test_randimoize_corrmat_tails(): """Test that the tail argument works.""" a = rs.randn(30) b = a + rs.rand(30) * 8 c = rs.randn(30) d = [a, b, c] p_mat_b = algo.randomize_corrmat(d, "both", False, random_seed=0) p_mat_u = algo.randomize_corrmat(d, "upper", False, random_seed=0) p_ma...
41,202
def clean_names_AZ(col): """ Removes any non-alpha characters (excluding spaces) from a string. Replaces these characters with an empty space. Trims outer whitespace. Example -------- >>> Input: "JOHN SMITH 2000" >>> Output: "JOHN SMITH" """ return trim(regexp_replace(col, "[^A-Z ]+...
41,203
def check_continent_node_membership(continents, continent_node_id): """The function checks that a node continent is bound to the corresponding relation through 'label' membership. """ assert continent_node_id[0] == 'n', ("A node expected in " "check_continent...
41,204
def remove_punctuation(input_string): """ remove the punctuation of input Parameters ---------- input_string : string Returns ------- output_string : string string without punctuation ###from assignment encoder """ out_string= '' ...
41,205
def field_value_between(value: Any = None, field: str = None, lower: float = None, upper: float = None) -> bool: """ Validate value at the given field to be between the lower/upper boundaries. """ if not value: return False if not isinstance(value, list): val...
41,206
def test_cert_about_to_expire(): """Tests if a certificate about to expires is detected""" cert = _generate_certificate(-10800, 432000) not_after_str, _ = bigacme.cert._get_cert_dates(cert) assert bigacme.cert._check_if_cert_about_to_expire(not_after_str, 14)
41,207
def j2_to_json(path_in, path_out, **kwargs): """Render a yaml.j2 chart to JSON. Args: path_in: the j2 template path path_out: the JSON path to write to kwargs: data to pass to the j2 template Returns: the file path and JSON string """ return pipe( render_yaml(path_i...
41,208
def user_logged_out(connection,user): """ update login status to false when user has logged out :param connection: :param user: :return: """ with connection: return connection.execute(UPDATE_USER_LOGIN_STATUS_TO_FALSE,(user,))
41,209
def findGrayscaleTilesInImage(img): """ Find chessboard and convert into input tiles for CNN """ if img is None: return None, None # Convert to grayscale numpy array img_arr = np.asarray(img.convert("L"), dtype=np.float32) # Use computer vision to find orthorectified chessboard corners in image cor...
41,210
def un_zip(file_name): """unzip zip file""" zip_file = zipfile.ZipFile(file_name) if os.path.isdir(file_name + "_files"): pass else: os.mkdir(file_name + "_files") for names in zip_file.namelist(): zip_file.extract(names,file_name + "_files/") zip_file.close()
41,211
def run(df, docs, columns): """ converts each column to type int :param df: :param columns: :return: """ for doc in docs: doc.start("t07 - Change type of {} to int".format(str(columns).replace("'", "")), df) for column in columns: df[column] = df[column].astype(int) ...
41,212
def _check_response_structure( response_bytes, status_code, expected_success, expected_code ): """ Check if response structure is correct like below. success response expect: { 'success': True, 'data' : data } error response expect: { 'success': False, '...
41,213
def get_articles(): """ Retreives the articles list (via an API request) """ endpoint = "%s%s" % ( settings.API_BASE_URL, reverse("api:articles-list") ) headers = DEFAULT_REQUESTS_HEADERS r = requests.get( endpoint, headers=DEFAULT_REQUESTS_HEADERS ...
41,214
def fmin_ncg(f, x0, fprime, fhess_p=None, fhess=None, args=(), avextol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0, callback=None, preconditioner = None): """ Unconstrained minimization of a function using the Newton-CG method. Parameters ---------- ...
41,215
def add_missing_flow_by_fields(flowby_partial_df, flowbyfields): """ Add in missing fields to have a complete and ordered :param flowby_partial_df: Either flowbyactivity or flowbysector df :param flowbyfields: Either flow_by_activity_fields, flow_by_sector_fields, or flow_by_sector_collapsed_fields ...
41,216
def main(): """Usage: lilac serve [<port>] [--watch] lilac (deploy|build|clean) lilac (start|stop|status|restart) lilac [-h|-v] Options: -h --help show this help message -v --version show version --watch watch source files for changes <port> which port for server to use(default: 8...
41,217
def calcular_diferencia_dias(fin_dia): """ Obtiene la diferencia de dias entre una fecha y hoy """ hoy = datetime.now() end = datetime.strptime(str(fin_dia), '%Y-%m-%d') return abs(end - hoy).days
41,218
def test_issue51_strict(): """Check that setting strict=False prevents a ParserError""" with warnings.catch_warnings(record=True) as w: report = Metar.Metar(sta_time + "90010KT", strict=False) assert len(w) == 1 assert report.wind_speed is None
41,219
def matrix_base_mpl(matrix, positions, substitutions, conservation=None, secondary_structure=None, wildtype_sequence=None, min_value=None, max_value=None, ax=None, colormap=plt.cm.RdBu_r, colormap_conservation=plt.cm.Oranges, na_color="#bbb...
41,220
def gaussian_laplace(input, sigma, output=None, mode="reflect", cval=0.0, **kwargs): """Multi-dimensional Laplace filter using Gaussian second derivatives. Args: input (cupy.ndarray): The input array. sigma (scalar or sequence of scalar): Standard deviations for each axis ...
41,221
def confrontTheMan(): """confronting the man when he comes out to fix the generator""" tempEnd()
41,222
def get_commits_after_forkpoint(main_dir, base_sha, head_sha, repo_name, log, secure_repo_name): """List commit hashes between base_sha and head_sha :param main_dir: model directory :param base_sha: base SHA i.e. point of the history when the branch started diverging from the main branch. :para...
41,223
def perimeter_mask(image, corner_fraction=0.035): """ Create boolean mask for image with a perimeter marked as True. The perimeter is the same width as the corners created by corner_mask. Args: image : the image to work with corner_fraction: determines the width of the perimeter Re...
41,224
def test_16vcpu_ht_enabled(test_microvm_with_ssh, network_config): """Check the CPUID for a microvm with the specified config.""" test_microvm_with_ssh.spawn() test_microvm_with_ssh.basic_config(vcpu_count=16, ht_enabled=True) _tap, _, _ = test_microvm_with_ssh.ssh_network_config(network_config, '1') ...
41,225
def write_image_annotation_pairs_to_tfrecord(filename_pairs, tfrecords_filename): """Writes given image/annotation pairs to the tfrecords file. The function reads each image/annotation pair given filenames of image and respective annotation and writes it to the tfrecord file. Parameters --------...
41,226
def vgg13_bn(**kwargs): """VGG 13-layer model (configuration "B") with batch normalization""" model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs) return model
41,227
def convert_version_to_tuple(version: str) -> VersionTuple: """ Convert version info from string representation to tuple representation. The tuple representation is convenient for direct comparison. """ m = regex.fullmatch(r"(?P<major>\d+)\.(?P<minor>\d+)", version) if not m: raise Val...
41,228
def SU3GradientTF( f: Callable[[Tensor], Tensor], x: Tensor, ) -> tuple[Tensor, Tensor]: """Compute gradient using TensorFlow GradientTape. y = f(x) must be a real scalar value. Returns: - (f(x), D), where D = T^a D^a = T^a ∂_a f(x) NOTE: Use real vector derivatives, e.g. ...
41,229
def create_app(config): """Flask application factory. Returns: Flask Application with BrazilDataCubeDB extension prepared. """ app = Flask(__name__) BrazilDataCubeDB(app) return app
41,230
def genpass_comprehension(length=8, chars=string.letters+string.digits): """Generate password using a list comprehension. """ # Can be rewritten as a list comprehension. return ''.join([choice(chars) for i in range(length)])
41,231
def typed(*types): """Type annotation. The final type is the output type. """ if len(types) < 1: raise SyntaxError('Too few arguments: typed{}'.format(types)) if len(types) > 3: raise NotImplementedError('Too many arguments: typed{}'.format(types)) result_type = types[-1] a...
41,232
def simulate_input_thread(fd, macro_file): """Reads the macro file line by line and sends input to the main event loop through a pipe (fd) Parameters: fd:file descriptor The pipe to the main loop macro_file:String Path to macro file """ with open(macro_file) as file: while True: ...
41,233
def insert_linebreaks( input_fragments: StyleAndTextTuples, max_line_width: int, truncate_long_lines: bool = True) -> Tuple[StyleAndTextTuples, int]: """Add line breaks at max_line_width if truncate_long_lines is True. Returns input_fragments with each character as it's own formatted te...
41,234
def score_reactant_combination(candidate_combination, scoring_fcn): """ Generates a score for a combination of reactant candidates according to the criteria. """ # Extract only the reactant candidate compound ID's. reactant_ids = [combo[0] for combo in candidate_combination] # Score the reactant candi...
41,235
def main(argv=None): """Provide the main entry point.""" help_builder.init("charmcraft", GENERAL_SUMMARY, COMMAND_GROUPS) emit.init(EmitterMode.NORMAL, "charmcraft", f"Starting charmcraft version {__version__}") if argv is None: argv = sys.argv extra_global_options = [ GlobalArgume...
41,236
def xmind_testsuite_to_json_file(xmind_file): """Convert XMind file to a testsuite json file""" xmind_file = get_absolute_path(xmind_file) logging.info('Start converting XMind file(%s) to testsuites json file...', xmind_file) testsuites = get_xmind_testsuite_list(xmind_file) testsuite_json_file = xm...
41,237
def get_named_entities(df): """ Count the named entities that are neither A nor B. Hopefully this correlates with class "Neither". :param df: competition data with one extra field spacy_nlp_doc: precomputed nlp(text) :return: """ named_df = pd.DataFrame(0, index=df.index, columns=["named_e...
41,238
def normalize(vectors): """ Normalize a set of vectors. The length of the returned vectors will be unity. Parameters ---------- vectors : np.ndarray Set of vectors of any length, except zero. """ if len(vectors.shape) == 1: return vectors / np.linalg.norm(vectors) ...
41,239
def get_all_requests(current_user): """Gets all requests""" all_requests = [] for request in request_model.requests.values(): all_requests.append(request) return jsonify(all_requests)
41,240
def plot(input_filename, output_filename, size=(3.45,2.0)): """Plots the a spectrogram to an output file """ s = spectrogram.Spectrogram().load(input_filename) d = s.data d = d/numpy.max(d) d = 1 - d min_freq = s.metadata.min_freq max_freq = s.metadata.max_freq min_time = s.metadat...
41,241
def RunManifestExe(target, source, env): """Calls RunManifest for updating an executable (resource_num=1).""" return RunManifest(target, source, env, resource_num=1)
41,242
def dist_reduce_tensor(tensor, dst=0): """Reduce to specific rank""" world_size = get_world_size() if world_size < 2: return tensor with torch.no_grad(): dist.reduce(tensor, dst=dst) if get_rank() == dst: tensor.div_(world_size) return tensor
41,243
def upload_blob(bucket_name, source_file_name, destination_blob_name): """Uploads a file to the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_file(source_file_name) print('File {} uploaded ...
41,244
def get_lines(matrix, loc): """Returns lines that pass though `loc`. Matrix can be indices. Args: matrix: a N by N matrix representing the board loc: a tuple of loc coordinates Returns: Numerical values on the horizontal, vertical, and diagonal lines that pass through loc. ...
41,245
def process_citations_in_paragraph(para_el: BeautifulSoup, sp: BeautifulSoup, bibs: Dict, bracket: bool) -> Dict: """ Process all citations in paragraph and generate a dict for surface forms :param para_el: :param sp: :param bibs: :param bracket: :return: """ # CHECK if range between...
41,246
def duration(start_time, end_time=None): """Get a timedelta between end_time and start_time, where end_time defaults to now(). WARNING: mixing tz-aware and naive datetimes in start_time and end_time will cause an error. """ if not start_time: return None last_time = end_time if end_...
41,247
def log10(x): # real signature unknown; restored from __doc__ """ log10(x) Return the base 10 logarithm of x. """ pass
41,248
def get_commands(cfg, clargs, *, what, **kwargs): """ Delegates the creation of commands lists to appropriate functions based on `what` parameter. Parameters ---------- cfg: dict Configuration dictionary. clargs: Namespace Command line arguments. cmds: iter(tuple(str)) what: str...
41,249
def heappush(heap, item): """ >>> heappush([4, 4, 8, 9, 4, 12, 9, 11, 13], 7) [4, 4, 8, 9, 4, 12, 9, 11, 13, 7] >>> heappush([4, 4, 8, 9, 4, 12, 9, 11, 13, 7], 10) [4, 4, 8, 9, 4, 12, 9, 11, 13, 7, 10] >>> heappush([4, 4, 8, 9, 4, 12, 9, 11, 13, 7, 10], 5) [4, 4, 5, 9, 4, 8, 9, 11, 13, 7, ...
41,250
def dx(scalar_field): """ Computes first derivative of a 1D scalar field :param scalar_field: :return: """ first_derivative = np.zeros((scalar_field.size - 1)) for i_scalar in range(scalar_field.size - 1): i_next_scalar = i_scalar + 1 first_derivative[i_scalar] = scalar_fiel...
41,251
async def new_player(ctx, token, nickname, rank, bio): """ Insert new player in the db """ query = f'INSERT INTO player VALUES (null, "{ctx.author.id}","{ctx.author}","{token}","{nickname}","{rank}","{bio}");' commit_query(query)
41,252
def makeParser(): """ Make a command-line argument parser. @return: An C{argparse.ArgumentParser} instance. """ parser = argparse.ArgumentParser( description=('Print a JSON object containing reference to read ' 'distances extracted from a SAM file.')) parser.add_ar...
41,253
def post_test(caplog, output_dir): """Post-test management""" # Write log file log_filename = f"{output_dir}/test.log" with open(log_filename, "w", encoding="utf-8") as log_file: log_file.write(caplog.text) caplog.clear()
41,254
def get_genetic_profiles(study_id, profile_filter=None): """Return all the genetic profiles (data sets) for a given study. Genetic profiles are different types of data for a given study. For instance the study 'cellline_ccle_broad' has profiles such as 'cellline_ccle_broad_mutations' for mutations, 'ce...
41,255
def cipher(sentence, n_rotate): """ Cipher string with Caesar algorithm ( Anything else than letters stays the same. ) :param sentence: String containing sentence/sentences/word/words. :param n_rotate: number to translate letters :return: string with ciphered words """ upper = [char f...
41,256
def _assert_in_fc( r: RestClient, uuids: Union[str, List[str]], all_keys: bool = False ) -> StrDict: """Also return data.""" if isinstance(uuids, str): uuids = [uuids] if all_keys: data = r.request_seq('GET', '/api/files', {'all-keys': True}) else: data = r.request_seq('GET'...
41,257
def power_law(uref, h, href, shear): """ Extrapolate wind speed (or other) according to power law. NOTE: see https://en.wikipedia.org/wiki/Wind_profile_power_law :param uref: wind speed at reference height (same units as extrapolated wind speed, u) :param h: height of extrapolated wind speed (...
41,258
def get_defaults(): """ Returns default frequencies to project intensities onto as well as default paths for locations of the pure and mixture spectroscopic data. Returns ------- frequency_range: numpy.ndarray Frequencies over which to project the intensities. pure_data_pat...
41,259
def binary_weight_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, wb_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True):...
41,260
def load_multiple(*args, _all=False): """Create `commands` object for a set of repositories Parameters ------------ args : int comma-separated string values Yields --------- A list of commands objects. One for each of the entered string """ if _all: NAME_SHELF = sh...
41,261
def dataset2Xy(dataset): """Convert a dataset (pd.DataFrame) to X, y and output_dim where X is the features, y is the labels (one-hot vectors), and output_dim is the number of labels overall. Args: dataset: A pandas dataframe that is composed of features columns...
41,262
def sysexit(func: Callable) -> Callable: """ use the function return value as the system exit code """ @wraps(func) def wrapper(*args, **kwargs): sys.exit(func(*args, **kwargs)) return wrapper
41,263
def curved_arc_illustration(ax, lensModel, kwargs_lens): """ :param ax: matplotlib axis instance :param lensModel: LensModel() instance :param kwargs_lens: list of lens model keyword arguments (only those of CURVED_ARC considered :return: """ # loop through lens models # check whether ...
41,264
def pairwise_list(a_list): """ list转换为成对list "s -> (s0,s1), (s1,s2), (s2, s3), ..." :param a_list: list :return: 成对list """ if len(a_list) % 2 != 0: raise Exception("pairwise_list error!") r_list = [] for i in range(0, len(a_list) - 1, 2): r_list.append([a_list[i], a...
41,265
def BaseWaveguideOFF(args,state,options)->GeomGroup: """ Offset the waveguide (jumps left or right of waveguide) Parameters ---------- args : list 1 argument: offset (in um), positive means on left of waveguide direction. state : dict Current state. options : dict Th...
41,266
def set_network_model(network, mod_dim1, mod_dim2, device): """ manage (segnet, unet, other network) """ if network == "segnet": model = MyNet(inp_dim=3, mod_dim1=mod_dim1, mod_dim2=mod_dim2).to(device) else: print("Undefined network:" + network) sys.exit() return model
41,267
def read_csv_profiles(file): """Read csv file and parse dates.""" return pd.read_csv(file, parse_dates=["valid"], index_col="valid")
41,268
def uCSIsMathematicalAlphanumericSymbols(code): """Check whether the character is part of MathematicalAlphanumericSymbols UCS Block """ ret = libxml2mod.xmlUCSIsMathematicalAlphanumericSymbols(code) return ret
41,269
def configBoat(self): """Set important information about the boat.""" pass
41,270
def test_repository_iterate_commits_with_revision(git_repository): """Test iterating commits in a repository with revision.""" commits = list(git_repository.iterate_commits(revision="HEAD~")) assert 7 == len(commits) assert "9c4c6804e2f9d834f125dc253026c71c1d26adf6" == commits[0].hexsha # One before l...
41,271
def builtin_localtime(t): """ Convert an epoch time to a [yr mon day hr min sec wd yd dst] list structure in the local timezone, or vice-versa. """ if isinstance(t, BReal): tv = [BInt(xv) for xv in time.localtime(t.value)] return BList(tv) elif isinstance(t, BList): tvv = [x.value for x in t.value] return...
41,272
def avg_gate_infidelity(A, B, mxBasis): """ Returns the average gate infidelity between A and B, where B is the "target" operation.""" return _tools.average_gate_infidelity(A, B, mxBasis)
41,273
def html_to_plain_text(html_str): """ Takes an HTML string and returns text with HTML tags removed and line breaks replaced with spaces. Shamelessly copied from open-discussions. Args: html_str (str): A string containing HTML tags Returns: str: Plain text """ soup = Beautifu...
41,274
def read_hotfilm_from_lvm(filename, dt=1e-3): """Reads 2-channel hotfilm data from a Labview text file.""" times = [] ch1 = [] ch2 = [] data = [line.rstrip() for line in open(filename).readlines()] line = data[0].split(',')[1:] t = [int(float(n)) for n in line[:5]] seconds = float(line[5...
41,275
def upload_user_app_stats(start_date=None, end_date=None): """ Uploads the catalog app records into the MySQL back end. Uses the other functions """ if start_date is not None or end_date is not None: if start_date is not None and end_date is not None: app_usage_list = get_user_...
41,276
def save_to_db( timed_values: Union[BeliefsDataFrame, List[Union[Power, Price, Weather]]], forecasting_jobs: List[Job] = [], save_changed_beliefs_only: bool = True, ) -> ResponseTuple: """Put the timed values into the database and enqueue forecasting jobs. Data can only be replaced on servers in pl...
41,277
def backup_timestamp(vin): """ Copy timestamp.der to backup_timestamp.der Example: >>> import demo.demo_director as dd >>> dd.clean_slate() >>> dd.backup_timestamp('111') """ timestamp_filename = 'timestamp.' + tuf.conf.METADATA_FORMAT timestamp_path = os.path.join(demo.DIRECTOR_REPO_DIR, vin, 'meta...
41,278
def quick(info): """Quick data process without configfile"""
41,279
def GetCategoryWrapper(func_name): """Return a C preprocessor token to test in order to wrap code. This handles extensions. Example: GetTestWrapper("glActiveTextureARB") = "CR_multitexture" Example: GetTestWrapper("glBegin") = "" """ cat = Category(func_name) if (cat == "1.0" or cat == "1.1" or cat == "1.2" ...
41,280
def get_capability_text(src_capability: SourceCapability) -> str: """ Returns markdown format cell text for a capability, hyperlinked to capability feature page if known """ capability_docs_mapping: Dict[SourceCapability, str] = { SourceCapability.DELETION_DETECTION: "../../../../metadata-ingest...
41,281
def camel_case_split(identifier): """CamelCase split""" matches = re.finditer( ".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", identifier) return [m.group(0) for m in matches]
41,282
def init_formation_goal_msg(): """Create formation goal msg Swarm goal is represented by a green sphere and arrow. Returns: [type]: [description] """ msg = Marker() msg.header.frame_id = "world" msg.header.stamp = rospy.Time() msg.ns = "swarm" msg.id = 2 msg.type = 2 ...
41,283
def cli(aws_profile_name): """ Removes AWS profile from your ~/.aws/credentials """ common = Common() remove = Remove() users_home = common.get_users_home() all_profiles = common.get_all_profiles(users_home) if not aws_profile_name: aws_profile_name = remove.choose_profile_to_remove(all...
41,284
def lcd_draw_polygon(vertices): """ .. [en] lcd_draw_polygon(vertices) Draw a polygon with specified vertices. :param 2D array vertices: [[x,y]] coordinates of the vertices. .. [/en] .. [sk] lcd_draw_polygon(vrcholy) Vykreslí polygón podľa zadaných vrcholov. :param 2D array ...
41,285
def get_cli_args(): """ gets command line arguments """ parser = argparse.ArgumentParser( description='Tool to increase YouTube views', add_help=False, ) # main arguments main = parser.add_argument_group( 'Main Arguments', ) main.add_argument( '--visits', ...
41,286
def mouse_crop_NW(event): """ Left-Upper corner """ x_preview = event.x y_preview = event.y xy_max = common.mouse_crop_calculation(file_in_width.get(), file_in_width.get(), int(co_preview_selector_orig.get())) wi...
41,287
async def remove(message: discord.Message, trigger: str): """ Remove a command. """ assert trigger in lambdas.data, "Command `{}` does not exist.".format(trigger) # The command specified exists and we remove it del lambdas.data[trigger] lambdas.save() await client.say(message, "Command `{}` rem...
41,288
def allow_pay_as_you_go(**kwargs): """Allow Pay As You Go Set pay as you go account settings to ``allow=True`` Reference: https://iexcloud.io/docs/api/#pay-as-you-go Data Weighting: ``Free`` .. warning:: This endpoint is only available using IEX Cloud. See :ref:`Migrating` for m...
41,289
def _process_user_data_for_order(checkout: Checkout): """Fetch, process and return shipping data from checkout.""" shipping_address = checkout.shipping_address if checkout.user: store_user_address(checkout.user, shipping_address, AddressType.SHIPPING) if ( shipping_address ...
41,290
def test_train(): """Check that the hyperparameters and likelihood are updated when the train method is called.""" sgp = get_updated_sgp() hyps_init = tuple(sgp.hyps) sgp.train() hyps_post = tuple(sgp.hyps) assert hyps_init != hyps_post assert sgp.likelihood != 0.0
41,291
def catastrophic_energy(rpb,rho,Vi): """ Return the catastrofic energy in c.g.s. Based in Stewart and Leinhardt(2009) rpb: parental radius in km rho: mean density of the system in cgs Vi: impact velocity in km/s """ # qs, qg, fi, mi: constants of material if rho < 4.0: qs, q...
41,292
def delete( id: int = typer.Option(...) ): """ Delete a link with the given ID """ api = Links(base_url=shared_ctx['api_url'], api_token=shared_ctx['api_token']) with console.status("[bold green]Deleting link..."): api.delete(id) print("[bold green]Link deleted successfully[/bold gre...
41,293
def edl_update_from_external_file_command(): """ Updates internal list data with external file contents """ file_path = demisto.args().get('file_path') if DOCUMENT_ROOT: file_path = os.path.join(DOCUMENT_ROOT, file_path) list_name = demisto.args().get('list_name') type_ = demisto.arg...
41,294
def hide_toolbar(notebook): """ Finds the display toolbar tag and hides it """ if 'celltoolbar' in notebook['metadata']: del(notebook['metadata']['celltoolbar']) return notebook
41,295
def patch_cdsapi(): """Monkey patch the cdsapi and add 20s timeout for hanging downloads. See also: https://jira.ecmwf.int/servicedesk/customer/portal/1/CUS-7104 > I am using the cdsapi package to download ERA5 data. I am having > troubles with frozen download connections. I don't really know why,...
41,296
def draft_github_comment(template, result): """ Use a template to draft a GitHub comment :template: (str) the name of the template file :result: (ContentError) the error to display in the comment """ # start with template with open(template, 'r') as f: contents = f.read() # replace variables in template wi...
41,297
def get_domains(sequence, disorder, disorder_threshold=0.42, minimum_IDR_size=12, minimum_folded_domain=50, gap_closure=10, override_folded_domain_minsize=False): """ Parameters ------------- sequence : str ...
41,298
def scd4x(): """Import scd4x module.""" import scd4x yield scd4x del sys.modules['scd4x']
41,299