content
stringlengths
22
815k
id
int64
0
4.91M
def _create_dhcp_entries_for_many_instances(instances, ip_or_network): """ Assign IP and create DHCP entries for multiple instances. """ for instance in instances: # when IP is assigned to many instances, mac is not provided through # form and first non-mgmt mac should be used et...
5,326,100
def test_psf_estimation(psf_data, true_psf_file, kernel=None, metric='mean'): """Test PSF Estimation This method tests the quality of the estimated PSFs Parameters ---------- psf_data : np.ndarray Estimated PSFs, 3D array true_psf_file : str True PSFs file name kernel : int...
5,326,101
def EulerBack(V_m0,n_0,m_0,h_0,T,opcion,t1,t2,t3,t4,I1,I2,h_res=0.01): """ :param V_m0: Potencial de membrana inicial :param n_0: Probabilidad inicial de n :param m_0: Probabilidad inicial de m :param h_0: Probabilidad inicial de h :param T: Temperatura indicada por el usuario :param opcion:...
5,326,102
def wiggle(shape, scope, offset, seed=0): """Shift points/contours/paths by a random amount.""" if shape is None: return None functions = { "points": wiggle_points, "contours": wiggle_contours, "paths": wiggle_paths} fn = functions.get(scope) if fn is None: retu...
5,326,103
def parseAndDisplay(line, indentLevel): """Indents lines.""" if line.startswith("starting "): printArgumentLine(indentLevel, line) indentLevel += 1 elif line.startswith("ending "): indentLevel -= 1 printArgumentLine(indentLevel, line) else: printLine(indentLevel, ...
5,326,104
def insert_question(question): """ Insert a particular question @param: question - JSON object containing question data to be inserted """ return db.questions.insert_one(question)
5,326,105
def chk_slv(slave, **kwargs): """Function: chk_slv Description: Compares the Slave's read file and postition with the executed file and position. Will also print GTID info, in pre-MySQL 5.6 this will be NULL. Arguments: (input) slave -> Slave instance. """ global PRT_...
5,326,106
def sequence_vectorize(train_texts, val_texts): """Vectorizes texts as sequence vectors. 1 text = 1 sequence vector with fixed length. # Arguments train_texts: list, training text strings. val_texts: list, validation text strings. # Returns x_train, x_val, word_index: vectoriz...
5,326,107
def fix_wcs_full(img, coords='radec.coo', iters=1): """ Try to improve the WCS solution of a final stacked image. Parameters ---------- img : str Name of image coords : str Name of coordinate file iter : int Number of desired iterations of ``msccmatch``. It is still...
5,326,108
def parse_preferences(file, preferences): """Parse preferences to the dictionary.""" for line in open(file, "r").readlines(): # all lower case line = line.lower() # ignore comment lines if line[0] == "!" or line[0] == "#" or not line.split(): continue key ...
5,326,109
def func_hex2str(*args): """字符串 -> Hex""" return func_hex2byte(*args).decode('utf-8')
5,326,110
def setup_indexes(db_name, collection): """ Ensure that indexes in eduid_am.attributes collection are correctly setup. To update an index add a new item in indexes and remove the previous version. """ indexes = { # 'index-name': {'key': [('key', 1)], 'param1': True, 'param2': False} ...
5,326,111
def book_link_retrieval(soup_object): """ soup_object : Soup object having parsed HTML for the user query """ global sp, dir_link i, retries = 0, 3 # fetching the title and book link for _ in soup_object.find_all("td"): for td in soup_object.find_all("h3"): f...
5,326,112
def warm_since(): """Return the date when the current warm version of the fn started. """ if is_warm() == 'warm': ts = os.path.getmtime(warm_file()) return ts
5,326,113
def test_opt_level(): """Test equivalence of nodes that pre-process to the same text.""" options = program_graph_options_pb2.ProgramGraphOptions( opt_level=0, ) unoptimized = llvm.BuildProgramGraph(SIMPLE_IR) options.opt_level = 3 optimized = llvm.BuildProgramGraph(SIMPLE_IR, options) ...
5,326,114
def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() with open(vocab_file, "r", encoding="utf-8") as reader: tokens = reader.readlines() for index, token in enumerate(tokens): token = token.rstrip("\n") vocab[token] = index return vocab
5,326,115
def triage(routes: List[Route]) -> Route: """ This function will be used to determine which route to use """ eva = {} for i, route in enumerate(routes): stored_route: StoredRoute = route.pop("stored_route") reg_path = stored_route["path"] segments = [s for s in reg_path.split...
5,326,116
def eval(**args): """ Evaluate selected model Args: seed (Int): Integer indicating set seed for random state save_dir (String): Top level directory to generate results folder model (String): Name of selected model dataset (String): Name of...
5,326,117
def submit_production(production_yaml, dry_run=False, error_if_not_available=False): """ Interprets a production_yaml file and submits the respective nights for processing within the defined production. Args: production_yaml, str. Pathname of the yaml file that defines the production. d...
5,326,118
def upsert_object(data, cursor=None): """ Upsert an object in the repository. """ cursor = check_cursor(cursor) data = _set_object_defaults(data, cursor) cursor.execute(''' INSERT INTO objects (pid_id, namespace, state, owner, label, versioned, log, created,...
5,326,119
def sparsity_line(M,tol=1.0e-3,device='cpu'): """Get the line sparsity(%) of M Attributes: M: Tensor - the matrix. tol: Scalar,optional - the threshold to select zeros. device: device, cpu or gpu Returns: spacity: Scalar (%)- the spacity of the matrix. """ ...
5,326,120
def geospace(lat0, lon0, length, dx, strike): """ returns a series of points in geographic coordinates""" pts_a = [] npts = length // dx + 1 for idx in range(npts): # convert to lat, lon new = convert_local_idx_to_geo(idx, lat0, lon0, length, dx, strike) pts_a.append(new) ret...
5,326,121
def linearOutcomePrediction(zs, params_pred, scope=None): """ English: Model for predictions outcomes from latent representations Z, zs = batch of z-vectors (encoder-states, matrix) Japanese: このモデルにおける、潜在表現Zから得られる出力の予測です。 zs = ベクトル z のバッチ(袋)です。 (encoder の状態であり、行列です) (恐らく、[z_0, z_...
5,326,122
def _check_flag_value(flag_value): """ Search for a given flag in a given blockette for the current record. This is a utility function for set_flags_in_fixed_headers and is not designed to be called by someone else. This function checks for valid entries for a flag. A flag can be either * ``bo...
5,326,123
def logout(): """ Logout a user """ session.pop('user_id', None) session.pop('player_id', None) return redirect(url_for('index'))
5,326,124
def test_request_response_has_status_code(): """An RequestResponseStub object's has expected properties.""" response = RequestResponseStub(status_code=301) assert str(response.status_code) == '301' assert str(RequestResponseStub().status_code) == '200'
5,326,125
def get_available_gpus(): """Returns a list of available GPU devices names. """ local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == "GPU"]
5,326,126
def download_config(impdb: str, branch: str) -> None: """Download the config from Github into the temp directory.""" requests = Request(META_URL.format(branch, impdb)) response = requests.get() meta = json.loads(response.read()) tables = meta["tables"] sha = get_git_branch_hash(branch) # In...
5,326,127
def runNoReLUSRModel(projectdir=projectdir,outdir=projectdir+'data/results/MAIN/srModelPredictionAccuracies/SRActFlowNoReLU/', nhidden=10,computeFC=False,ncomponents=500,nproc=10): """ No ReLU model - remove nonlinearity in hidden area (see thresh=None) """ #### Don't change this pa...
5,326,128
def configure_ident_username(keystone): """Requests a user to the Identity Service """ username = 'manila' keystone.request_credentials(username)
5,326,129
def tgamma ( x ) : """'tgamma' function taking into account the uncertainties """ fun = getattr ( x , '__tgamma__' , None ) if fun : return fun() return math.gamma ( x )
5,326,130
def detect_peaks_by_channel(traces, peak_sign, abs_threholds, n_shifts): """Detect peaks using the 'by channel' method.""" traces_center = traces[n_shifts:-n_shifts, :] length = traces_center.shape[0] if peak_sign in ('pos', 'both'): peak_mask = traces_center > abs_threholds[None, :] f...
5,326,131
def multi_gauss_psf_kernel(psf_parameters, BINSZ=0.02, NEW_BINSZ=0.02, **kwargs): """Create multi-Gauss PSF kernel. The Gaussian PSF components are specified via the amplitude at the center and the FWHM. See the example for the exact format. Parameters ---------- psf_parameters : dict ...
5,326,132
def show_stress(off_screen=None): """ Load and plot 1st bend of a hexahedral beam """ # get location of this file result = pymapdl_reader.read_binary(rstfile) print('Displaying node averaged stress in x direction for Mode 6') result.plot_nodal_stress(5, 'x', off_screen=off_screen, n_colors=9)
5,326,133
def Wavefunction( # type: ignore # pylint: disable=function-redefined param: List[List[int]], broken: Optional[Union[List[str], str]] = None) -> 'Wavefunction': """Initialize a wavefunction through the fqe namespace Args: param (List[List[int]]): parameters for the sectors bro...
5,326,134
def extractFiles(comment): """Find all files in a comment. @param comment: The C{unicode} comment text. @return: A C{list} of about values from the comment, with no duplicates, in the order they appear in the comment. """ return uniqueList(findall(FILE_REGEX, comment))
5,326,135
def showModelsStatic(ptcode,codes, vols, ss, mm, vs, showVol, clim, isoTh, clim2, clim2D, drawMesh=True, meshDisplacement=True, drawModelLines=True, showvol2D=False, showAxis=False, drawVessel=False, vesselType=1, meshColor=None, **kwargs): """ show one to four models in multipanel figure. I...
5,326,136
def rint_compute(input_x): """rint compute implementation""" res = akg.lang.cce.round(input_x) res = akg.lang.cce.cast_to(res, input_x.dtype) return res
5,326,137
def _solequal(sol1, sol2, prec): """ Compare two different solutions with a given precision. Return True if they equal. """ res = True for sol_1, sol_2 in zip(sol1, sol2): if np.ndim(sol_1) != 0 and np.ndim(sol_2) != 0: res &= _dist(sol_1, sol_2) < prec elif np.ndim...
5,326,138
def printFactor(f): """ argument `f`, a factor to print on screen """ # Create a empty list that we will fill in with the probability table entries table = list() # Iterate over all keys and probability values in the table for key, item in f['table'].items(): # Convert the ...
5,326,139
def get_template_filepath(filename, basepath="templates"): """ Get the full path to the config templates, using a relative path to where the shippy script is stored :param filename: (str) Name of the template file to look for :param basepath: (str) Base directory to search for templates. Default: /temp...
5,326,140
def clip_rows(data, ord=2, L=1): """ Scale clip rows according the same factor to ensure that the maximum value of the norm of any row is L """ max_norm = get_max_norm(data, ord=ord) print("For order {0}, max norm is {1}".format(ord, max_norm)) normalized_data = data.copy() modified = ...
5,326,141
def extrapolate_to_zero_linear(pattern): """ Extrapolates a pattern to (0, 0) using a linear function from the most left point in the pattern :param pattern: input Pattern :return: extrapolated Pattern (includes the original one) """ x, y = pattern.data step = x[1] - x[0] low_x = np.sort...
5,326,142
def findKthSmallest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def partition(left, right, pivot_index): pivot = nums[pivot_index] # 1. move pivot to end nums[pivot_index], nums[right] = nums[right], nums[pivot_index] # 2. m...
5,326,143
def create_server(zkclient, server_id, parent_id): """Creates server definition in Zookeeper.""" server_node = z.path.server(server_id) server_acl = zkutils.make_host_acl(server_id, 'rwcd') zkutils.ensure_exists(zkclient, server_node, acl=[server_acl]) # zkutils.get return dict/tuple if need_metad...
5,326,144
def racetrack_AP_RR_TF( wavelength, sw_angle=90, radius=12, couplerLength=4.5, gap=0.2, width=0.5, thickness=0.2, widthCoupler=0.5, loss=[0.99], coupling=[0], ): """This particular transfer function assumes that the coupling sides of the ring resonator are straight, and t...
5,326,145
def test_pp_default_2d( fixture_localhost, generate_calc_job_node, generate_parser, generate_inputs_2d, data_regression, num_regression ): """Test a default `pp.x` calculation producing a 2D data set.""" entry_point_calc_job = 'quantumespresso.pp' entry_point_parser = 'quantumespresso.pp' node = ge...
5,326,146
def reset_config(): """ This fixture is called for every test in the project, and resets the configuration to default. """ conf.config_init(None) conf.testing_overrides = None
5,326,147
def _get_event_data(tr, tt_model, phase, acc_type, depth_unit="km"): """ Update a sac trace to a obspy trace and update trace header, and calculate theoretical traveltime of a specific model and phase :param tr: :param tt_model: :param phase: :param acc_type: :param depth_unit: :ret...
5,326,148
def fetch_ccgp_bid_info(keyword, pages, filename, **kwargs): """Fetch and store bidding information.""" bid = BidInfo() if os.path.isfile(filename): bid.load(filename) directory = os.path.splitext(filename)[0] if not os.path.exists(directory): os.makedirs(directory) if bid.next...
5,326,149
def cmd_pool(args): """ Sub-command: "pool", down-sample image cube along the spatial dimension. """ if not args.clobber and os.path.exists(args.outfile): raise OSError("output file already exists: %s" % args.outfile) cube = FITSCube(args.infile) print("Data cube unit: %s" % cube.unit) ...
5,326,150
def consume_chunks(generator: Union[PandasTextFileReader, Iterator], progress: bool = True, total: int = None): """Transform the result of chained filters into a pandas DataFrame :param generator: iterator to be transformed into a dataframe :param progress: whether to show progress :param total: total ...
5,326,151
def lang_not_found(s): """Is called when the language files aren't found""" return s + "⚙"
5,326,152
def _get_corr_matrix(corr, rho): """Preprocessing of correlation matrix ``corr`` or correlation values ``rho``. Given either ``corr`` or ``rho`` (each may be an array, callable or process instance), returns the corresponding, possibly time-dependent correlation matrix, with a ``shape`` attribut...
5,326,153
def init_lqr(hyperparams): """ Return initial gains for a time-varying linear Gaussian controller that tries to hold the initial position. """ config = copy.deepcopy(INIT_LG_LQR) config.update(hyperparams) x0, dX, dU = config['x0'], config['dX'], config['dU'] dt, T = config['dt'], confi...
5,326,154
def sequence_exact_match(true_seq, pred_seq): """ Boolean return value indicates whether or not seqs are exact match """ true_seq = strip_whitespace(true_seq) pred_seq = strip_whitespace(pred_seq) return pred_seq["start"] == true_seq["start"] and pred_seq["end"] == true_seq["end"]
5,326,155
def same_variable(a, b): """ Cette fonction dit si les deux objets sont en fait le même objet (True) ou non (False) s'ils sont différents (même s'ils contiennent la même information). @param a n'importe quel objet @param b n'importe quel objet @return ``True`` ...
5,326,156
def _check_legal_sampling_frequency_and_duration(sampling_frequency, duration): """ By convention, sampling_frequency and duration have to multiply to an integer This will check if the product of both parameters multiplies reasonably close to an integer. Parameters ========== sampling_frequenc...
5,326,157
def inform_report_issue(exception_msg): """ Informs user that he can report an issue. The use of `memoize` makes it reporting only once for a given exception message. """ print(message.notice( "If that is an issue, you can report it on https://github.com/pwndbg/pwndbg/issues\n" "(Ple...
5,326,158
def format_level_2_memory(memory, header=None): """Format an experiment result memory object for measurement level 2. Args: memory (list): Memory from experiment with `meas_level==2` and `memory==True`. header (dict): the experiment header dictionary containing useful information fo...
5,326,159
def convert_objects_to_polar(rendering_items): """Apply conversion to turn all Objects block formats into polar.""" from .objectbased.conversion import to_polar return list(apply_to_object_blocks(rendering_items, to_polar))
5,326,160
def test_getMonthFromIntToString(): """ It should return the number of the month if given a string and returns the name of the month if given and int """ # months = ['January', 'February', 'March', 'April', 'May', 'June', # 'July', 'August', 'September', 'October' 'November', ...
5,326,161
def compile(file_address): """main function. Args: file_address (str): address of file that given in the command line. """ scanner = Scanner() data = open(file_address, 'r').read() tokens, symbol_table = scanner.get_tokens_symbol_table(data) pprint(tokens) print(...
5,326,162
def find_in_module(var_name: str, module, i: int = 0) -> Tuple[str, ast.AST]: """Find the piece of code that assigned a value to the variable with name *var_name* in the module *module*. :param var_name: Name of the variable to look for. :param module: Module to search. :returns: Tuple with source ...
5,326,163
def empty(shape, dtype="f8", order="C", device=None, usm_type="device", sycl_queue=None): """Creates `dpnp_array` from uninitialized USM allocation.""" array_obj = dpt.empty(shape, dtype=dtype, order=order, ...
5,326,164
def test_exception_attribute_in_extra(): """ In an except block, passing an exception attribute into logging as a value of extra dict is ok. """ tree = parse(dedent("""\ import logging class CustomException(Exception): def __init__(self, custom_arg): self.cu...
5,326,165
def solve2(input_data): """use scipy.ndimage""" data_array = np.array(parse(input_data)) # boundaries of objects must be 0 for scipy label # convert 0 in data to -1 and 9 to 0 data_array[data_array == 0] = -1 data_array[data_array == 9] = 0 labels, _ = label(data_array) _, counts = n...
5,326,166
def yolox_semi_warm_cos_lr( lr, min_lr_ratio, warmup_lr_start, total_iters, normal_iters, no_aug_iters, warmup_total_iters, semi_iters, iters_per_epoch, iters_per_epoch_semi, iters, ): """Cosine learning rate with warm up.""" min_lr = lr * min_lr_ratio ...
5,326,167
def command_hash(user: UserMessages, m: MicroPythonRepl, args): """\ Get hash of files on the targets file system. """ for path in expand_pattern(connect_repl(args.PATH, m)): if path.is_dir(): if args.recursive: for dirpath, dirnames, filenames in walk(path): ...
5,326,168
def builder(obj, dep, denominator=None): """ A func that modifies its obj without explicit return. """ def decorate(func): tasks.append(Builder(func, obj, dep, denominator)) return func return decorate
5,326,169
def regex_split(input_string=None, regex=None, strip_whitespace=None, **kwargs): """ Use a regular expression to split an input_string into multiple items. Args: input_string (CEF type: *): The input string to split. regex: The regular expression to use to split the string. Reserved reg...
5,326,170
def configure_for_tests(): """Set logger for tests.""" set_logger(logging.getLogger()) logging.basicConfig() _logger.setLevel(logging.INFO)
5,326,171
def on_segment(p, r, q, epsilon): """ Given three colinear points p, q, r, and a threshold epsilone, determine if determine if point q lies on line segment pr """ # Taken from http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment cr...
5,326,172
def groupby_times(df, kind, unit=None): """Groupby specific times Parameters ---------- df : pandas.DataFrame DataFrame with `pandas.TimedeltaIndex` as index. kind : {'monthly', 'weekly', 'daily', 'hourly', 'minutely', 'all'} How to group `df`. unit : str (optional) What...
5,326,173
def pid_to_path(pid): """Returns the full path of the executable of a process given its pid.""" ps_command = "ps -o command " + pid ps_output = execute(ps_command) command = get_command(ps_output) whereis_command = "whereis " + command whereis_output = execute(whereis_command) path = get_path(whe...
5,326,174
def get_script_histogram(utext): """Return a map from script to character count + chars, excluding some common whitespace, and inherited characters. utext is a unicode string.""" exclusions = {0x00, 0x0A, 0x0D, 0x20, 0xA0, 0xFEFF} result = {} for cp in utext: if ord(cp) in exclusions: ...
5,326,175
def ja_nein_vielleicht(*args): """ Ohne Argumente erstellt diese Funktion eine Ja-Nein-Vielleicht Auswahl. Mit einem Argument gibt es den Wert der entsprechenden Auswahl zurück. """ values = { True: "Vermutlich ja", False: "Vermutlich nein", None: "Kann ich noch nicht sagen" ...
5,326,176
def to_sql(query, df, ini_path=PATH.INI_FILE): """SQL 쿼리를 실행하여 DB에 데이터를 입력 :param str query: 쿼리 :param :class:`pandas.DataFrame` df: 입력할 데이터 :param str ini_path: ini file 경로, default: ``PATH.INI_FILE`` """ list_of_tuples = list(map(tuple, df.values)) DBHandler(ini2dict(ini_path, 'DB')).to_s...
5,326,177
def ebic(covariance, precision, n_samples, n_features, gamma=0): """ Extended Bayesian Information Criteria for model selection. When using path mode, use this as an alternative to cross-validation for finding lambda. See: "Extended Bayesian Information Criteria for Gaussian Graphical Mode...
5,326,178
def register_function(name, func, tagging_func, example_args, params_index, precedence): """Registers a function as a pattern in the graph matcher registry. The graph matcher needs to trace at least once the full function, which means you need to provide it with dummy arguments. The shapes ...
5,326,179
def _process_cli_plugin(bases, attrdict) -> dict: """Process a CLI plugin, generate its hook functions, and return a new attrdict with all attributes set correctly. """ attrdict_copy = dict(attrdict) # copy to avoid mutating original if cli.Command in bases and cli.CommandExtension in bases: ...
5,326,180
def get_group(yaml_dict): """ Return the attributes of the light group :param yaml_dict: :return: """ group_name = list(yaml_dict["groups"].keys())[0] group_dict = yaml_dict["groups"][group_name] # Check group_dict has an id attribute if 'id' not in group_dict.keys(): prin...
5,326,181
def close_db(error): """Zamykanie połączenia z bazą.""" if hasattr(g, 'db'): g.db.close()
5,326,182
def plot_time( monitors, labels, savefile, title="Average computation time per epoch", ylabel="Seconds", log=False, directory=DEFAULT_DIRECTORY, ): """Plots the computation time required for each step as a horizontal bar plot :param monitors: a list of monitor sets: [(training,...
5,326,183
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradi...
5,326,184
def recommend(model): """ Generate n recommendations. :param model: recommendation model :return: tuple(recommendations made by model, recommendations made by primitive model, recall, coverage) """ n = 10 hit = 0 # used for recall calculation total_recommendations = 0 all_recommend...
5,326,185
def GetTrace(idp_name, package_name, version, launcher_activity, proxy_port, \ change_account=True, with_access_token=True, revoke_access_token=True, reset=False, \ uiconfig='uiaction.json', user='Eve1', port='4723', system_port=8200, tracefile='eveA.trace', \ emulator_name=None, snapshot_tag=None): """...
5,326,186
def drop_nondominant_term(latex_dict: dict) -> str: """ given x = \\langle\\psi_{\\alpha}| \\hat{A} |\\psi_{\\beta}\\rangle return x = \\langle\\psi_{\\alpha}| a_{\\beta} |\psi_{\\beta} \\rangle >>> latex_dict = {} >>> latex_dict['input'] = [{'LHS': parse_latex(''), 'RHS': parse_latex('')}]...
5,326,187
def exampleCallback(**kwargs): """ kwargs hasgi event = event trigger hidDevice = trigger device buttonId = tigger button ID eventTypes = all registered event types eventCount = Number of times even occured TODO: Add timers """ print(kwargs["action"],":",kwargs["hidDevice"].getNa...
5,326,188
def template_introduce(): """ This function constructs three image carousels for self introduction. Check also: faq_bot/model/data.py reference - `Common Message Property <https://developers.worksmobile.com/kr/document/100500805?lang=en>`_ :return: image carousels type message content....
5,326,189
def assign_distance_to_mesh_vertex(vkey, weight, target_LOW, target_HIGH): """ Fills in the 'get_distance' attribute for a single vertex with vkey. Parameters ---------- vkey: int The vertex key. weight: float, The weighting of the distances from the lower and the upper target, ...
5,326,190
def _get_user_by_email_or_username(request): """ Finds a user object in the database based on the given request, ignores all fields except for email and username. """ if 'email_or_username' not in request.POST or 'password' not in request.POST: raise AuthFailedError(_('There was an error receivi...
5,326,191
def test__apply_with_missing_info(test_teardown): """ Failure scenario: Missing information should throw errors. """ user_id = "someid456" url, position, company = "", "", "" result = apply_external(user_id, url, position, company, resume, date_posted, deadline, comment) assert result['stat...
5,326,192
def timer(save=False, precision=3): """ Timer Decorator with Logging """ def decorator(function): @wraps(function) def inner(*args, **kwargs): start = default_timer() value = function(*args, **kwargs) end = default_timer() if save: ...
5,326,193
def get_minsize_assignment(N, min_comm_size): """Create membership vector where each community contains at least as a certain number of nodes. Parameters ---------- N : int Desired length of membership vector min_comm_size : int Minimum number of nodes each community should have...
5,326,194
def _combine_plots( p1, p2, combine_rules=None, sort_plot=False, sort_key=lambda x_y: x_y[0] ): """Combine two plots into one, following the given combine_rules to determine how to merge the constants :param p1: 1st plot to combine :param p2: 2nd plot to combine :param combine_rules:...
5,326,195
def shape_of(array, *, strict=False): """ Return the shape of array. (sizes of each dimension) """ shape = [] layer = array while True: if not isinstance(layer, (tuple, list)): break size = len(layer) shape.append(size) if not size: break ...
5,326,196
def ingest(study_dir, log_level): """ Ingest a study into the Kids First OMOP db \b Arguments: \b study_dir - Path to study directory containing extract_configs dir """ from common import etl # Setup logging output_dir = _setup_output_and_logging(study_dir, log_level) ...
5,326,197
def return_state_dict(network): """ save model to state_dict """ feat_model = {k: v.cpu() for k, v in network["feat_model"].state_dict().items()} classifier = {k: v.cpu() for k, v in network["classifier"].state_dict().items()} return {"feat_model": feat_model, "classifier": classifier}
5,326,198
def assert_allclose( actual: Tuple[float, float], desired: Tuple[numpy.float64, numpy.float64], err_msg: Literal["(-1.0,) d ['double']"], ): """ usage.scipy: 1 """ ...
5,326,199