content
stringlengths
22
815k
id
int64
0
4.91M
def get_env_loader(package, context): """This function returns a function object which extends a base environment based on a set of environments to load.""" def load_env(base_env): # Copy the base environment to extend job_env = dict(base_env) # Get the paths to the env loaders ...
5,353,100
def sampen(L, m): """ """ N = len(L) r = (np.std(L) * .2) B = 0.0 A = 0.0 # Split time series and save all templates of length m xmi = np.array([L[i: i + m] for i in range(N - m)]) xmj = np.array([L[i: i + m] for i in range(N - m + 1)]) # Save all matches minus the self-match,...
5,353,101
def close_socket(): """ This function is used to close client's socket. Returns: """ # send a close signal to cpp server and close its socket global client_socket signal = struct.pack("!I", 0) client_socket.send(signal) respond = client_socket.recv(4) respond = struct.unpack("!I...
5,353,102
def total(score: Union[int, RevisedResult]) -> int: """ Return the total number of successes (negative for a botch). If `score` is an integer (from a 1st/2nd ed. die from :func:`standard` or :func:`special`) then it is returned unmodified. If `score` is a :class:`RevisedResult` (from :func:`revise...
5,353,103
def test_register_user_with_password(api_client): """ Test if a new user can register himself providing his own new password. """ from testshop.models import Customer register_user_url = reverse('shop:register-user') data = { 'form_data': { 'email': '[email protected]', ...
5,353,104
def load_vgg16(model_dir, gpu_ids): """ Use the model from https://github.com/abhiskk/fast-neural-style/blob/master/neural_style/utils.py """ # if not os.path.exists(model_dir): # os.mkdir(model_dir) # if not os.path.exists(os.path.join(model_dir, 'vgg16.weight')): # if not os.path.exists(os...
5,353,105
def findExchange(username, password, region, orgId, envId, name): """This command will try to find an exchange in a given region, org id and environment id""" #### Anypoint login #### token = login(username, password) #### Request destinations to AMQ Rest API #### destinations_request_url = 'https...
5,353,106
def rbbox_overlaps_v3(bboxes1, bboxes2, mode='iou', is_aligned=False): """Calculate overlap between two set of bboxes. Args: bboxes1 (torch.Tensor): shape (B, m, 5) in <cx, cy, w, h, a> format or empty. bboxes2 (torch.Tensor): shape (B, n, 5) in <cx, cy, w, h, a> format ...
5,353,107
def write_comparison(report_fh, result: Tuple[Dict, List[BadResult]])-> None: """Write comparison output.""" (config, bad_results) = result logging.debug("writing report for %s", config['paper_id']) if bad_results: # data = json.dumps( [ config, bad_results], sort_keys=True, default=_serialize)...
5,353,108
def get_target_compute_version(target=None): """Utility function to get compute capability of compilation target. Looks for the arch in three different places, first in the target attributes, then the global scope, and finally the GPU device (if it exists). Parameters ---------- target : tvm.t...
5,353,109
def get_poet_intro_by_id(uid): """ get poet intro by id :param uid: :return: """ return Poet.get_poet_by_id(uid)
5,353,110
def create_post(): """Создать пост""" user = get_user_from_request() post = Post( created_date=datetime.datetime.now(), updated_date=datetime.datetime.now(), creator=user, ) json = request.get_json() url = json["url"] if Post.get_or_none(Post.url == url) is not Non...
5,353,111
def plot_absorption_spectrum(pairlist): """Plot line pairs along with transmission spectrum """ import subprocess for pair in tqdm(pairlist): args = ['/Users/dberke/code/plotSpec.py', 'HD45184/ADP.2014-09-26T16:54:56.573.fits', 'HD45184/ADP.2015-09-30T02:00:51.5...
5,353,112
async def fetch(session, url): """Method to fetch data from a url asynchronously """ async with async_timeout.timeout(30): async with session.get(url) as response: return await response.json()
5,353,113
def recurse_while(predicate, f, *args): """ Accumulate value by executing recursively function `f`. The function `f` is executed with starting arguments. While the predicate for the result is true, the result is fed into function `f`. If predicate is never true then starting arguments are returned...
5,353,114
def unparse(node: Optional[ast.AST]) -> Optional[str]: """Unparse an AST to string.""" if node is None: return None elif isinstance(node, str): return node elif node.__class__ in OPERATORS: return OPERATORS[node.__class__] elif isinstance(node, ast.arg): if node.annot...
5,353,115
def test_convert_nonnumeric_value(): """Test exception is thrown for nonnumeric type.""" with pytest.raises(TypeError): speed_util.convert("a", SPEED_KILOMETERS_PER_HOUR, SPEED_MILES_PER_HOUR)
5,353,116
def construct_lookup_variables(train_pos_users, train_pos_items, num_users): """Lookup variables""" index_bounds = None sorted_train_pos_items = None def index_segment(user): lower, upper = index_bounds[user:user + 2] items = sorted_train_pos_items[lower:upper] negatives_since_...
5,353,117
def total_allocation_constraint(weight, allocation: float, upper_bound: bool = True): """ Used for inequality constraint for the total allocation. :param weight: np.array :param allocation: float :param upper_bound: bool if true the constraint is from above (sum of weights <= allocation) else from b...
5,353,118
def sigmoid(x): """ computes sigmoid of x """ return 1.0/(1.0 + np.exp(-x))
5,353,119
def handle_error(err): """Catches errors with processing client requests and returns message""" code = 500 error = 'Error processing the request' if isinstance(err, HTTPError): code = err.code error = str(err.message) return jsonify(error=error, code=code), code
5,353,120
def dimensionality(quantity_or_unit: str) -> Dict[str, int]: """ Returns the dimensionality of the quantity or unit. Parameters ----------- quantity_or_unit : str A quanitity or a unit Returns ------- dimensionality_dict : dict Dictionary whi...
5,353,121
def split_prec_rows(df): """Split precincts into two rows. NOTE: Because this creates a copy of the row values, don't rely on total vote counts, just look at percentage. """ for idx in df.index: # look for rows with precincts that need to be split if re.search('\d{4}/\d{4}',idx): ...
5,353,122
def socfaker_elasticecsfields_host(): """ Returns an ECS host dictionary Returns: dict: Returns a dictionary of ECS host fields/properties """ if validate_request(request): return jsonify(str(socfaker.products.elastic.document.fields.host))
5,353,123
def _moog_writer(photosphere, filename, **kwargs): """ Writes an :class:`photospheres.photosphere` to file in a MOOG-friendly format. :param photosphere: The photosphere. :path filename: The filename to write the photosphere to. """ def _get_xi(): xi = photosphere....
5,353,124
def upcomingSplits( symbol="", exactDate="", token="", version="stable", filter="", format="json", ): """This will return all upcoming estimates, dividends, splits for a given symbol or the market. If market is passed for the symbol, IPOs will also be included. https://iexcloud.io/docs/...
5,353,125
async def async_media_pause(hass, entity_id=None): """Send the media player the command for pause.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call(DOMAIN, SERVICE_MEDIA_PAUSE, data)
5,353,126
def mu_model(u, X, U, k): """ Returns the utility of the kth player Parameters ---------- u X U k Returns ------- """ M = X.T @ X rewards = M @ u penalties = u.T @ M @ U[:, :k] * U[:, :k] return rewards - penalties.sum(axis=1)
5,353,127
def tokenizer_init(model_name): """simple wrapper for auto tokenizer""" tokenizer = AutoTokenizer.from_pretrained(model_name) return tokenizer
5,353,128
def insert_message(nick, message, textDirection): """ Insert record """ ins = STATE['messages_table'].insert().values( nick=nick, message=message, textDirection=textDirection) res = STATE['conn'].execute(ins) ltr = 1 if textDirection == 'ltr' else 0 rtl = 1 if textDirection == 'rtl'...
5,353,129
def process_metadata(metadata) -> Tuple[Dict[str, str], Dict[str, str]]: """ Returns a tuple of valid and invalid metadata values. """ if not metadata: return {}, {} valid_values = {} invalid_values = {} for m in metadata: key, value = m.split("=", 1) if key in supported_met...
5,353,130
def rightOfDeciSeperatorToDeci(a): """This function only convert value at the right side of decimal seperator to decimal""" deciNum = 0 for i in range(len(a)): deciNum += (int(a[i]))*2**-(i+1) return deciNum
5,353,131
def test_single_download_from_requirements_file(script): """ It should support download (in the scratch path) from PyPi from a requirements file """ script.scratch_path.join("test-req.txt").write(textwrap.dedent(""" INITools==0.1 """)) result = script.pip( 'install', '-r'...
5,353,132
def init_logging(): """ Initialize logging and write info both into logfile and console Usage example: land.logger.logging.info('Your message here') Logger levels: critical, error, warning, info, debug, notset """ this_dir = os.path.dirname(os.path.realpath(__file__)) # path to this directory ...
5,353,133
def conv(input, weight): """ Returns the convolution of input and weight tensors, where input contains sequential data. The convolution is along the sequence axis. input is of size [batchSize, inputDim, seqLength] """ output = torch.nn.functional.conv1d(input=input, weight=...
5,353,134
def irr_repr(order, alpha, beta, gamma, dtype = None): """ irreducible representation of SO3 - compatible with compose and spherical_harmonics """ cast_ = cast_torch_tensor(lambda t: t) dtype = default(dtype, torch.get_default_dtype()) alpha, beta, gamma = map(cast_, (alpha, beta, gamma)) ...
5,353,135
def label_to_span(labels: List[str], scheme: Optional[str] = 'BIO') -> dict: """ convert labels to spans :param labels: a list of labels :param scheme: labeling scheme, in ['BIO', 'BILOU']. :return: labeled spans, a list of tuples (start_idx, end_idx, label) """ assert sche...
5,353,136
def marker_genes_text( marker_res, groups: Union[str, Sequence[str]] = 'all', markers_num: int = 20, sort_key: str = 'scores', ascend: bool = False, fontsize: int = 8, ncols: int = 4, sharey: bool = True, ax: Optional[Axes] = None, **kwargs...
5,353,137
def get_storage_account(account_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStorageAccountResult: """ The storage account. :param str account_name: The name of the storage...
5,353,138
def format_and_add(graph, info, relation, name): """ input: graph and three stirngs function formats the strings and adds to the graph """ info = info.replace(" ", "_") name = name.replace(" ", "_") inf = rdflib.URIRef(project_prefix + info) rel = rdflib.URIRef(project_prefix + rela...
5,353,139
def get_dataset(dir, batch_size, num_epochs, reshape_size, padding='SAME'): """Reads input data num_epochs times. AND Return the dataset Args: train: Selects between the training (True) and validation (False) data. batch_size: Number of examples per returned batch. num_epochs: Number of times...
5,353,140
def to_log_space(p:float, bounds: BOUNDS_TYPE): """ Interprets p as a point in a rectangle in R^2 or R^3 using Morton space-filling curve :param bounds [ (low,high), (low,high), (low,high) ] defaults to unit cube :param dim Dimension. Only used if bounds are not supplied. Very ...
5,353,141
def advection2D(iplot=False,use_petsc=False,htmlplot=False,outdir='./_output',solver_type='classic'): """ Example python script for solving the 2d advection equation. """ #=========================================================================== # Import libraries #============================...
5,353,142
def rsi_tradingview(ohlc: pd.DataFrame, period: int = 14, round_rsi: bool = True): """ Implements the RSI indicator as defined by TradingView on March 15, 2021. The TradingView code is as follows: //@version=4 study(title="Relative Strength Index", shorttitle="RSI", format=format.price, prec...
5,353,143
def bin_by(x, y, nbins=30): """Bin x by y, given paired observations of x & y. Returns the binned "x" values and the left edges of the bins.""" bins = np.linspace(y.min(), y.max(), nbins+1) # To avoid extra bin for the max value bins[-1] += 1 indicies = np.digitize(y, bins) output = [] ...
5,353,144
def calc_stats_with_cumsum(df_tgt, list_tgt_status, dict_diff, calc_type=0): """ Calculate statistics with cumulative sum of target status types. \n "dict_diff" is dictionaly of name key and difference value. ex) {"perweek": 7, "per2week": 14} \n calc_type=0: calculate for each simulation result. \n...
5,353,145
def savestates(plate, filename, n, newpath, number=NUMBER): """ Create a JPEG and a PNG of the snowflake. :param plate: (list of list of dict) The plate which contain the cristal. :param filename: (str) Name of the file. :param n: (int) The n-th iteration of the snowflake. 0 by default,...
5,353,146
def _normalize_handler_method(method): """Transforms an HTTP method into a valid Python identifier.""" return method.lower().replace("-", "_")
5,353,147
def getContentType(the_type): """ Get the content type based on the type name which is in settings :param the_type: :return: """ if the_type not in settings.XGDS_MAP_SERVER_JS_MAP: return None the_model_name = settings.XGDS_MAP_SERVER_JS_MAP[the_type]['model'] splits = the_model...
5,353,148
def calculateGravityAcceleration(stateVec, epoch, useGeoid): """ Calculate the acceleration due to gravtiy acting on the satellite at a given state (3 positions and 3 velocities). Ignore satellite's mass, i.e. use a restricted two-body problem. Arguments ---------- numpy.ndarray of shape (1...
5,353,149
def points_on_line(r0, r1, spacing): """ Coordinates of points spaced `spacing` apart between points `r0` and `r1`. The dimensionality is inferred from the length of the tuples `r0` and `r1`, while the specified `spacing` will b...
5,353,150
def index() -> Response: """ Return application index. """ return APP.send_static_file("index.html")
5,353,151
def compare_files(og_maxima,new_maxima, compare_file, until=100, divisor=1000): """ given input of the maxima of a graph, compare it to the maxima from data100.txt maxima will be a series of x,y coordinates corresponding to the x,y values of a maximum from a file. First see if there is a maxima ...
5,353,152
def parseDatetimetz(string, local=True): """Parse the given string using :func:`parse`. Return a :class:`datetime.datetime` instance. """ y, mo, d, h, m, s, tz = parse(string, local) s, micro = divmod(s, 1.0) micro = round(micro * 1000000) if tz: offset = _tzoffset(tz, None) / 60 ...
5,353,153
def median_ratio_flux(spec, smask, ispec, iref, nsig=3., niter=5, **kwargs): """ Calculate the median ratio between two spectra Parameters ---------- spec smask: True = Good, False = Bad ispec iref nsig niter kwargs Returns ------- med_scale : float Medi...
5,353,154
def merge_chars(lgr, script, merged_lgr, ref_mapping, previous_scripts): """ Merge chars from LGR set. :param lgr: A LGR from the set :param script: The LGR script :param merged_lgr: The merged LGR :param ref_mapping: The reference mapping from base LGR to new LGR :param previous_scripts: T...
5,353,155
def configure_parser(parser): """ Configure parser for this action """ qisys.parsers.worktree_parser(parser)
5,353,156
def get_tags_from_event(): """List of tags Arguments: event {dict} -- Lambda event payload Returns: list -- List of AWS tags for use in a CFT """ return [ { "Key": "OwnerContact", "Value": request_event['OwnerContact'] } ]
5,353,157
def _verify(symbol_table: SymbolTable, ontology: _hierarchy.Ontology) -> List[Error]: """Perform a battery of checks on the consistency of ``symbol_table``.""" errors = _verify_there_are_no_duplicate_symbol_names(symbol_table=symbol_table) if len(errors) > 0: return errors errors.extend( ...
5,353,158
def gsl_eigen_symmv_alloc(*args, **kwargs): """gsl_eigen_symmv_alloc(size_t n) -> gsl_eigen_symmv_workspace""" return _gslwrap.gsl_eigen_symmv_alloc(*args, **kwargs)
5,353,159
def add_poll_answers(owner, option): """ Add poll answer object. Matching user and option is considered same. :param owner: User object. :param option: Chosen poll option. :return: Poll answer object, Boolean (true, if created). """ ''' owner = models.ForeignKey(User, related_name='poll_...
5,353,160
def calculate_rrfdi ( red_filename, nir_filename ): """ A function to calculate the Normalised Difference Vegetation Index from red and near infrarred reflectances. The reflectance data ought to be present on two different files, specified by the varaibles `red_filename` and `nir_filename`. The file...
5,353,161
def retry_on_failure(retries=NO_RETRIES): """Decorator which runs a test function and retries N times before actually failing. """ def logfun(exc): print("%r, retrying" % exc, file=sys.stderr) # NOQA return retry(exception=AssertionError, timeout=None, retries=retries, log...
5,353,162
def command_line(): """Generate an Argument Parser object to control the command line options """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("-w", "--webdir", dest="webdir", help="make page and plots in DIR", metavar="DIR", d...
5,353,163
def test_xonfg_help(capsys, xonsh_builtins): """verify can invoke it, and usage knows about all the options""" with pytest.raises(SystemExit): xonfig_main(["-h"]) capout = capsys.readouterr().out pat = re.compile(r"^usage:\s*xonfig[^\n]*{([\w,-]+)}", re.MULTILINE) m = pat.match(capout) a...
5,353,164
def strip_price(header_list): """input a list of tag-type values and return list of strings with surrounding html characters removed""" import re match_obs = [] regex = '\$(((\d+).\d+)|(\d+))' string_list = []#['' for item in range(len(header_list))] for item in range(len(header_list)): ...
5,353,165
def test_set(): """Test raw_to_bids conversion for EEGLAB data.""" # standalone .set file output_path = _TempDir() data_path = op.join(testing.data_path(), 'EEGLAB') raw_fname = op.join(data_path, 'test_raw_onefile.set') raw_to_bids(subject_id=subject_id, session_id=session_id, run=run, ...
5,353,166
def module(input, output, version): """A decorator which turn a function into a module""" def decorator(f): class Wrapper(Module): def __init__(self): super().__init__(input, output, version) @property def name(self): """The module's na...
5,353,167
def compile_modules_to_ir( result: BuildResult, mapper: genops.Mapper, compiler_options: CompilerOptions, errors: Errors, ) -> ModuleIRs: """Compile a collection of modules into ModuleIRs. The modules to compile are specified as part of mapper's group_map. Returns the IR of the modules. ...
5,353,168
def minutes_to_restarttime(minutes) : """ converts an int meaning Minutes after midnight into a restartTime string understood by the bos command """ if minutes == -1 : return "never" pod = "am" if minutes > 12*60 : pod = "pm" minutes -= 12*60 time = "%d:%02d %s"...
5,353,169
def create_checkpoint(conn): """Function use config getter or get checkpoint file and write to disk""" if "nxos" in conn.platform: filename = f"{conn.hostname}-checkpoint.txt" backup = conn._get_checkpoint_file() with open(filename, "w") as f: f.write(backup) else: ...
5,353,170
def clean_storage_exceeding_containers(): """Remove containers which exceeds the max container size defined by $MAX_CONTAINER_SIZE """ if max_container_size == -1: logging.info("The environment variable MAX_CONTAINER_SIZE was not set.") return container_size_field = "SizeRw" contai...
5,353,171
def main(args): """ Parses command line arguments and do the work of the program. "args" specifies the program arguments, with args[0] being the executable name. The return value should be used as the program's exit code. """ print(random.choice(FACTS), file = sys.stderr) options = ...
5,353,172
def ccm_test(x, y,emb_dim = "auto", l_0 = "auto", l_1 = "auto", tau=1, n=10,mean_num = 10,max_dim = 10): """ estimate x from y to judge x->y cause :param x: :param y: :param l_0: :param l_1: :param emb_dim: :param tau: :param n: :return: """ if emb_dim == "auto...
5,353,173
def load_carla_env( env_name='why_carla-v0', discount=1.0, number_of_vehicles=100, number_of_walkers=0, display_size=256, max_past_step=1, dt=0.1, discrete=False, discrete_acc=[-3.0, 0.0, 3.0], discrete_steer=[-0.2, 0.0, 0.2], continuous_accel_range=[-3.0, 3.0], continuous_steer_range=[-0.3, 0.3...
5,353,174
def make_indiv_spacing(subject, ave_subject, template_spacing, subjects_dir): """ Identifies the suiting grid space difference of a subject's volume source space to a template's volume source space, before a planned morphing takes place. Parameters: ----------- subject : str Sub...
5,353,175
def sqlpool_blob_auditing_policy_update( cmd, instance, state=None, storage_account=None, storage_endpoint=None, storage_account_access_key=None, storage_account_subscription_id=None, is_storage_secondary_key_in_use=None, retention_days=None, ...
5,353,176
def check_arguments_for_rescoring(usage_key): """ Do simple checks on the descriptor to confirm that it supports rescoring. Confirms first that the usage_key is defined (since that's currently typed in). An ItemNotFoundException is raised if the corresponding module descriptor doesn't exist. NotI...
5,353,177
def from_system() -> Optional[Config]: """ Config-factory; producing a Config based on environment variables and when environment variables aren't set, fall back to the ``cij_root`` helper. """ conf = Config() # Setup configuration using environment variable definitions paths_from_evars = ...
5,353,178
def format_search_filter(model_fields): """ Creates an LDAP search filter for the given set of model fields. """ ldap_fields = convert_model_fields_to_ldap_fields(model_fields); ldap_fields["objectClass"] = settings.LDAP_AUTH_OBJECT_CLASS search_filters = import_func(settings.LDAP_AUT...
5,353,179
def test_postagging_with_kytea(): """Test KyTea tokenizer.""" try: tokenizer = WordTokenizer(tokenizer="kytea", with_postag=True) except ImportError: pytest.skip("MyKyTea is not installed.") expect = [Token(**kwargs) for kwargs in kytea_tokens_list] result = tokenizer.tokenize("吾輩は猫...
5,353,180
def multiprocess(func=None, pycsp_host='', pycsp_port=None): """ @multiprocess(pycsp_host='', pycsp_port=None) @multiprocess decorator for making a function into a CSP MultiProcess factory. Each generated CSP process is implemented as a single OS process. All objects and variables provided to multipro...
5,353,181
def only_percentage_ticks(plot): """ Only show ticks from 0.0 to 1.0. """ hide_ticks(plot, min_tick_value=0, max_tick_value=1.0)
5,353,182
def normalize_img(img): """ normalize image (caffe model definition compatible) input: opencv numpy array image (h, w, c) output: dnn input array (c, h, w) """ scale = 1.0 mean = [104,117,123] img = img.astype(np.float32) img = img * scale img -= mean img = np.transpose(img, ...
5,353,183
def pages(lst: List[Any], n: int, title: str, *, fmt: str = "```%s```", sep: str = "\n") -> List[discord.Embed]: # noinspection GrazieInspection """ Paginates a list into embeds to use with :class:disputils.BotEmbedPaginator :param lst: the list to paginate :param n: the number of elemen...
5,353,184
def Substitute_Percent(sentence): """ Substitutes percents with special token """ sentence = re.sub(r'''(?<![^\s"'[(])[+-]?[.,;]?(\d+[.,;']?)+%(?![^\s.,;!?'")\]])''', ' @percent@ ', sentence) return sentence
5,353,185
def ready_df1(df): """ This function prepares the dataframe for EDA. """ df = remove_columns(df, columns=[ 'nitrogen_dioxide', 'nitrogen_dioxide_aqi', 'sulfur_dioxide', 'sulfur_dioxide_aqi',...
5,353,186
def save_reward_history(reward_history, file_name): """ Saves the reward history of the agent teams to create plots for learning performance :param reward_history: :param file_name: :return: """ dir_name = 'Output_Data/' # Intended directory for output files save_file_name = os.path.joi...
5,353,187
def _wrap(func, args, flip=True): """Return partial function with flipped args if flip=True :param function func: Any function :param args args: Function arguments :param bool flip: If true reverse order of arguments. :return: Returns function :rtype: function """ @wraps(func) def ...
5,353,188
def compute_kkt_optimality(g, on_bound): """Compute the maximum violation of KKT conditions.""" g_kkt = g * on_bound free_set = on_bound == 0 g_kkt[free_set] = np.abs(g[free_set]) return np.max(g_kkt)
5,353,189
def replace_cipd_revision(file_path, old_revision, new_revision): """Replaces cipd revision strings in file. Args: file_path: Path to file. old_revision: Old cipd revision to be replaced. new_revision: New cipd revision to use as replacement. Returns: Number of replaced occurrences. Raises: ...
5,353,190
def spectral_derivs_plot(spec_der, contrast=0.1, ax=None, freq_range=None, fft_step=None, fft_size=None): """ Plot the spectral derivatives of a song in a grey scale. spec_der - The spectral derivatives of the song (computed with `spectral_derivs`) or the song itself...
5,353,191
def scale_center(pnt, fac, center): """scale point in relation to a center""" return add(scale(sub(pnt, center), fac), center)
5,353,192
def constrain_uptakes(model, xi): """When the cells are not competing (resource excess, high ξ) uptakes are restricted by the limits of metabolite importers. When competion occurs competiton is modeled by limiting uptakes to metabolite_concentration/ξ Parameters ---------- model : cobra....
5,353,193
def gopherize_feed(feed_url, timestamp=False, plug=True): """Return a gophermap string for the feed at feed_url.""" return gopherize_feed_object(feedparser.parse(feed_url), timestamp, plug)
5,353,194
def first_sunday_of_month(datetime: pendulum.DateTime) -> pendulum.DateTime: """Get the first Sunday of the month based on a given datetime. :param datetime: the datetime. :return: the first Sunday of the month. """ return datetime.start_of("month").first_of("month", day_of_week=7)
5,353,195
def evaluate_single_model( model_path, model_index, save_preds_to_db, save_prefix, metrics, k_values, X, y, labeled_indices): """ Evaluate a single model with provided model specifications and data. Arguments: - model_path: path to load the model - model_index: index for the model ...
5,353,196
def slack_notify_update_user_queue(username: str): """ Queue 등록 알림 """ channel = settings.SLACK_CHANNEL_CRONTAB server = 'PROD' if settings.IS_PROD else 'LOCAL' attachments = [ { "color": "#ff0000", "title": 'RATE LIMIT 제한으로 update 실패', "pretext": ...
5,353,197
async def test_update_raceplan( http_service: Any, token: MockFixture, context: dict ) -> None: """Should return No Content.""" url = f"{http_service}/raceplans" headers = { hdrs.CONTENT_TYPE: "application/json", hdrs.AUTHORIZATION: f"Bearer {token}", } id = context["id"] ur...
5,353,198
def parse_args ( ) -> argparse.Namespace: """ Parser for cli arguments. Returns: A Namespace containing all parsed data """ # The parser itself parser = argparse.ArgumentParser(add_help=False) parser.description = "Evaluates single choice sheets" # Groups for ordering argu...
5,353,199