content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_nblocks_ntraces(f,nblocks,ntraces,pts,nbheaders,dt,read_blockhead): """ Read n blocks from a Varian binary file which may have multiple traces per block. Parameters: * f File object of Varian binary file to read from. * nblocks Number of blocks to read. * ...
b99ddcf842dbc02e1afb9067e198e7e241d1a8c0
1,600
def calcMedian(list_o_tuples): """Given a list of tuples (A, B), where A = category, and B = counts, returns A that represents the median count value""" #calc total ct = 0 for (a, b) in list_o_tuples: ct += float(b) med = ct / 2 #find A ct = 0 for (i, (a, b)) in enumerate(li...
f09a9ac4b1e7a84982bf6b33e4f43e1b2c9f64f6
1,601
def add(n1, n2): """Adds the 2 given numbers""" return n1 + n2
ca670819dab8230e355e1b236d9cc74ed0b3b868
1,602
def kwarg_any(kwarg_functions): """Resolve kwarg predicates with short-circuit evaluation. This optimization technique means we do not have to evaluate every predicate if one is already true. """ return any(kwarg_function() for kwarg_function in kwarg_functions)
3303e1a871bb41920ba0f41e4928e05b6d876c1e
1,603
def _behler_parrinello_cutoff_fn(dr: Array, cutoff_distance: float=8.0) -> Array: """Function of pairwise distance that smoothly goes to zero at the cutoff.""" # Also returns zero if the pairwise distance is zero, # to prevent a particle from interacting with itself. return jnp....
707f3521edf1be13c6f3c830404f851a8b606613
1,604
from typing import Tuple from typing import Optional def _get_build_to_download(build: str) -> Tuple[str, Optional[str]]: """Get the build version to download. If the passed value is not an explict build number (eg. 15.0) then the build for the current day of that major/minor will be downloaded. :p...
96215d80af60c25877da3eb7ff65147b2652a592
1,605
def label(type=None, is_emphasis=True, is_label_show=False, label_pos=None, label_text_color="#000", label_text_size=12, formatter=None, **kwargs): """ Text label of , to explain some data information about graphic item like value, name and so on...
728997988797baef2ad080c8a317936e91f5c579
1,606
def MPC_ComputeCrc(card_type: TechnologyType, frame: bytes) -> bytes: """Computes frame CRC Parameters ---------- card_type : TechnologyType Technology type frame : bytes Input frame Returns ------- bytes CRC bytes """ if not isinstance(card_type, Techno...
3a545aea7adbae35d7fa3a8f4bd758a45dae78ae
1,607
def max_contiguous(input, value, _builder=None): """ Let the compiler knows that the `value` first values in :code:`input` are contiguous. """ value = _constexpr_to_value(value) return semantic.max_contiguous(input, value)
6e90d76487677c270ecd73ece7ebbf39e4fdb9bf
1,608
import torch def kl_reverse(logu: torch.Tensor) -> torch.Tensor: """ Log-space Csiszar function for reverse KL-divergence D_f(p,q) = KL(q||p). Also known as the exclusive KL-divergence and negative ELBO, minimizing results in zero-forcing / mode-seeking behavior. Args: logu (torch.Tensor...
fcc9035de183cb6d5b51e169dd764ff92ab290aa
1,609
import sys def twos_comp_to_signed(val: int, n_bits: int) -> int: """ Convert a "two's complement" representation (as an integer) to its signed version. Args: val: positive integer representing a number in two's complement format n_bits: number of bits (which must reflect a whole numb...
cfd9556b79cee7f07c9f7ba8cfa781907fa5da45
1,610
import os def delete_file(subject_file_id): """deletes a particular file :rtype tuple :return (subject_file_id, deleted_file_path) """ file_entity = SubjectFileEntity.query.filter_by(id=subject_file_id).one() file_path = file_entity.get_full_path(app.config['REDIDROPPER_UPLOAD_SAVED_DIR']) ...
99cd73c52717fa18c1a5e965b78d788337df7db0
1,611
import os import shlex import subprocess def do_lint() -> str: """ Execute pylint """ check_command_exists("pylint") with safe_cd(SRC): lint_output_file_name = f"{PROBLEMS_FOLDER}/lint.txt" if os.path.isfile(lint_output_file_name): os.remove(lint_output_file_name) ...
1d7454ea9df06599f6802e55cf4f7cd5e76d4e53
1,612
import json def json_configs(type, name): """ Base method that extracts the configuration info from the json file defined in SETTINGS Args: type - the name of the type of configuration object to look in name - the name of the object whose configs will be extracted Returns...
57507adc7a41666084df734972e067015d055cce
1,613
def reload() -> bool: """Gracefully reloads uWSGI. * http://uwsgi.readthedocs.io/en/latest/Management.html#reloading-the-server """ return False
f020356774d0a500b6755d53d548a804392c39d3
1,614
import re def predict_imagen(titulo=None, grados=None, ano_lanzamiento=None, paginas=None, codbarras=None): """ Predictor for Imagen from model/5a143f443980b50a74003699 Created using BigMLer """ tm_tokens = 'tokens_only...
ecee556bf9eb563cb40bf759bb6c4bfdf74922a0
1,615
def traducir_texto(texto, lenguaje_destino): """ Permite traducir un texto de entrada. .. note:: Es importante tener en cuenta los siguientes aspectos al utilizar la \ función **traducir_texto**: * La función utiliza la librería googletrans, que hace uso de la API \ de ...
d075b9216f7fc8a53778b41b3a5a7ac67e7556f1
1,616
def euler_to_axis_angle(roll: float, pitch: float, yaw: float) -> np.ndarray: """Converts Euler angle to Axis-angle format. Args: roll: rotation angle. pitch: up/down angle. yaw: left/right angle. Returns: Equivalent Axis-angle format. """ r = Rotation.from_euler('xyz', [roll, pitch, yaw]) ...
89fff617c2335c35110fa0cf2f7a2d1da194846c
1,617
def add_scalebar(axis, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): """ Add scalebars to axes Adds a set of scale bars to *ax*, matching the size to the ticks of the plot and optionally hiding the x and y ax...
2d481f0313608a1a29d3c99fe4ac21faf1ab1d9d
1,618
import getopt import sys def parse_args(): """Parse and enforce command-line arguments.""" try: options, args = getopt(sys.argv[1:], "l:dh", ["listen=", "debug", "help"]) except GetoptError as e: print("error: %s." % e, file=sys.stderr) print_usage() sys.exit(1) liste...
15225a7d0802787c0ede62b3c94a9af09b92ed33
1,619
def create_medoids_summary(season, country, result, d, names): """ Create cluster based summary of medoids' description Parameters: season: str, season sued to cluster country: str, used to cluster result: cluster resutls joint to customer features d: trajectory clustering re...
b86a266a7bf31ccd836b653d1e137f60d65c02ff
1,620
from typing import Iterable import time def backtest( strategy, data, # Treated as csv path is str, and dataframe of pd.DataFrame commission=COMMISSION_PER_TRANSACTION, init_cash=INIT_CASH, data_format="c", plot=True, verbose=True, sort_by="rnorm", **kwargs ): """ Backtest...
4822d7f6ec2bdc260b084408b3668c0636c5f19c
1,621
def mapflatdeep(iteratee, *seqs): """ Map an `iteratee` to each element of each iterable in `seqs` and recurisvely flatten the results. Examples: >>> list(mapflatdeep(lambda n: [[n, n]], [1, 2])) [1, 1, 2, 2] Args: iteratee (object): Iteratee applied per iteration. ...
df297c279f93edca4bff348189386241832c7e5b
1,622
def eHealthClass_getSkinConductanceVoltage(): """eHealthClass_getSkinConductanceVoltage() -> float""" return _ehealth.eHealthClass_getSkinConductanceVoltage()
f97edfe96d443991a16cb94a405806815c29546a
1,623
def construct_item(passage: str, labels): """ 根据输入的passage和labels构建item, 我在巴拉巴拉... ['B-ASP', 'I-ASP', 'I-ASP', 'I-ASP', ..., 'I-OPI', 'I-OPI', 'O'] 构造结果示例如下: { 'passage': '使用一段时间才来评价,淡淡的香味,喜欢!', 'aspect': [['香味', 14, 16]], 'opinion': [['喜欢', 17, 19]] } :return: ...
b4a31b67df7c82b56e0eb388e964422f257a9293
1,624
def getStartingAddress(packet): """Get the address of a modbus request""" return ((ord(packet[8]) << 8) + ord(packet[9]))
83dc55585d67169b0716cc3e98008574c434213b
1,625
from typing import Union def rf_local_unequal(left_tile_col, rhs: Union[float, int, Column_type]) -> Column: """Cellwise inequality comparison between two tiles, or with a scalar value""" if isinstance(rhs, (float, int)): rhs = lit(rhs) return _apply_column_function('rf_local_unequal', left_tile_c...
3d2b95d35744f35c4f27802952366a5ffb1cf557
1,626
def get_normalized_star_spectrum(spectral_type, magnitude, filter_name): """ spec_data = get_normalized_star_spectrum(spectral_type, magnitude, filter_name) Returns a structure containing the synthetic spectrum of the star having the spectral type and magnitude in the specified input filter. Magnitude...
001406dc4ffa1bc08960c27950333965ffa07836
1,627
def header(**kwargs): """ Create header node and return it. Equivalent to :code:`return Element("header", attributes...)`. """ return Element("header", **kwargs)
e02784bbb8bf153fc7c815fb06a3e1246dbb1847
1,628
def bump_func(xs_arg, low, high, btype): """ Setup initial displacement distribution of a bump, either sine or triangular. """ # check the case of a single float as input if isinstance(xs_arg, (int, float)): xs_in = np.array([float(xs_arg)]) scalar = True else: xs_in ...
22991769be4f0c09992fcf3a069d05f98e6c0d55
1,629
def setup_session(username, password, check_url=None, session=None, verify=True): """ A special call to get_cookies.setup_session that is tailored for URS EARTHDATA at NASA credentials. """ if session is not None: # URS connections cannot be kept alive at the moment. ...
e5d6eae8c79343249a7d22b1a8e90f94d4ee2420
1,630
import numbers def is_number(item): """Check if the item is a number.""" return isinstance(item, numbers.Number)
6c3fb6817a0eda2b27fcedd22763461dceef6bc1
1,631
def from_list(commands): """ Given a list of tuples of form (depth, text) that represents a DFS traversal of a command tree, returns a dictionary representing command tree. """ def subtrees(commands, level): if not commands: return acc = [] parent, *commands...
39dad022bf81712e074f6e8bb26813302da9ef9f
1,632
def get_cassandra_config_options(config): """Parse Cassandra's Config class to get all possible config values. Unfortunately, some are hidden from the default cassandra.yaml file, so this appears the only way to do this.""" return _get_config_options(config=config, config_class='org.apache.cassandra.config...
2a52a50bed46105c7c1a1ea85e0c10a33ee02de1
1,633
def get_possible_zeros(coefficients: list) -> list: """Rational Zeros Theorem possible zeros of a polynomial function. Args: coefficients (list): The coefficients of a polynomial function, in order of degree including all from a_n to a_0. Returns: list: A list containing all possib...
751337e2a324ddba126ced8a896630eb816c63a6
1,634
import site def view() -> pn.Column: """# Bootstrap Dashboard Page. Creates a Bootstrap Dashboard Page with a Chart and a Table - inspired by the [GetBoostrap Dashboard Template] (https://getbootstrap.com/docs/4.4/examples/dashboard/) - implemented using the `awesome_panel' Python package and in...
d3365ca9064a2354d5e848dd2c7666d90241c456
1,635
import doctest def load_tests(loader, tests, ignore): """ Creates a ``DocTestSuite`` for each module named in ``DOCTEST_MODULES`` and adds it to the test run. """ for module in DOCTEST_MODULES: tests.addTests(doctest.DocTestSuite(module)) return tests
33befd96fc2401fe0ae4b03b4d8eb26098273150
1,636
def buildGeneMap(identifiers, separator="|"): """build map of predictions to genes. Use an identifier syntax of species|transcript|gene. If none is given, all transcripts are assumed to be from their own gene. """ map_id2gene, map_gene2ids = {}, {} for id in identifiers: f = id.spli...
e854639142bd600338563ffc1160b43359876cdd
1,637
import warnings import requests import json def get_kline(symbol, end_date, freq, start_date=None, count=None): """获取K线数据 :param symbol: str 聚宽标的代码 :param start_date: datetime 截止日期 :param end_date: datetime 截止日期 :param freq: str K线级别,可选值 ['1min', '5min', '30min', ...
5750784f2ef0a3080eac881faa1ee33d6b3b1a3d
1,638
from typing import Type from typing import Optional from typing import Dict from typing import Any def create_trial_instance( trial_def: Type[det.Trial], checkpoint_dir: str, config: Optional[Dict[str, Any]] = None, hparams: Optional[Dict[str, Any]] = None, ) -> det.Trial: """ Create a trial i...
2a8bec728d874e448686c4d67792885f915feb01
1,639
def magnitude(number: SnailNumber) -> int: """Calculates the magnitude of asnail number Args: number (SnailNumber): input number Returns: (int): mangitude Examples: >>> magnitude([[1, 1], [2, 2]]) 35 >>> magnitude([[[[0,7],4],[[7,8],[6,0]]],[8,1]]) 1384...
d89099f97e2c96e2e41c1e47a3b7ee74f5f0111c
1,640
import tarfile def _load_model_from_tarball(tarball_path, gpg_home_dir): """Load a model from a tarball Args: tarball_path: a path to a model gzipped tar file gpg_home_dir: home directory for gpg to verify signed model (e.g. path/to/.gnupg) Returns: something of type Serializable...
cf6e9dedc0278847011ffaf0470813230d83e2dc
1,641
def strip_begin_end_key(key) : """ Strips off newline chars, BEGIN PUBLIC KEY and END PUBLIC KEY. """ return key.replace("\n", "")\ .replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "")
ef989872c5c1c136114310c142a0f989e2f888ca
1,642
def add_expdvr(npoints: int, qmin: float, qmax: float) -> DVRSpecification: """Register a new exponential DVR Args: npoints (int): number of grid points qmin (float): minimal x value qmax (float): maximal x value """ return DVRSpecification("ExponentialDVR", npoints, qmin, qmax)
c0a6aa6f349433fc0c4266807343d73fad37a279
1,643
import os import logging def main(): """Main CLI function. :rtype: int :returns: exit code, which is sum of all exit codes """ opts, args = parse_args() setup_logging(opts.verbose) if opts.show_configs: print_configs() return 0 build_env = os.environ.copy() chpl_...
dee02bd8c7c4de774f35f5bd5120b3fc4b1c989d
1,644
def sync_now(r, **attr): """ Manual synchronization of a repository @param r: the S3Request @param attr: controller options for the request """ T = current.T auth = current.auth response = current.response rheader = attr.get("rheader", None) if rheader: rhe...
85ac3be60da29982ac203dee2b408e18422f431a
1,645
def checkdnsrr(): """Check DNS records corresponding to a given Internet host name or IP address""" return NotImplementedError()
7fda596230cc5f61e946e8a0949c67f365cf5563
1,646
from re import I def get_horizontal_rainbow_00(): """ Returns the main horizontal rainbow Programs that use this function: - Diagonal Ripple 1 - Diagonal Ripple 2 - Diagonal Ripple 3 - Diagonal Ripple 4 - Double Ripple 1 - Double Ripple 2 - Double R...
86c1d632f3a9e7df94c710a323cd099bb5602e19
1,647
def xml_attr_or_element(xml_node, name): """ Attempt to get the value of name from the xml_node. This could be an attribute or a child element. """ attr_val = xml_node.get(name, None) if attr_val is not None: return attr_val.encode('utf-8').strip() for child in xml_node.getchildren()...
4ec061a9a865291d8d26d8de474141175d5aab28
1,648
import numpy def kmeans_init_centroids(x_array, num_centroids_K): """ This function initializes K centroids that are to be used in K-means on the dataset x_array. Parameters ---------- x_array : array_like The dataset of size (m x n). num_centroids_K : int The number of clust...
2e310dd3fe9eb6dd32999e32f583fc4a7fd0bbf0
1,649
def get_coinbase_candle_url(url, timestamp_from, pagination_id): """Get Coinbase candle URL.""" start = timestamp_from.replace(tzinfo=None).isoformat() url += f"&start={start}" if pagination_id: url += f"&end={pagination_id}" return url
a1bb4e975060ba5e3438b717d1c2281349cd51f1
1,650
def part2(): """This view will be at the path ``/part2``""" return "Part 2"
92a8789b669a66989a74be2c2126e8958e4beece
1,651
def create_strings_from_file(filename, count): """ Create all strings by reading lines in specified files """ strings = [] with open(filename, 'r') as f: lines = [l.strip()[0:200] for l in f.readlines()] if len(lines) == 0: raise Exception("No lines could be read in...
35eac3661e31f8e6e895c7575ad725a7ea27d846
1,652
def drive_around(a_th_gld=1.2): """ Function that implements the logic with which the robot will decide to navigate in 2D space, it is essentially based on the (frontal and lateral) distance values of the golden tokens obtained by find_obstacles() Args: dist_left (float): distance of the closest golden token o...
c4ea2b855fdf40bc268232d11ff58f45362878b5
1,653
def a_request(session_request): """AnonymousUser request""" session_request.user = AnonymousUser() return session_request
ea651f420e62c455ee63ae1d158a07be719fa48c
1,654
def subplot_index(nrow, ncol, k, kmin=1): """Return the i, j index for the k-th subplot.""" i = 1 + (k - kmin) // ncol j = 1 + (k - kmin) % ncol if i > nrow: raise ValueError('k = %d exceeds number of rows' % k) return i, j
2d2b7ef9bf9bc82d06637157949ca9cb3cc01105
1,655
import os import glob def read_transport_maps(input_dir, ids=None, time=None): """ Find and parse all transport maps in a directory. Returns a list containing the transport maps and start/end timepoints. Parameters ---------- input_dir : str The directory in which to look for transpor...
d296e0033b2c58b19e92cdcfe7574c27036d57c3
1,656
def _split_keys(keypath, separator): """ Splits keys using the given separator: eg. 'item.subitem[1]' -> ['item', 'subitem[1]']. """ if separator: return keypath.split(separator) return [keypath]
2f67a35a2e08efce863d5d9e64d8a28f8aa47765
1,657
from contextlib import suppress import subprocess def get_code_base_url() -> str | None: """Get current code base url.""" code_base = None with suppress(subprocess.CalledProcessError): code_base = subprocess.check_output("git config --get remote.origin.url".split()).decode("utf-8").strip() ret...
f2e04852a4f3325cd3c8510dbb8051799b0b4ae6
1,658
def _get_referenced_type_equivalences(graphql_types, type_equivalence_hints): """Filter union types with no edges from the type equivalence hints dict.""" referenced_types = set() for graphql_type in graphql_types.values(): if isinstance(graphql_type, (GraphQLObjectType, GraphQLInterfaceType)): ...
f92f4dba0d694e17ebecdb62922b121eeba23f87
1,659
import numpy def E(poly, dist=None, **kws): """ Expected value operator. 1st order statistics of a probability distribution or polynomial on a given probability space. Args: poly (Poly, Dist) : Input to take expected value on. dist (Dist) : Defines the space the expected value is...
c3f051e522e0cecf0b951c194c43850b4016dd17
1,660
def spacify(string, spaces=2): """Add spaces to the beginning of each line in a multi-line string.""" return spaces * " " + (spaces * " ").join(string.splitlines(True))
7ab698d8b38a6d940ad0935b5a4ee8365e35f5da
1,661
def simple_line_plot(x, y = None, title = "", xlabel = "", ylabel = "", context = 'notebook', xlim = None, ylim = None, color = 'blue', parse_axe...
6839b12307c2ab8e2747f8d8fe8f913126253a28
1,662
def generate(parsed_data, template, opath, dme_vault, helper, **kwargs): """Generates collection and data-object metadata needed for DME upload. For each collection (directory) and data-object (file), an output file is generated in JSON format. 'opath' dictates where these files will be saved. Returns a...
885c25f4d7dcb933449bbf028f00a6cecae4233a
1,663
from pysnmp.entity.rfc3413.oneliner import cmdgen def _get_snmp(oid, hostname, community): """SNMP Wrapper function. Returns tuple of oid, value Keyword Arguments: oid -- community -- """ cmd_gen = cmdgen.CommandGenerator() error_indication, error_status, error_index, var_bind =...
8911dbeece2bac9cc398fafc6a8fde8033752d00
1,664
from fontbakery.utils import get_glyph_name def com_google_fonts_check_048(ttFont): """Font has **proper** whitespace glyph names?""" def getGlyphEncodings(font, names): result = set() for subtable in font['cmap'].tables: if subtable.isUnicode(): for codepoint, name in subtable.cmap.items()...
baa2c101859bc08060ff23d9bc12d2c3e573bc44
1,665
import re def ensure_format_is_valid( r, dataset_name ): """ This extracts the format from the given resource and maps it according to the formats mapping, if provided.""" if not 'format' in r: log.error( '%s resources-object is missing format-property. Cannot save this value', dataset_name )...
08311e9642d9cb3415e24f2764c792347e45c986
1,666
def find_nearest(array, value): """ Inputs: array - array... value - value to search for in array Outputs: array[idx] - nearest value in array """ array = np.asarray(array) idx = (np.abs(array - value)).argmin() return array[idx]
f65156f8b084e8dff388fe51f56162be668a1bbc
1,667
def sync_contacts(contacts, create_missing=True, quiet=True): """ contacts is a list of dictionaries like this: [{ u'E-Mail': u'[email protected]', u'Gender': 2, u'First Name': u'Admin', u'Last Name': u'von Total Berlin', ... ...
f5b893868ffd9e967ed17593a9d89b3cc45141f0
1,668
def vader_entity_sentiment(df, textacy_col, entity, inplace=True, vader_sent_types=['neg', 'neu', 'pos', 'compound'], keep_stats=['count', 'mean', 'min', '25%', '50%', '7...
6ef61a7f79c5ff148cf35309e3f828ffa17947f6
1,669
def post_list(request): """ Create a view that will return a list of Posts that were published prior to 'now' and render them to the 'blogposts.html' template :param request: :return: """ posts = Post.objects.filter(published_date__lte=timezone.now() ).or...
043aff58ba50934d06b6a8221bcf270d1d0f98f5
1,670
def get_model(): """ Returns a compiled convolutional neural network model. Assume that the `input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`. The output layer should have `NUM_CATEGORIES` units, one for each category. """ # initialize a convolutional model model = tf.keras.mo...
735d6fc343a1e1eb1ab3cce51387284bfee113ba
1,671
def get_app_icon_path(): """Path to OpenPype icon.""" return resources.get_openpype_icon_filepath()
20985ef5f0ada38ff466bb9160ea2264d53a83f4
1,672
def post_create_ipsec_endpoint_tunnel( api_client, endpoint_id, remote_subnet=None, local_subnet=None, enabled=None, ping_ipaddress=None, ping_interface=None, ping_interval=None, description=None, **kwargs ): # noqa: E501 """post_create_ipsec_endpoint_tunnel # noqa: E501 ...
c876113db138db252274d3f07ecec30ba4796701
1,673
from typing import List from datetime import datetime def cow_service( wfo: List[str] = Query( [], min_length=3, max_length=4, title="WFO Identifiers" ), begints: datetime = Query(...), endts: datetime = Query(...), phenomena: List[str] = Query(None, max_length=2), lsrtype: List[str] =...
2e565deb0e2534c125fec70823c51ea6952ccbf4
1,674
def add_edges_reverse_indices(edge_indices, edge_values=None, remove_duplicates=True, sort_indices=True): """Add the edges for (i,j) as (j,i) with the same edge values. If they do already exist, no edge is added. By default, all indices are sorted. Args: edge_indices (np.array): Index list of shape...
0b35d67b6322371d7c7fac35d45b3c4a7da3bda1
1,675
from typing import Any def isint(var:Any, raise_error:bool=False)-> bool: """Check if var is an integer Args: var (str): variable to check raise_error (bool, optional): TypeError raised if set to `True`. Defaults to `False`. Raises: TypeError: raised if var is not an integer ...
c4698e4cead5fdd7c73b3efebd3c475c3cbdeca3
1,676
def convert_interpolate2d(g, op, x): """Operator converter for interpolate 2D(dims == 4).""" def get_interpolate_mode(op): """conver 'interp_method' attr of paddle to tvm""" interp_method = op.attr("interp_method") align_corners = op.attr("align_corners") align_mode = op.attr("...
9c089baf0a5d8d8ff78d3cadff1e17d8a19b7b0d
1,677
def get_stats_on_spatial_predictions_4x5_2x25_by_lat(res='4x5', ex_str='', target='Iodide', use_annual_mean=False, filename=None, folder=None, ds=None, ...
dbcd103a3f3a7b6ab97439dec7ca43ced776a434
1,678
import math def calc_dif_mod_cn (x, y): """ Check if the difference between the modulus of consecutive numbers is a prime number """ modx = math.sqrt(x.real ** 2 + x.imag ** 2) # modulus of the first complex number mody = math.sqrt(y.real ** 2 + y.imag ** 2) # modulus of the second complex number d...
88e353e4a948c3b6adc65b91265a5f6d2e68a1c1
1,679
import re def mitochondrialGTF(concatenated_gff, output_directory): """Convert GFF file with information for mitochondrial genes to GTF and return the path to GTF file. Keyword arguments: concatenated_gff -- path to concatenated GFF file output_directory -- path to directory where GTF file should be placed Imp...
24c0987d5c2208b1a96020b8eea19791c86b3f5e
1,680
def get_none_zero_region(im, margin): """ get the bounding box of the non-zero region of an ND volume """ input_shape = im.shape if(type(margin) is int ): margin = [margin]*len(input_shape) assert(len(input_shape) == len(margin)) indxes = np.nonzero(im) idx_min = [] idx_max =...
6ca56b94becd254b0ecbaf85e25475bb574586a9
1,681
import json from datetime import datetime def create_short_link(request): """Given an URL, return a shortened link. Args: url: URL to be shortened. Returns: short_link: Shortened result of URL. expires_at: Timestamp before which the link is valid. """ payload = json.loads(requ...
4d870b21484ced46e5fd538545cb5cca6c1b3b8a
1,682
import gzip def get_mapped_tracks_file(mode='r', **kwargs): """ Returns a file descriptor-like object to the file containing the raw track. (A mapped track is a collection of tuples). Each tuple is: - linking pairs - paths - linking pairs - points Arguments: mode: r/w mode driver_id: s...
281ba7bd0f05b61fb13041c2193caed1de1f918f
1,683
def ne_2beta(r, ne0, rc_outer, beta_outer, f_inner, rc_inner, beta_inner): """ Electron number density [cm^-3] in the double-beta profile of the hydrostratic equilibrium model. r : distance from the center of the cluster [kpc] ne0 : central electron number density [cm^-3] rc_outer : core radius fro...
cac79f2f9a76cb94c2ad08c344844ddec6ff3a45
1,684
def sell(): """Sell shares of stock""" """Sell shares of stock""" if request.method == "POST": symbol = request.form.get("symbol") amount = request.form.get("shares") try: amount = int(amount) except: return apology("enter a proper value") prin...
ae385e94eb6765eca7b9b4b74ef3320c2a265e62
1,685
from typing import Any def assemble_block(n_rows: Int, n_cols: Int, pdf: pd.DataFrame, cov_matrix: NDArray[(Any, Any), Float], row_mask: NDArray[Any]) -> NDArray[Float]: """ Creates a dense n_rows by n_cols ...
25f8c3923050c64cb4c7a7b9842007a9e8d7723b
1,686
def calc_xixj_from_braggphi( det_cent=None, det_nout=None, det_ei=None, det_ej=None, det_outline=None, summit=None, nout=None, e1=None, e2=None, bragg=None, phi=None, option=None, strict=None, ): """ Several options for shapes de_cent, det_nout, det_ei and det_ej are always of shape (3,...
f11829d0d3dfe6b523a8336c8b7dbf5cfaa9f36e
1,687
def _check_index_good(X): """Check the index of X and return boolean.""" # check the first index elements for "__total" tot_chk = np.any(X.index.get_level_values(level=0).isin(["__total"])) return tot_chk
8e39b7d18af2c247c427a4e9658fc1e18ff1dd89
1,688
def seguimientos_list_csv(request, codigo): """Lista todos los eventos de seguimiento para cada proyecto de ley. --- type: codigo: required: true type: string parameters: - name: codigo description: código del proyecto de ley incluyendo legislatura, por ejemplo 00002...
846d8da6dac93d23eb444b023e1de4fb123a579f
1,689
import torch def endpoint_error(estimate, ground_truth): """Computes the average end-point error of the optical flow estimates.""" error = torch.norm( estimate - ground_truth[:, :2, :, :], 2, 1, keepdim=False) if ground_truth.size(1) == 3: mask = (ground_truth[:, 2, :, :] > 0).float() ...
f40de83768ad6760620120c59eb377d1e12ff8b1
1,690
import functools def output(log_message=None, success_message=None, fail_message=None): """This is a decorator to trap the typical exceptions that occur when applying and removing modules. It returns the proper output corresponding to the error messages automatically. If the function return...
18d39d94c930a0ec99e0fb122f20e3a18d62328d
1,691
def custom_mape(approxes, targets): """Competition metric is a slight variant on MAPE.""" nominator = np.abs(np.subtract(approxes, targets)) denominator = np.maximum(np.abs(targets), 290000) return np.mean(nominator / denominator)
7c8b8eab352f516c63202ef0b26253265acc68a4
1,692
import collections import re def article_text_to_dict(article_text: str): """ Translates an article text into a dict. """ data = collections.defaultdict(list) field = '' for line in re.split(r'\n+', article_text): # Fix little bug with isi files if line.startswith('null'): ...
84ac8d96840696e1392de3dbf87ab7026978d36c
1,693
def frohner_cor_3rd_order(sig1,sig2,sig3,n1,n2,n3): """ Takes cross-sections [barns] and atom densities [atoms/barn] for three thicknesses of the same sample, and returns extrapolated cross section according to Frohner. Parameters ---------- sig1 : array_like Cross section of the ...
d6f0b39368c19aeda899265eb187190bb4beb944
1,694
def nodeInTree(root, k): """ Checks if the node exists in the tree or not """ if root == None: return False if root.data == k or nodeInTree(root.left, k) or nodeInTree(root.right, k): return True return False
14db01c8d2370bfaa01220d3608798165ea1a096
1,695
import struct # for handling binary data import os def read_xvec(path, base_type, N=-1): """ A utility function to read YAEL format files (xxx.ivec, xxx.fvec, and xxx.bvec) :param path: The path of xvec file :param base_type: The type of xvec; 'f', 'i' or 'b' :param N: The number of vectors t...
1bc4f857a0c1f0b1e6994d12f61006a3de9ac7c8
1,696
def split_and_filter(intermediate_str, splitter): """ Split string with given splitter - practically either one of "," or "/'". Then filter ones that includes "https" in the split pickles :param intermediate_str : string that in the middle of parsing :param splitter :return: chunk of string(s) a...
a4b800df1aca89ca1e8eedfc65a5016a995acd48
1,697
def organism_code(genus, species): """Return code from genus and species.""" return ( f"{genus[:GENUS_CODE_LEN].lower()}{species[:SPECIES_CODE_LEN].lower()}" )
6b52342ccf8388a2b8a98cc3d640dc3ea5b97e66
1,698
import os def verify_image(filename): """Verifies whether the file exists""" image_extensions = ['tif', 'jpg', 'gif', 'png', 'jpeg'] if type(filename) is str: extension = filename.split('.') if len(extension) == 2: if extension[1].lower() in image_extensions: re...
84e9845ab3e146d94f2ba3e0a2fb3ecd458b822f
1,699