content
stringlengths
22
815k
id
int64
0
4.91M
def get_standard_dev_pkgs() -> set[str]: """Check the standard dev package locations for hutch-python""" pythonpath = os.environ.get('PYTHONPATH', '') if not pythonpath: return set() paths = pythonpath.split(os.pathsep) valid_paths = filter(not_ignored, paths) pkg_names = set(n.name for ...
5,332,200
def create_alert_from_slack_message(payload, time): """ Create a new raw alert (json) from the new alert form in Slack """ alert_json = {} values = payload['view']['state']['values'] for value in values: for key in values[value]: if key == 'severity': alert_js...
5,332,201
def generate(self): """generate card number that satisfies the Luhn's algorithm""" pass
5,332,202
def psd(buf_in, buf_out): """ Perform discrete fourier transforms using the FFTW library and use it to get the power spectral density. FFTW optimizes the fft algorithm based on the size of the arrays, with SIMD parallelized commands. This optimization requires initialization, so this is a factory ...
5,332,203
def get_cell_ids(num_celltypes=39): """get valid cell ids by removing cell types with missing data. Return: A cell id list. """ missing_ids = [8,23,25,30,32,33,34,35,38,39,17] return [item for item in list(range(1,num_celltypes+1)) if item not in missing_ids]
5,332,204
def test_from_storage_table(haiku_metadata): """Test the from_storage_table method.""" metadata = haiku_metadata.from_storage_table( { "PartitionKey": "FIVE", "RowKey": "1", "MaxID": 7, } ) assert metadata.size == HaikuKey.FIVE assert metadata.max_...
5,332,205
def limit_data(): """Slice data by dolphot values and recovered stars in two filters""" fmt = '{:s}_{:s}' filter1, filter2 = filters.value.split(',') selected = data[ (np.abs(data[fmt.format(filter1, 'VEGA')]) <= 60) & (np.abs(data[fmt.format(filter2, 'VEGA')]) <= 60) & (data[fmt...
5,332,206
def setup_app(app): """Initialize database extensions on application.""" # Set default configuration app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:////tmp/test.db') # Add extension CLI to application. app.cli.add_command(database) db.init_app(app)
5,332,207
def purge_versions(path, suffix, num_keep, reverse=False): """ Purge file versions created by get_versioned_path. Purge specified quantity in normal or reverse sequence. """ (base, ext) = os.path.splitext(path) re_strip_version = re.compile('(.*)-%s(-[0-9]*)?' % suffix) matched = re_strip_v...
5,332,208
def make_valance_getter( lexicon: Dict[str, float], lemmatize: bool = True, lowercase: bool = True, cap_differential: Optional[float] = C_INCR, ) -> Callable[[Token], float]: """Creates a token getter which return the valence (sentiment) of a token including the capitalization of the token. Arg...
5,332,209
def proper_units(text: str) -> str: """ Function for changing units to a better form. Args: text (str): text to check. Returns: str: reformatted text with better units. """ conv = { r"degK": r"K", r"degC": r"$^{\circ}$C", r"degrees\_celsius": r"$^{\circ}...
5,332,210
def coerce_number(value, convert = float): """ 将数据库字段类型转为数值类型 """ pattern = re.compile(r'^\d{4}(-\d\d){2}') format = '%Y-%m-%d %H:%M:%S' if isinstance(value, basestring) and pattern.match(value): #将字符串的日期时间先转为对象 try: mask = format[:len(value) - 2] value = datetime...
5,332,211
async def test_option_flow(hass): """Test config flow options.""" entry, _, _ = await setup_onvif_integration(hass) result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "onvif_devices" resul...
5,332,212
def create_credential_resolver(): """Create a credentials resolver for Localstack.""" env_provider = botocore.credentials.EnvProvider() default = DefaultCredentialProvider() resolver = botocore.credentials.CredentialResolver( providers=[env_provider, default] ) return resolver
5,332,213
def does_algorithm_implementation_have_capabilities_to_execute_parameter(parameter_kisao_id, algorithm_specs): """ Determine if an implementation of an algorithm has the capabilities to execute a model langugae Args: parameter_kisao_id (:obj:`str`): KiSAO id for an algorithm parameter algorithm...
5,332,214
def branch(_, verbose=False, no_stash=False): """ Creates a branch from a release tag for creating a new patch or minor release from that branch. """ _ensure_configured('release') from invoke_release.version import __version__ _standard_output('Invoke Release {}', __version__) _setup_task(...
5,332,215
def win_sparkle_set_app_details(company_name, app_name, app_version): """ Sets application metadata. Normally, these are taken from VERSIONINFO/StringFileInfo resources, but if your application doesn't use them for some reason, using this function is an alternative. note company_name and app_name...
5,332,216
def run_saliency(): """Method called when click saliency button""" print("Exec saliency code for explanation") output = XAI.run_saliency() print("run_saliency") update_state("xai_type", output.get("type")) if output.get("type") == "classification": _xai_saliency = output.get("saliency")...
5,332,217
def main(): """ This method allows the script to be run in stand alone mode. @return Exit code from running the script """ record = Record() result = record.Run() return result
5,332,218
def stamp_pixcov_from_theory(N,cmb2d_TEB,n2d_IQU=0.,beam2d=1.,iau=False,return_pow=False): """Return the pixel covariance for a stamp N pixels across given the 2D IQU CMB power spectrum, 2D beam template and 2D IQU noise power spectrum. """ n2d = n2d_IQU cmb2d = cmb2d_TEB assert cmb2d.ndim==4 ...
5,332,219
def format(): # noqa """Formats raw data Returns: None """ format_data()
5,332,220
def make_data_parallel(module, expose_methods=None): """Wraps `nn.Module object` into `nn.DataParallel` and links methods whose name is listed in `expose_methods` """ dp_module = nn.DataParallel(module) if expose_methods is None: if hasattr(module, 'expose_methods'): expose_methods ...
5,332,221
def model_creator(model_dict, X_train, y_train, rd=None, rev=None): """Returns a SVM classifier""" # Load model based on model_dict clf = model_loader(model_dict, rd, rev) # If model does not exist, train a new SVM if clf is None: clf = model_trainer(model_dict, X_train, y_train, rd, rev) ...
5,332,222
async def folder2azureblob(container_client_instance=None, src_folder=None, dst_blob_name=None, overwrite=False, max_concurrency=8, timeout=None ): """ Asynchronously upload a local folder (including its content) to Azure blob container :param containe...
5,332,223
def bert_predict(model, loader): """Perform a forward pass on the trained BERT model to predict probabilities on the test set. """ # Put the model into the evaluation mode. The dropout layers are disabled during # the test time. model.eval() all_logits = [] # For each batch in our test...
5,332,224
def write_v3dtxt(fname, trc, forces, freq=0, show_msg=True): """Write Visual3d text file from .trc and .forces files or dataframes. The .trc and .forces data are assumed to correspond to the same time interval. If the data have different number of samples (different frequencies), the data will be ...
5,332,225
def eval_input_fn(training_dir, params): """Returns input function that feeds the model during evaluation""" return _input_fn('eval')
5,332,226
def GNIs(features, labels, mode, params, config): """Builds the model function for use in an estimator. Arguments: features: The input features for the estimator. labels: The labels, unused here. mode: Signifies whether it is train or test or predict. params: Some hyperparameters as a dictionary....
5,332,227
def b58decode(v, length): """ decode v into a string of len bytes """ long_value = 0L for (i, c) in enumerate(v[::-1]): long_value += __b58chars.find(c) * (__b58base**i) result = '' while long_value >= 256: div, mod = divmod(long_value, 256) result = chr(mod) + result ...
5,332,228
def create_sample_meta_info(args): """ Load and parse samples json for templating """ if not os.path.exists(args.samples_json): print('could not find file: {}!'.format(args.samples_json)) sys.exit(1) sample_info = json.load(open(args.samples_json)) for i, sample_data in enumera...
5,332,229
def has_remove_arg(args): """ Checks if remove argument exists :param args: Argument list :return: True if remove argument is found, False otherwise """ if "remove" in args: return True return False
5,332,230
def supported_locales(prefix, parsed_args, **kwargs): """ Returns all supported locales. :param prefix: The prefix text of the last word before the cursor on the command line. :param parsed_args: The result of argument parsing so far. :param kwargs: keyword arguments. :returns list: list of all...
5,332,231
def test_less_than_or_equal(valOne, unitOne, valTwo, unitTwo): """Verify that the less than or equal to operator properly compares the VALUE of two instances.""" first = ComplesTypeStub(valOne, unitOne) second = ComplesTypeStub(valTwo, unitTwo) assert first is not second assert first <= second
5,332,232
def printmat(name, matrix): """ Prints matrix in a easy to read form with dimension and label. Parameters ========== name: data type : str The name displayed in the output. matrix: data type : numpy array The matrix to be displayed. """ print("matrix...
5,332,233
def pre_process_nli_df(data): """ Apply preprocess on the input text from a NLI dataframe :param data: data frame with the colum 'text' :type data: pd.DataFrame """ simple_pre_process_text_df(data, text_column="premise") simple_pre_process_text_df(data, text_column="hypothesis")
5,332,234
def display_screen_data(ticker: str, export: str = ""): """FinViz ticker screener Parameters ---------- ticker : str Stock ticker export : str Format to export data """ fund_data = finviz_model.get_data(ticker) print("") if gtff.USE_TABULATE_DF: print(tabulat...
5,332,235
def generate_tool_panel_dict_for_tool_config( guid, tool_config, tool_sections=None ): """ Create a dictionary of the following type for a single tool config file name. The intent is to call this method for every tool config in a repository and append each of these as entries to a tool panel dictionary for...
5,332,236
def finalize_client(client): """Stops and closes a client, even if it wasn't started.""" client.stop() client.close()
5,332,237
def test_load_current_directory(create_config, monkeypatch): """Init the config using charmcraft.yaml in current directory.""" tmp_path = create_config( """ type: charm """ ) monkeypatch.chdir(tmp_path) with patch("datetime.datetime") as mock: mock.utcnow.return_value = "...
5,332,238
def get_tmp_dir(): """get or create the tmp dir corresponding to each process""" tmp_dir = result_dir / "tmp" tmp_dir.mkdir(exist_ok=True) return tmp_dir
5,332,239
def get_logs(job_id, user, index): """get logs""" return instance().get_logs(job_id=job_id, user=user, log_index=int(index))
5,332,240
def repeat_as_list(x: TensorType, n: int): """ :param x: Array/Tensor to be repeated :param n: Integer with the number of repetitions :return: List of n repetitions of Tensor x """ return [x for _ in range(n)]
5,332,241
def transition(x, concat_axis, nb_filter, dropout_rate=None, weight_decay=1E-4): """Apply BatchNorm, Relu 1x1Conv2D, optional dropout and Maxpooling2D :parameter x: keras model :parameter concat_axis: int -- index of contatenate axis :parameter nb_filter: int -- number of filters :parameter dropout...
5,332,242
def test_get_file(): """Verify that an image is writable to a file after modifying its EXIF metadata. Assert the produced file is equivalent to a known baseline. """ image = Image(os.path.join(os.path.dirname(__file__), "noise.jpg")) image.software = "Python" file_hex = binascii.hexlify(image...
5,332,243
def _generate(args: list): """Обработка команды генерации миссии""" _args_count = len(args) if _args_count > 0: _type = args[0].lower() generate(*args) else: show_help('generate')
5,332,244
def apply_defaults(conf): """ applies default values for select configurations This call will populate default values for various configuration options. This method is used in alternative to the default values provided in the `add_config_value` call, which allows this extension to apply defaults at...
5,332,245
def _bug_data_diff_plot( project_name: str, project_repo: pygit2.Repository, bugs_left: tp.FrozenSet[PygitBug], bugs_right: tp.FrozenSet[PygitBug] ) -> gob.Figure: """Creates a chord diagram representing the diff between two sets of bugs as relation between introducing/fixing commits.""" commits_to_...
5,332,246
def test_elias_gamma(stream_encoder, data): """Test that elias gama encoder and decoder are inverse of each other.""" int_type, value = data encoded = stream_encoder.call("elias_gamma", str(int_type), value) decoded = decoder_utils.decode_elias_gamma(_br(encoded)) assert decoded == value
5,332,247
async def test_client_handles_network_issues_unexpected_close( event_loop: asyncio.AbstractEventLoop, hyperion_fixture: HyperionFixture, ) -> None: """Verify an unexpected close causes a reconnection.""" # == Verify an empty read causes a disconnect and reconnect. (rw, _) = hyperion_fixture.rw, hyp...
5,332,248
def scale_params(cfg): """ Scale: * learning rate, * weight decay, * box_loss_gain, * cls_loss_gain, * obj_loss_gain according to: * effective batch size * DDP world size * image size * num YOLO output layers * num classes "...
5,332,249
async def test_loading_non_existing(hass, store): """Test we can save and load data.""" with patch("homeassistant.util.json.open", side_effect=FileNotFoundError): data = await store.async_load() assert data is None
5,332,250
def get_model(args): """ Load model and move tensors to a given devices. """ if args.model == "lstm": model = LSTM(args) if args.model == "lstmattn": model = LSTMATTN(args) if args.model == "bert": model = Bert(args) if args.model == "lqt": model = LastQuery(a...
5,332,251
def convert_to_boolean(value): """Turn strings to bools if they look like them Truthy things should be True >>> for truthy in ['true', 'on', 'yes', '1']: ... assert convert_to_boolean(truthy) == True Falsey things should be False >>> for falsey in ['false', 'off', 'no', '0']: ... asser...
5,332,252
def set_default_input(input): """ Set the default `Input` class. (Used for instance, for the telnet submodule.) """ assert isinstance(input, Input) _default_input.set(input)
5,332,253
def progress_plots(histories, filename, start_epoch: int = 0, title: str = None, moving_avg: bool = False, beta: float = 0.9, plot_folds: bool = False): """ Plot various metrics as a function of training epoch. :param histories: list List of history objects (each corresponding to...
5,332,254
def getSampleBandPoints(image, region, **kwargs): """ Function to perform sampling of an image over a given region, using ee.Image.samp;e(image, region, **kwargs) Args: image (ee.Image): an image to sample region (ee.Geometry): the geometry over which to sample Returns: An ee.F...
5,332,255
def updateRIPCount(idx,RIPtracker,addRev=0,addFwd=0,addNonRIP=0): """Add observed RIP events to tracker by row.""" TallyRev = RIPtracker[idx].revRIPcount + addRev TallyFwd = RIPtracker[idx].RIPcount + addFwd TallyNonRIP = RIPtracker[idx].nonRIPcount + addNonRIP RIPtracker[idx] = RIPtracker[idx]._replace(revRIPcoun...
5,332,256
def sync(dir_path, archive_pass, client_id, client_secret): """ archives all files(not dirs) in a given location and uploads them to onedrive :param dir_path: str path to directory with files desired to be synced :param archive_pass: archive password :param client_id: one dri...
5,332,257
def serialize(obj): """ Return a JSON-serializable representation of an object """ cls = obj.__class__ cls_name = cls.__name__ module_name = cls.__module__ serializer = None if hasattr(obj, "to_serializable"): # The object implements its own serialization s = obj.to_serializable(...
5,332,258
def download_file(url, offset=0, filename='tmp', verbosity=True): """ Intended for simulating the wget linux command :param url: The URL for the resource to be downloaded :param offset: Number of bytes to be skipped :param filename: Name of file where the content downloaded will be stored :param...
5,332,259
def GenerateAggregatorReduceStore(emitter, registers, aggregators, result_type, lhs_add, rhs_add, left, right, lhs, rhs, results, results_stride): """Emit code that reduces 4 lane aggregators to 1 value, and stores them.""" if lhs_add: left_off...
5,332,260
async def async_unload_entry(hass, config_entry): """Unload a config entry.""" controller_id = CONTROLLER_ID.format( host=config_entry.data[CONF_CONTROLLER][CONF_HOST], site=config_entry.data[CONF_CONTROLLER][CONF_SITE_ID] ) controller = hass.data[DOMAIN].pop(controller_id) return aw...
5,332,261
def convert_1D_to_lists(file='j234420m4245_00615.1D.fits'): """ Convert 1D spectral data to lists suitable for putting into dataframes and sending to the databases. """ from collections import OrderedDict import astropy.io.fits as pyfits from .. import utils if not os.path.exists(file):...
5,332,262
def get_farthest_three_shots(gps_shots): """get three shots with gps that are most far apart""" areas = {} for (i, j, k) in combinations(gps_shots, 3): areas[(i, j, k)] = area(np.array(i.metadata.gps_position), np.array(j.metadata.gps_position), np.array(k.metadata.gps_position)) return max(are...
5,332,263
def __parse_entry(entry_line): """Parse the SOFT file entry name line that starts with '^', '!' or '#'. :param entry_line: str -- line from SOFT file :returns: tuple -- type, value """ if entry_line.startswith("!"): entry_line = sub(r"!\w*?_", '', entry_line) else: entry_line =...
5,332,264
def test_generate_validation_message(): """Test for static method to generate a ValidationMessage Test for a basic message without a kind set. """ message = { 'message': 'message', 'error': False } expected = { 'message': 'message', 'error': False, 'kind'...
5,332,265
def _mut_insert_is_applied(original, mutated): """ Checks if mutation was caused by `mut_insert`. :param original: the pre-mutation individual :param mutated: the post-mutation individual :return: (bool, str). If mutation was caused by function, True. False otherwise. str is a message explaini...
5,332,266
def add_base(this, base): """ Add a base class to a class. :params class this: a class instance :params class base: a class to add as a base class """ cls = this.__class__ namespace = this.__class__.__dict__.copy() this.__class__ = cls.__class__(cls.__name__, (cls, base), namespace) bas...
5,332,267
def remap_ids( mapping_table: Dict[Any, int] = {}, default: int = 0, dtype: DTypes = "i" ) -> Model[InT, OutT]: """Remap string or integer inputs using a mapping table, usually as a preprocess before embeddings. The mapping table can be passed in on input, or updated after the layer has been created. Th...
5,332,268
def test_ant(): """ target_files = [ "tests/apache-ant/main/org/apache/tools/ant/types/ArchiveFileSet.java", "tests/apache-ant/main/org/apache/tools/ant/types/TarFileSet.java", "tests/apache-ant/main/org/apache/tools/ant/types/ZipFileSet.java" ] """ ant_dir = "tests/apache-an...
5,332,269
def test_fold_along_delay_mismatched_uncertainty_shape(): """Test fold_along_delay errors if inputs are a different sizes.""" delays = np.arange(20) * units.s array = np.ones((1, 10, 20)) * units.mK ** 2 * units.Mpc ** 3 errs = np.ones((1, 10, 21)) * units.mK ** 2 * units.Mpc ** 3 axis = 2 pytes...
5,332,270
def list_repos_command(): """List source code repos that have been discovered by the checkoutproject command.""" __author__ = "Shawn Davis <shawn@develmaycare.com>" __date__ = "2017-03-20" __help__ = """FILTERING Use the -f/--filter option to by most project attributes: - name (partial, case insensit...
5,332,271
def get_text(cell): """ get stripped text from a BeautifulSoup td object""" return ''.join([x.strip() + ' ' for x in cell.findAll(text=True)]).strip()
5,332,272
async def test_dispense_implementation( decoy: Decoy, mock_cmd_handlers: CommandHandlers, ) -> None: """A PickUpTipRequest should have an execution implementation.""" location = WellLocation(origin=WellOrigin.BOTTOM, offset=(0, 0, 1)) request = DispenseRequest( pipetteId="abc", labw...
5,332,273
def main(api_endpoint, credentials, project_id, device_model_id, device_id, device_config, lang, verbose, input_audio_file, output_audio_file, audio_sample_rate, audio_sample_width, audio_iter_size, audio_block_size, audio_flush_size, grpc_deadline, once, *args, **kwargs): ...
5,332,274
def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--dataset', dest='dataset', help='training dataset', default='pascal_voc', type=str) parser.add_argument('--net', dest='net', help='vgg16,...
5,332,275
def test_augmentation(text, text_lengths, augmentation_class): """ test_augmentation method is written for augment input text in evaluation :param text: input text :param text_lengths: text length :param augmentation_class: augmentation class :return: """ augmentation_text = augmentatio...
5,332,276
def selfintersection(linear_ring: Points): """ not support warp polygon. """ validate.linear_ring(linear_ring) if len(linear_ring) == 4: return ( abs( linear_ring[0][1] * (linear_ring[1][0] - linear_ring[2][0]) + linear_ring[1][1] * (linear_ring[2]...
5,332,277
def ToMercPosition(lat_deg, num_tiles): """Calculate position of a given latitude on qt grid. LOD is log2(num_tiles) Args: lat_deg: (float) Latitude in degrees. num_tiles: (integer) Number of tiles in the qt grid. Returns: Floating point position of latitude in tiles relative to equator. """ la...
5,332,278
def test_list_disks(): """Validate disk list""" assert False
5,332,279
def conv3x3(in_planes, out_planes, stride=1, dilation=1, groups=1, bias=False): """2D 3x3 convolution. Args: in_planes (int): number of input channels. out_planes (int): number of output channels. stride (int): stride of the operation. dilation (int): dilation rate of the operation. ...
5,332,280
def assert_dataframes_equal(abseil_testcase_instance, actual, expected, sort_by_column=None, nan_equals_nan=False): """Assert dataframes equal up to reordering of columns and rows. Supports non-indexable...
5,332,281
def extract_current_alarm(strValue): """抽取show alarm current命令的信息 Args: strValue (str): show alarm current显示的信息 Returns: list: 包含信息的字典 """ # TODO: FIXME: 抽取告警信息没有实现 titleExpr = re.compile('\s*(Item Description)\s+(Code vOLT)\s+(Object)\s+(Begintime)\s+(Endtime)\s*') valueE...
5,332,282
def parse_hostnames(filename, hostnames): """Parses host names from a comma-separated list or a filename. Fails if neither filename nor hostnames provided. :param filename: filename with host names (one per line) :type filename: string :param hostnames: comma-separated list of host names :type hostnames: ...
5,332,283
def ssh(host, command, stdin=None): """Run 'command' (list) on 'host' via ssh. stdin is an string to send.""" return run([*SSH_COMMAND, ssh_user_host(host), *command], stdin=stdin)
5,332,284
def getScope(parameters, nonConstantParameters): """ Asks user to define the ranges for the parameters. The parameters can be constant aswell, in that case, the user will only define one value. :param parameters: List containing all parameters, the ranges will be added to each parameter inside this list...
5,332,285
def start_south_north(clean_setup_foglamp_packages, add_south, start_north_pi_server_c_web_api, remove_data_file, foglamp_url, pi_host, pi_port, pi_admin, pi_passwd, asset_name=ASSET): """ This fixture clean_setup_foglamp_packages: purge the foglamp* packages and install latest for giv...
5,332,286
def _bgzip_file(finput, config, work_dir, needs_bgzip, needs_gunzip, needs_convert, data): """Handle bgzip of input file, potentially gunzipping an existing file. Handles cases where finput might be multiple files and need to be concatenated. """ if isinstance(finput, six.string_types): in_file...
5,332,287
def test_event_add_maintenance_view_get(client, authenticated_user): """test the get method on add maintenance event view""" response = client.get("/add-maintenance-event") assert response.status_code == 200 assert "add_maintenance_form" in response.context assertTemplateUsed("event/add_maintenance_...
5,332,288
def parse_period(data, out): """parse the period int-string into int (OT => 4)""" period = data['period'] period.replace('OT', '4', inplace=True) log.debug(period.astype(int)) out['per'] = period.astype(int)
5,332,289
def cart_step1_choose_type_of_order(request): """ This view is not login required because we want to display some summary of ticket prices here as well. """ special_fares = get_available_fares_for_type(TicketType.other) context = {"show_special": bool(special_fares)} return TemplateResponse(...
5,332,290
def buildAndTrainModel(model, learningRate, batchSize, epochs, trainingData, validationData, testingData, trainingLabels, validationLabels, testingLabels, MODEL_NAME, isPrintModel=True): """Take the model and model parameters, build and train the model""" # Build and compile model # To use other optimi...
5,332,291
def vflip(): """Toggle vertical flipping of camera image.""" # Catch ajax request with form data vflip_val = 'error' if request.method == 'POST': vflip_val = request.form.get('vflip') if vflip_val is not None: app.logger.info('Form brightness submitted: %s', vflip_val) ...
5,332,292
def draw_map(console: 'Curses_Window', map: '2D_Numpy_Array', px: 'float', py: 'float', depth: 'integer'): """This method is used to draw the map, coming from the 2D_Numpy_Array in the console, Args: console (Curses_Window): A window defined using the curses library map (2D_Numpy_Array): 2D Arr...
5,332,293
def getGoalHistogramData(responses): """ Goal Completion histogram chart on project detail page. Return: {obj} Counts and % of each Goal Completion rating across given responses. """ try: snapshotResponses = responses.exclude(Q(primary_goal__isnull=True) | Q(primary_goal__name='')) respsnapshotResponsesCount =...
5,332,294
def hookes_law(receiver_nodes, sender_nodes, k, x_rest): """Applies Hooke's law to springs connecting some nodes. Args: receiver_nodes: Ex5 tf.Tensor of [x, y, v_x, v_y, is_fixed] features for the receiver node of each edge. sender_nodes: Ex5 tf.Tensor of [x, y, v_x, v_y, is_fixed] features...
5,332,295
def test_make_inverse_operator(): """Test MNE inverse computation (precomputed and non-precomputed) """ # Test old version of inverse computation starting from forward operator evoked = _get_evoked() noise_cov = read_cov(fname_cov) inverse_operator = read_inverse_operator(fname_inv) fwd_op =...
5,332,296
def check_output_filepath(filepath): """ Check and return an appropriate output_filepath parameter. Ensures the file is a csv file. Ensures a value is set. If a value is not set or is not a csv, it will return a default value. :param filepath: string filepath name :returns: a string re...
5,332,297
def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:',...
5,332,298
def compile_and_install(source, target, platform, arch, flag_mapping): """Compiles the given source directories into the mapped target directories. - source directory must be configure/make/make install-able - target is the directory where the products will be installed - platform directory is searched for 'CONFI...
5,332,299