content
stringlengths
22
815k
id
int64
0
4.91M
def print_ofpt_stats_reply(msg): """ Args: msg: OpenFlow message unpacked by python-openflow """ def print_ofpt_stats_reply_description(msg): """ Args: msg: OpenFlow message unpacked by python-openflow """ print('StatRes Type: OFPST_DESC') p...
6,000
def validate_logger(lname): """ Make sure the datalogger name (lname) is a valid datalogger in the current configuration. Raises: ValueError """ if lname in sy.loggers: pass else: print('Available logger names are {0}'.format(sy.loggers)) raise ValueError('No...
6,001
def computeAbsoluteMagnitudes(traj, meteor_list): """ Given the trajectory, compute the absolute mangitude (visual mangitude @100km). """ # Go though every observation of the meteor for i, meteor_obs in enumerate(meteor_list): # Go through all magnitudes and compute absolute mangitudes for...
6,002
def associate_routes(stack, subnet_list=()): """Add Route Association Resources.""" for association in subnet_list: stack.stack.add_resource( SubnetRouteTableAssociation( '{0}RouteAssociation'.format(association['name']), SubnetId=Ref(association['subnet']), ...
6,003
def list_tris_nibbles(fp, reg): """ Create TRIS functions for lower- and upper-nibbles only Input: - file pointer - TRIS register """ port = "PORT" + reg[4:] if port.endswith("IO"): port = "PORTA" fp.write("--\n") half = port + "_low_direction" fp.write("procedure " + ...
6,004
def map_parallel(function, xs): """Apply a remote function to each element of a list.""" if not isinstance(xs, list): raise ValueError('The xs argument must be a list.') if not hasattr(function, 'remote'): raise ValueError('The function argument must be a remote function.') # EXERCISE:...
6,005
def verify(medusaconfig, backup_name): """ Verify the integrity of a backup """ medusa.verify.verify(medusaconfig, backup_name)
6,006
def test_build_reader_antenna__geometry( num_lanes, lane, side, angle, width, offset, height, forward, pos): """ Validate that forward direction, right direction and position of the reader antenna are computed and set properly. """ # Define constant values for expected right_dir values: ...
6,007
def log_interp(x,y,xnew): """ Apply interpolation in logarithmic space for both x and y. Beyound input x range, returns 10^0=1 """ ynew = 10**ius(np.log10(x), np.log10(y), ext=3)(np.log10(xnew)) return ynew
6,008
def inten_sat_compact(args): """ Memory saving version of inten_scale followed by saturation. Useful for multiprocessing. Parameters ---------- im : numpy.ndarray Image of dtype np.uint8. Returns ------- numpy.ndarray Intensity scale and saturation of input. """...
6,009
def test_gtfeatures_to_variants(patient_37): """Test the function that parses variants dictionaries from patient's genomic features""" # GIVEN a patient containing 1 genomic feature (and one variant) gt_features = patient_37["patient"]["genomicFeatures"] assert len(gt_features) == 1 # WHEN gtfeatu...
6,010
def write_subjectvolume(fn, subjdict): """subjdict is a dictionary subid -> volume""" # read if os.path.exists(fn): with open(fn, 'rb') as f: subjectvolume = json.load(f) subjectvolume.update(subjdict) else: subjectvolume = subjdict with open(fn, 'wb') as f: ...
6,011
def iob_to_docs(input_data, n_sents=10, no_print=False, *args, **kwargs): """ Convert IOB files with one sentence per line and tags separated with '|' into Doc objects so they can be saved. IOB and IOB2 are accepted. Sample formats: I|O like|O London|I-GPE and|O New|B-GPE York|I-GPE City|I-GPE .|O...
6,012
def masseuse_memo(A, memo, ind=0): """ Return the max with memo :param A: :param memo: :param ind: :return: """ # Stop if if ind > len(A)-1: return 0 if ind not in memo: memo[ind] = max(masseuse_memo(A, memo, ind + 2) + A[ind], masseuse_memo(A, memo, ind + 1)) ...
6,013
def unique_pairs(bonded_nbr_list): """ Reduces the bonded neighbor list to only include unique pairs of bonds. For example, if atoms 3 and 5 are bonded, then `bonded_nbr_list` will have items [3, 5] and also [5, 3]. This function will reduce the pairs only to [3, 5] (i.e. only the pair in which the...
6,014
def permission(*perms: str): """ Decorator that runs the command only if the author has the specified permissions. perms must be a string matching any property of discord.Permissions. NOTE: this function is deprecated. Use the command 'permissions' attribute instead. """ def decorator(func): ...
6,015
def validate_script(value): """Check if value is a valid script""" if not sabnzbd.__INITIALIZED__ or (value and sabnzbd.filesystem.is_valid_script(value)): return None, value elif (value and value == "None") or not value: return None, "None" return T("%s is not a valid script") % value, ...
6,016
async def post_user(ctx: Context, user: MemberOrUser) -> t.Optional[dict]: """ Create a new user in the database. Used when an infraction needs to be applied on a user absent in the guild. """ log.trace(f"Attempting to add user {user.id} to the database.") payload = { 'discriminator': ...
6,017
def setup(app): """ Install the plugin. :param app: Sphinx application context. """ app.add_role('tl', tl_role) app.add_config_value('tl_ref_url', None, 'env') return
6,018
def create_preferences_docs(): """Create preferences docs from SETTINGS using a jinja template.""" sections = {} for setting in CORE_SETTINGS: schema = setting.schema() title = schema.get("title", "") description = schema.get("description", "") preferences_exclude = getattr(...
6,019
def delete(ids: List = Body(...)): """ Deletes from an embeddings index. Returns list of ids deleted. Args: ids: list of ids to delete Returns: ids deleted """ try: return application.get().delete(ids) except ReadOnlyError as e: raise HTTPException(status_c...
6,020
def main(): """ Simple Event Viewer """ events = None try: events = remote('127.0.0.1', EventOutServerPort, ssl=False, timeout=5) while True: event_data = '' while True: tmp = len(event_data) event_data += events.recv(numb=8192, timeout=1).decode('latin-1') if tmp == len(event_data): bre...
6,021
def test_slack_chart_alert( screenshot_mock, email_mock, create_alert_email_chart, ): """ ExecuteReport Command: Test chart slack alert """ # setup screenshot mock screenshot_mock.return_value = SCREENSHOT_FILE with freeze_time("2020-01-01T00:00:00Z"): AsyncExecuteReportScheduleComm...
6,022
def fsi_acm_up_profiler_descending(vp1, vp2, vp3): """ Description: Calculates the VEL3D Series A and L upwards velocity data product VELPTMN-VLU-DSC_L1 for the Falmouth Scientific (FSI) Acoustic Current Meter (ACM) mounted on a McLane profiler. Because of the orientation of th...
6,023
def colour_name(colour: Tuple[int, int, int]) -> str: """Return the colour name associated with this colour value, or the empty string if this colour value isn't in our colour list. >>> colour_name((1, 128, 181)) 'Pacific Point' >>> colour_name(PACIFIC_POINT) 'Pacific Point' """ ...
6,024
def score_fn(subj_score, comp_score): """ Generates the TextStim with the updated score values Parameters ---------- subj_score : INT The subjects score at the moment comp_score : INT The computer's score at the moment' Returns ------- score_stim : psychopy.visual.t...
6,025
def parse_write_beam(line): """ Write_beam (type -2) If btype = −2, output particle phase-space coordinate information at given location V3(m) into filename fort.Bmpstp with particle sample frequency Bnseg. Here, the maximum number of phase- space files which can be output is 100. Here, 40 and ...
6,026
def sleep(sleep_time=0.250): """Default sleep time to enable the OS to reuse address and port. """ time.sleep(sleep_time)
6,027
def add_column_opt(M_opt, tgt, src): """For a matrix produced by siqs_build_matrix_opt, add the column src to the column target (mod 2). """ M_opt[tgt] ^= M_opt[src]
6,028
def list_s3(bucket, prefix, ext=None): """Get listing of files on S3 with prefix and extension """ s3 = boto3.resource('s3') s3_bucket = s3.Bucket(bucket) if ext: ext = '.' + ext.lstrip('.') else: ext = '' for item in s3_bucket.objects.filter(Prefix=prefix): key = i...
6,029
def get_tone(pinyin): """Renvoie le ton du pinyin saisi par l'utilisateur. Args: pinyin {str}: l'entrée pinyin par l'utilisateur Returns: number/None : Si pas None, la partie du ton du pinyin (chiffre) """ # Prenez le dernier chaine du pinyin tone = pin...
6,030
def authIfV2(sydent, request, requireTermsAgreed=True): """For v2 APIs check that the request has a valid access token associated with it :returns Account|None: The account object if there is correct auth, or None for v1 APIs :raises MatrixRestError: If the request is v2 but could not be authed or the user...
6,031
def gen_rho(K): """The Ideal Soliton Distribution, we precompute an array for speed """ return [1.0/K] + [1.0/(d*(d-1)) for d in range(2, K+1)]
6,032
async def test_initialize_ncbi_blast(mock_blast_server): """ Using a mock BLAST server, test that a BLAST initialization request works properly. """ seq = "ATGTACAGGATCAGCATCGAGCTACGAT" assert await virtool.bio.initialize_ncbi_blast({"proxy": ""}, seq) == ("YA40WNN5014", 19)
6,033
def print_rules() -> None: """ Load a text files 'rules_eng.txt' saved inside the same directory. Open a second window. Returns ------- None. """ ruleWindow=tk.Toplevel() ruleWindow.title("How to play?") with open('rules_eng.txt') as f: gameRules=f.read() lbl_rules=...
6,034
def assert_array_max_ulp(a, b, maxulp=1, dtype=None): """ Check that all items of arrays differ in at most N Units in the Last Place. Parameters ---------- a, b : array_like Input arrays to be compared. maxulp : int, optional The maximum number of units in the last place that el...
6,035
def add_default_field_spec_settings(field_spec_model, field_spec_db_rec): """ Add default settings for field spec. :param field_spec_model: Internal rep of the field spec. :param field_spec_db_rec: The DB record for the field spec. """ base_settings_db = FieldSettingDb.objects.filter( av...
6,036
def Ambient_Switching(crop_PPFDmin, Trans, consumption): """ Inputs: consumption (returned from Light_Sel) """ #How much energy can you save if you switch off when ambient lighting is enough for plant needs? #Assume that when ambient is higher than max recommended PPFD, that the greenhouse is cloaked, allowin...
6,037
def callStructuralVariants(bam, reffa, wSizeMax, svLen, lengthWiggle, positionWiggle, basepairIdWiggle, mapq, secondary, duplicate, qcfail, margin, gapdistance, samples): """To identify structural variants from BAM alignments: 1. Find windows in each read that contain an excess of...
6,038
def get_numerical_gradient(position: np.ndarray, function: Callable[[np.ndarray], float], delta_magnitude: float = 1e-6) -> np.ndarray: """ Returns the numerical derivative of an input function at the specified position.""" dimension = position.shape[0] vec_low = np.zeros(di...
6,039
def plot_psd(dpl, *, fmin=0, fmax=None, tmin=None, tmax=None, layer='agg', ax=None, show=True): """Plot power spectral density (PSD) of dipole time course Applies `~scipy.signal.periodogram` from SciPy with ``window='hamming'``. Note that no spectral averaging is applied across time, as most ...
6,040
def stable_point(r): """ repeat the process n times to make sure we have reaches fixed points """ n = 1500 x = np.zeros(n) x[0] = np.random.uniform(0, 0.5) for i in range(n - 1): x[i + 1] = f(x[i], r) print(x[-200:]) return x[-200:]
6,041
def test_regexp_message(dummy_form, dummy_field, grab_error_message): """ Regexp validator should return given message """ validator = regexp("^a", message="foo") dummy_field.data = "f" assert grab_error_message(validator, dummy_form, dummy_field) == "foo"
6,042
def vary_on_headers(*headers): """ A view decorator that adds the specified headers to the Vary header of the response. Usage: @vary_on_headers('Cookie', 'Accept-language') def index(request): ... Note that the header names are not case-sensitive. """ def decorator(fu...
6,043
def load_frames( frame_dir: pathlib.Path, df_frames: pd.DataFrame, ) -> Dict[int, Dict[str, Union[str, np.ndarray]]]: """Load frame files from a directory. Args: frame_dir: Path to directory where frames are stored in a target class folder or background class folder df_frame...
6,044
def calc_Z(pattern): """Calculate Z values using Z-algorithm as in Gusfield""" Z = [] len_p = len(pattern) Z.append(len_p) Z.append(0) l=1 Z[1] = match(pattern, 0, 1) r = Z[1]+1 l = 1 for k in range(2, len_p): if k>r: zk = match(pattern,0, k) r = z...
6,045
def non_daemonic_process_pool_map(func, jobs, n_workers, timeout_per_job=None): """ function for calculating in parallel a function that may not be run a in a regular pool (due to forking processes for example) :param func: a function that accepts one input argument :param jobs: a list of input arg...
6,046
def register_commands(subparsers, context): """Register devtool subcommands from the package plugin""" if context.fixed_setup: parser_package = subparsers.add_parser('package', help='Build packages for a recipe', ...
6,047
def condense_alignment(outfile, aln_file, logger=lambda x: None): """Call viruses from the alignment file.""" pass
6,048
def test_output_simple(): """ Elbow should be at 2. """ X = np.array([10, 9, 3, 2, 1]) elbows, _ = select_dimension(X, n_elbows=1) assert_equal(elbows[0], 2)
6,049
def result_list_handler(*args: list, **kwargs) -> str: """ Handles the main search result for each query. It checks whether there are any result for this qeury or not. 1. If there was results, then it sorts and decorates the them. 2 Otherwise it shows a message containing there were no results f...
6,050
def flip_mask(mask, x_flip, y_flip): """ Args: mask: バイナリマスク [height, width] """ mask = mask.copy() if y_flip: mask = np.flip(mask, axis=0) if x_flip: mask = np.flip(mask, axis=1) return mask
6,051
def sbn2journal(sbn_record, permalink_template="http://id.sbn.it/bid/%s"): """ Creates a `dbmodels.Journal` instance out of a dictionary with metadata. :param record: the dictionary returned by `resolution.supporting_functions.enrich_metadata()` :return: an instance of `dbmodels.Journal` """ bi...
6,052
def run(rendering=True): """ Runs the balls demo, in which the robot moves according to random torques as 10 balls bounces around. You may run the executable roboball2d_balls_demo after install. Parameters ---------- rendering : renders the environment if True """ ...
6,053
def median(data): """Calculates the median value from |data|.""" data = sorted(data) n = len(data) if n % 2 == 1: return data[n / 2] else: n2 = n / 2 return (data[n2 - 1] + data[n2]) / 2.0
6,054
def test_regression_1(): """ Regression test for https://github.com/sjjessop/omnidice/issues/1 """ expr = (-dice.d6).explode() check_approx(expr, eval(repr(expr), dice.__dict__))
6,055
def evaluation(eval_loader, model, criterion, num_classes, batch_size, ep_idx, progress_log, scale, vis_params, batch_metrics=None, dataset='val', device=N...
6,056
def split_text_by_length(text: str, length: Optional[int] = None, # 方案一:length + delta delta: Optional[int] = 30, max_length: Optional[int] = None, # 方案二:直接确定长度上下限 min_length: Optional[int] = None, ...
6,057
def _tfidf_fit_transform(vectors: np.ndarray): """ Train TF-IDF (Term Frequency — Inverse Document Frequency) Transformer & Extract TF-IDF features on training data """ transformer = TfidfTransformer() features = transformer.fit_transform(vectors).toarray() return features, transformer
6,058
def _is_missing_sites(spectra: List[XAS]): """ Determines if the collection of spectra are missing any indicies for the given element """ structure = spectra[0].structure element = spectra[0].absorbing_element # Find missing symmeterically inequivalent sites symm_sites = SymmSites(structure...
6,059
def get_objects(params, meta): """ Retrieve a list of objects based on their upas. params: guids - list of string - KBase IDs (upas) to fetch post_processing - object of post-query filters (see PostProcessing def at top of this module) output: objects - list of ObjectData - see t...
6,060
def heat_transfer_delta(): """ :return: net - OpenModelica network converted to a pandapipes network :rtype: pandapipesNet :Example: >>> pandapipes.networks.simple_water_networks.heat_transfer_delta() """ return from_json(os.path.join(heat_tranfer_modelica_path, "delta.json"))
6,061
def test_list_decimal_max_length_nistxml_sv_iv_list_decimal_max_length_1_2(mode, save_output, output_format): """ Type list/decimal is restricted by facet maxLength with value 5. """ assert_bindings( schema="nistData/list/decimal/Schema+Instance/NISTSchema-SV-IV-list-decimal-maxLength-1.xsd", ...
6,062
def configure_pin_as_input(pin_number): """ :param pin_number: an integer """ GPIO.setup(pin_number, GPIO.IN)
6,063
def set_testcase_path(testcase_file_path): """ Set testcase path """ global tc_path tc_path = testcase_file_path
6,064
def extract(file_path, extract_path): """ Extract if exists. Args: file_path (str): Path of the file to be extracted extract_path (str): Path to copy the extracted files Returns: True if extracted successfully, False otherwise """ if (os.path.exists(file_path) and os.p...
6,065
def assert_if_provinces_have_no_cases_and_deaths(country: DataCollector, data: dict): """Check if the data contains all required provinces and that each province has an entry for 'cases' and 'deaths'. Assert if not.""" for p, p_info in country.provinces.items(): short_name = p_info['short_name'] ...
6,066
def parseMidi(midifile): """Take a MIDI file and return the list Of Chords and Interval Vectors. The file is first parsed, midi or xml. Then with chordify and PC-Set we compute a list of PC-chords and Interval Vectors. """ mfile = ms.converter.parse(midifile) mChords = mfile.chordify() chor...
6,067
def get_similarity(s1, s2): """ Return similarity of both strings as a float between 0 and 1 """ return SM(None, s1, s2).ratio()
6,068
def preCheck(path: str): """preCheck.""" if not os.path.exists(path): os.makedirs(path) else: print("dir is okay!")
6,069
def test_embed(): """ Test that embedding is treated like a Variable""" embed_dense = L.EmbedID(5, 10) embed_sparse = L.EmbedID(5, 10) embed_dense.W.data[:] = np.random.randn(5, 10).astype('float32') embed_sparse.W.data[:] = np.random.randn(5, 10).astype('float32') embed_sparse.W.data[:, 1:] /=...
6,070
def concrete_values_from_iterable( value: Value, ctx: CanAssignContext ) -> Union[None, Value, Sequence[Value]]: """Return the exact values that can be extracted from an iterable. Three possible return types: - ``None`` if the argument is not iterable - A sequence of :class:`Value` if we know the ...
6,071
def hatch_egg(*, egg_name: str, potion_name: str) -> NoReturn: """ Hatch an egg by performing an API request and echo the result to the terminal. """ requester = HatchRequester( egg_name=egg_name, hatch_potion_name=potion_name ) response: requests.Response = requester.post_ha...
6,072
def ReadSimInfo(basefilename): """ Reads in the information in .siminfo and returns it as a dictionary """ filename = basefilename + ".siminfo" if (os.path.isfile(filename)==False): print("file not found") return [] cosmodata = {} siminfofile = open(filename,"r") line = siminfofile.readline().strip().spl...
6,073
def quat_conjugate(quat_a): """Create quatConjugate-node to conjugate a quaternion. Args: quat_a (NcNode or NcAttrs or str or list or tuple): Quaternion to conjugate. Returns: NcNode: Instance with quatConjugate-node and output-attribute(s) Example: :: ...
6,074
def payment_successful(sender, **kwargs): """Успешный платёж. Списываем средства, начисляем баланс""" try: bill = Bill.objects.get(id=kwargs['InvId']) except ObjectDoesNotExist: return if bill.status != Bill.BILL_STATUS_UNPAID: return bill.client.balance_minutes += bill.min...
6,075
def askfont(): """ Opens a :class:`FontChooser` toplevel to allow the user to select a font :return: font tuple (family_name, size, \*options), :class:`~font.Font` object """ chooser = FontChooser() chooser.wait_window() return chooser.font
6,076
def load_data(train_file, test_file): """ The method reads train and test data from their dataset files. Then, it splits train data into features and labels. Parameters ---------- train_file: directory of the file in which train data set is located test_file: directory of the file in which ...
6,077
def split_dataset_random(data_path, test_size=0.2): """Split the dataset in two sets train and test with a repartition given by test_size data_path is a string test_size is a float between 0 and 1""" #Initialise list for the names of the files sample_name = [] #Get the file of the dataset fo...
6,078
def guide(batch_X, batch_y=None, num_obs_total=None): """Defines the probabilistic guide for z (variational approximation to posterior): q(z) ~ p(z|x) """ # we are interested in the posterior of w and intercept # since this is a fairly simple model, we just initialize them according # to our prior b...
6,079
def show_images_row(imgs, titles, rows=1): """ Display grid of cv2 images image :param img: list [cv::mat] :param title: titles :return: None """ assert ((titles is None) or (len(imgs) == len(titles))) num_images = len(imgs) if titles is None: titles = ['Image (%...
6,080
def downloads_dir(): """ :returns string: default downloads directory path. """ return os.path.expanduser('~') + "/Downloads/"
6,081
def get_namespace(Id=None): """ Gets information about a namespace. See also: AWS API Documentation Exceptions :example: response = client.get_namespace( Id='string' ) :type Id: string :param Id: [REQUIRED]\nThe ID of the namespace that you want to get informa...
6,082
def get_reddit_tables(): """Returns 12 reddit tables corresponding to 2016""" reddit_2016_tables = [] temp = '`fh-bigquery.reddit_posts.2016_{}`' for i in range(1, 10): reddit_2016_tables.append(temp.format('0' + str(i))) for i in range(10, 13): reddit_2016_tables.append(temp.format(...
6,083
def first_empty(): """Return the lowest numbered workspace that is empty.""" workspaces = sorted(get_workspace_numbers(get_workspaces().keys())) for i in range(len(workspaces)): if workspaces[i] != i + 1: return str(i + 1) return str(len(workspaces) + 1)
6,084
def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Demonstrate affect on SVM of removing a support vector' , formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-o', '--outfile', help='File to wri...
6,085
def get_local_tzone(): """Get the current time zone on the local host""" if localtime().tm_isdst: if altzone < 0: tzone = '+' + \ str(int(float(altzone) / 60 // 60)).rjust(2, '0') + \ str(int(float( ...
6,086
def subscribers_tables_merge(tablename1: Tablename, tablename2: Tablename, csv_path=csvpath, verbose=True): """ Сводит таблицы, полученные загрузчиком, в одну. Может принимать pandas.DataFrame или имя группы, в этом случае группа должна быть в списке групп, а соответствующий файл - в <csv_path> """ ...
6,087
def delete_api_key_v1(key_id: str) -> None: """Delete api key by key ID ONLY if it is not the last key on the chain Args: key_id: ID of api key to delete """ # Don't allow removal of reserved keys if key_id.startswith("SC_") or key_id.startswith("INTERCHAIN"): raise exceptions.Action...
6,088
def get_current_offset(session): """ For backfilling only, this function works with the init container to look up it's job_id so it can line that up with it's consumer group and offest so that we can backfill up to a given point and then kill the worker afterwards. """ if settings.JOB_ID is None...
6,089
def get_params(p1, p2, L): """ Return the curve parameters 'a', 'p', 'q' as well as the integration constant 'c', given the input parameters. """ hv = p2 - p1 m = p1 + p2 def f_bind(a): return f(a, *hv, L) def fprime_bind(a): return fprime(a, hv[0]) # Newton-Raphson algorithm to fin...
6,090
def _unpack(f): """to unpack arguments""" def decorated(input): if not isinstance(input, tuple): input = (input,) return f(*input) return decorated
6,091
def chain_rich(iterable: Iterable['WriteRichOp']) -> 'WriteRichOp': """Take an `iterable` of `WriteRich` segments and combine them to produce a single WriteRich operation.""" from .ops.classes import WriteRichOp return reduce(WriteRichOp.then, iterable)
6,092
def sum_plot_chi2_curve(bin_num, sum_bin, r_mpc, ax=None, cov_type='bt', label=None, xlabel=True, ylabel=True, show_bin=True, ref_sig=None): """Plot the chi2 curve.""" if ax is None: fig = plt.figure(figsize=(6, 6)) fig.subplots_adjust( left=0.165, bottom=0.13...
6,093
def configure_logger(): """Default log format""" log_header = "%(asctime)s [bold cyan]%(levelname)s[/] [yellow]-[/] [royal_blue1]%(name)s[/] [yellow]-[/]" log_body = "%(message)s [yellow]([/][chartreuse4]%(filename)s[/]:%(lineno)d[yellow])[/]" log_format = f"{log_header} {log_body}" logging.basicCon...
6,094
def compute_importance(model, sequences, tasks, score_type='gradient_input', find_scores_layer_idx=0, target_layer_idx=-2, reference_gc=0.46, reference_shuffle_type=None, num_refs_pe...
6,095
def test_check_non_existing() -> None: """Test a check on a non-existing column.""" class Schema(pa.SchemaModel): a: Series[int] @pa.check("nope") @classmethod def int_column_lt_100(cls, series: pd.Series) -> Iterable[bool]: return series < 100 err_msg = ( ...
6,096
def xy_slicing_animation(filename, Z_direction, number_slices, x_actual, y_actual, x_size, y_size): """XY Slicing Animation function depend on the number of slices input""" if Z_direction == "up": Z_dir = create_pslist.create_pslist(filename, x_size, y_size)[2] else: Z_dir = create_psli...
6,097
def update_user(user): """ 更新用户的账号信息 """ accounts = list(Account.query({'user': user})) u = User.query_one({'_id': user}) for key, value in accounts_summary(accounts).items(): setattr(u, key, value) u.num_accounts = len(accounts) u.num_exchanges = len(set(a.exchange for a in accounts)) ...
6,098
def fetch_url(url): """Fetches the specified URL. :param url: The URL to fetch :type url: string :returns: The response object """ return requests.get(url)
6,099