content
stringlengths
22
815k
id
int64
0
4.91M
def get_unique_filepath(stem): """NOT thread-safe! return stems or stem# where # is the smallest positive integer for which the path does not exist. useful for temp dirs where the client code wants an obvious ordering. """ fp = stem if os.path.exists(stem): n = 1 fp = ste...
5,325,000
def write_h5_header(hf, run_params, model): """Write header information about the run. """ serialize = {'run_params': run_params, 'model_params': [functions_to_names(p.copy()) for p in model.config_list], 'paramfile_text': paramfile_string(**run_params)} for k, v in lis...
5,325,001
def optimize_model(input, model_type='bert', num_heads=0, hidden_size=0, optimization_options=None, opt_level=None, use_gpu=False, only_onnxruntime=False): """ Optimize Model by OnnxR...
5,325,002
def transect_rotate(adcp_transect,rotation,xy_line=None): """ Calculates all possible distances between a list of ADCPData objects (twice...ineffcient) Inputs: adcp_obs = list ADCPData objects, shape [n] Returns: centers = list of centorids of ensemble locations of input ADCPData object...
5,325,003
def F(x, t, *args, **kwds): """ F(x) = ddx """ return -kwds.get('μ', 1) * x / np.sum(x**2)**(3/2)
5,325,004
def test_granule_id(granule: Granule, expected_result: str): """Check that the granule id is correct.""" assert granule.granule_id == expected_result
5,325,005
def get_capacity_potential_per_country(countries: List[str], is_onshore: float, filters: Dict, power_density: float, processes: int = None): """ Return capacity potentials (GW) in a series of countries. Parameters ---------- countries: List[str] List o...
5,325,006
def all_statements(tree: ast.AST) -> Set[ast.stmt]: """ Return the set of all ast.stmt nodes in a tree. """ return {node for node in ast.walk(tree) if isinstance(node, ast.stmt)}
5,325,007
def calc_predicted_points_for_pos( pos, gw_range, team_model, player_model, season, tag, session ): """ Calculate points predictions for all players in a given position and put into the DB """ predictions = {} df_player = None if pos != "GK": # don't calculate attacking points for keepe...
5,325,008
def test_cache_catches_nothing(client): """ GIVEN a cache of last found secrets same as config ignored-matches WHEN I run a scan (therefore finding no secret) THEN config matches is unchanged and cache is empty """ c = Commit() c._patch = _MULTIPLE_SECRETS config = Config() config.ma...
5,325,009
def resmgr_cli(): """ Managing processor resources """ initLogging()
5,325,010
def image_preprocess2(img): """ image preprocess version 2 using: yellow threshold, white threshold, sobelX, sobelY, ROI Parameters ---------- img: image (np.array()) Return ---------- the source points """ # set white and yellow threshold ...
5,325,011
def get_all_feeds(cb: CbThreatHunterAPI, include_public=True) -> Dict: """Retrieve all feeds owned by the caller. Provide include_public=true parameter to also include public community feeds. """ url = f"/threathunter/feedmgr/v2/orgs/{cb.credentials.org_key}/feeds" params = {"include_public": inclu...
5,325,012
def spkltc( targ: int, et: float, ref: str, abcorr: str, stobs: ndarray ) -> Tuple[ndarray, float, float]: """ Return the state (position and velocity) of a target body relative to an observer, optionally corrected for light time, expressed relative to an inertial reference frame. https://naif....
5,325,013
def test_calculate_angle_90(): """Test the calculate_distance function""" r1 = np.array([1,0,0]) r2 = np.array([0,0,0]) r3 = np.array([0,1,0]) expected_theta = (math.pi) / 2 calculated_theta = geometry_analysis.calculate_angle(r1, r2, r3) assert expected_theta == calculated_theta
5,325,014
def mode(bot, trigger): """Set a user mode on Sopel. Can only be done in privmsg by an admin.""" mode = trigger.group(3) if not mode: bot.reply('What mode should I set?') bot.write(('MODE', bot.nick, mode))
5,325,015
def remove_outlier_from_time_average(df, time=4, multiplier=3): """ Remove outliers when averaging transients before performing the fitting routines, used to improve the signal to noise ratio in low biomass systems. The function sets a time window to average over, using upper and lower limits for outl...
5,325,016
def main(): """Start up NagCat, profiling things as requested""" options = parse_options() if options.profile_init or options.profile_run: import cProfile profiler = cProfile.Profile() if options.profile_init: profiler.runcall(init, options) else: init(options) ...
5,325,017
def on_backtest_finished(context, indicator): """ :param context: :param indicator: https://www.myquant.cn/docs/python/python_object_trade#bd7f5adf22081af5 :return: """ logger = context.logger logger.info(str(indicator)) logger.info("回测结束 ... ") cash = context.account().cash...
5,325,018
def parse_tb_file(path, module): """ Parse a translation block coverage file generated by S2E's ``TranslationBlockCoverage`` plugin. """ with open(path, 'r') as f: try: tb_coverage_data = json.load(f) except Exception: logger.warning('Failed to parse translati...
5,325,019
def load(filename): """ Load nifti2 single or pair from `filename` Parameters ---------- filename : str filename of image to be loaded Returns ------- img : Nifti2Image or Nifti2Pair nifti2 single or pair image instance Raises ------ ImageFileError: if `filenam...
5,325,020
def run_sklearn(args, out_dir, out_flp, ldrs): """ Trains an sklearn model according to the supplied parameters. Returns the test error (lower is better). """ # Unpack the dataloaders. ldr_trn, _, ldr_tst = ldrs # Construct the model. print("Building model...") net = models.MODELS[ar...
5,325,021
def create_softmax_loss(scores, target_values): """ :param scores: [batch_size, num_candidates] logit scores :param target_values: [batch_size, num_candidates] vector of 0/1 target values. :return: [batch_size] vector of losses (or single number of total loss). """ return tf.nn.softmax_cross_en...
5,325,022
def predict_8_bit_rgb(image_path, model_weights_path, output_json_path): """ Sample call: python3 classifier.py predict-8-bit-rgb sample_images/15OCT22183656-S2AS_R5C4-056155973040_01_P001_8_bit.jpg /data/working/ALL_IN_ONE/model_weights/model_2/weights_for_epoch_29.h5 annotation.json """ gpu_number...
5,325,023
def page_not_found(e): """ Catches 404 errors and render a 404 page stylized with the design of the web app. Returns 404 static page. """ return render_template('404.html'), 404
5,325,024
def effort_remaining_after_servicing_tier_2_leads(): """ Real Name: Effort Remaining after Servicing Tier 2 Leads Original Eqn: MAX(Effort Remaining after Servicing Existing Clients - Effort Devoted to Tier 2 Leads, 0) Units: Hours/Month Limits: (None, None) Type: component Subs: None H...
5,325,025
def sliceThreshold(volume, block_size = 5): """ convert slice into binary using adaptive local ostu method volume --- 3D volume block_size --- int value """ if type(volume) != np.ndarray: raise TypeError('the input must be numpy array!') x, y, z = volume.shape ...
5,325,026
def rastrigin_d_dim(x: chex.Array) -> chex.Array: """ D-Dim. Rastrigin function. x_i ∈ [-5.12, 5.12] f(x*)=0 - Minimum at x*=[0,...,0] """ A = 10 return A * x.shape[0] + jnp.sum(x ** 2 - A * jnp.cos(2 * jnp.pi * x))
5,325,027
def v(tag, message): # pylint: disable=invalid-name """Print a verbose message (non-debug)""" date = __get_date() if LOG_LEVEL_STDOUT >= 4: __log_to_stdout(colors.COLOR_VERB, date, tag+"/V", message) if LOG_LEVEL_FILE >= 4: __log_to_file(date, tag+"/V", message)
5,325,028
def fMaxConfEV(arr3_EvtM_bol, arr3_Evt, arr3_Conf): """ Return highest confidence and its corresponding timing, given arr3_EvtM_bol already masked to year of interest. Something in this fuction or calling it is broken. """ print('\t\tStats (max conf)...', end='') arr3_ConfM...
5,325,029
def set_infosec (db, cl, nodeid, new_values) : """ When going from open->approving, set the infosec attributes on the PR """ apr = db.pr_status.lookup ('approving') opn = db.pr_status.lookup ('open') ost = cl.get (nodeid, 'status') nst = new_values.get ('status', ost) if ost != opn o...
5,325,030
def regex_validation_recursion(node: dict) -> (bool, str): """ Validates the regex inside a singular node of a Spcht Descriptor :param dict node: :return: True, msg or False, msg if any one key is wrong :rtype: (bool, str) """ # * mapping settings if 'map_setting' in node: if '$...
5,325,031
def get_beat_times(audio_file, beats_folder, include_beat_numbers=False): """ Read beat times from annotation file. :param audio_file: path to audio files :param beats_folder: folder with preanalysed beat times (in .beats.txt format per track) :return: beat times in seconds """ file_name = ...
5,325,032
def build_probability_matrix(graph): """Get square matrix of shape (n, n), where n is number of nodes of the given `graph`. Parameters ---------- graph : :class:`~gensim.summarization.graph.Graph` Given graph. Returns ------- numpy.ndarray, shape = [n, n] Eigenvector of...
5,325,033
def clear_config_except_panel_css(): """Reset pn.config except for panel css""" # pylint: disable=protected-access pn.config.raw_css = [] pn.config.js_files = {} pn.config.css_files = [ file for file in pn.config.css_files if TemporaryResources._is_panel_style_file(file) ]
5,325,034
def test_im_templates(self): """Test appropriate selection of templates for the IM for 1.11.0.0.""" post_setup(self) with open(self.config, "r") as c: with open(self.updated_config, "w") as n: for line in c: if "<information_model>1.5.0.0</information_model>" in line: ...
5,325,035
def create_image_parser(subparsers): """Create the argument parser for ``openproblems-cli image``.""" parser = subparsers.add_parser( "image", help="Fetch a Docker image associated with a function" ) parser.add_argument( "-t", "--task", type=str, help="Select func...
5,325,036
def yuanshanweir_transfer_loss_amount(): """ Real Name: YuanShanWeir Transfer Loss Amount Original Eqn: (Tranfer From YuanShanWeir To DaNanWPP+Transfer From YuanShanWeir To BanXinWPP)/(1-WPP Transfer Loss Rate)*WPP Transfer Loss Rate Units: m3 Limits: (None, None) Type: component Subs: None ...
5,325,037
def create_request(request: Request) -> Request: """Create a database entry (mongo Document based Request object) from a brewtils Request model object. Some transformations happen on a copy of the supplied Request prior to saving it to the database. The returned Request object is derived from this trans...
5,325,038
def _gifti_to_array(gifti): """ Converts tuple of `gifti` to numpy array """ return np.hstack([load_gifti(img).agg_data() for img in gifti])
5,325,039
def learn_naive_factorization( data: np.ndarray, distributions: List[Type[Leaf]], domains: List[Union[list, tuple]], scope: List[int], learn_leaf_func: LearnLeafFunc, **learn_leaf_kwargs ) -> Node: """ Learn a leaf as a naive factorized model. :param data: The data. :param distr...
5,325,040
def opt_IA_search_assist(fun, lbounds, ubounds, budget): """Efficient implementation of uniform random search between `lbounds` and `ubounds` """ lbounds, ubounds = np.array(lbounds), np.array(ubounds) dim, x_min, f_min = len(lbounds), None, None opt_ia = optIA.OptIA(fun, lbounds, ubounds, ssa=...
5,325,041
def load_investigation(fp): """Used for rules 0005 :param fp: A file-like buffer object pointing to an investigation file :return: Dictionary of DataFrames for each section """ def check_labels(section, labels_expected, df): """Checks each section is syntactically structured correctly ...
5,325,042
def _fi18n(text): """Used to fake translations to ensure pygettext retrieves all the strings we want to translate. Outside of the aforementioned use case, this is exceptionally useless, since this just returns the given input string without any modifications made. """ return text
5,325,043
def animate(dlist, tlist, mlist): """function to move or animate objects on screen""" # fixation_cross() for d in dlist: d.detect_collision(mlist) d.draw_circle(win) for t in tlist: t.detect_collision(mlist) t.draw_circle(win) """for d in dlist: for t in tlist...
5,325,044
def is_required_version(version, specified_version): """Check to see if there's a hard requirement for version number provided in the Pipfile. """ # Certain packages may be defined with multiple values. if isinstance(specified_version, dict): specified_version = specified_version.get("versio...
5,325,045
def draw_tree(artist, colors, start_size = 20): """this function draws the christmas tree""" while start_size != 0: draw_row(artist, start_size, colors[20-start_size]) move_up_row(artist, start_size) start_size -= 1
5,325,046
async def cmd_project_uninstall(ls: TextXLanguageServer, params) -> bool: """Command that uninstalls a textX language project. Args: params: project name Returns: True if textX project is uninstalled successfully, otherwise False Raises: None """ project_name = params[0...
5,325,047
def test_timespan_args_week_str_and_thru_str(): """Tests timespan arguments: week_str, thru_str. """ start, end = timespan(week_str=REF_BEGIN_ISO, thru_str=REF_THRU_STR) begin = datetime.fromisocalendar(2020, 10, 1).astimezone() assert isinstance(start, datetime) assert start.isoformat() == beg...
5,325,048
def _check_load_mat(fname, uint16_codec): """Check if the mat struct contains 'EEG'.""" read_mat = _import_pymatreader_funcs('EEGLAB I/O') eeg = read_mat(fname, uint16_codec=uint16_codec) if 'ALLEEG' in eeg: raise NotImplementedError( 'Loading an ALLEEG array is not supported. Please...
5,325,049
def local_desired_velocity(env, veh_ids, fail=False): """ Encourage proximity to a desired velocity. We only observe the velocity of the specified car. If a collison or failure occurs, we return 0. """ vel = np.array(env.k.vehicle.get_speed(veh_ids)) num_vehicles = len(veh_ids) if any...
5,325,050
def All(q, value): """ The All operator selects documents where the value of the field is an list that contains all the specified elements. """ return Condition(q._path, to_refs(value), '$all')
5,325,051
def download_dataset(local: bool = True): """ :param local: on a local machine only use subset of the data. on a server uses full dataset """ base_data_dir = "./data" dataset_dir = base_data_dir + "/celeba_dataset_medium" # Create the directories if necessary if not os.path.exists(base_data...
5,325,052
def key(i): """ Helper method to generate a meaningful key. """ return 'key{}'.format(i)
5,325,053
def pool_metatile_batch(pool, fn, metatiles, size): """ Use the pool 'pool' (a multiprocessing.Pool) to execute 'fn' on 'metatiles' batched into 'size' batches. """ pool.map(fn,metatile_batches(metatiles, size))
5,325,054
def patch(): """monkey-patch class methods in web/form.py""" # update the render methods web.form.Form.render = Form.__dict__['render'] web.form.Form.rendernote = Form.__dict__['rendernote'] web.form.Input.render = Input.__dict__['render'] web.form.File.render = File.__dict__['render'] web.form.Textarea.r...
5,325,055
def svn_repos_fs_change_rev_prop3(*args): """ svn_repos_fs_change_rev_prop3(svn_repos_t repos, svn_revnum_t rev, char author, char name, svn_string_t new_value, svn_boolean_t use_pre_revprop_change_hook, svn_boolean_t use_post_revprop_change_hook, svn_repos_authz_func_t authz_read_...
5,325,056
def read_dir(p: Path): """ Recursively read through a directory and subdirectories For each pdf file found, extract PFT results by calling parse_pdf() """ logging.info('Reading {0}'.format(p.name)) for f in p.glob('*.pdf'): if 'TREND' in str(f): continue parse_pdf(f, Parsetype.PT...
5,325,057
def test_extension(): """Basic test for flask extension.""" app = Flask(__name__) app.config['SWAG_TITLE'] = "Test application." app.config['SWAG_API_VERSION'] = '1.0.1' swag = Swag(app) with app.test_request_context('/swagger/swagger.json'): swagger_json = app.generate_swagger() ...
5,325,058
def session_travis(session): """On travis, just run with python3.4 and don't run slow or flaky tests.""" session_tests( session, 'python3.4', extra_pytest_args=['-m not slow and not flaky']) session_gae( session, extra_pytest_args=['-m not slow and not flaky'])
5,325,059
def pretty_ct(ct): """ Pretty-print a contingency table Parameters ---------- ct : the contingency table Returns ------- pretty_table : a fancier string representation of the table """ output = StringIO() rich_ct(ct).to_csv(output) output.seek(0) try...
5,325,060
def mark(symbol): """Wrap the symbol's result in a tuple where the first element is `symbol`. Used where the information about "which branch of the grammar was used" must be propagated upwards for further checks. """ def mark_action(x): return (symbol, x) return mark_action << symbol
5,325,061
def restore_dimensions(array, from_dims, result_like, result_attrs=None): """ Restores a numpy array to a DataArray with similar dimensions to a reference Data Array. This is meant to be the reverse of get_numpy_array. Parameters ---------- array : ndarray The numpy array from which to ...
5,325,062
def test_woe_mixed_vars(titanic): """Numeric and string data, with missings""" data = titanic target_var = 'Survived' explanatory = ['Age', 'Sex'] X = data[explanatory] y = data[target_var] woe_transformer = WoETransformer() woe_transformer.fit(X, y) woe_transformer.transform(X) ...
5,325,063
def _combine_qc_samples(samples): """Combine split QC analyses into single samples based on BAM files. """ by_bam = collections.defaultdict(list) for data in [utils.to_single_data(x) for x in samples]: batch = dd.get_batch(data) or dd.get_sample_name(data) if not isinstance(batch, (list,...
5,325,064
def prepare_outdir(): """ prepares the directory structure on disk, returns output directory as well as the s3 destination folder """ out_dir, s3_dest_folder = file_destination() if os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir) return out_dir, s3_des...
5,325,065
def doc( package_name: str, plugin_name: str, long_doc: bool = True, include_details: bool = False, ) -> str: """Document one plug-in Documentation is taken from the module doc-string. If the plug-in is not part of the package an UnknownPluginError is raised. Args: package_name...
5,325,066
def microsecond(dt): """:yaql:property microsecond Returns microseconds of given datetime. :signature: datetime.microsecond :returnType: integer .. code:: yaql> datetime(2006, 11, 21, 16, 30, 2, 123).microsecond 123 """ return dt.microsecond
5,325,067
def decompose_label_vector(label_vector, n_xgrids, n_ygrids, mean_lwh, xlim=(0.0, 70.0), ylim=(-50.0,50.0), zlim=(-10.0,10.0), conf_thres=0.5, nms=True, iou_thres=0.1): """ Build the ground-truth label vector given a set of poses, classes, and ...
5,325,068
def gen_delay_phs(fqs, ants, dly_rng=(-20, 20)): """ Produce a set of mock complex phasors corresponding to cables delays. Args: fqs (array-like): shape=(NFREQS,), GHz the spectral frequencies of the bandpasses ants (iterable): the indices/names of the antennas ...
5,325,069
def test_genitive_complements(): """Test whether "berauben" is in the list of verbs that can take genitive complements""" genitive_complements = germanet_data.frames.extract_gentive_complement() berauben = germanet_data.get_lexunit_by_id('l74138') np.testing.assert_equal(berauben in genitive_complements...
5,325,070
def convOutp(images, hidSums, targets, numModulesX, paddingStart, filterSizeX, moduleStride, numImgColors): """ images - (n_images, img_w**2 * n_chans) hidSums - (n_images, n_locs**2 * n_filters) targets - (n_filters, filter_w**2 * n_chans) """ numGroups = 1 partialSum = 0 numImages = images.shape[0] ...
5,325,071
def sharpen(img, bg=None, t='laplace', blur_radius=30, blur_guided_eps=1e-8, use_guidedfilter='if_large_img'): """Use distortion model to deblur image. Equivalent to usharp mask: 1/t * img - (1-1/t) * blurry(img) Then, apply guided filter to smooth result but preserve edges. img - im...
5,325,072
def mypy(_): """Run mypy optional static type checker""" pass
5,325,073
def what_to_add(qtype, origword, newword, terminate): """Return a qtype that is needed to finish a partial word. For example, given an origword of '\"frog' and a newword of '\"frogston', returns either: terminate=False: 'ston' terminate=True: 'ston\"' This is useful when calculating tab...
5,325,074
def test_kwargs() -> None: """Test functionality when signature uses ``**kwargs``. """ @argcomb(a="b") def f(**kwargs: Any) -> None: ... f(a=1, b=1) f(b=1, c=1) with pytest.raises(InvalidArgumentCombination): f(a=1)
5,325,075
def intersect(start1, end1, start2, end2): """Return the intersection point of two lines, else return None. Ideas: For parallel lines to intercept (equal slope and y-intercept), they must be overlapping segments of the same infinite line. Intersection point is given by solving line equation 1 =...
5,325,076
def start(update, context): """Displays welcome message.""" # choose_lang = True # If we're starting over we don't need do send a new message if not context.user_data.get(START_OVER): user = update.message.from_user try: context.user_data[LANG] = user.language_code ...
5,325,077
def model_dir_str(model_dir, hidden_units, logits, processor=lambda: pc.IdentityProcessor(), activation=tf.nn.relu, uuid=None): """Returns a string for the model directory describing the network. Note that it only stores the information that describes the layout of the network - in partic...
5,325,078
def validate_search_inputs(row_id, search_column, search_value): """Function that determines if row_id, search_column and search_value are defined correctly""" return_value = { "valid": True, "msg": None } a_search_var_defined = True if search_column or search_value else False if r...
5,325,079
def B1(i,n,t): """Restituisce il polinomio di Bernstein (i,n) valutato in t, usando la definizione binomiale""" if i < 0 or i > n: return 0 return binom(n,i)* t**i * (1-t)**(n-i)
5,325,080
def tint(bot, update, args): """Set background tint percentage.""" usrin = 100 - int(args[0]) # invert percentage usrin = 'back@{},{},{}'.format( int(usrin * 2.56), int(usrin * 2.56), int(usrin * 2.56)) # format string to be passed to handler update.message.reply_text(colorSplit(usrin)...
5,325,081
def get_text_between(text, before_text, after_text): """Return the substring of text between before_text and after_text.""" pos1 = text.find(before_text) if pos1 != -1: pos1 += len(before_text) pos2 = text.find(after_text, pos1) if pos2 != -1: return text[pos1:pos2].strip...
5,325,082
def test_open_group_from_paths(zarr_version): """Verify zarr_version is applied to both the store and chunk_store.""" store = tempfile.mkdtemp() chunk_store = tempfile.mkdtemp() atexit.register(atexit_rmtree, store) atexit.register(atexit_rmtree, chunk_store) path = 'g1' g = open_group(store...
5,325,083
def configure_mq_backend(admin_user: str, admin_pass: str, config_path: str = None, run_rabbit_mq: bool = True, allow_bind_existing: bool = False, url: str = "http://0.0.0.0:15672", services: dic...
5,325,084
def add_video(eplist, playlist, current_playlist, var): """Add video to playlist being created.""" current = eplist.get(ACTIVE) playlist.insert(END, current) current_playlist.append(current) # adds the video to playback list. var.set(1)
5,325,085
def avi_common_argument_spec(): """ Returns common arguments for all Avi modules :return: dict """ credentials_spec = dict( controller=dict(default=os.environ.get('AVI_CONTROLLER', '')), username=dict(default=os.environ.get('AVI_USERNAME', '')), password=dict(default=os.envir...
5,325,086
def _get_functional_form_section(input_string): """ grabs the section of text containing all of the job keywords for functional form of PIPs """ pattern = (escape('$functional_form') + LINE_FILL + NEWLINE + capturing(one_or_more(WILDCARD, greedy=False)) + escape('$end')...
5,325,087
async def test_select_source(hass, remote): """Test for select_source.""" await setup_samsungtv(hass, MOCK_CONFIG) assert await hass.services.async_call( DOMAIN, SERVICE_SELECT_SOURCE, {ATTR_ENTITY_ID: ENTITY_ID, ATTR_INPUT_SOURCE: "HDMI"}, True, ) # key and update ca...
5,325,088
def rfftn(a, s=None, axes=None): """Multi-dimensional discrete Fourier transform for real input. Compute the multi-dimensional discrete Fourier transform for real input. This function is a wrapper for :func:`pyfftw.interfaces.numpy_fft.rfftn`, with an interface similar to that of :func:`numpy.fft.rfftn...
5,325,089
async def ChannelLogoAPI( channel_id:str = Path(..., description='チャンネル ID 。ex:gr011'), ): """ チャンネルのロゴを取得する。 """ # チャンネル情報を取得 channel = await Channels.filter(channel_id=channel_id).get_or_none() # 指定されたチャンネル ID が存在しない if channel is None: raise HTTPException( status...
5,325,090
def ImportFromNpb( db: bytecode_database.Database, cmake_build_root: pathlib.Path ) -> int: """Import the cmake files from the given build root.""" bytecodes_to_process = FindBitcodesToImport(cmake_build_root) i = 0 with sqlutil.BufferedDatabaseWriter(db, max_buffer_length=10) as writer: for i, bytecode i...
5,325,091
def _partial_ema_scov_init(n_dim=None, r:float=0.025, n_emp=None, target:float=None)->dict: """ Initialize object to track partial moments r: Importance of current data point n_emp: Discouraged. Really only used for tests. This is the number of samples for which empirical is u...
5,325,092
def handle_enterprise_cookies_for_logistration(request, response, context): """ Helper method for setting or deleting enterprise cookies on logistration response. Arguments: request (HttpRequest): The request for the logistration page. response (HttpResponse): The response for the logistrat...
5,325,093
def inner(thing): """ one level """ if isinstance(thing, DataPackage): return thing, else: return list(thing)
5,325,094
def MPC_SendNFC_WUP_RES(did: Union[int, bytes] = 0xFF, crc: Union[int, bytes] = 0) -> None: """Sends WUP_RES response Parameters ---------- did : int or bytes, optional 1-byte DID crc : int or bytes, optional 2-byte CRC """ if isinstance(did, bytes): ...
5,325,095
def load_dataset(data_name): """Load dataset. Args: data_name (str): The name of dataset. Returns: dataset (pgl.dataset): Return the corresponding dataset, containing graph information, feature, etc. data_mode (str): Currently we have 's' and 'm' mode, which mean small dataset a...
5,325,096
def require_dataset(hdf5_data, path, shape, dtype, maxshape=(None)): """ Create or update a dataset, making sure that its shape is resized if needed Args: hdf5_data: object, an already opened hdf5 file path: string, the path to the dataset shape: tuple of integers, the shape of t...
5,325,097
def test_set_primary(email_factory): """ Setting an email as the primary should update all of the user's other email addresses to not be the primary. """ old = email_factory(is_primary=True) new = email_factory(is_primary=False, user=old.user) new.set_primary() old.refresh_from_db() ...
5,325,098
def findquote(lrrbot, conn, event, respond_to, query): """ Command: !findquote QUERY Section: quotes Search for a quote in the quote database. """ quotes = lrrbot.metadata.tables["quotes"] with lrrbot.engine.begin() as pg_conn: fts_column = sqlalchemy.func.to_tsvector('english', quotes.c.quote) query = sql...
5,325,099