content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import random def create_solution_board(width=6, height=6): """Randomly generates a new board with width by height size """ if type(width) != int or type(height) != int: raise TypeError('Arguments must be int type') boxes = width * height if boxes % 2 != 0: raise ValueError('...
0b6e30d726cec61581d93c909761f80d739eb917
10,842
from pydft.poisson import _O_operator, _L_operator, _B_operator def _getE(s,R,W,V = None): """The sum of the energies for the states present in the solution. Args: s (list of int): The number of samples points along each basis vector. R (numpy.ndarray): The basis vectors for the un...
7759c68e5774f809cfac1038014144cabe5c9410
10,843
def get_gt_list(request): """ This view returns the list of groundtruths associated to a user and a specific configuration of institute, usecase and language. .js files: InfoAboutConfiguration.js DownloadGT.js""" groundTruths = 0 json_resp = {} ins = request.GET.get('inst',None) lang = re...
46cb039c9811eac5a43c08776b59b8cef12c7133
10,844
from typing import Any from typing import MutableMapping from typing import Hashable def to_dict(item: Any) -> MutableMapping[Hashable, Any]: """Converts 'item' to a MutableMapping. Args: item (Any): item to convert to a MutableMapping. Raises: TypeError: if 'item' is a type that is ...
c3ba483bde73a35ed036debcc4b87575b1c8b962
10,845
import copy def node(*args, **kwargs): """ args[0] -- a XML tag args[1:] -- an array of children to append to the newly created node or if a unicode arg is supplied it will be used to make a text node kwargs -- attributes returns a xml.dom.minidom.Element """ blocked_attributes...
2a0f9a953d07a114e0a426f4225fb3c5076513ee
10,846
import math def mylog10(x): """Return the base-10 logarithm of x.""" return math.log10(x)
d32113c16047175125e1b79c9ce0ea8822e4853c
10,848
import numpy def get_RGB_to_RGB_matrix(in_colorspace, out_colorspace, primaries_only=False): """Return RGB to RGB conversion matrix. Args: in_colorspace (str): input colorspace. out_colorspace (str): output colorspace. Kwargs: primaries_only (bool): primaries matrix only, doesn't...
6c864fc45d254c38bc00a381f55dc3d2ad80aa9a
10,849
import re import string def normalize_string(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): regex = re.compile(r'\b(a|an|the)\b', re.UNICODE) return re.sub(regex, ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_...
85a77dca1110460a1c445cc32f78cadb8c70ebd5
10,850
def full_reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None, scheme=None, domain=None, subdomain=None): """ First, obtains the absolute path of the URL matching given ``viewname`` with its parameters. Then, prepends the path with the scheme name and the authority ...
b061cdc1369af0c60b95da58f262563e5ea93aa3
10,852
def get_object_or_none(model_class, **kwargs): """Identical to get_object_or_404, except instead of returning Http404, this returns None. """ try: return model_class.objects.get(**kwargs) except model_class.DoesNotExist: return None
d74b84e9186d9fb4faabb7eaa70f53672665d304
10,853
def GenerateTests(): """Generate all tests.""" filelist = [] for ii in range(len(_GROUPS)): filename = GenerateFilename(_GROUPS[ii]) filelist.append(filename) WriteTest(filename, ii, ii + 1) return filelist
1160454ae0fab7008051bf9d4f5d2b94a74888b9
10,854
def shift_df_generator(empty_df, day_lower_hr_lim, day_upper_hr_lim): """Generate day and night dataframe. Parameters ---------- empty_df : DataFrame A DataFrame with timestamp and 'Temperature (Celsius)' with all zeros. day_lower_hr_lim : int The lower hour limit that constitutes t...
cc8f3675d88dc920fd1762894c859cd93a523aab
10,855
import json import regex def json_loads(data, handle=False): """ 封装的json load :param data: :param handle: 补丁, False: 默认不特殊处理: True: 不走正则 :return: """ if handle: return json.loads(data.strip()) return json.loads(regex.sub(r"\\\\", data.strip()))
34156a594b203af041fba8da65601bb17da95a3e
10,856
def elina_linexpr0_size(linexpr): """ Return the size of an ElinaLinexpr0. Parameters ---------- linexpr : ElinaLinexpr0Ptr Pointer to the ElinaLinexpr0 that needs to be checked for its size. Returns ------- size_linexpr = c_size_t Size of the ElinaLinexpr0. ""...
b68a9874dd795876dae1ff2ffe3de98728e521a7
10,857
def _make_index(df, cols=META_IDX, unique=True): """Create an index from the columns/index of a dataframe or series""" def _get_col(c): try: return df.index.get_level_values(c) except KeyError: return df[c] index = list(zip(*[_get_col(col) for col in cols])) if ...
4356de2531f150c80bc364315ebf547fd345967f
10,858
import json def handler(event, context): """ Lambda Handler. Returns Hello World and the event and context objects """ print(event) print(context) return { "body": json.dumps('Hello World!') }
561326fec784aa72a133b217f1e2cecaf12ec1ad
10,859
from typing import List def flatten_concat(tensors: List[tf.Tensor], batch_dims: int = 1) -> tf.Tensor: """Flatten given inputs and concatenate them.""" # tensors [(B, ...), (B, ...)] flattened: List[tf.Tensor] = list() # [(B, X), (B, Y) ...] for tensor in tensors: final_dim = -1 if a...
1a4b9bbf12f75aff43273a7f44c659b7afecdddc
10,860
def analyze_friends (names,phones,all_areacodes,all_places): """ names: tuple of names phones: tuple of phone numbers (cleaned) all_areacodes: tuple of area codes (3char ints) all_places: tuple of places Goal: Print out how many friends you have and every unique state """ # For TES...
b90f938c9c019dc331c38cafb36d1a7e0cb3f83f
10,861
def fast_autoregressive_predict_fn(context, seq_len): """Given a context, autoregressively generate the rest of a sine wave.""" core = hk.LSTM(32) dense = hk.Linear(1) state = core.initial_state(context.shape[0]) # Unroll over the context using `hk.dynamic_unroll`. # As before, we `hk.BatchApply...
bf61799a8f34045cb214fd68095e1b9346fc797f
10,862
def get_entities(corpus_name): """ Load the dataset from the filesystem corresponding to corpus_name (to see the list of allowed names, use utils.list_corpora() ), and extract all annotated entities. Returns a dict, in which each key is an entity type, which contains a list of entity mentions in th...
274d82c4d5ae978452aaa7cf3aae14a7b86b3030
10,863
def _reporthook(t): """``reporthook`` to use with ``urllib.request`` that prints the process of the download. Uses ``tqdm`` for progress bar. **Reference:** https://github.com/tqdm/tqdm """ last_b = [0] def inner(b: int = 1, bsize: int = 1, tsize: int = None): """ ...
9a4d527ff0b964e4220db7a22a522657947e91cb
10,864
def serial_rx(sysclk, reset_n, n_stop_bits_i, half_baud_rate_tick_i, baud_rate_tick_i, recieve_i, data_o, ready_o): """ Serial This module implements a reciever serial interface Ports: ----- sysclk: sysclk input reset_n: reset input half_baud_rate_tick_i: half baud rate tick baud_rate_...
62f215644004b61738db9fd249f28a4abc1391ea
10,865
def zpad(x, l): """ Left zero pad value `x` at least to length `l`. >>> zpad('', 1) '\x00' >>> zpad('\xca\xfe', 4) '\x00\x00\xca\xfe' >>> zpad('\xff', 1) '\xff' >>> zpad('\xca\xfe', 2) '\xca\xfe' """ return b'\x00' * max(0, l - len(x)) + x
605aab22fa54f9df85397793c65d46dcf2ec3588
10,866
def clf2D_slope_intercept(coef=None, intercept=None, clf=None): """ Gets the slop an intercept for the separating hyperplane of a linear classifier fit on a two dimensional dataset. Parameters ---------- coef: The classification normal vector. intercept: The classifier inte...
9376c34a3836ee028c4b0497e1088ddd50bb1fc6
10,867
def build_driver_for_task(task): """Builds a composable driver for a given task. Starts with a `BareDriver` object, and attaches implementations of the various driver interfaces to it. They come from separate driver factories and are configurable via the database. :param task: The task containing ...
5283b91e5a42fe7ebec20b91e0f1463abbc8b724
10,869
import torch def evaluate(eval_model, criterion, ntokens, data_source, cnf): """ Evaluates the training loss of the given model """ eval_model.eval() # Turn on the evaluation mode total_loss = 0.0 src_mask = generate_square_subsequent_mask(cnf.input_length).to(cnf.device) with torch.no_gr...
4570f5e7751683157ca8f3155052e484a1b3962e
10,870
def km_to_meters(kilometers): """ (int or float) -> float Takes a distance in kilometers and returns the distance in meters. """ return kilometers * 1000.0
33e40914c9d2b10009889ebfcbc543863a9ca363
10,871
from typing import List from typing import Optional from typing import Dict from typing import Callable from typing import Any def build(plan: List[Step], instances_stock: Optional[Dict[Callable, Any]] = None): """ Build instances dictionary from a plan """ instances_stock = instances_stock or {} instance...
a1b3ecc98097d9a5d998cca1484b22a4b83124ca
10,872
def make_module_spec(options, weight_file): """Makes a module spec. Args: options: LM hyperparameters. weight_file: location of the hdf5 file with LM weights. Returns: A module spec object used for constructing a TF-Hub module. """ def module_fn(): """Spec function for a ...
2293f00186438a6cc3318be6a25ab5223b8e9a91
10,873
import math def get_initial_scoreboard(): """ Retrieve the initial scoreboard (first pages of global and student views). If a user is logged in, the initial pages will instead be those on which that user appears, and their group scoreboards will also be returned. Returns: dict of scoreboard info...
3e5998a0cc94a6c99ca58336ef0a350a4170240e
10,874
async def resolve(qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN, tcp=False, source=None, raise_on_no_answer=True, source_port=0, lifetime=None, search=None, backend=None): """Query nameservers asynchronously to find the answer to the question. This is a convenienc...
90a79f18d5c8887cbede733e7e05778ea78b36eb
10,875
import re def compare_xml(want, got): """Tries to do a 'xml-comparison' of want and got. Plain string comparison doesn't always work because, for example, attribute ordering should not be important. Comment nodes are not considered in the comparison. Based on http://codespeak.net/svn/lxml/trunk/s...
6632c723c2461dcb34b7e4f0bca0b4d096b5def8
10,876
def _tf_equal(a, b): """Overload of "equal" for Tensors.""" return gen_math_ops.equal(a, b)
899cff2abe9613d798fb59190c1860ef6a6599d7
10,877
def faq(): """FAQ page for SciNet""" return render_template("faq.html")
67bbdcc713789f71b0506206ef8a4f2a56b3f1a1
10,878
def render_table(sheet, header, width, data, header_style, data_style, tt_id_style): """Рендерим страницу""" # Render table header for i in range(len(header)): sheet.write(0, i, header[i], header_style) sheet.col(i).width = width[i] sheet.row(1).height = 2500 # Render table data ...
bc181ff96319daef3cad10e5072124a6c43172a6
10,879
def texsafe(value): """ Returns a string with LaTeX special characters stripped/escaped out """ special = [ [ "\\xc5", 'A'], #'\\AA' [ "\\xf6", 'o'], [ "&", 'and'], #'\\"{o}' ] for char in ['\\', '^', '~', '%', "'", '"']: # these mess up things value = value.replace(char...
b40b60a34629f75dfdac298bd2937af52ef797b1
10,880
def match_against_host_software_profile(db_session, hostname, software_packages): """ Given a software package list, return an array of dictionaries indicating if the software package matches any software package defined in the host software profile package list. """ results = [] system_option =...
30a1bbf8a548a9578324a60aa3bc18998457671a
10,881
from typing import Mapping from typing import Any def get_inputs_by_op(op: Op, store: Mapping[str, Any], copy_on_write: bool = False) -> Any: """Retrieve the necessary input data from the data dictionary in order to run an `op`. Args: op: The op to run. store: The system's data dictionary to ...
1f3ee5bfe98793c4e8002f2a7f7ea834bf0d93c0
10,882
from typing import Type def finalize_post(func, store: Type['ParameterStore']): """Finalizes the store prior to executing the function Parameters ---------- func : callable The function to wrap. store : ParameterStore The parameter store to finalize. Returns ------- c...
92195a0005b94dad7606609f99da4c824e39d5b1
10,883
def searchaftertext(filename, startterm, searchterm): """Start search after a certain text in a file""" #print startterm #print searchterm startline = findLastString (filename, startterm) searchtermfound = findLastString (filename, searchterm) if searchtermfound > startline: return True ...
32adc5bebab42ac721c04c8f16bceea53f9e0d79
10,884
def vec_list_to_tensor(vec_list): """Convert list to vector tensor.""" return jnp.stack(vec_list, axis=-1)
8e4dd60199c17dade87392f059412e00ae9defcc
10,885
from datetime import datetime def to_ecma_datetime_string(dt, default_timezone=local): """ Convert a python datetime into the string format defined by ECMA-262. See ECMA international standard: ECMA-262 section 15.9.1.15 ``assume_local_time`` if true will assume the date time is in local time if the...
bec3a52976552a0c0cc9ff5afde5bbf5578ff020
10,886
def _logfile_readme() -> str: """Returns a string containing a 'how to read this logfile' message. Returns ------- str Returns a formatted paragraph-long message with tips on reading log file output. """ line1 = "Messages are displayed below in the format" line2 = " <DATE> <TIME>...
5e418b20df1ebb486d0b1c3ecf38d6c72ae8a5a7
10,887
def taxon_lookup(es, body, index, taxonomy_index_template, opts, return_type): """Query elasticsearch for a taxon.""" taxa = [] with tolog.DisableLogger(): res = es.search_template(body=body, index=index, rest_total_hits_as_int=True) if "hits" in res and res["hits"]["total"] > 0: if retu...
52604947804581f633603d0728a68bc16f198503
10,888
async def get_south_services(request): """ Args: request: Returns: list of all south services with tracked assets and readings count :Example: curl -X GET http://localhost:8081/fledge/south """ if 'cached' in request.query and request.query['cached'].lower() == ...
a134bcf3c899212afc4b805ddaa9a19db901578a
10,889
def filter_bam_file(bamfile, chromosome, outfile): """ filter_bam_file uses samtools to read a <bamfile> and read only the reads that are mapped to <chromosome>. It saves the filtered reads into <outfile>. """ inputs = [bamfile] outputs = [outfile] options = { 'cores': 1, ...
317e1283d4722483e4bc98080ef99abd9876d045
10,890
def import_teachers(): """ Import the teachers from Moodle. :return: Amount of imported users. :rtype: int """ course_list = dict(Course.objects.values_list("courseId", "pk")) teachers_list = parse_get_teachers(get_teachers(list(course_list.keys()))) teacher_group = create_auth_group() ...
25b03c5b79d348171d23bce54a67ebbab2911440
10,891
def baryvel(dje, deq): """ Calculate helio- and barycentric velocity. .. note:: The "JPL" option present in IDL is not provided here. Parameters ---------- dje : float Julian ephemeris date deq : float Epoch of mean equinox of helio- and barycentric velocity output. ...
76f6dccceb697996541748704b293de6cfe77cf6
10,892
def uniform(low=0.0, high=1.0, size=None): """This function has the same `nlcpy.random.RandomState.uniform` See Also -------- nlcpy.random.RandomState.uniform : Draws samples from a uniform distribution. """ rs = generator._get_rand() return rs.uniform(low, high, size=size)
48de653a1721e5602eeefc2bf5182e0100759a31
10,893
def parse_time_interval(interval_str): """Convert a human-readable time interval to a tuple of start and end value. Args: interval_str: (`str`) A human-readable str representing an interval (e.g., "[10us, 20us]", "<100s", ">100ms"). Supported time suffixes are us, ms, s. Returns: ...
4edbc180722ddb84f6f2fae1e9854db14571f2d3
10,894
def submatrix(M, x): """If x is an array of integer row/col numbers and M a matrix, extract the submatrix which is the all x'th rows and cols. i.e. A = submatrix(M,x) => A_ij = M_{x_i}{x_j} """ return M[np.ix_(x,x)]
ba3aab45b77d8f7462fd0f2a29c96fb573618d62
10,895
def inventory_report(products: list) -> str: """Gives a detailed report on created products""" unique_names, average_price, average_weight, average_flam = _build_report_metrics(products) report = f'''ACME CORPORATION OFFICIAL INVENTORY REPORT Unique product names: {unique_names} Average price: {ave...
96080f5aff04ae8d8578be3940f756b471fdce48
10,896
def iou(a, b): """ Calculates intersection over union (IOU) over two tuples """ (a_x1, a_y1), (a_x2, a_y2) = a (b_x1, b_y1), (b_x2, b_y2) = b a_area = (a_x2 - a_x1) * (a_y2 - a_y1) b_area = (b_x2 - b_x1) * (b_y2 - b_y1) dx = min(a_x2, b_x2) - max(a_x1, b_x1) dy = min(a_y2, b_y2) - max(a...
0e72d00a672c430cce69246cb7d7889ae41ae216
10,897
def svn_path_is_empty(*args): """svn_path_is_empty(char path) -> int""" return _core.svn_path_is_empty(*args)
bf6db11940db6767c50a002104a528cf8c7a5363
10,898
def compute_lorentz(Phi, omega, sigma): """In a time-harmonic discretization with quantities .. math:: \\begin{align} A &= \\Re(a \\exp(\\text{i} \\omega t)),\\\\ B &= \\Re(b \\exp(\\text{i} \\omega t)), \\end{align} the time-average of :math:`A\\times B` over one ...
5b82df614d8245565e3427277ace2e0ba3fd27c5
10,900
def play_db(cursor, query_string, lookup_term): """ Given a query string and a term, retrieve the list of plays associated with that term """ play_list = [] try: cursor.execute(query_string, [lookup_term]) play_res = cursor.fetchall() except DatabaseError as err: LOG...
35ee0f96e122cddf65dbce7b127a8123b703b8f8
10,901
def find_nocc(two_arr, n): """ Given two sorted arrays of the SAME lengths and a number, find the nth smallest number a_n and use two indices to indicate the numbers that are no larger than a_n. n can be real. Take the floor. """ l = len(two_arr[0]) if n >= 2 * l: return l, l if n ...
42c8998e24095f03b0d873a0c9ad1f63facab8cb
10,902
import json def get_dict(str_of_dict: str, order_key='', sort_dict=False) -> list: """Function returns the list of dicts: :param str_of_dict: string got form DB (e.g. {"genre_id": 10, "genre_name": "name1"}, {"genre_id": 11, "genre_name": "name12"},...), :param order_key: the key by which dictionaries...
81d20db2dbe929693994b5b94aa971850ef9c838
10,903
import hashlib import struct def get_richpe_hash(pe): """Computes the RichPE hash given a file path or data. If the RichPE hash is unable to be computed, returns None. Otherwise, returns the computed RichPE hash. If both file_path and data are provided, file_path is used by default. Source : https...
30e5437f36f76a6225eaba579d55218440ab46b9
10,904
def get_input(label, default=None): """Prompt the user for input. :param label: The label of the prompt. :param label: str :param default: The default value. :rtype: str | None """ if default: _label = "%s [%s]: " % (label, default) else: _label = "%s: " % label ...
11de813f0fcfd16f1198299030656c07392f95c9
10,905
import logging def get_pretrain_data_text(data, batch_size, num_ctxes, shuffle, num_buckets, vocab, tokenizer, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, whole_word_mask, num_parts=1, part_idx=0, num_workers...
986ba7afc87f8ce5b054816de365e1c2793f6876
10,906
def define_app_flags(scenario_num): """ Define the TensorFlow application-wide flags Returns: FLAGS: TensorFlow flags """ FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_boolean('save_model', False, 'save model to disk') tf.app.flags.DEFINE_string('summaries_dir', './logs', 'tens...
de79e076db37f7981633b3b2b38db6b462155709
10,907
def longitude_validator(value): """Perform longitude validation. """ valid = -180 < value < 180 if not valid: raise ValidationError(_('longitude not in range of -90 < value < 90')) return value
866c45da71d1b4d6b2d5bd60e331caecb365f297
10,908
def test_create_batch_multi_record_update_fails(shared_zone_test_context): """ Test recordsets with multiple records cannot be edited in batch (relies on config, skip-prod) """ client = shared_zone_test_context.ok_vinyldns_client ok_zone = shared_zone_test_context.ok_zone # record sets to setup...
b2fe0cea07af57996058cdb0f9a31cbbf11a88ce
10,911
from typing import OrderedDict def _build_colormap(data, hue, palette, order): """Builds a colormap.""" if hue is None: color_map = {} else: if palette is None: palette = sns.color_palette() if order is None: order = data[hue].unique() color_map =...
82294634a1295fc68e5d3afb05fa00d83dfdc6ea
10,912
def f_is_oword(*args): """ f_is_oword(F, arg2) -> bool See 'is_oword()' @param F (C++: flags_t) """ return _ida_bytes.f_is_oword(*args)
a6d75a65b527ebdd029a5d3e65a756bcbb86561a
10,913
def aggregate_CSV_files(data_path): """ Aggregate the data in CSV files, specified in the config file, into a single pandas DataFrame object. """ merge_queue = [] for path in data_path: data_df = pd.read_csv(path, na_values = ['.']); data_df.index = pd.to_datetime(data_df['DATE'], forma...
281ca2a5e84e2dfbb2c2269083d0d2be5654fb75
10,914
def dR2(angle: np_float) -> np.ndarray: """Derivative of a rotation matrix around the second axis with respect to the rotation angle Args: angle: Scalar, list or numpy array of angles in radians. Returns: Numpy array: Rotation matrix or array of rotation matrices. """ zero = _ze...
5080c78c46505ed9e155fb76ae4a9be3b6e5d685
10,915
def clear_predecessor(n): """ Sets n's predecessor to None :param n: node on which to call clear_predecessor :return: string of response """ def clear(node): node.predecessor = None n.event_queue.put(clear) resp_header = {"status": STATUS_OK} return utils.create_request(resp...
e5c071572799c8df6b629d0bb1cbde4d106a4e95
10,917
def get_local_variable_influence(model, form_data): """ """ row = format_data_to_row(form_data) model_obj = read_model(model.path, model.file_type) df = load_dataset_sample(model.dataset, nrows=50) df = df[model.dataset.model_columns] explainer = load_model_explainer_from_obj(model_obj, ...
403c2e89937a7b8bfbeb1ce44d49147fe9c35ddc
10,919
def submit_experiment(body, **kwargs): """Submit an experiment :param body: experiment payload :type body: dict | bytes :rtype: StatusSerializer """ serializer = ExperimentSerializer.from_dict(body) check_experiment_permission(serializer, kwargs["token_info"]) stub = get_experiments_s...
21b91876f1d9ffa4b55c296a2e1dc9a2c66e1026
10,920
def obj_assert_check(cls): """ The body of the assert check for an accessor We allow all versions of add/delete/modify to use the same accessors """ if cls in ["of_flow_modify", "of_flow_modify_strict", "of_flow_delete", "of_flow_delete_strict", "of_flow_add"]: ...
4ebddebdd87c0bdb28e7687ec2b0da623507f89e
10,921
from typing import List import hashlib def ripemd160(data: List[int]) -> List[int]: """ :param data: :return: """ try: bytes_data = bytes(data) except TypeError: raise NativeContractException digest = hashlib.new("ripemd160", bytes_data).digest() padded = 12 * [0] + li...
bfa29479b6d2633c0075462f558f21562fc96a04
10,922
def has_duplicates(s:list) -> dict: """Returns True if any element appears more than once in a sequence.""" d = dict() for char in s: if char in d: return True d[char] = 1 return False
f702e53cded0c18a0e1b7cffb58bccbff3386bce
10,923
def get_from_chain(J, domain, nof_coefficients, ncap=10000, disc_type='sp_quad', interval_type='lin', mapping_type='lan_bath', permute=None, residual=True, low_memory=True, stable=False, get_trafo=False, force_sp=False, mp_dps=30, sort_by=None, **kwargs): """ Returns st...
d5cd09a088d4946015eb9556b0fed3ca5be55187
10,924
from typing import Type def factory(kernel_type, cuda_type=None, gpu_mode=None, *args, **kwargs): """Return an instance of a kernel corresponding to the requested kernel_type""" if cuda_type is None: cuda_type = default.dtype if gpu_mode is None: gpu_mode = default.gpu_mode # turn enu...
2d9bf5fb0fd45e367d31b76656dfc611912f7202
10,925
from typing import Dict from typing import Union def init_scaler( scaler_parameters: Dict, fit_data: np.ndarray, ) -> Union[MinMaxScaler, StandardScaler, RobustScaler]: """Initialize and return scaler. Args: scaler_parameters: Parameters of scaler. fit_data: Data to be fit. ...
18f15e8e6bebb32ad659636f46ee2e5f54ccc69d
10,926
def get_dynamic_resource(previous_length: str): """Get the job with job_name. Returns: None. """ name_to_node_usage = redis_controller.get_resource_usage( previous_length=int(previous_length) ) return name_to_node_usage
05efd928f66b8237e39bd04df2482d8b24259700
10,927
def _margo_bin(exe=""): """Returns the path of the margo executable. """ return gs.home_path("bin", exe or INSTALL_EXE)
a540357e84411ec84820163966440d75ae142d8b
10,928
def csl_density(basis, mini_cell, plane): """ returns the CSL density of a given plane and its d_spacing. """ plane = np.array(plane) c = csl_vec(basis, mini_cell) h = np.dot(c.T, plane) h = smallest_integer(h)[0] h = common_divisor(h)[0] g = np.linalg.inv(np.dot(c.T, c)) h_norm ...
852ba976f1bfc9b1fa30ba660f8b660e023bed94
10,929
def mw_Av(): """Build the A_V attenuation by the MW towards M31.""" curve = SF11ExtinctionCurve() ratio = curve['Landolt V'] # A_V / E(B-V) from T6 of SF2011 return ratio * 0.07
ff53a5c302945ab6020a3734950bc8449c522faa
10,930
def load_data(filenames): """Load a single file or sequence of files using skimage.io""" filenames = [filenames, ] if isinstance(filenames, str) else filenames loadfunc = tifffile.imread if all(f.lower().endswith("tif") for f in filenames) else skio.imread if len(fi...
be9c451c5aa3469a2bcaceb2fb6ab8ab09195794
10,932
def GetInverseMatrix(matrix): """ :param matrix: the matrix which will get its inverse matrix :return: the inverse matrix(two dimensions only) """ matrix[0, 0], matrix[1, 1] = -matrix[1, 1], -matrix[0, 0] matrix = matrix / -(matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0]) return m...
c4fdba364cc6b73a3b72a40f980a0fa402a1968f
10,933
import re def petsc_memory_stats(log): """Return the memory stats section of PETSc's -log_view output as a dictionary.""" # first search for the 'Memory usage' header, then match anything that follows # after the first line starting with --- up until the first line starting with ===== # re.DOTALL make...
c7756190ae2a4c25f5cf7a16764ace06da95b0f6
10,934
import torch def track2result(bboxes, labels, ids, num_classes): """Convert tracking results to a list of numpy arrays. Args: bboxes (torch.Tensor | np.ndarray): shape (n, 5) labels (torch.Tensor | np.ndarray): shape (n, ) ids (torch.Tensor | np.ndarray): shape (n, ) num_class...
ae2dda3abd32d8b6c3dd0fc0c8c5f65268a8e747
10,935
def build_result_dataframe(gh, pred, df): """ Construct a datarame that contain the prediction. :param gh: the geohas6 code of the prediction :param pred: numpy array of prediction :param df: the dataframe used for prediction :returns: prediction dataframe :rtype: pandas.core.frame.DataFrame ...
0b1523aa42c7a31aa286522ee81ec93690dfbf0c
10,936
def day_1_puzzle_1_solution() -> int: """Use this function to return the total fuel requirements for all of the modules. This function is used for reading the text file of puzzle data and returning the total amount of fuel that is required for the modules. :return: the total fuel requirement. """ ...
625497ea7e7619b1e84abc9eb8dfdfd1076af392
10,938
def is_description_style(style): """ True if this is a style used for Relationships paragraph text """ return is_style(style, 'Normal') or is_style(style, 'Note')
0e96d9977f7d18e8253a87e3af59f31e8326f4ae
10,939
def inject_content_head_last(html, content): """ 将文本内容插入到head的尾部 :type html: str :type content: str :rtype: str """ head_end_pos = html.find("</head") # 找到 </head> 标签结束的位置 if head_end_pos == -1: # 如果没有 </head> 就不进行插入 return html return html[:head_end_pos] + conten...
61792831f859a966e8cfa01ca56a6b9be10ede4d
10,940
from typing import Union def download(ticker: str, start: Union[pd.Timestamp, str] = None, end: Union[pd.Timestamp, str] = None, frequency: str = "day") -> pd.DataFrame: """ Download market data from yahoo finance using the yfinance library from ticker `ticker` from `sta...
733d5ac8244ca6fdbcb73a11585067c90dd7210b
10,941
def _ps_run_one_reset_kwargs(G, reset_kwargs: tuple, eval: bool): """ Sample one rollout with given init state and domain parameters, passed as a tuple for simplicity at the other end. This function is used when a minimum number of rollouts was given. """ if len(reset_kwargs) != 2: raise pyr...
95e23ad682d6afc3014bfa7932b00a955cc5bd3d
10,944
from exopy_pulses.testing.context import TestContext from typing import OrderedDict def test_compiling_a_sequence_not_compiling2(workspace, root, monkeypatch, exopy_qtbot, dialog_sleep): """Test compiling a sequence that can be evaluated but not compiled. """ ...
eec3ee453346a75398da230e59013bfaa47f8b23
10,945
import warnings def deprecated(message, exception=PendingDeprecationWarning): """Throw a warning when a function/method will be soon deprecated Supports passing a ``message`` and an ``exception`` class (uses ``PendingDeprecationWarning`` by default). This is useful if you want to alternatively pass a...
86ccfeb53048d130a7fe35a0609dc5e95440da23
10,946
def x_dot(y): """x_dot(y) Describes the differential equation for position as given in CW 12. """ return y
7fa01584b09c6e83e28ddf63b300323fdcb7fa0b
10,948
def get_comp_depends(comp_info, comps): """ Get comp depends from comp index """ depends = [] for comp in comps: if comp in comp_info: depends += comp_info[comp]["dependencies"] if depends: depends += get_comp_depends(comp_info, depends) return list(set(depends))
79a8b51e329cf9be414391508cc0ecbe76ff0707
10,949
def get_naiveb_model(x_train: pd.DataFrame, y_train: pd.Series) -> GaussianNB: """ Trains and returns a naive Bayes model Data must all be on the same scale in order to use naive Bayes """ gnb = GaussianNB(priors=None) gnb.fit(x_train, y_train) return gnb
f1b93acf80ee88f1eb0be7a61aa0d9ac94248966
10,950
def updateDF(df, fields, id_patient): """ fields is a dictionary of column names and values. The function updates the row of id_patient with the values in fields. """ for key in fields: df.loc[df["id_patient"] == id_patient, key] = fields[key][0] return df
5ced64eca8d8736836f82dacd1750cb8ac612989
10,951
def gcd(num1: int, num2: int) -> int: """Computes the greatest common divisor of integers a and b using Euclid's Algorithm. """ while num2 != 0: num1, num2 = num2, num1 % num2 return num1
c53ff5be770570278f497d7ce2a2146a3ac3d9da
10,952
import json async def check_user_name(request): """Check if a user exists with provided username.""" log_request(request) conn = await create_connection() response = await users_query.users_search_duplicate( conn, request.args.get("username") ) conn.close() return json({"exists": b...
72ff533a02e6377b78bfbfc631e87acc5fe59779
10,954
def azip_longest(*aiterables, fillvalue=None): """async version of izip_longest with parallel iteration""" return _azip(*aiterables, fillvalue=fillvalue, stop_any=False)
22f4ef6b4f1294ccca71a59337913a64e89a9e62
10,955