content
stringlengths
22
815k
id
int64
0
4.91M
def html(obj): """ Shorthand to pretty print HTML EXAMPLES:: sage: from sage.interacts.library import html sage: html("<h1>Hello world</h1>") <h1>Hello world</h1> """ from sage.all import html pretty_print(html(obj))
71,600
def run(bam_file, data, out_dir): """ Run SignatureGenerator to create normalize vcf that later will be input of qsignature_summary :param bam_file: (str) path of the bam_file :param data: (list) list containing the all the dictionary for this sample :param out_dir: (str) path of t...
71,601
def to_ascii(x): """ Converts a 0-indexed integer to the corresponding Excel-style column name """ x += 1 result = [] while x: x, rem = divmod(x-1, 26) result[:0] = ascii_uppercase[rem] return ''.join(result)
71,602
def step(stripped, pos, prev): """ Move along the path one or two steps (if ducking under), at location pos, and previous given. Return new location, plus the number of steps (1 or 2) that was taken. """ (x, y) = pos tile = stripped[pos] dx, dy, steps = direction(pos, prev) if tile == "...
71,603
def test_subraph_left(): """ Extraction of the 'left subgraph' """ x = basicdata() g = cross_knn(x, x, 2) valid = np.arange(10) < 7 sl = g.subgraph_left(valid) assert sl.V == 7 assert sl.W == 10 assert sl.edges[:, 0].max() == 6
71,604
def read_data(absfile: str) -> pd.DataFrame: """ Read Raw Data. """ assert os.path.exists(absfile) return pd.read_excel(absfile, names=[ 'Time', 'Temp', 'pH', 'DO', 'Elecon', 'Turbidity', 'CODMn', 'NH3N', 'TP', 'TN' ])
71,605
def validate_actions(data): """ Validate an Action configuration dictionary, as imported from actions.yml, for example. The method returns a validated and sanitized configuration dictionary. :arg data: The configuration dictionary :rtype: dict """ # data is the ENTIRE schema... cle...
71,606
def plot_t1err_noshow(pv, i_causal, label="", gc_correct=False): """ False Positive Rate = FP / N = 1 - specificity """ pv_thresholds, t1err = compute_t1err_data(pv, i_causal) draw_t1err_curve(pv_thresholds, t1err, label, len(pv), gc_correct=gc_correct)
71,607
def to_anaesthetic_csv(episode_data, anaesthetist): """Write tuple of anaesthetic billing data to csv for billing anaesthetists""" surname = anaesthetist.split()[-1] csvfile = 'd:\\JOHN TILLET\\episode_data\\sedation\\{}.csv'.format(surname) with open(csvfile, 'a') as handle: datawrite...
71,608
def load_model_from_tarball_stream( tarball_stream, gpg_home_dir=None, run_model_validation=True ) -> SerializableModel: """Load a model from a tarball stream Args: tarball_stream: a readable stream gpg_home_dir: home directory for gpg to verify signed model (e.g. path/to/.gnupg) ...
71,609
def TChA_LoadTxt(*args): """ TChA_LoadTxt(PSIn const & SIn, TChA ChA) Parameters: SIn: PSIn const & ChA: TChA & """ return _snap.TChA_LoadTxt(*args)
71,610
def logging_est(logfile_path, debug=False): """ Establish Logging logfile_path: path to the logfile. Default: current directory. debug: Set debug mode on (True) or off (False). Default: False """ if logfile_path is None: return logger = logging.getLogger() logger.setLevel(logg...
71,611
def init_default_parser() -> ArgumentParser: """Creates the default argument parser. :returns: an ArgumentParser with the default options. """ version = "1.1.0" parser = ArgumentParser() parser.add_argument( "target_path", help="path to the xml file or directory", t...
71,612
def msi_file_finder(pth): """ Return True if pth represents a msi file file. """ return bool(pth.fname.endswith('.msi.txt'))
71,613
def expandBuilding(session, cityId, building, waitForResources): """ Parameters ---------- session : ikabot.web.session.Session cityId : int building : dict waitForResources : bool """ current_level = building['level'] if building['isBusy']: current_level += 1 levels_to_upgrade = building['upgradeTo'] - cu...
71,614
def get_flat_tree(dependencies: List, package_map: Dict[str, str]) -> Dict: """Parse yarn list json dependencies and add them locked version Example: { "package@1.2.3": { "name": "package", "version": "1.2.3", dependencies: { "utils@1.2.3": { "name": "uti...
71,615
def test_count_log_lines_with_substring_returns_zero_for_no_matches(): """Test that returns zero if there are no matching lines.""" logs = """ DEBUG: log example 1 \r\n ERROR: log example 2 \r\n ERROR: log example 3 \r\n INFO: log example 1 \r\n """ count = utility.count_log_lines_with_substring(logs, "...
71,616
def inference(input_img_path, sess, scale, window_size, tile, tile_overlap, output_img_path, patch_inference, args): """ Loads image and returns enlarged image. Can be called in loop for multiple images. """ (img_name, img_ext) = os.path.splitext(os.path.basename(input_img_path)) img_old = cv2.imrea...
71,617
def windows_start(args, version): """ :type args: WindowsIntegrationConfig :type version: str :rtype: AnsibleCoreCI """ core_ci = AnsibleCoreCI(args, 'windows', version, stage=args.remote_stage, provider=args.remote_provider) core_ci.start() return core_ci.save()
71,618
def load_spacy_model(model_name: str = CONFIG["spacy_model"]) -> Any: """ Loading Spacy model for name entity recognition. Pre-trained models should be downloaded in advance by `python -m spacy download <model_name>` """ logging.info("Loading pre-trained model {}".format(model_name)) nlp = spacy...
71,619
def create_message(account, subject, body, to_recipients): """ Consolida os elementos mais básicos para a criação de um objeto de mensagem a ser gerenciado externamente pelo usuário ou por demais funções neste módulo. Em linhas gerais, o código neste bloco instancia a classe Message() da biblio...
71,620
def client_from_parameters( base_url: str, password: str, team_name: str, username: str, verify_ssl: bool = True, concourse_api_version=None, ): """ returns a concourse-client w/ the credentials valid for the current execution environment. The returned client is authorised to perform...
71,621
def test_spectral_euclidean_distance(): """Test the Spectral Euclidean Distance algorithm.""" # Data X = np.load("sample_data/graphs/spectral_mtx1_10x10.npy") Y = np.load("sample_data/graphs/spectral_mtx2_10x10.npy") # Run result = spectral_euclidean_distance(X, Y) # Test against the grou...
71,622
def get_k2_epic_catalog(): """ Parameters ---------- Returns ------- """ global k2_epic_table if k2_epic_table is None: catalogs = Vizier.get_catalogs(huber2016) k2_epic_table = catalogs[0] # This is the table with the data k2_epic_table.add_index('EPIC') r...
71,623
def create_snapshot(conn): """ Dumps database content as SQL creating a snapshot that other nodes can load easily """ if conn.host != conn.config.aws.bastion: raise Exit(f"Did not expect the host {conn.host} while the bastion is {conn.config.aws.bastion}") database = conn.config.postgres.da...
71,624
def download_work(shard_id, current_idx, local_path, cache, q): """ daemon process in backend. """ from .config_loader import config from .util import try_load_from_obs, get_used_disk_per while True: idx, dataset_file = q.get() used_disk = get_used_disk_per() while used_disk > c...
71,625
def bandpass_unit_conversion( freqs, weights=None, output_unit=None, input_unit=u.uK_RJ, cut=1e-10 ): """Unit conversion from input to output unit given a bandpass The bandpass is always assumed in power units (Jy/sr) Gain weights below cut are removed. Parameters ---------- freqs : astrop...
71,626
def get_bearer_token(): """ Creates the bearer key in order to perform requests from the Green Invoice API. Since a new key has to be generated at least every 30 mim, this function will be used many times. :return: request's bearer login token. """ conn = http.client.HTTPSConnection("san...
71,627
def CheckIssueClosed(issue_id): """Checks if a given issue is closed. Returns False when in doubt.""" try: return GetIssueState(issue_id) == 'closed' except IssueTrackerQueryException: # When we can't be sure we return false return False
71,628
def get_accuracy_and_plot_confusion(y_correct, y_pred, classes, plot=True, title='Confusion matrix'): """Return the accuracy of the prediction and plot the corresponding confusion matrix if desired""" if plot: cm = confusion_matrix(y_correct, y_pred) plt.imshow(cm, interpolation='nearest', cmap=...
71,629
def fetch_spm_auditory(data_dir=None, data_name='spm_auditory', subject_id='sub001', verbose=1): """Function to fetch SPM auditory single-subject data. Parameters ---------- data_dir: string Path of the data directory. Used to force data storage in a specified loc...
71,630
async def aclosing(thing): """Asynchronous closing context manager. :param thing: Thing to close. :type thing: Any """ try: yield thing finally: if iscoroutinefunction(thing.close): await thing.close() else: await sync_to_async(thing.close)
71,631
def set_byz_behavior(new_behavior): """Sets the Byzantine behavior for this node. Used during runtime.""" global byz_behavior if new_behavior == NONE or is_valid_byz_behavior(new_behavior): byz_behavior = new_behavior
71,632
def random_stochastic_function(x, delta): """ Creates a random stochastic function that adds a value between [-delta, delta] Parameters ============ x: the input value. delta: defines the range """ return (np.random.random_sample() * 2 * delta) - delta
71,633
def dashboard(context): """ Fonction affichant le dashboard d'actions """ print('Solde: {}€'.format(round(context['balance'], 2))) print('Actions') print('=======') total_balance = list_my_shares(context) print('Solde total: {}€'.format(round(total_balance, 2)))
71,634
def _converter(val): """ """ lval = val.lower() if lval in ENABLE_STRINGS: return True if lval in DISABLE_STRINGS: return False return val
71,635
def cagr(qf_series: QFSeries, frequency=None): """ Returns the Compound Annual Growth Rate (CAGR) calculated for the given series. Parameters ---------- qf_series: QFSeries series of returns of an asset frequency: Frequency Frequency of the timeseries of returns; if it i...
71,636
def decrypt_sun_message(sdm_meta_read_key: bytes, sdm_file_read_key: Callable[[bytes], bytes], picc_enc_data: bytes, sdmmac: bytes, enc_file_data: Optional[bytes] = None) -> dict: """ Decrypt SUN message for NTAG 424...
71,637
def head_pos(raw, param_compute_amplitudes_t_step_min, param_compute_amplitudes_t_window, param_compute_amplitudes_ext_order, param_compute_amplitudes_tmin, param_compute_amplitudes_tmax, param_compute_locs_t_step_max, param_compute_locs_too_close, ...
71,638
def classify_and_save(arch_path, set_path, set_size, batch_size, networks, epochs, img_size, use_gpu=True): """ Classify some images against a Caffe model and print the results Arguments: caffemodel -- path to a .caffemodel deploy_file -- path to a .prototxt image_files -- list of paths...
71,639
def line_intersect(line_a, line_b) -> bool: """ Check if two line segments intersect @param line_a A tuple (Vector2, Vector2) representing both end points of line segment @param line_b Same as `line_a` """ # line_a and line_b have the same end point if (line_a[0] == line_b[0] or ...
71,640
def flush_certs(): """Remove all certificates""" crt_folder = app.config['CRT_CERTS_PATH'] pki_path = app.config['PKI_PATH'] ovpn_path = app.config['OVPN_CERTS_PATH'] if os.path.isdir(crt_folder): print(f'removing {crt_folder}') rmtree(crt_folder) if os.path.isdir(pki_path): ...
71,641
def test_version(doc_worktree): """ Test Version """ foo_sphinx = doc_worktree.create_sphinx_project("foo") foo_path = py.path.local(foo_sphinx.path) # pylint:disable=no-member conf_py = foo_path.join("source", "conf.py").ensure(file=True) conf_py.write('project = "foo"\n') foo_sphinx.configure...
71,642
def parseNum(num): """0x is hex, 0b is binary, 0 is octal. Otherwise assume decimal.""" num = str(num).strip() base = 10 if (num[0] == '0') & (len(num) > 1): if num[1] == 'x': base = 16 elif num[1] == 'b': base = 2 else: base = 8 return int(num, base)
71,643
def compute_with_trace(*args): """Do Dask compute(), but with added Eliot tracing. Dask is a graph of tasks, but Eliot logs trees. So we need to emulate a graph using a tree. We do this by making Eliot action for each task, but having it list the tasks it depends on. We use the following algorit...
71,644
def read_mem(addr, size): """Read a chunk of memory.""" buf = create_string_buffer(size) memmove(buf, addr, size) return buf.raw
71,645
def read_events(istream): """ Generator that accepts a stream of input lines and parses it into a sequence of events. It assumes that the input stream represents the complete output from mysqlbinlog and will first read the header, continuing with each individual event. """ # Read heade...
71,646
def get_ranges(headervalue, content_length): """Return a list of (start, stop) indices from a Range header, or None. Each (start, stop) tuple will be composed of two ints, which are suitable for use in a slicing operation. That is, the header "Range: bytes=3-6", if applied against a Python string, ...
71,647
def analyze(session, apk): """Open a IPython Shell and start reverse engineering.""" androlyze_main(session, apk)
71,648
def families_dipoles(): """.""" return ['B']
71,649
async def get_currencies_rates( # noqa: WPS234 api_key: Optional[str], base_currency: str = BASE_CURRENCY, ) -> List[Tuple[str, float]]: """Get currencies rates from remote server. Args: api_key: service access key base_currency: base currency for calculate rates Returns: ...
71,650
def mon_vm_sync(task_id, sender, vm_uuid=None, log=LOG, **kwargs): """ Create or synchronize zabbix host according to VM. """ assert vm_uuid vm = log.obj = Vm.objects.select_related('dc', 'slavevm').get(uuid=vm_uuid) log.dc_id = vm.dc.id if vm.is_slave_vm(): logger.info('Ignoring VM...
71,651
def scan(spec_path, output_path, reporter, template, log_level): """Automated Testing and Documentation for your REST API.""" logging.basicConfig(level=log_level) logger = logging.getLogger(__name__) SETTINGS.update({"spec_path": spec_path, "output_path": output_path}) # custom templates to be imp...
71,652
def get_emissions(infile, outfile=None, fuelin=None, emisin=None): """Get emissions estimates with FINN Args: infile (str) - path to input file outfile (str) - optional path to output file. If None, then this is constructed by appending '_output' to the input filename fuelin...
71,653
def _verify_bore_connectivity(bore_connectivity, nBoreholes): """ Verifies that borehole connectivity is valid. This function raises an error if the supplied borehole connectivity is invalid. Parameters ---------- bore_connectivity : list Index of fluid inlet into each borehole. -1...
71,654
def save_json(path: str, data: dict): """Save json file in given path""" with open(path, "w") as outfile: json.dump(data, outfile)
71,655
def pad_subword_sequence(subword_seq, max_seq_length): """ The subword sequence (graphemic / phonetic) can be of variable length. In order to store this data in a numpy array, one pads and masks the subword dimension to the max sequence length. subword_seq: numpy array with dimensions (grap...
71,656
def program_to_instrument_name(program_number): """Converts a MIDI program number to the corresponding General MIDI instrument name. Parameters ---------- program_number : int MIDI program number, between 0 and 127. Returns ------- instrument_name : str Name of the inst...
71,657
def test_plc_read(address, timeout): """test to see if reading of plc data works""" lsv2 = pyLSV2.LSV2(address, port=19000, timeout=timeout, safe_mode=False) lsv2.connect() assert lsv2.read_plc_memory(address=0, mem_type=pyLSV2.MemoryType.MARKER, count=1) is not False assert lsv2.read_plc_memory(ad...
71,658
def recordcomfort(): """Record comfort-score today""" # User reached route via GET (as by clicking a link or via redirect) if not request.method == "POST": pass # User reached route via POST (as by submitting a form via POST) else: pass # DB connection and cursor generation c...
71,659
def test_sleep_mode(scd4x): """ Test power down and wake up commands """ scd4x.power_down() try: scd4x.get_data_ready_status() except I2cNackError: assert True else: assert False, "SCD4x should respond with NACK when in sleep mode" scd4x.wake_up() try: ...
71,660
def GetLatestAFDOFile(cpv, arch, buildroot, gs_context): """Try to find the latest suitable AFDO profile file. Try to find the latest AFDO profile generated for current release and architecture. If there is none, check the previous release (mostly in case we have just branched). Args: cpv: cpv object fo...
71,661
def HadamardTest(P: QuantumCircuit, U: QuantumCircuit, U_active_qubits: list, shots: int = 10000): """ :param shots: the number of measurement :param U: Testing state generation circuit :param U_active_qubits: :param P: Pauli matrix :return: Re(<x|P|x>) """ p_size = len(P.qubits)...
71,662
def download_blob(blob, file_group, destination, blob_service, progress_callback): """Download the specified file to the specified container""" def _wrap_callback(curr, total): if progress_callback: progress_callback(curr, total, destination) blob_service.get_blob_to_path( get_...
71,663
def test_checkpoint_save_ckpt_seconds(): """Test checkpoint save ckpt seconds.""" train_config = CheckpointConfig( save_checkpoint_steps=16, save_checkpoint_seconds=100, keep_checkpoint_max=0, keep_checkpoint_per_n_minutes=1) ckpt_cb = ModelCheckpoint(config=train_config) ...
71,664
def get_entry_points(config): """Process the [entry_points] section of setup.cfg. Processes setup.cfg to handle setuptools entry points. This is, of course, not a standard feature of distutils2/packaging, but as there is not currently a standard alternative in packaging, we provide support for them. ...
71,665
def beginColumn(where=None, x=0, y=0, width=-1, height=-1, padding=0, bgColor=None): """Start a new column. One of the most annoying tasks when building UI is to calculate where each component should be placed on the screen. cvui has a set of methods that abstract the process of positioning components, so you don't ...
71,666
def _label_haplotypes(labels, genotype, interval=None): """Label each haplotype in a genotype with the index of its first occurance. Parameters ---------- labels : ndarray, int, shape(ploidy, ) An array to be updated with the haplotype labels genotype : ndarray, int, shape (ploidy, n_ba...
71,667
def scp(mc_endpoint, verify, no_cache, token, oa_account, iss, dry_run, scp_command): """Copies files between hosts on a network over SSH using the provided OIDC Access Token to authenticate. The SOURCE and TARGET may be specified as a local pathname, a remote host with optional path in the form [user@...
71,668
def TickMonitoringCustomMetric(metric_name): """Increments the stackdriver custom metric with the given name. This is used for cron job monitoring; if these metrics stop being received an alert mail is sent. For more information on custom metrics, see https://cloud.google.com/monitoring/custom-metrics/using-cu...
71,669
def multiple_assign(module: tf.Module, parameters: Dict[str, tf.Tensor]): """ Multiple assign takes a dictionary with new values. Dictionary keys are paths to the `tf.Variable`s or `gpflow.Parameter` of the input module. :param module: `tf.Module`. :param parameters: a dictionary with keys of the f...
71,670
def convert_all(input_dir, output_dir): """ convert a whole directory of xml files Parameters ---------- input_dir : str path to the directory containing .phonwords files output_dir : str desired location of the output textgrids """ succ = 0 total = 0 with open(...
71,671
def dag_shortest_path(graph, start, **kwargs): """Finds the single-source shortest path in a directed acyclic graph. Allows for negative weights, running time is linear in the number of edges. For custom node classes, **kwargs can be used to redirect encapsulated attributes, e.g.: (args, ..., 'neig...
71,672
def __define_matriz(tamanho: int) -> List[List]: """ Metodo de definicao da matriz. :return: Matriz em forma de lista """ _matriz = __cria_matriz_quadrada(tamanho) return _matriz
71,673
def logout(): """User logout route.""" do_logout() return redirect(url_for('auth.index'))
71,674
def _maybe_expand_labels(labels, predictions): """If necessary, expand `labels` along last dimension to match `predictions`. Args: labels: `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels] or [D1, ... DN]. The latter implies num_labels=1, in which case the result is an expanded `labels...
71,675
def quat_loss_geodesic(q1, q2): """ Geodesic rotation loss. Args: q1: N X 4 q2: N X 4 Returns: loss : N x 1 """ q1 = torch.unsqueeze(q1, 1) q2 = torch.unsqueeze(q2, 1) q2_conj = torch.cat([ q2[:, :, [0]] , -1*q2[:, :, 1:4] ], dim=-1) q_rel = hamilton_prod...
71,676
def _expectation(p, mean1, none1, mean2, none2, nghp=None): """ Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.), m2(.) :: Constant mean functions :return: NxQ1xQ2 """ return mean1(p.mu)[:, :, None] * mean2(p.mu)[:, None, :]
71,677
def get_accuracy(y_true, y_predicted): """Compute the accuracy for given predicted class labels. Parameters ---------- y_true: numpy array The true class labels of shape=(number_points,). y_predicted: numpy array The predicted class labels of shape=(number_points,). Returns ...
71,678
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ with Configurator(settings=settings) as config: config.include("pyramid_chameleon") config.include(".routes") init_database() config.scan() return config.make_wsgi_app()
71,679
def make_stream_dict(m): """Adds _streams to m, which contains a dictionary of streams for display Args: m (ConcreteModel): A Pyomo model from create_model() Returns: None """ m._streams = OrderedDict( [ ("FUEL_IN", m.fs.reformer_recuperator.tube_inlet), ...
71,680
def process_csv(filename): """Actual CSV file processing logic """ num_attached = num_notattached = 0 sum_attached = sum_notattached = 0 num_nomember = num_nopayment = num_nocycle = num_old = 0 log_user = User.objects.get(id=1) with open(filename, 'r') as f: reader = csv.reader(f) ...
71,681
def make_motif(desc, full_name, rep_list, seq_left, seq_right, rep_type, chromosome, start, end, unmapped, mapq, min_flank, min_flank_complex, min_rep): """ Make motif for config file. :param desc: str - motif description :param full_name: str - motif full name :param rep_list: list(R...
71,682
def get_connections(network): """ Function creates a dictionary with agent id's as a key and adjacent nodes as a value. :param network: object of graph :type network: networkx.classes.graph.Graph """ return {agent_id: list(adj_agents.keys()) for (agent_id, adj_agents) in network.adjacency()}
71,683
def run_length_encode(mask): """ Descripition: Convert mask image into run-length enconde. Args ----- mask: A simple of gray image. The simple consists of digital signals(1 and 0). Returns -------- rle: A list of positions which encoded by run-length. """ signals = np....
71,684
def cube_attack(f, X, y, eps, n_trials, p=0.5, deltas_init=None, independent_delta=False, min_val=0.0, max_val=1.0): """ A simple, but efficient black-box attack that just adds random steps of values in {-2eps, 0, 2eps} (i.e., the considered points are always corners). The random change is added if the loss dec...
71,685
def svn_utf_initialize(*args): """svn_utf_initialize(apr_pool_t pool)""" return _core.svn_utf_initialize(*args)
71,686
def update_profile(request): """Update a user's profile view.""" profile = request.user.profile if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.website = data['website'] profile.phone_number = data['phone_number'] pro...
71,687
def compute(data, ncols, alg, compress=False, n_power_iter=0): """ Compute separable NMF of the input matrix. :param data: Input matrix :type data: numpy.ndarray :param ncols: Number of columns to select :type ncols: int :param alg: Choice of algorithm for computing the columns. One of...
71,688
def prox_owl(v, w): """Proximal operator of the OWL norm dot(w, reversed(sort(v))) Follows description and notation from: X. Zeng, M. Figueiredo, The ordered weighted L1 norm: Atomic formulation, dual norm, and projections. eprint http://arxiv.org/abs/1409.4271 """ # wlog operate on ab...
71,689
def get_repo(path="."): """ Returns a git repo from the specified path :param path: is the optional path to the git repo :return: git.Repo representing the input path """ return git.Repo(path)
71,690
def setplot(plotdata): """ Plot solution using VisClaw. """ from mapc2p import mapc2p import numpy as np from clawpack.visclaw import colormaps plotdata.clearfigures() # clear any old figures,axes,items data plotdata.mapc2p = mapc2p # Figure for contour plot plotfigure = ...
71,691
def disclaimers(): """Sign-in disclaimer.""" return render_template("disclaimers.html", routes_to=url_for(request.args["routes_to"]))
71,692
def meta_name(file_name): """Generate the name of the meta file""" return "{}.json".format(file_name)
71,693
def quicksort_r(array, left, right): """Quicksort recursion.""" if right > left: pivot_i = partition(array, left, right) quicksort_r(array, left, pivot_i - 1) quicksort_r(array, pivot_i + 1, right)
71,694
def has_down(pdgid): """Does this particle contain a down quark?""" return _has_quark_q(pdgid, 1)
71,695
def main(wg_iface, base_url=None, config_file=None, verbose=False, dryrun=False): """ Fetches data from Encrypt.me, parses local WireGuard interface configuration information and ensures all peers are configured correctly based on any changes. """ # get the config data from Encrypt.me and from w...
71,696
def _JMS_to_Flavio_VII(C, parameters): """From JMS to flavio basis for class VII, i.e. flavour blind operators.""" d = {} dtrans = json.loads(pkgutil.get_data('wilson', 'data/flavio_jms_vii.json').decode('utf8')) for cj, cf in dtrans.items(): d[cf] = C.get(cj, 0) gs = sqrt(4 * pi * parameter...
71,697
def to_csv(lattice, filepath: str): """This method saves the lattice to a csv file Args: filepath: path to the csv file """ # volume to panda dataframe vol_df = lattice.to_panadas() # specifying metadata and transposing it metadata = pd.DataFrame({ 'minbound': lattice.minbo...
71,698
def static_file(path): """ apps/static下静态文件获取(本视图函数只针对apps/static下的图片),apps/static下其他可以直接哟你flask默认的 注意:图片获取路由(apps/static下) 参数w,h可指定图片大小 :param path:原图片路径 :param w:获取的宽 :param h:获取的高 :return:w和h都大于0则返回相应尺寸图片; w和h都等于0则返回原图; 其中一个值大于0则返回以这个值为基础等比缩放图片 """ w = str_to_num(request.args...
71,699