content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import hashlib import six def make_hashkey(seed): """ Generate a string key by hashing """ h = hashlib.md5() h.update(six.b(str(seed))) return h.hexdigest()
38d088005cb93fc0865933bbb706be171e72503a
3,638,454
import asyncio async def report(database, year, month, limit): """Get a report.""" matches_query = """ select count(*) as count from matches where extract(year from played)=:year and extract(month from played)=:month """ players_query = """ select count(distinct players...
91059c5a8bd44536f24a7edbb88ff27b9036b83a
3,638,455
def dy3(vector, g, m1, m2, L1, L2): """ Abbreviations M = m0 + m1 S = sin(y1 - y2) C = cos(y1 - y2) s1 = sin(y1) s2 = sin(y2) Equation y3' = g*[m2 * C * s2 - M * s1] - S*m2*[L1 * y3^2 * C + L2*y4^2] ------------------------------------------------------------- ...
b93086cfcbb9d5f32143279ad01972d3f8719a78
3,638,457
from typing import Any def getType(resp: falcon.Response, class_type: str, method: str) -> Any: """Return the @type of object allowed for POST/PUT.""" for supportedOp in get_doc(resp).parsed_classes[class_type]["class"].supportedOperation: if supportedOp.method == method: return supportedO...
d20b77b4f40d266e685ce87f67d8f2fcbcfbe3eb
3,638,458
def full_data_numeric(): """DataFrame with numeric data """ data_dict = {'a': [2, 2, 2, 3, 4, 4, 7, 8, 8, 8], 'c': [1, 2, 3, 4, 4, 4, 7, 9, 9, 9], 'e': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } df = pd.DataFrame(data_dict) return df
ebd105f2648475dc7dcd40f51482d18e29486254
3,638,459
def fix(x): """ Replaces spaces with tabs, removes spurious newlines, and lstrip()s each line. Makes it really easy to create BED files on the fly for testing and checking. """ s = "" for i in x.splitlines(): i = i.lstrip() if i.endswith('\t'): add_tab = '\t' ...
ecd3a4d7f470feae1b697025c8fbf264d5c6b149
3,638,460
def get_collect_method(collect_method_name): """Return the collect method.""" try: collect_method = CollectMethod.get(name=collect_method_name) except ValueError: raise RuntimeError(f'Collect Method {collect_method_name} not found!') return collect_method
b80fcb916d461deea1784386062017291292f218
3,638,461
def TriangleBackwardSub(U,b): """C = TriangleBackwardSub(U,b) Solve linear system UC = b """ C = solve(U,b) return C
95c7fb76ad02a5546a79b95f18b51fe385307329
3,638,462
from unittest.mock import patch def test_binance_query_balances_unknown_asset(function_scope_binance): """Test that if a binance balance query returns unknown asset no exception is raised and a warning is generated. Same for unsupported asset.""" binance = function_scope_binance def mock_unknown_asse...
7521fd3039398c3eedccb16e16202687b4c28b2d
3,638,463
def petsc_to_stencil(x, Xh): """ converts a numpy array to StencilVector or BlockVector format""" x = x.array u = array_to_stencil(x, Xh) return u
6df02bbbfb9e9e386ca03510f2e4d563a6fed1aa
3,638,464
from typing import Optional import contextlib def index_internal_txs_task(self) -> Optional[int]: """ Find and process internal txs for monitored addresses :return: Number of addresses processed """ with contextlib.suppress(LockError): with only_one_running_task(self): logger....
b1a40ec713ff8d302f5c47b2c5d41300c699f3b4
3,638,465
import math def make_lagrangian(func, equality_constraints): """Make a Lagrangian function from an objective function `func` and `equality_constraints` Args: func (callable): Unary callable with signature `f(x, *args, **kwargs)` equality_constraints (callable): Unary callable with signature `...
c5795cded21e9cc4a7092eee63b88a4fac3b346a
3,638,466
def ungroup(expr): """Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. """ return TokenConverter(expr).addParseAction(lambda t: t[0])
c007a51e5073d8a3cbcbe52ca32ad84d58f4100a
3,638,468
def test_qnn_legalize(): """Test directly replacing an operator with a new one""" def before(): x = relay.var("x", shape=(1, 64, 56, 56), dtype='int8') y = relay.qnn.op.requantize(x, input_scale=1, input_zero_point=0, ...
b6f4a930e5c7156e60a5b26583b6e8fc48a6f441
3,638,471
import yaml def load(data, schema, yamlLoader=yaml.UnsafeLoader): """ Loads the given data and validates it according to the schema provided. Data must be either JSON or YAML, it must be a dictionary, a path, or a string of JSON. Schema must be JSON, it must be a dictionary, a path, or a string of JSO...
e7f29e1b61e60ce1cac5b1b1217f1df645691c17
3,638,472
from typing import List def calculate_slice_rotations(im_stack: np.ndarray, max_rotation:float = 45) -> List[float]: """Calculate the rotation angle to align each slice so the objects long axis is aligned with the horizontal axis. Parameters ---------- im_stack : np.ndarray A stack of ima...
42c0fdbdf02e937f449cb3ca137588003c715651
3,638,473
def calc_rest_interval(data): """ SubTool for Investigate: after median_deviation filters through all the points run entropy on the remaining non_rest points. This will filter the close but could still be rest points. """ lst, rest = median_deviation(data) average = median(data) st_entr...
7710e0784a5a025d99c8ead9799b1062942e3cdc
3,638,474
def get_objanno(fin_anno, godag, namespace='all'): """Get annotation object""" fin_full = get_anno_fullname(fin_anno) return get_objanno_factory(fin_full, godag=godag, namespace=namespace)
5e071190596ab37943d4001b4f03cf20d6395e06
3,638,475
def create_table_descriptives(datasets): """Merge dataset descriptives.""" df = pd.concat( [pd.read_json(ds, orient="index") for ds in datasets], axis=0 ) df.index.name = "dataset_name" return df
7c4554381ffb14572d949c27035411567d69e25d
3,638,476
def get_ngram_universe(sequence, n): """ Computes the universe of possible ngrams given a sequence. Where n is equal to the length of the sequence, the resulting number represents the sequence universe. Example -------- >>> sequence = [2,1,1,4,2,2,3,4,2,1,1] >>> ps.get_ngram_universe(sequence, 3) 64 """ # if...
3dbfe1822fdefb3e683b3f2b36926b4bb066468f
3,638,477
from typing import Union from typing import Iterable def as_nested_dict( obj: Union[DictLike, Iterable[DictLike]], dct_class: type = DotDict ) -> Union[DictLike, Iterable[DictLike]]: """ Given a obj formatted as a dictionary, transforms it (and any nested dictionaries) into the provided dct_class ...
a89261253174ce5b75d61343f0b45d3fe65e12f9
3,638,478
def twoindices_positive_up_to(n, m): """ build 2D integer indices up to n (each scanned from 0 to n) """ if not isinstance(n, int) or n <= 0: raise ValueError("%s is not a positive integer" % str(n)) nbpos_n = n + 1 nbpos_m = m + 1 gripos = np.mgrid[: n : nbpos_n * 1j, : m : nbpo...
63f850703f7598f1a4611c13700aa1921d77dd1a
3,638,479
def ban_user(request, user): """Bans a given user.""" user = User.query.filter_by(username=user).first() if user is None: raise NotFound() next = request.next_url or url_for('admin.bans') if user.is_banned: request.flash(_(u'The user is already banned.')) return redirect(next...
dd8c2a43a3843a6055e9e690d8cffee8cfac2b0e
3,638,481
def lastDate(): """[summary] lastDate() function: return the total revenue of the nearest day Returns: [type]: [description] """ lastDate = totalDate().tail(1) last_date = lastDate.iloc[0]['total'].round(2) return last_date
93130bf39dc2a82fa2cae11a6ea11468211f61b6
3,638,482
import json def multitask_result(request): """多任务结果""" task_id = request.GET.get('task_id') task_obj = models.Task.objects.get(id=task_id) results = list(task_obj.tasklog_set.values('id','status', 'host_user_bind__host__hostname', 'host...
c9c37fe4852a8c04662a5061445c1565400e94a1
3,638,484
from typing import Dict def process_xpath_list(node, property_manifest: Dict): """ Return a list of values as a result of running a list of XPath expressions against an input node :param node: Input node :param property_manifest: Manifest snippet of the property :return: List of values """...
e52ef3a7ff6b2f74554a69a5fec53125c077f6e5
3,638,485
def collect_username_and_password(db: Session) -> UserCreate: """Collect username and password information and validate""" username = get_username("Enter your username: ") password = get_password("Enter your password: ") verify_pass = get_password("Enter your password again: ") if password != verif...
be1557a4aa24cfb653c5e03f7f3cb340be1a6c1b
3,638,486
def replace_header(input_df): """replace headers of the dataframe with first row of sheet""" new_header = input_df.iloc[0] input_df = input_df[1:] input_df.columns=new_header return input_df
c8946fc269dd313b80df421af8d0b3fc6c47aed7
3,638,487
def cartToRadiusSq(cartX, cartY): """Convert Cartesian coordinates into their corresponding radius squared.""" return cartX**2 + cartY**2
3fb79d2c056f06c2fbf3efc14e08a36421782dbd
3,638,488
def unique_entity_id(entity): """ :param entity: django model :return: unique token combining the model type and id for use in HTML """ return "%s-%s" % (type(entity).__name__, entity.id)
c58daf9a115c9840707ff5e807efadad36a86ce8
3,638,489
def normalize_tuple(value, n, name): """Transforms a single int or iterable of ints into an int tuple. # Arguments value: The value to validate and convert. Could be an int, or any iterable of ints. n: The size of the tuple to be returned. name: The name of the argument being ...
cf396bac48b720686bb65ae7ab91b2e4cb22ac0e
3,638,490
def load_user(user_id): """ @login_manager.user_loader Passes in a user_id to this function and in return the function queries the database and gets a user's id as a response... """ return User.query.get(int(user_id))
2c2a2e7f6f9a5bc7392056bfd16402c9d2e96c22
3,638,491
def replaceall(table, a, b): """ Convenience function to replace all instances of `a` with `b` under all fields. See also :func:`convertall`. .. versionadded:: 0.5 """ return convertall(table, {a: b})
19d6c0fb60c71994de02deafb5ec9c2995aba622
3,638,492
def get_job_metadata(ibs, jobid): """ Web call that returns the metadata of a job CommandLine: # Run Everything together python -m wbia.web.job_engine --exec-get_job_metadata # Start job queue in its own process python -m wbia.web.job_engine job_engine_tester --bg #...
24ba96d6a71f105057a9fc9012de9edb187787d5
3,638,493
import math def create_learning_rate_scheduler(max_learn_rate, end_learn_rate, warmup_proportion, n_epochs): """Learning rate scheduler, that increases linearly within warmup epochs then exponentially decreases to end_learn_rate. Args: max_learn_rate: Float. Maximum learning rate. end_lea...
5c5649e429ad5f138894d30064c24bf23e547f85
3,638,494
def matchyness(section, option): """Assign numerical 'matchyness' value between target and value Parameters: section -- target value option -- proposed match """ if section != option: return _hc.NEQ if isinstance(section, rt.flask_placeholder): if isinstance(option, rt.flask_placeholder): return _hc.PP ...
c8e3773a8afe190181fd7552460852a27b2534d3
3,638,495
def log_sum_exp_elem(*a): """ :param a: elements :return: (a[0].exp() + a[1].exp() + ...).log() """ bias = max(a).detach() ans = bias + sum([(ai-bias).exp() for ai in a]).log() return ans
a87871a7c8af9d2c6c8db683ba63124319d09a0d
3,638,496
def car_portrayal(agent): """Visualises the cars for the Mesa webserver :return: Dictionary containing the settings of an agent""" if agent is None: return portrayal = {} # update portrayal characteristics for each CarAgent object if isinstance(agent, CarAgent): if agent.is_fro...
68c0bffb02299f2b03abf6ee2dc590375ad8e2a5
3,638,497
import re from typing import OrderedDict def _load_spc_format_type_a(filepath: str): """load A(w,k) in the spc format type a Args: filepath (str): output filename Returns: np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray: kcrt, Awk, kdist, energy, kpath """ with open(fi...
0a5c3f316875495e37502dd426e6eee7dd76ee53
3,638,498
def variable_to_json(var): """Converts a Variable object to dict/json struct""" o = {} o['x'] = var.x o['y'] = var.y o['name'] = var.name return o
86497a7915e4825e6e2cbcfb110c9bc4c229efed
3,638,499
import math def getDewPoint(temp, humidity): """ A utility function to get the temperature to which an amount of air must be cooled in order for water vapor to condense into water. This is only valid for: 1) temperatures between 0C and 60C, 2) relative humidity between 1% and 100%, and 3) dew poin...
0e67eef5a90d9e55f85906d57e6c2eb347044897
3,638,502
import json def get_result_handler(rc_value, sa_file=None): """Returns dict of result handler config. Backwards compatible for JSON input. rc_value (str): Result config argument specified. sa_file (str): SA path argument specified. """ try: result_handler = json.loads(rc_value) except...
83c6aa6e0cacdc64422553050072af5d8ea46bf6
3,638,503
def speedup_experiment_ts(args, model_iter_fn, model, example_inputs): """ Measure baseline performance (without using TorchDynamo) of TorchScript and optimize_for_inference. Writes to ./baseline_ts.csv """ return baselines( [ ("eager", model), ("ts", try_script(mode...
0936d5e24759ae5e04027f8e68e467caa24d5ccb
3,638,504
from typing import Tuple def my_polyhedron_to_label( rays: Rays_Base, dists: ArrayLike, points: ArrayLike, shape: Tuple[int, ...] ) -> npt.NDArray[np.int_]: """Convenience funtion to pass 1-d arrays to polyhedron_to_label.""" return polyhedron_to_label( # type: ignore [no-any-return] np.expand_di...
f967a963fcb47c964895da182a48568a2a8a8ee2
3,638,505
from typing import Optional def get_incident_comment(incident_comment_id: Optional[str] = None, incident_id: Optional[str] = None, operational_insights_resource_provider: Optional[str] = None, resource_group_name: Optional[str] = None, ...
c0fa6ec1bb7bcccc379455454296bc6a5814946f
3,638,507
def getOrElseUpdate(dictionary, key, opr): """If given key is already in the dictionary, returns associated value. Otherwise compute the value with opr, update the dictionary and return it. None dictionary are ignored. >>> d = dict() >>> getOrElseUpdate(d, 1, lambda _: _ + 1) 2 >>> print(d) {...
95454d7ca34d6ae243fda4e70338cf3d7584b827
3,638,508
from operator import add from operator import mul def gs_norm(f, g, q): """ Compute the squared Gram-Schmidt norm of the NTRU matrix generated by f, g. This matrix is [[g, - f], [G, - F]]. This algorithm is equivalent to line 9 of algorithm 5 (NTRUGen). """ sqnorm_fg = sqnorm([f, g]) ffgg ...
da30e1bac41cba3a6c051ba0159234aac5e6e3cc
3,638,509
from phaser import substructure def find_anomalous_scatterers(*args, **kwds): """ Wrapper for corresponding method in phaser.substructure, if phaser is available and configured. """ if (not libtbx.env.has_module("phaser")): if "log" in kwds: print("Phaser not available", file=kwds["log"]) retu...
0c88f0df336802fa798ac26966485b28105a6238
3,638,510
def OpChr(ea, n): """ @param ea: linear address @param n: number of operand - 0 - the first operand - 1 - the second, third and all other operands - -1 - all operands """ return idaapi.op_chr(ea, n)
39c2716ed7344fccd85edda2d27b7a7f305cb14b
3,638,511
def check_access(func): """ Check whether user is in policy owners group """ def inner(*args, **kwargs): keycloak = get_keycloak() if 'policy_id' in kwargs: current_user = kwargs['user'] group_name = f'policy-{kwargs["policy_id"]}-owners' group_list = ...
6655af97f11ae04587904f1aaf2a2225ace5b64d
3,638,512
def score_ranking(score_dict): """ 用pandas实现分组排序 :param score_dict: dict {'591_sum_test_0601': 13.1, '591_b_tpg7': 13.1, '591_tdw_ltpg6': 14.14} :return: DataFrame pd.DataFrame([['591_sum_test_0601', 13.10, 2.0, 0.6667], ['591_b_tpg7', 13.10, 2.0, 0.6667], ['591_tdw_ltpg6', 14.14, 3.0, 1.0]]...
d799576afe382c13124c703351b69b8bcb7393b2
3,638,513
def dock_widget(widget, label="DockWindow", area="right", floating=False): """Dock the given widget properly for both M2016 and 2017+.""" # convert widget to Qt if needed if not issubclass(widget.__class__, QObject): widget = utils.to_qwidget(widget) # make sure our widget has a name name =...
80ef6bde493585e0010a497dfb179600aae04e9e
3,638,514
def compute_benjamin_feir_index(bandwidth, steepness, water_depth, peak_wavenumber): """Compute Benjamin-Feir index (BFI) from bandwidth and steepness estimates. Reference: Serio, Marina, et al. “On the Computation of the Benjamin-Feir Index.” Nuovo Cimento Della Societa Italiana Di Fisica C, ...
2b3ef715a85a6dab837a36f86c3eeeaed05f8345
3,638,515
def plaintext_property_map(name: str) -> Mapper: """ Arguments --------- name : str Name of the property. Returns ------- Mapper Property map. See Also -------- property_map """ return property_map( name, python_to_api=plaintext_to_noti...
9b909de0eba2d8f55375896bb2acbbb53c6d759f
3,638,517
def pooling_layer(net_input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1)): """ TensorFlow pooling layer :param net_input: Input tensor :param ksize: kernel size of pooling :param strides: stride of pooling :return: Tensor after pooling """ return tf.nn.max_pool(net_input, ksize=ksize, strid...
4de6b7bdb5860cfa235975f799204522e77b9299
3,638,518
from typing import OrderedDict def set_standard_attrs(da): """ Add standard attributed to xarray DataArray""" da.coords["lat"].attrs = OrderedDict( [ ("standard_name", "latitude"), ("units", "degrees_north"), ("axis", "Y"), ("long_name", "latitude"), ...
21f83552466127928c9a30e9354e91c3031225aa
3,638,519
def isnotebook(): """ Utility function to detect if the code being run is within a jupyter notebook. Useful to change progress indicators for example. Returns ------- isnotebook : bool True if the function is being called inside a notebook, False otherwise. """ try: shel...
71e0a77c4bbf3afe16723b01ee5a8d08cf3b98a3
3,638,521
from typing import Optional from typing import Tuple from typing import List from typing import Dict def get_poagraph(dagmaf: DAGMaf.DAGMaf, fasta_provider: missings.FastaProvider, metadata: Optional[msa.MetadataCSV]) -> \ Tuple[List[graph.Node], Dict[msa.SequenceID, graph.Se...
cdc62d444cd22a8ff4c1b99382ffcc35a0ab33a6
3,638,522
def const_bool(value): """Create an expression representing the given boolean value. If value is not a boolean, it is converted to a boolean. So, for instance, const_bool(1) is equivalent to const_bool(True). """ return ['constant', 'bool', ['{0}'.format(1 if value else 0)]]
d11d01f94b8ad20d393a39a28dbfd18cc8fa217e
3,638,523
import struct def long_to_bytes(n, blocksize=0): """Convert an integer to a byte string. In Python 3.2+, use the native method instead:: >>> n.to_bytes(blocksize, 'big') For instance:: >>> n = 80 >>> n.to_bytes(2, 'big') b'\x00P' If the optional :data:`blocksize` i...
1157a466ce9754c12e01f7512e879cc28a2a4b23
3,638,524
def peek(library, session, address, width): """Read an 8, 16 or 32-bit value from the specified address. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param address: Source address to read the value. :param width: Number of bits to read...
6203a516f5a67daa67ec0f37c0e3a8818515f2de
3,638,526
def mtf_from_psf(psf, dx=None): """Compute the MTF from a given PSF. Parameters ---------- psf : `prysm.RichData` or `numpy.ndarray` object with data property having 2D data containing the psf, or the array itself dx : `float` sample spacing of the data Returns ----...
fb009d3068c67447d2f10c3448e91b258a0d7ca3
3,638,528
def check_intersection(vertical_line: Line, other_line: Line) -> bool: """ Check for intersection between two line segments. :param vertical_line: The first line segment. Guaranteed to be vertical. :param other_line: The second line segment. :return: Whether or not they intersect. """ intersection = get...
7e9279ea5976b99c9edb36ae5c59bcc69d22aa59
3,638,529
from krun.scheduler import ManifestManager from krun.platform import detect_platform def get_session_info(config): """Gets information about the session (for --info) Overwrites any existing manifest file. Separated from print_session_info for ease of testing""" platform = detect_platform(None, conf...
25729c3838fc7b600600dd74da44a3be9fd7b46d
3,638,530
def rotate(x, y, a): """Rotate vector (x, y) by an angle a.""" return x * np.cos(a) + y * np.sin(a), -x * np.sin(a) + y * np.cos(a)
2858539f3de5c15072657af5f39231f8e7867b6b
3,638,531
def filt_all(list_, func): """Like filter but reverse arguments and returns list""" return [i for i in list_ if func(i)]
72010b483cab3ae95d49b55ca6a70b0838b0a34d
3,638,532
def auth_user_logout(payload, override_authdb_path=None, raiseonfail=False, config=None): """Logs out a user. Deletes the session token from the session store. On the next request (redirect from POST /auth/logout to GET /), the frontend will is...
1f468a53f82a58f8c5c3f5397d6f026276a93f05
3,638,533
def rx_observer(on_next: NextHandler, on_error: ErrorHandler = default_error, on_completed: CompleteHandler = default_on_completed) -> Observer: """Return an observer. The underlying implementation use an named tuple. Args: on_next (NextHandler): on_next handler which process items on_erro...
2ebfd3c6b4e5ed854fdc89e76ac006fddd20ad0b
3,638,534
def _rav_setval_ ( self , value ) : """Assign the valeu for the variable >>> var = ... >>> var.value = 10 """ value = float ( value ) self.setVal ( value ) return self.getVal()
80ad7ddec68d5c97f72ed63dd6ba4a1101de99cb
3,638,535
import scipy def import_matrix_as_anndata(matrix_path, barcodes_path, genes_path): """Import a matrix as an Anndata object. :param matrix_path: path to the matrix ec file :type matrix_path: str :param barcodes_path: path to the barcodes txt file :type barcodes_path: str :param genes_path: pat...
83f5ccdaa945f26451ab2834c832e0e1ea58ce89
3,638,536
import torch import tqdm def get_representations(dataset, pretrained_model, alphabet, batch_size=128): """Returns: N x 1280 numpy array""" device = torch.device("cuda" if torch.cuda.is_available() else "cpu") pretrained_model = pretrained_model.to(device) dataloader = DataLoader( dataset, bat...
7a199156810b787ae7fb8ea059ebe69b6de70250
3,638,537
def rem_hap_cands(): """json endpoint to set a sample or set of sample's haplotype candidate designation to false""" form = flask.request.form samples = form['samples'] return mds.remove_hap_cands(samples)
ca22c2af4b6079f3b03accb3b414d553da75e1e3
3,638,538
def UndistortImage(image,image_size,\ image_rotation=None,image_center=None,\ out_xs=None,out_ys=None,\ direction='fwd',regenerate_grids=True,\ **kwargs): """Remember the recipe for fixin gwyddion image orientation: `image0=image0.T[:,:...
12cc1e1e428b8a860b0b29a6b81169cb6c1dc73d
3,638,541
def quartic_oscillator(grids, k=1.): """Potential of quantum quartic oscillator. Args: grids: numpy array of grid points for evaluating 1d potential. (num_grids,) k: strength constant for potential. Returns: vp: Potential on grid. (num_grid,) """ vp = 0.5 * k * gr...
c4a386816cd85e24080d62365d2bcd25b6735d5f
3,638,542
def compute_row_similarities(A): """ Compute pairwise similarities between the rows of a binary sparse matrix. Parameters ---------- A: scipy csr_matrix, shape (rows, cols) Binary matrix. Returns ------- sim: numpy array, shape (rows, rows) Pairwise column similarities....
96ab44ec15f94bf666da248100a98f282119caf1
3,638,543
def sha9(R, S): """Shape functions for a 4-noded quad element Parameters ---------- x : float x coordinate for a point within the element. y : float y coordinate for a point within the element. Returns ------- N : Numpy array Array of interpolation functions. Exa...
ba34cde6b5673853d34b9e074e2fbc05dc845aa5
3,638,544
def padding(seq, size, mode): """ Parameters ---------- seq: np.array The sequence to be padded. mode: str Select padding mode among {"zero", "repeat"}. Returns ------- seq: np.ndarray """ if mode == "zero": seq = np.array(trimmer(seq, size, fille...
3a0a070f784a355ead8439ff63f09918fa401014
3,638,545
def get_dense_span_ends_from_starts(dense_span_starts, dense_span_ends): """For every mention start positions finds the corresponding end position.""" seq_len = tf.shape(dense_span_starts)[0] start_pos = tf.cast(tf.where(tf.equal(dense_span_starts, 1)), tf.int32) end_pos = tf...
d825ed109b6055ca84adf46f6e5fd91cb5dd513a
3,638,546
def bb_to_plt_plot(x, y, w, h): """ Converts a bounding box to parameters for a plt.plot([..], [..]) for actual plotting with pyplot """ X = [x, x, x+w, x+w, x] Y = [y, y+h, y+h, y, y] return X, Y
10ea3d381969b7d30defdfdbbac0a8d58d06d4d4
3,638,547
def handler404(request, *args): """ Renders 404 page. :param request: the request object used :type request: HttpRequest """ return render(request, '404.html', status=404)
2ae6e036bb56b46ee16a4c0bec4182ba999f14ed
3,638,548
def merge_dimensions(z, axis, sizes): """Merge dimensions of a tensor into one dimension. This operation is the opposite of :func:`split_dimension`. Args: z (tensor): Tensor to merge. axis (int): Axis to merge into. sizes (iterable[int]): Sizes of dimensions to merge. Returns: ...
5ef62cd90ebf5bd9276f334a65a7a9075f5d3710
3,638,549
import collections import re def get_assignment_map_replaced(init_ckpt, name_replacement_dict={}, list_vars=None): """ name_replacement_dict = { old_name_str_chunk: new_name_str_chunk } """ if list_vars is None: list_vars = tf.global_...
fd7df6630f84bde9caf747540c05729b8898ffa0
3,638,550
def RULE110(): """RULE 110 celular automata node. .. code:: 000 : 0 001 : 1 010 : 1 011 : 1 100 : 0 101 : 1 110 : 1 111 : 0 """ return BooleanNode.from_output_list(outputs=[0,1,1,1,0,1,1,0], name="RULE 110")
3c79a7b6c25f031fdeac4a86f2afc770ad71ea23
3,638,551
def search_cut(sentence): """ HMM的切割方式 :param sentence: :return: """ return jieba.lcut_for_search(sentence)
7ee0f7eb1a16cd24920b98e38387b2c9b576990f
3,638,552
from typing import Counter def count_items(column_list:list): """ Contar os tipos (valores) e a quantidade de items de uma lista informada args: column_list (list): Lista de dados de diferentes tipos de valores return: Retorna dois valores, uma lista de tipos (list) e...
06cf25aed4d0de17fa8fb11303c9284355669cf5
3,638,553
import cloudpickle def py_call(obj, inputs=(), direct_args=()): """Create a task that calls Python code Example: >>> def hello(x): return b"Hello " + x.read() >>> a = tasks.const("Loom") >>> b = tasks.py_call((a,), hello) >>> client.submit(b) b'Hello Loom' """ task = ...
f89a5876fcf9b4c192f2b7c6d1362bf5a97e399c
3,638,554
def to_graph(grid): """ Build adjacency list representation of graph Land cells in grid are connected if they are vertically or horizontally adjacent """ adj_list = {} n_rows = len(grid) n_cols = len(grid[0]) land_val = "1" for i in range(n_rows): for j in range(n_cols): ...
ebdd0406b123a636a9d380391ef4c13220e2dabd
3,638,555
def validate_doc(doc): """ Check to see if the given document is a valid dictionary, that is, that it contains a single definition list. """ return len(doc.content) == 1 and \ isinstance(doc.content[0], pf.DefinitionList)
c60799ebbdaa7ec2e3a7e6607853ff021a40ed17
3,638,556
def V_bandpass(V, R_S, C, L, R_L, f): """ filter output voltage input voltage minus the current times the source impedance """ # current in circuit I = V/(R_S + Z_bandpass(C, L, R_L, f)) # voltage across circuit V_out = V - I*R_S return V_out
c21c54e7065a32531dca417eb7e50ea63db820d8
3,638,559
from admiral.celery import celery def celery(): """Celery app test fixture.""" return celery
69f672e1c6a568e14a4ad9f5df723b454a346b03
3,638,561
def perm_cache(func): """ 根据用户+请求参数,把权限验证结果结果进行缓存 """ def _deco(self, request, view): # 只对查询(GET方法)进行权限缓存 if request.method != "GET": return func(self, request, view) user = request.user.username kwargs = "_".join("{}:{}".format(_k, _w) for _k, _w in list(vi...
4ca53057b12efb15dddb422b3aaaddd11898f4bd
3,638,562
def ast_walker(handler): """ A generic AST walker decorator. Decorates either a function or a class (if dispatching based on node type is required). ``handler`` will be wrapped in a :py:class:`~peval.Dispatcher` instance; see :py:class:`~peval.Dispatcher` for the details of the required class struct...
978e6718d81663914017af89cf41101ca68dd2bb
3,638,563
def html_escape(text): """Produce entities within text.""" L=[] for c in text: L.append(html_escape_table.get(c,c)) return "".join(L)
de73c127de8b6338c5db5c9ba7d1f5ebbd6d23a9
3,638,564
def qs_without_parameter(arg1, arg2): """ Removes an argument from the get URL. Use: {{ request|url_without_parameter:'page' }} Args: arg1: request arg2: parameter to remove """ parameters = {} for key, value in arg1.items(): if parameters.get(key, None) is ...
649931de5490621c92513877b21cb8cfce8d66ff
3,638,565
def find_power_graph(I, J, w_intersect=10, w_difference=1): """takes a graph with edges I,J, and returns a power graph with routing edges Ir,Jr and power edges Ip,Jp. Note that this treats the graph as undirected, and will internally convert edges to be undirected if not already.""" n = int(max(max(...
9e682eebd9664863d80689f0aa718f30e3ad611a
3,638,566
import string def getcomments(pyObject): """Get lines of comments immediately preceding an object's source code. Returns None when source can't be found. """ try: lines, lnum = findsource(pyObject) except (IOError, TypeError): return None if ismodule(pyObject): # Look...
f58421f176b42ecb2e1e883f48deb31025b13559
3,638,567
import time import requests import io def crack_captcha(headers): """ 破解验证码,完整的演示流程 :return: """ currentTime = str(int(time.time())*1000) # 向指定的url请求验证码图片 rand_captcha_url = 'http://59.49.77.231:81/getcode.asp?t=' + currentTime res = requests.get(rand_captcha_url, stream=True,headers=h...
538843289a64dde1229f7df0a260632fbbd557b6
3,638,568
from . import sill from clawpack.pyclaw.util import check_diff import numpy as np from clawpack.pyclaw.util import gen_variants from itertools import chain def test_2d_sill(): """test_2d_sill Tests against expected classic solution of shallow water equations over a sill.""" def verify_expected(expe...
5d37c3ad21d842c3f03d1b464609f94ee86e1496
3,638,569
def draw_box( canvas, layout, box_width=None, box_alpha=0, color_map=None, show_element_id=False, show_element_type=False, id_font_size=None, id_font_path=None, id_text_color=None, id_text_background_color=None, id_text_background_alpha=1, ): """Draw the layout region...
9d8ca19a35e91c6e8670aed05c2e61b2c89958c5
3,638,570
def login(request): """Home view, displays login mechanism""" return render(request, 'duck/login.html')
5d4474d4ce7bb8f7327e1a005fe9e485d8784ec7
3,638,571