content
stringlengths
22
815k
id
int64
0
4.91M
def get_email(package): """ Return package email as listed in `__email__` in `init.py`. """ init_py = codecs.open(os.path.abspath(os.path.join(package, '__init__.py')), encoding='utf-8').read() return re.search("^__email__ = ['\"]([^'\"]+)['\"]", init_py, re.MULTILINE).group(1)
5,358,600
def update_conf_file(): """Update the logging configuration file with the paths defined in the CONFIG file """ sett = AlgoSettings() saving_path = pathlib.Path(sett.log_saving_path()) config_file = pathlib.Path(sett.log_configuration()) with open(config_file) as my_file: doc = yaml....
5,358,601
def get_class_name(obj, instance=True): """ Given a class or instance of a class, returns a string representing the fully specified path of the class. Parameters ---------- obj : object An instance of any object instance: bool Indicates whether given object is an instance o...
5,358,602
def contour(*data, **kwargs): """ Contour line plots of scalar data in a roughly Matlab-compatible way. Data are assumed to be a scalar image. Any additional *kwargs* passed in are broadcast to all plots. Example:: xs = linspace(0,10,100) ys = linspace(0,20,200) x,y=meshgrid(x...
5,358,603
def pipeline(opts): """Construct the pipeline""" outdir = path.join(opts.outdir, opts.cancer) pTCGADownload.input = [opts.snpmani] pTCGADownload.args.nthread = opts.nthread pTCGADownload.args.token = opts.token pTCGADownload.config.export_dir = outdir pTCGADownload.cache = 'export' pSa...
5,358,604
def create_tarfile(files, project_name): """Create a tar file based on the list of files passed""" fd, filename = tempfile.mkstemp(prefix="polyaxon_{}".format(project_name), suffix='.tar.gz') with tarfile.open(filename, "w:gz") as tar: for f in files: tar.add(f) yield filename ...
5,358,605
def mol_to_smiles(molecule, isomeric=True, explicit_hydrogen=True, mapped=True): """ Generate canonical SMILES with RDKit Parameters ---------- molecule: RDKit Chem.rdchem.Mol instance The molecule to generate SMILES for isomeric: bool If True, SMILES will have isomeric informat...
5,358,606
def _plot_events_nday(ax, grid, events, scale_factor=1.0): """ Plot a map of the total number of days spent in dry spell events. Parameters ---------- ax : <matplotlib.axes.Axes> instance. The axes to which the map will be drawn. grid : <geo_grid.LandGrid> instance Object descr...
5,358,607
def rank_transform(arr: np.ndarray, centered=True) -> np.ndarray: """ Transform a 1-dim ndarray with arbitrary scalar values to an array with equally spaced rank values. This is a nonlinear transform. :param arr: input array :param centered: if the transform should by centered around zero :retu...
5,358,608
def edit_post(id, alias): """Edit an existing post. User has to be logged in and be either: - Author of the post - Editor (role) - Administrator (role) """ post = Post.query.get_or_404(id) if current_user != post.author and not ( current_user.has_role('Administrator') or current...
5,358,609
def baseline(parent,params,label='result'): """ Add a `_params` result from `biasd.utils.baseline` to HDF5 group """ # pi,mu,var,r,baseline,R2,ll,iter group = parent.create_croup(label) _addhash(group) group.attrs['description'] = 'White-noise baseline correction parameters' group.attrs['pi'] = params.pi grou...
5,358,610
def delete_all_extensions(imagename, keep_exts=None): """ Parameters ---------- imagename : str keep_exts : None, iterable A list of extensions to keep, example: ['mask', 'psf'] """ for filen in glob(imagename+'.*'): if keep_exts is not None and any(filen.endswith(ext) for ex...
5,358,611
def generate_glove(dataset="bigvul", sample=False, cache=True): """Generate Glove embeddings for tokenised dataset.""" savedir = svd.get_dir(svd.processed_dir() / dataset / f"glove_{sample}") if os.path.exists(savedir / "vectors.txt") and cache: svd.debug("Already trained GloVe.") return ...
5,358,612
def _date_list_to_num(ifg_date_list): """Convert list of dates, or list of date pairs, numpy array of floats for 'days since 1970' Handles both strings and datetimes """ from matplotlib import dates arr = np.array(ifg_date_list) if isinstance(arr.ravel()[0], str): return dates.dates...
5,358,613
def lief(phenny, input): """ Maar ze is eigenlijk wel lief """ asker = input.nick phenny.say(random.choice(NICE_CHOICES) % asker)
5,358,614
def get_font(): """ Sets up a font capable of rendering the characters """ path = os.path.join(os.getcwd(), 'scripts', 'assets', 'fonts', 'NotoSansCJKjp-Regular.otf') return font_manager.FontProperties(fname=path)
5,358,615
def maxindices(l): """ Get indices for all occurences of maximal element in list :param l: :return: """ max_indices = [] max_value = l[0] #Assume un-exhaustible iterator for i, v in enumerate(l): if v > max_value: max_value = v max_indices = [i] el...
5,358,616
def sta2inv(sta_file,out_file="sta.inv",ele_zero=True): """ Convert station file into HYPOINVERSE format """ sta_dict =load_sta(sta_file) to_inv_sta_file(sta_dict,out_file,ele_zero=True)
5,358,617
def get_grid_extents(data, edges=True): """ Get min and max lat and lon from an input GEOS-Chem xarray dataset or grid dict Args: data: xarray Dataset or dict A GEOS-Chem dataset or a grid dict edges (optional): bool Whether grid extents should use cell edges instead...
5,358,618
def test_interpolation (): """Test bernstein interpolation """ logger = getLogger("test_interpolation") from math import sin,pi, sqrt fun = lambda x : sin(2*pi*x) bs = ostap.math.bernstein.interpolate ( fun , [0] + [ random.uniform(0.01,0.99) for i in range(25) ] + [1] , 0 , 1 ) ...
5,358,619
def millisToNanos(millis): """ Converts milliseconds to nanoseconds. :param millis: (long) - The long milliseconds value to convert. :return: (long) QueryConstants.NULL_LONG if the input is equal to QueryConstants.NULL_LONG. Throws DBTimeUtils.DBDateTimeOverflowException if the input is too la...
5,358,620
def recursive_seed_part( graph, parts, pop_target, pop_col, epsilon, method=bipartition_tree, node_repeats=1, n=None, ceil=None ): """ Returns a partition with ``num_dists`` districts balanced within ``epsilon`` of ``pop_target`` by recursively splitting graph using recur...
5,358,621
def codegen_reload_data(): """Parameters to codegen used to generate the fn_carbon_black_cloud_devices package""" reload_params = {"package": u"fn_carbon_black_cloud_devices", "incident_fields": [], "action_fields": [], "function_params": [u"carbon_b...
5,358,622
def plot_3DW(att, ti, tf, dt): """ %run: plot_3DW(att, 0, 365*5, 0.1) :param att: attitude object :param ti: initial time [days] :param tf: final time [days] :param dt: step time for calculating the data point [days] :return: plot of the total inertia vector (unitary) of the scanner wrt LMN...
5,358,623
def validate_investment_amount(investment_amount, intent_request): """ Validates the investment_amount provided by the user. """ # Validate the investment_amount should be equal to or greater than 5000. if investment_amount is not None: investment_amount = parse_int( investment_...
5,358,624
def test_create_feature_request_missing_field(): """ tests creating a feature request with one or more missing fields :param app: :return: """ # with one missing field with pytest.raises(TypeError): feature.FeatureRequestService.objects_new( client_id=1, t...
5,358,625
def new_id(): """ Generates new bson ObjectId """ return str(ObjectId())
5,358,626
def gc_sweep( session=None, draw_function=gc2d, dirpath=CONFIG["workspace"], overwrite=False, run=True, base_fsp_path=str(CONFIG["grating_coupler_2D_base"]), **kwargs ): """ grating coupler sweep grating_coupler_2D_base optimizes Transmission and does not calculate Sparameters "...
5,358,627
def stem(word, stemmer=PORTER, **kwargs): """ Returns the base form of the word when counting words in count(). With stemmer=PORTER, the Porter2 stemming algorithm is used. With stemmer=LEMMA, either uses Word.lemma or inflect.singularize(). (with optional parameter language="en", pattern.en...
5,358,628
def verify_bounce_message(msg): """ Verify an SES/SNS bounce notification message. """ verifier = BounceMessageVerifier(msg) return verifier.is_verified()
5,358,629
def multiples(a, b): """This function checks if a number is a multiple of another.""" if type(a) != int or type(b) != int: raise Exception('Values must be integers.') elif a == 0: raise Exception('0 is not valid.') elif a == b: raise Exception('Numbers should not be the same.') ...
5,358,630
def plot_masks(im_h=150, im_w=235): """ Plots the preallocated masks of the steerable pyramid :param im_h: :param im_w: :return: """ py = Steerable_complex_wavelet_pyramid(im_h=im_h, im_w=im_w) py.plot_lo_masks() py.plot_high_masks() py.plot_angle_masks_b1()
5,358,631
def test_release_version(three_experiments_same_name_with_trials): """Test releasing a specific experiment version""" experiments = get_storage().fetch_experiments({}) storage = get_storage() assert len(experiments) == 3 assert len(storage._fetch_trials({})) > 0 uid = None for experiment in ...
5,358,632
def train_gilbo(gan, sess, outdir, checkpoint_path, dataset, options): """Build and train GILBO model. Args: gan: GAN object. sess: tf.Session. outdir: Output directory. A pickle file will be written there. checkpoint_path: Path where gan"s checkpoints are written. Only used to ...
5,358,633
def unquote_keys(data): """Restores initial view of 'quoted' keys in dictionary data :param data: is a dictionary :return: data with restored keys if they were 'quoted'. """ if isinstance(data, dict): for key, value in data.items(): if isinstance(value, dict): un...
5,358,634
def retr_amplslen(peri, radistar, masscomp, massstar): """ Calculate the self-lensing amplitude. Arguments peri: orbital period [days] radistar: radius of the star [Solar radius] masscomp: mass of the companion [Solar mass] massstar: mass of the star [Solar mass] R...
5,358,635
def main_work(indir, outdir, aux=None, hv=None): """ :param indir: :param outdir: :param aux: :param hv: :return: """ if not os.path.exists(outdir): os.makedirs(outdir) if hv is None: hv_ = all_hv else: hv_ = [hv] if aux is None: ...
5,358,636
def calculate_current_teach_week(semester_first_week_date='2021-3-08 08:00:00'): """ 计算当前日期所属教学周,实现思路是:当前日期所属一年中的周 - 每学期的第一周 ---- param: semester_first_week_date: 学期第一周的日期,例如 '2021-3-08 08:00:00' return: 当前教学周 """ # 获取指定日期属于当年的第几周, 返回字符串 semester_first_week = datetime.strptime(semester_...
5,358,637
def get_first_model_each_manufacturer(cars=cars): """return a list of matching models (original ordering)""" return [cars[key][0] for key in cars]
5,358,638
def get_sandbox_table_name(dataset_id, rule_name): """ A helper function to create a table in the sandbox dataset :param dataset_id: the dataset_id to which the rule is applied :param rule_name: the name of the cleaning rule :return: the concatenated table name """ return '{dataset_id}_{rul...
5,358,639
def index(): """for i in range(0, 30): data = QuizQuestions("math", None, "en_US", 7, "normal", "This is placeholder question number " + str(i), "c", "Answer A", "Answer B", "Answer C", "Answer D", True) db.session.add(data) db.session.commit()""" return render_template("quiz_index.html")
5,358,640
def _get_invoke_function_name() -> Any: """ Get invoke function Name. Returns ------- Function Name. """ props = get_properties() functionName = f"orbit-{props['AWS_ORBIT_ENV']}-{props['AWS_ORBIT_TEAM_SPACE']}-container-runner" return functionName
5,358,641
def metadata_table(samples): """Return a pandas dataframe with metadata from `samples`.""" pass
5,358,642
def sigmaG(a, axis=None, overwrite_input=False, keepdims=False): """ Compute the rank-based estimate of the standard deviation Parameters ---------- a : array_like Array containing numbers whose mean is desired. If `a` is not an array, a conversion is attempted. axis : int, opti...
5,358,643
def traverse_tagged_databases( functional_unit, method, label="tag", default_tag="other", secondary_tags=[], fg_databases=None ): """Traverse a functional unit throughout its foreground database(s) or the listed databses in fg_databses, and group impacts by tag label. Contribution analysis work...
5,358,644
def graft( repo, ctx, base=None, labels=None, keepparent=False, keepconflictparent=False, wctx=None, ): """Do a graft-like merge. This is a merge where the merge ancestor is chosen such that one or more changesets are grafted onto the current changeset. In addition to the me...
5,358,645
def GetSiteFilters(filename): """ Reader for a file of reportable sites. The file contains 2 tokens: the site name and a normalization factor. The method returns a hash table with the key being site and the value the normalization factor to use. """ try: #--- process the reportable sites ...
5,358,646
def MiniMobileNetV2(input_shape=None, alpha=1.0, expansion_factor=6, depth_multiplier=1, dropout=0., weight_decay=0., include_top=True, weights=None, input_tens...
5,358,647
def update_forward_cnt(**kwargs): """ 更新被转发的次数,进行加1操作 :param kwargs: {'object_id': object_id} :return: """ session = None try: session = get_session() # 转发次数 +1 session.query(SecondHand).filter(SecondHand.OBJECT_ID == kwargs['object_id']).update( ...
5,358,648
def _show_list(images: list, width: int=-1, height: int=-1) -> None: """Gets list of images and display them all Args: images (list): list of numpy arrays width (int, optional): width of the image grid. Defaults to -1. height (int, optional): height of the image grid. Defaults to -1...
5,358,649
def test_get_geosol_gs(config_geosol_gs_WFS): """Testing query for a specific object""" p = OGRProvider(config_geosol_gs_WFS) result = p.get('Unesco_point.123') assert result['id'] == 'Unesco_point.123' assert 'Centro storico di San Gimignano' in result['properties']['sito']
5,358,650
def recursive_dict_merge(dict1, dict2): """ Merges dictionaries (of dictionaries). Preference is given to the second dict, i.e. if a key occurs in both dicts, the value from `dict2` is used. """ result = copy.deepcopy(dict1) for key in dict2: if key in dict1 and isinstance(dict1[k...
5,358,651
def define_loss(name, device="cuda"): """ Defines the loss function associated to the name. Supports losses in the LOSSES list, as well as the Lovasz, Softdice and Haussdorf losses. Args: name (str): Loss name. device (str, optional): Device for torch. Defaults to "cuda". Raises: ...
5,358,652
def get_default_archive_path(): """ Makeup default archive path. Unify the archive path between local machine and cloud. """ if not XT_HWC_WORKSPACE: return os.path.join(os.path.expanduser("~"), DEFAULT_ARCHIVE_DIR) else: return os.path.join(XT_HWC_WORKSPACE, DEFAULT_ARCHIVE_DIR...
5,358,653
def python_3000_async_await_keywords(logical_line, tokens): """'async' and 'await' are reserved keywords starting at Python 3.7. W606: async = 42 W606: await = 42 Okay: async def read(db):\n data = await db.fetch('SELECT ...') """ # The Python tokenize library before Python 3.5 recognizes ...
5,358,654
def get_hosts_from_file(hostfile): """ Return the list of hosts from a given host file. """ hosts = [] if os.path.exists(hostfile): for line in open(hostfile, "r").readlines(): hosts.append(line.split(' ', 1)[0]) return hosts
5,358,655
def process_exists(pid): # type: (int) -> bool """ Checks if the processed with the given *pid* exists. Returns #True if that is the case, #False otherwise. """ if pid == 0: return False try: os.kill(pid, 0) except OSError as exc: if exc.errno == errno.ESRCH: return False return True
5,358,656
def get_application_name(): """Attempts to find the application name using system arguments.""" if hasattr(sys, 'argv') and sys.argv[0]: app_name = os.path.basename(sys.argv[0]) else: app_name = None return app_name
5,358,657
def test_can_pluck_single_element(base_clumper, elem): """ We can pluck single elements by selecting on the character. """ collected = base_clumper.keep(lambda d: d["c"] == elem).collect() assert collected[0]["c"] == elem assert len(collected) == 1
5,358,658
def test_repr(redis_dict, str_dict): """Test ``__repr__`` method.""" assert str(redis_dict) == '{0}: {1}'.format(type(redis_dict).__name__, str_dict)
5,358,659
def check_clioncode(projroot: Path, full: bool, verbose: bool) -> None: """Run clion inspections on all our code.""" import time cachepath = Path('.cache/check_clioncode') filenames = get_code_filenames(projroot) clionroot = Path('/Applications/CLion.app') # clionbin = Path(clionroot, 'Contents...
5,358,660
def get_atomate_wflows(wf_coll, states, seed_regex=None, project_regex=None) -> pd.DataFrame: """Obtain workflow informaton for atomate jobs""" return get_workflows(wf_coll, ['atomate-relax'], states, ...
5,358,661
def the_H_function(sorted_citations_list, n=1): """from a list of integers [n1, n2 ..] representing publications citations, return the max list-position which is >= integer eg >>> the_H_function([10, 8, 5, 4, 3]) => 4 >>> the_H_function([25, 8, 5, 3, 3]) => 3 >>> the_H_function([1000, 20]) => 2...
5,358,662
def test_parse_assignments_expressions(code, target): """Test parse_assignments_expressions function.""" res = kale_ast.parse_assignments_expressions(code) compare(res, target)
5,358,663
def InitGoldData(packet_addresses, gold_data, host): """Gold standard is data from first read.""" packet_addresses.append(TEST_PACKET0_ADDRESS % host) packet_addresses.append(TEST_PACKET1_ADDRESS % host) gold_data.append(urllib2.urlopen(packet_addresses[0]).read()) gold_data.append(urllib2.urlopen(packet_addr...
5,358,664
def build_trainer(model: BaseModel, params: Parameters, dataset: Dataset, target_processor: TargetProcessor, batch_processor: BatchProcessor) \ -> BaseTrainer: """ Build a neural network trainer/optimizer based on different backend ...
5,358,665
def get_random_quote(quotes_list): """Return a random quote to user.""" upper_limit = len(quotes_list)-1 select = random.randint(0, upper_limit) selected_quote = quotes_list[select] soup = BeautifulSoup(selected_quote, 'html.parser') return soup.text
5,358,666
def record_states(hass): """Record some test states. We inject a bunch of state updates from media player, zone and thermostat. """ mp = "media_player.test" mp2 = "media_player.test2" mp3 = "media_player.test3" therm = "thermostat.test" therm2 = "thermostat.test2" zone = "zone.h...
5,358,667
def generate_char_gap_report(fp, char_gap_accuracies): """Generate a accuracy report for the char-gap set. Outputs to file fp.""" fp.write("==== Character gaps ====\n") all_pc_accs = [] all_ps_accs = [] for i, acc in enumerate(char_gap_accuracies): pc_acc = acc[0] * 100 ps_acc = acc[...
5,358,668
def input_change(attr, old, new): """Executes whenever the input form changes. It is responsible for updating the plot, or anything else you want. Args: attr : the name of the attr that changed old : old value of attr new : new value of attr """ update_data() plot.title...
5,358,669
def ask_why(doc): """ Ask questions of the form “Why is ..x..?” where x is either a combination of object and adjective or subject and adjective or “Why ..prep.. the ..noun..” """ chunk = find_subj_chunk(doc) if chunk != None and chunk["adjective"] != None: subj = chunk["subject"] ...
5,358,670
def get_extension(fname): """ Get file extension. """ return '.' + fname.split(".")[-1]
5,358,671
def large_xyz_to_luv_star(large_xyz, white_xyz): """ # 概要 XYZ から L*u*v* を計算する。 # 参考 https://en.wikipedia.org/wiki/CIELUV """ large_x, large_y, large_z = np.dsplit(large_xyz, 3) white_xyz = np.array(white_xyz) white_xyz = (white_xyz / white_xyz[1]).reshape((1, 1, 3)) x_n, y_n, z_n...
5,358,672
def rotation(new_rotation=0): """Set the display rotation. :param new_rotation: Specify the rotation in degrees: 0, 90, 180 or 270 """ global _rotation if new_rotation in [0, 90, 180, 270]: _rotation = new_rotation return True else: raise ValueError("Rotation: 0, 90, 1...
5,358,673
def parse_url (url:str) -> str: """ 规范化 URL -> hello/world <- /hello/world """ if url == "": url = "/" if not url.startswith ('/'): url = "/" + url # 添加开头斜杠 # if not url.endswith ("/"): url += "/" # 添加末尾斜杠 return url
5,358,674
def bulk_edit(modeladmin, request, queryset): """ Bulk edit selected items. """ form = None if 'apply' in request.POST: form = BulkEditForm(request.POST) if form.is_valid(): property = form.cleaned_data['property'] cf_value = form.cleaned_data['cf_value'] ...
5,358,675
def smooth_GF(C,S,avg_rad, start_deg): """from Wahr et al: Time-variable gravity recovery from space eq. 34. This is Jekeli's [1981] smoothing method.""" C_smooth = C S_smooth = S Re = 6378.1363; # Radius of Earth in km b = np.log(2) / (1 - np.cos(avg_rad / Re)) W=[] W.append(1 / (2 * np.pi)) W.append(1 / (2 *...
5,358,676
def get_vmstat(): """ Get and format the content of /proc/vmstat """ buf = open("/proc/vmstat").read() buf = [v.replace(' ', ":") for v in buf.split("\n")] buf = ";".join(buf) return buf
5,358,677
def upcomingIPOs( symbol="", exactDate="", token="", version="stable", filter="", format="json", ): """This will return all upcoming estimates, dividends, splits for a given symbol or the market. If market is passed for the symbol, IPOs will also be included. https://iexcloud.io/docs/ap...
5,358,678
def sort_tokens(tokens: Iterable[Cwf]) -> List[Cwf]: """Sort tokens by natural order (sent, offset)""" return sorted(tokens, key=lambda t: (t.get_sent(), int(t.get_offset())))
5,358,679
def is_zero(evm: Evm) -> None: """ Checks if the top element is equal to 0. Pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. Raises ------ ethereum.frontier.vm.error.StackUnderflowError If `len(stack)` is less than `1`. eth...
5,358,680
def deep_seq_map(xss, fun, keys=None, fun_name=None, expand=False): """Applies fun to list of or dict of lists; adds the results in-place. Usage: Transform a corpus iteratively by applying functions like `tokenize`, `lower`, or vocabulary functions (word -> embedding id) to it. from jtr.sisyphos.vocab...
5,358,681
def create_user(steamid, admin): """Create a user""" steamid = string_to_steamid(steamid) if not steamid.is_valid() or not steamid.type == EType.Individual: echo('Invalid steam ID') return 1 user = User(steamid64=steamid.as_64, admin=admin) user.refresh_name() if user.name is no...
5,358,682
def get_vocabularies(): """ Return the currently used ontology :return: """ vocabs = vocs.get_vocabularies() vocabs = [(x, url_for('get_vocabulary', vid=x, _external=True)) for x in vocabs] response = make_response(json.dumps(dict(vocabs))) response.headers['Content-Type'] = 'application...
5,358,683
def test_handle_transient_files(transient_files, transient_files_contents, transient_files_cids, expected_output): """Check the parsing of transient files Given: - Files names (as a string) - Files contents (as a string) - Files cids (as a string) When: - Parsing the data fo...
5,358,684
def test_port_stripper_invalid_protocol(): """Test the port stripper for using invalid protocol""" _, _, valid = _port_stripper("127.0.0.1:8080", protocol='IPv9') assert valid is False
5,358,685
def plot_feature_importance(sorted_series_features, title_str): """ Plot feature importance from tree models """ sns.set() plt.figure() sorted_series_features.plot(kind = 'barh', color = 'blue') plt.title(title_str) plt.xlabel('Importance') plt.ylabel('Feature') plt.tight_layout(pad=2.0,...
5,358,686
def do3byte(*args): """do3byte(ea_t ea, asize_t length) -> bool""" return _idaapi.do3byte(*args)
5,358,687
def test_simple_seed_only(driver, function_store): """ Simple integration test w/ a seed dataset only. This is the most simple way to create a cube. """ df = pd.DataFrame({"x": [0, 1, 2, 3], "p": [0, 0, 1, 1], "v": [10, 11, 12, 13]}) cube = Cube(dimension_columns=["x"], partition_columns=["p"], uuid...
5,358,688
def compute_sap(ground_truth_data, representation_function, random_state, num_train=gin.REQUIRED, num_test=gin.REQUIRED, batch_size=16, continuous_factors=gin.REQUIRED): """Computes the SAP score. Args: ground_truth...
5,358,689
def process_request(ctx: click.Context, results: Sequence[Any], **kwargs: Any) -> None: """ All click commands finished, start any jobs necessary """ options: Options = ctx.obj if options.exit: return config = options.config contexts = resolve_contexts(config) if options.python...
5,358,690
def clean_cmd(cmd): """Removes multiple spaces and whitespace at beginning or end of command. Args: cmd (str): A string containing the command to clean. Returns: A cleaned command string. """ return re.sub(r'\s{2, }', ' ', cmd).strip(' \t\n\r')
5,358,691
def multiply_scalar(mat, value): """ Multiplies every element in the matrix by the given scalar value. Args: mat (Matrix): The input matrix. value (int or float): The number that mat will be multipled by. Returns: Matrix: The resulting matrix from the multiplication of mat and value...
5,358,692
def bin4D(data4D, bin_factor): """ Bin 4D data in spectral dimensions Parameters ---------- data4D: ndarray of shape (4,4) the first two dimensions are Fourier space, while the next two dimensions are real space bin_factor: int ...
5,358,693
def test_life_cycle(err_workbench): """Test basic behavior of ErrorsPlugin. """ plugin = err_workbench.get_plugin(ERRORS_ID) assert len(plugin.errors) == 4 plugin._errors_handlers.contributions = {} assert len(plugin.errors) == 0 plugin.stop() assert not len(plugin.errors)
5,358,694
def lorentz(x, a, mu, ga): """ Input: x - value and a=I, mu=x_0, ga - lorentz f. coeffitients (float) Return: value of function with desired parameters in x (float) Descr.: Calculate L-type function for given x and parameters""" return (a * ga ** 2) / ((x - mu) ** 2 + ga ** 2)
5,358,695
def main(arguments): """ if you call this then it will create and return the thunder obj for you :param arguments: a thunder object or a dicitonary to initialise the thunder obj :return: """ thunder = Thunder(deepcopy(arguments)) # load object return thunder
5,358,696
def scriptSaveAs(): """scriptSaveAs(filename=None, overwrite=-1) -> None Saves the current script with the given file name if supplied, or (in GUI mode) asks the user for one using the file chooser. If Nuke is not running in GUI mode, you must supply a filename. @param filename: Saves the current ...
5,358,697
def remove_existing_furigana(tree: ET.ElementTree, parent_map: dict): """ Replace all existing ruby elements by their text, e.g., <ruby>X<rt>Y</rt></ruby> becomes X. """ elems = tree.findall(f'.//{NAMESPACE}ruby') for elem in elems: # Remove all the <rt> children, e.g., the readings, but kee...
5,358,698
def make_train_func( model, loss_func, optimizer, dtype=None, device=None, call_model=None, get_train_loss=None, ): """Create a train func for ``ignite``. This function assumes that each batch is of the form ``(x, y)`` with no assumptions placed on ``x`` or ``y``. Each batch wil...
5,358,699