content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def heg_kfermi(rs): """ magnitude of the fermi k vector for the homogeneous electron gas (HEG) Args: rs (float): Wigner-Seitz radius Return: float: kf """ density = (4*np.pi*rs**3/3)**(-1) kf = (3*np.pi**2*density)**(1./3) return kf
4f210939ee7ec3c591c33ae7ec1b688ce2a257c6
23,660
import requests import json def stock_em_jgdy_detail(): """ 东方财富网-数据中心-特色数据-机构调研-机构调研详细 http://data.eastmoney.com/jgdy/xx.html :return: 机构调研详细 :rtype: pandas.DataFrame """ url = "http://datainterface3.eastmoney.com/EM_DataCenter_V3/api/JGDYMX/GetJGDYMX" params = { "js": "datata...
5d161ef69a77243202e48d80743c6664d8487549
23,661
def intersect_with_grid(int_coords, fill=False): """ Args: - int_coords: projected coordinates to be used for intersection - fill: whether to include the interior of the intersected cells. I.e. if the coords of a box are provided and intersect with 0,0 and 4,4, this would inc...
460faccf0280749f96b34e676a936cf8a39d4b61
23,662
def safe_epsilon_softmax(epsilon, temperature): """Tolerantly handles the temperature=0 case.""" egreedy = epsilon_greedy(epsilon) unsafe = epsilon_softmax(epsilon, temperature) def sample_fn(key: Array, logits: Array): return jax.lax.cond(temperature > 0, (key, logits), lambda tup:...
cf9d09dcd82638c526fb9508161181af6452dad5
23,663
def get_object_from_controller(object_type, object_name, controller_ip, username, password, tenant): """ This function defines that it get the object from controller or raise exception if object status code is less than 299 :param uri: URI to get the object :param controller_ip: ip of controller ...
590107e0106b87faa4fc228b6225e2317047ec19
23,664
from typing import DefaultDict def scale_reshaping(scale: np.ndarray, op2d: common.BaseNode, kernel_channel_mapping: DefaultDict, in_channels: bool = True) -> np.ndarray: """ Before scaling a kernel, the scale factor needs is reshaped to the correct ...
edaa0ecbfc172f0a8a32a7bcc70629f1b51b3f57
23,665
def add_new_exif(info): """ 创建exif记录(从表) :param info: :return: """ return ExifInfo(make=info.get('Image Make'), model=info.get('Image Model'), orientation=info.get('Image Orientation'), date_original=info.get('EXIF DateTimeOriginal'), ...
55122efc1ef612b769be30a1e0735e237e12ab29
23,667
def prefetch_input_data(reader, file_pattern, is_training, batch_size, values_per_shard, input_queue_capacity_factor=16, num_reader_threads=1, shard_que...
b754c1163cb868214e9ab74e1ae127a794a04808
23,668
def Chat_(request): """ { "value" : "Your query" } """ print(request.data) serializer = PatternSerializer(request.data) try: response = ChatBot(serializer.data["value"]) except: response = { "error": "Data is in wrong formate use { 'value' : 'Your quer...
33cada0ccbbea0e65d01179d51e5f1ed28f498bd
23,669
def get_solubility(molecular_weight, density): """ Estimate the solubility of each oil pseudo-component Estimate the solubility (mol/L) of each oil pseudo-component using the method from Huibers and Lehr given in the huibers_lehr.py module of py_gnome in the directory gnome/utilities/weathering...
64a951e8a6d9579cf934893fe5c9bc0a9181d4cc
23,670
def build_1d_frp_matrix(func, x, sigma, B=1): """ Builds quadratic frp matrix respecting pbc. func: Kernel function x: position of points sigma: width of Kernel """ N = len(x) A = np.zeros((N, N)) shifts = np.arange(-5, 6) * B for r in range(N): for p in range(N): ...
cc2d2d51935847cc01aacb2afe5c42ad19c91fe8
23,671
def invalid_item(item_key, valid_flag=False): """ Update item valid_flag. """ if kind.str_is_empty(item_key): raise RequiredError("item_key") query = Registry.all() query.filter("item_key =", item_key) query.set("valid_flag", valid_flag) return query.update(context.get_us...
a99408dd770be0f8eb2e3c899b8d51160359b4fa
23,672
def ret_str() -> str: """ # blahs blahs # blahs Returns ------- """ # blahs # blahs # blahs return ''
56c182f971ff38444f5cc04fa1ea537ebbc3cb5f
23,673
from typing import Union def get_wh_words(document: Union[Doc, Span]): """ Get the list of WH-words\n - when, where, why\n - whence, whereby, wherein, whereupon\n - how\n - what, which, whose\n - who, whose, which, what\n Resources:\n - https://grammar.collinsdictionary.com/easy-l...
a3dd46902bf161358239a5613c5037dfe4e831ff
23,674
def sample_mixture_gaussian(batch_size, p_array, mu_list, sig_list, k=K, d=DIM): """ samples from a mixture of normals :param batch_size: sample size :param p_array: np array which includes probability for each component of mix :param mu_list: list of means of each component :param sig_list: lis...
80374ed474ccb284a0cdb5efb63e44652318f0a2
23,675
def sign(x: float) -> float: """Return the sign of the argument. Zero returns zero.""" if x > 0: return 1.0 elif x < 0: return -1.0 else: return 0.0
5998061fcb57ef0133c6ccd56e1ad79a31b06732
23,676
import numpy def CalculateLocalDipoleIndex(mol): """ Calculation of local dipole index (D) """ GMCharge.ComputeGasteigerCharges(mol, iter_step) res = [] for atom in mol.GetAtoms(): res.append(float(atom.GetProp('_GasteigerCharge'))) cc = [numpy.absolute(res[x.GetBeginAtom().GetIdx...
f4e1f0cd0130cc1e94430eac2df910946f4e98d0
23,677
def tile1(icon="", **kw): """<!-- Tile with icon, icon can be font icon or image -->""" ctx=[kw['tile_label']] s = span(cls="icon %s" % icon) ctx.append(s) d2 = div(ctx=ctx, cls="tile-content iconic") return d2
fdcdecbc81733ae6b615cf5db5bce60585337efe
23,678
from typing import Optional def config_server(sender_email:str, sender_autorization_code:str, smtp_host: Optional[str] = None, smtp_port: Optional[int] = None, timeout=10): """ smtp server configuration :param sender_email: sender's email :param sender_autorization_code: sender's smtp authorization ...
f93b9efff8e8f415242bb9dbb5e09529baa1e238
23,679
def try_to_import_file(file_name): """ Tries to import the file as Python module. First calls import_file_as_package() and falls back to import_file_as_module(). If fails, keeps silent on any errors and returns the occured exceptions. :param file_name: The path to import. :return: The loaded mod...
15ab5c695bb7801b894c4466994abbb9f4ad791a
23,680
def is_uppervowel(char: str) -> bool: """ Checks if the character is an uppercase Irish vowel (aeiouáéíóú). :param char: the character to check :return: true if the input is a single character, is uppercase, and is an Irish vowel """ vowels = "AEIOUÁÉÍÓÚ" return len(char) == 1 and char[0] i...
14e87fc53fbb31c2a1ba66d17082be533ef8c5a9
23,681
from typing import Optional def visualize_permutation_results( obs_r2: float, permuted_r2: np.ndarray, verbose: bool = True, permutation_color: str = "#a6bddb", output_path: Optional[str] = None, show: bool = True, close: bool = False, ) -> float: """ Parameters ---------- ...
cfdf84fd78cd54b39eb6db9b0af799a230a294c8
23,682
def htmlmovie(html_index_fname,pngfile,framenos,figno): #===================================== """ Input: pngfile: a dictionary indexed by (frameno,figno) with value the corresponding png file for this figure. framenos: a list of frame numbers to include in movie figno: integer with...
7be1cf8ffce35e51667a67f322fbf038f396e817
23,683
from pathlib import Path import re import io def readin_q3d_matrix_m(path: str) -> pd.DataFrame: """Read in Q3D cap matrix from a .m file exported by Ansys Q3d. Args: path (str): Path to .m file Returns: pd.DataFrame of cap matrix, with no names of columns. """ text = Path(path)....
35a79ff4697ba1df3b2c1754d8b28064b459201f
23,684
def get_DB(type='mysql'): """ Parameters ---------- type Returns ------- """ if type == 'mysql': return MySQLAdapter elif type == 'mongodb': return MongoAdapter
07a3f0c1fcac691855f616e2e96d5ab947ca7be3
23,685
def movstd(x,window): """ Computes the moving standard deviation for a 1D array. Returns an array with the same length of the input array. Small window length provides a finer description of deviation Longer window coarser (faster to compute). By default, each segment is centered, ...
e9c4bc43f92d6d22c8191d1d15b93a51aadef32c
23,686
def get_attribute(parent, selector, attribute, index=0): """Get the attribute value for the child element of parent matching the given CSS selector If index is specified, return the attribute value for the matching child element with the specified zero-based index; otherwise, return the attribute value for the first...
fff9ec0a30dd00431164c69f5ba3430ec09f804a
23,687
import torch def cal_head_bbox(kps, image_size): """ Args: kps (torch.Tensor): (N, 19, 2) image_size (int): Returns: bbox (torch.Tensor): (N, 4) """ NECK_IDS = 12 # in cocoplus kps = (kps + 1) / 2.0 necks = kps[:, NECK_IDS, 0] zeros = torch.zeros_like(necks)...
546b4d4fcf756a75dd588c85ab467c21e9f45550
23,689
def my_json_render(docs, style="dep", options=None, manual=False) -> list: """ Render nlp visualisation. Args: docs (list or Doc): Document(s) to visualise. style (unicode): Visualisation style, 'dep' or 'ent'. options (dict): Visualiser-specific options, e.g. colors. manual ...
a19068ae0c9e4eb89e810f378ccc8d5fbd14547a
23,690
import json def get_testcase_chain(testcase_id, case_type, chain_list=None, with_intf_system_name=None, with_extract=None, only_first=False, main_case_flow_id=None, childless=False): """ 根据testcase_id获取调用链, 包含接口用例和全链路用例 return example: [ { "preCaseId": 1, ...
92892c432a46287559c41fe9d1b5fb11dec35e86
23,691
from typing import Iterable def approximate_parameter_profile( problem: Problem, result: Result, profile_index: Iterable[int] = None, profile_list: int = None, result_index: int = 0, n_steps: int = 100, ) -> Result: """ Calculate profiles based on an approximati...
478a95b370360c18a808e1753a8ad60f6a7b1bb7
23,692
def _process_input(data, context): """ pre-process request input before it is sent to TensorFlow Serving REST API Args: data (obj): the request data, in format of dict or string context (Context): object containing request and configuration details Returns: (dict): a JSON-ser...
05d48d327613df156a5a3b6ec76e6e5023fa54ca
23,693
from ibmsecurity.appliance.ibmappliance import IBMError def update_policies(isamAppliance, name, policies, action, check_mode=False, force=False): """ Update a specified policy set's policies (add/remove/set) Note: Please input policies as an array of policy names (it will be converted to id's) """ ...
666fd658f8d6748f8705a098b0f773f3fa758bbe
23,694
def is_bullish_engulfing(previous: Candlestick, current: Candlestick) -> bool: """Engulfs previous candle body. Wick and tail not included""" return ( previous.is_bearish and current.is_bullish and current.open <= previous.close and current.close > previous.open )
ab46a10009368cbb057ddf79ee9eda56ab862169
23,695
import math def yaw_cov_to_quaternion_cov(yaw, yaw_covariance): """Calculate the quaternion covariance based on the yaw and yaw covariance. Perform the operation :math:`C_{\\theta} = R C_q R^T` where :math:`C_{\\theta}` is the yaw covariance, :math:`C_q` is the quaternion covariance and :math:`R` is ...
f98a7b996ea290f735214704d592c5926ca4d07f
23,696
import logging async def token(req: web.Request) -> web.Response: """Auth endpoint.""" global nonce, user_eppn, user_family_name, user_given_name id_token = { "at_hash": "fSi3VUa5i2o2SgY5gPJZgg", "sub": "smth", "eduPersonAffiliation": "member;staff", "eppn": user_eppn, ...
771d21043a1185a7a6b4bd34fda5ae78ad45d51e
23,697
def split_train_test(observations, train_percentage): """Splits observations into a train and test set. Args: observations: Observations to split in train and test. They can be the representation or the observed factors of variation. The shape is (num_dimensions, num_points) and the split is over t...
8b6aa5896c5ae8fc72414e707013248fcb320d88
23,698
def InitF11(frame): """F6 to navigate between regions :param frame: see InitShorcuts->param :type frame: idem :return: entrie(here tuple) for AcceleratorTable :rtype: tuple(int, int, int) """ frame.Bind(wx.EVT_MENU, frame.shell.SetFocus, id=wx.ID_SHELL_FOCUS) return (wx.ACCEL_NORMAL, w...
055852664e48154768353af109ec1be533a7ad4a
23,699
def ReadExactly(from_stream, num_bytes): """Reads exactly num_bytes from a stream.""" pieces = [] bytes_read = 0 while bytes_read < num_bytes: data = from_stream.read(min(MAX_READ, num_bytes - bytes_read)) bytes_read += len(data) pieces.append(data) return ''.join(pieces)
5fcd6f204734779e81e7c4b9f263ad4534426278
23,700
import json import phantom.rules as phantom from hashlib import sha256 def indicator_collect(container=None, artifact_ids_include=None, indicator_types_include=None, indicator_types_exclude=None, indicator_tags_include=None, indicator_tags_exclude=None, **kwargs): """ Collect all indicators in a container and...
1e7681f66231e856a9f6a264884556c44fa5b42d
23,701
def remove_duplicates(iterable): """Removes duplicates of an iterable without meddling with the order""" seen = set() seen_add = seen.add # for efficiency, local variable avoids check of binds return [x for x in iterable if not (x in seen or seen_add(x))]
d98fdf8a4be281008fa51344610e5d052aa77cae
23,702
def verify_my_token(user: User = Depends(auth_user)): """ Verify a token, and get basic user information """ return {"token": get_token(user), "email": user.email, "is_admin": user.is_admin, "restricted_job": user.restricted_job}
ee628ab199c7b60ee5fd79103735f6bba51e26a0
23,703
def inv_partition_spline_curve(x): """The inverse of partition_spline_curve().""" c = lambda z: tf.cast(z, x.dtype) assert_ops = [tf.Assert(tf.reduce_all(x >= 0.), [x])] with tf.control_dependencies(assert_ops): alpha = tf.where( x < 8, c(0.5) * x + tf.where( x <= 4, ...
815b91cff13aea862fe1681eed33ebf6497a047b
23,704
def _orbit_bbox(partitions): """ Takes a granule's partitions 'partitions' and returns the bounding box containing all of them. Bounding box is ll, ur format [[lon, lat], [lon, lat]]. """ lon_min = partitions[0]['lon_min'] lat_min = partitions[0]['lat_min'] lon_max = partitions[0]['lon_m...
8e040b549cbdf9587f08a285bd6f867ae580d584
23,705
def GetModel(name: str) -> None: """ Returns model from model pool that coresponds to the given name. Raises GraphicsException if certain model cannot be found. param name: Name of a model. """ if not name in _models: raise GraphicsException(f"No such model '{name}'.") return _models[name]
162b7279f7491c614a72bbb9dc6bbdfd591a7c9c
23,706
def db_to_dict(s_str, i = 0, d = {}): """ Converts a dotbracket string to a dictionary of indices and their pairs Args: s_str -- str: secondary_structure in dotbracket notation KWargs: i -- int: start index d -- dict<index1, index2>: the dictionary so far Returns: dictio...
5440bc318b0b5c8a137e0a3f739031603994e89c
23,707
def identify_event_type(event): """Look at event to determine type of device. Async friendly. """ if EVENT_KEY_COMMAND in event: return EVENT_KEY_COMMAND if EVENT_KEY_SENSOR in event: return EVENT_KEY_SENSOR return "unknown"
d6c504e4edd2993a407ce36eea7688010a46c2be
23,708
def pcolormesh_nan(x: np.ndarray, y: np.ndarray, c: np.ndarray, cmap=None, axis=None): """handles NaN in x and y by smearing last valid value in column or row out, which doesn't affect plot because "c" will be masked too """ mask = np.isfinite(x) & np.isfinite(y) top = None bottom = None f...
cfd26ee1b110099220390c6771668ba1b422278a
23,709
def delete_post(post_id): """Delete a post :param post_id: id of the post object :return: redirect or 404 """ if Post.delete_post(post_id): logger.warning('post %d has been deleted', post_id) return redirect(url_for('.posts')) else: return render_template('page_not_found...
0511287930d66143ee152c5f670918b73fb34250
23,710
from typing import Callable import functools from typing import Any def log_arguments(func: Callable) -> Callable: """ decorate a function to log its arguments and result :param func: the function to be decorated :return: the decorator """ @functools.wraps(func) def wrapper_ar...
a50af7d31049c0da929f649affbd51c12aa6d810
23,711
import time def collect_gsso_dict(gsso): """ Export gsso as a dict: keys are cls, ind, all (ie cls+ind)""" print('Importing gsso as dict') t0 = time.time() gsso_cls_dict, gsso_ind_dict = _create_gsso_dict(gsso) gsso_all_dict = _create_gsso_dict_all(gsso) print("Executed in %s seconds." % str(t...
cdf14ae2ea6e5fe6e445d7b95a93b0df6423901c
23,714
def H_squared(omega): """Square magnitude of the frequency filter function.""" return 1 / ( (1 + (omega * tau_a) ** 2) * (1 + (omega * tau_r) ** 2) ) * H_squared_heaviside(omega)
60cda08d097901f679ce0fade20b062cb409bbae
23,715
def get_neighbor_distances(ntw, v0, l): """Get distances to the nearest vertex neighbors along connecting arcs. Parameters ---------- ntw : spaghetti.Network spaghetti Network object. v0 : int vertex id l : dict key is tuple (start vertex, end vert...
a7ec81a0c258a691786557e0f66e8ae17c5bbb86
23,716
from typing import Any from typing import List def is_generic_list(annotation: Any): """Checks if ANNOTATION is List[...].""" # python<3.7 reports List in __origin__, while python>=3.7 reports list return getattr(annotation, '__origin__', None) in (List, list)
0ed718eed16e07c27fd5643c18a6e63dc9e38f69
23,717
from pathlib import Path def create_folder(base_path: Path, directory: str, rtn_path=False): """ Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory Parameters ----------- base_path : pathlib.PosixPath Glob...
7c3724b009ef03fc6aa4fbc2bf9da2cbfa4c784d
23,718
import numpy def extract_track_from_cube(nemo_cube, track_cube, time_pad, dataset_id, nn_finder=None): """ Extract surface track from NEMO 2d cube """ # crop track time st = ga.get_cube_datetime(nemo_cube, 0) et = ga.get_cube_datetime(nemo_cube, -1) # NOTE do no...
ebe226ee7fca3507cebd2d936ef2419c2ec7413a
23,720
import re def get_mean_series_temp(log_frame: pd.DataFrame): """Get temperature time series as mean over CPU cores.""" columns_temp = [c for c in log_frame.columns if re.fullmatch(r"Temp:Core\d+,0", c)] values_temp = log_frame[columns_temp].mean(axis=1) return values_temp
2da22c316433460a8b9f9ec53a8e6542bd6da699
23,721
def new_channel(): """Instantiates a dict containing a template for an empty single-point channel. """ return { "channel_name": "myChannel", "after_last": "Goto first point", "alternate_direction": False, "equation": "x", "final_value": 0.0, "optimizer_con...
af05dfda58a0e14f7448f59b057546728dbbeba7
23,722
from typing import Optional def Log1p(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ :param input_vertex: the vertex """ return Vertex(context.jvm_view().Log1pVertex, label, cast_to_vertex(input_vertex))
fddb06841e528ed7014ef75ecab3354d53e4b901
23,723
def test(request): """ Controller for the app home page. """ context = {} return render(request, 'ueb_app/test.html', context)
3d578e9acbcdec1467162f22d71e1c01979ed778
23,724
def get_node_backups(request, queryset): """ Return dict with backups attribute. """ user_order_by, order_by = get_order_by(request, api_view=VmBackupList, db_default=('-id',), user_default=('-created',)) bkps = get_pager(request, queryset.order_by(*order_b...
5c5c92b1221037805182efeed6da38d413aa5f16
23,726
def xpath(elt, xp, ns, default=None): """Run an xpath on an element and return the first result. If no results were returned then return the default value.""" res = elt.xpath(xp, namespaces=ns) if len(res) == 0: return default else: return res[0]
2252a15d621d01b58c42790622ffa66022e90dac
23,727
def check_response_stimFreeze_delays(data, **_): """ Checks that the time difference between the visual stimulus freezing and the response is positive and less than 100ms. Metric: M = (stimFreeze_times - response_times) Criterion: 0 < M < 0.100 s Units: seconds [s] :param data: dict of trial d...
9abe61acd4ce085eb6e9f7b7deb06f6a6bcb8a46
23,729
import vtool.keypoint as ktool def get_invVR_aff2Ds(kpts, H=None): """ Returns matplotlib keypoint transformations (circle -> ellipse) Example: >>> # Test CV2 ellipse vs mine using MSER >>> import vtool as vt >>> import cv2 >>> import wbia.plottool as pt >>> img_fp...
c32f2d3b833ebc7212dec95f0ead393847297be7
23,730
def get_string(string_name): """ Gets a string from the language file """ if string_name in lang_file[lang]: return lang_file[lang][string_name] elif string_name in lang_file["english"]: return lang_file["english"][string_name] else: return string_name
18ed37668394e40bf70110d9dd26f2a739a6e2e3
23,732
import math import logging def build_streambed(x_max, set_diam): """ Build the bed particle list. Handles calls to add_bed_particle, checks for completness of bed and updates the x-extent of stream when the packing exceeds/under packs within 8mm range. Note: the updates to x-e...
1a4093ebf31b2f19c1144c332addaf5dadad5eee
23,733
def rotate_around_point_highperf_Numpy(xy, radians, origin): """ Rotate a point around a given point. I call this the "high performance" version since we're caching some values that are needed >1 time. It's less readable than the previous function but it's faster. """ adjust_xy = x...
068651134692976e01530a986d6257a45939d741
23,734
def eval(cfg, env, agent): """ Do the evaluation of the current agent :param cfg: configuration of the agent :param env: :param agent: :return: """ print("========= Start to Evaluation ===========") print("Environment:{}, Algorithm:{}".format(cfg.env, cfg.algo)) for i_episode in ...
f0f5f2bf4eabba13fabfd782de53f8a5ef0db982
23,735
def phi(input): """Phi function. :param input: Float (scalar or array) value. :returns: phi(input). """ return 0.5 * erfc(-input/np.sqrt(2))
fd9988c4257c82697a46bee71eb1e67aab286353
23,736
def _is_correct_task(task: str, db: dict) -> bool: """ Check if the current data set is compatible with the specified task. Parameters ---------- task Regression or classification db OpenML data set dictionary Returns ------- bool True if the task and the da...
49790d8e2b7a16ee9b3ca9c8bc6054fde28b3b6f
23,737
import re def is_valid_semver(version: str) -> bool: """return True if a value is a valid semantic version """ match = re.match(r'^[0-9]+\.[0-9]+\.[0-9]+(-([0-9a-z]+(\.[0-9a-z]+)*))?$', version) return match is not None
811a29a497515d23169916b9d9450fed6364c966
23,738
from typing import Optional from typing import List async def role_assignments_for_team( name: str, project_name: Optional[str] = None ) -> List[RoleAssignment]: """Gets all role assignments for a team.""" try: return zen_store.get_role_assignments_for_team( team_name=name, project_nam...
3ba5336882978109e4333aead0bf8d5990a52880
23,739
def set_nested_dict_value(input_dict, key, val): """Uses '.' or '->'-splittable string as key and returns modified dict.""" if not isinstance(input_dict, dict): # dangerous, just replace with dict input_dict = {} key = key.replace("->", ".") # make sure no -> left split_key = key.split...
2f2a160348b0c5d5fac955a8c6cec6c0ec0d5f0d
23,740
from unittest.mock import Mock def cube_1(cube_mesh): """ Viewable cube object shifted to 3 on x """ obj = Mock() obj.name = 'cube_1' obj.mode = 'OBJECT' obj.mesh_mock = cube_mesh obj.to_mesh.return_value = cube_mesh obj.matrix_world = Matrix.Identity(4) obj.mesh_mock.vertices = cube_v...
7d60199dcf41a818346e91014b4f041ab14313da
23,741
def deserialize_model_fixture(): """ Returns a deserialized version of an instance of the Model class. This simulates the idea that a model instance would be serialized and loaded from disk. """ class Model: def predict(self, values): return [1] return Model()
946e0cc67e4cb14da9b08e6790d336126bb9e43a
23,742
def _get_bfp_op(op, name, bfp_args): """ Create the bfp version of the operation op This function is called when a bfp layer is defined. See BFPConv2d and BFPLinear below """ op_name = _get_op_name(name, **bfp_args) if op_name not in _bfp_ops: _bfp_ops[name] = _gen_bfp_op(op, name, bfp_a...
27cac342cbb30159ce7d0bbda8c42df4cefea118
23,743
from typing import Sequence def compute_dmdt(jd: Sequence, mag: Sequence, dmdt_ints_v: str = "v20200318"): """Compute dmdt matrix for time series (jd, mag) See arXiv:1709.06257 :param jd: :param mag: :param dmdt_ints_v: :return: """ jd_diff = pwd_for(jd) mag_diff = pwd_for(mag) ...
af6f7c59de8ec7b38f22f3ffa5e3d17641b9ed32
23,744
def all_bin_vecs(arr, v): """ create an array which holds all 2^V binary vectors INPUT arr positive integers from 1 to 2^V, (2^V, ) numpy array v number of variables V OUTPUT edgeconfs all possible binary vectors, (2^V, V) numpy array """ to_str_func = np.vectorize(lambda x: np.binary_repr(x).zfill(...
1844545f85a1404a0c2bcb094e28e993e369f6df
23,745
def unpack_domains(df): """Unpack domain codes to values. Parameters ---------- df : DataFrame """ df = df.copy() for field, domain in DOMAINS.items(): if field in df.columns: df[field] = df[field].map(domain) return df
9c6c9607439aa24e944d9a8055e741ae3454d0cb
23,746
def generate_region_info(region_params): """Generate the `region_params` list in the tiling parameter dict Args: region_params (dict): A `dict` mapping each region-specific parameter to a list of values per FOV Returns: list: The complete set of `region_params` sort...
aa80e1e4ea9693b362fa18a435d886a09ecff533
23,748
def is_decorator(tree, fname): """Test tree whether it is the decorator ``fname``. ``fname`` may be ``str`` or a predicate, see ``isx``. References of the forms ``f``, ``foo.f`` and ``hq[f]`` are supported. We detect: - ``Name``, ``Attribute`` or ``Captured`` matching the given ``fname`` ...
f4fdd760aefae9c1be3d40cc249b242e0be65db5
23,749
def Nbspld1(t, x, k=3): """Same as :func:`Nbspl`, but returns the first derivative too.""" kmax = k if kmax > len(t)-2: raise Exception("Input error in Nbspl: require that k < len(t)-2") t = np.array(t) x = np.array(x)[:, np.newaxis] N = 1.0*((x > t[:-1]) & (x <= t[1:])) dN = np.zero...
f2535888715ec28c2b089c7f92b692b14c26bea7
23,750
def getStyleSheet(): """Returns a stylesheet object""" stylesheet = StyleSheet1() stylesheet.add(ParagraphStyle(name='Normal', fontName="Helvetica", fontSize=10, leading=12)) stylesheet.add(ParagraphS...
fcdb8cc7792254c4c7fb6a55333ad037c914b647
23,751
def parse_faq_entries(entries): """ Iterate through the condensed FAQ entries to expand all of the keywords and answers """ parsed_entries = {} for entry in entries: for keyword in entry["keywords"]: if keyword not in parsed_entries: parsed_entries[keyword] = ...
5258802d9384502f8a00692080cc9ae6ae7e9591
23,752
from datetime import datetime def dh_to_dt(day_str, dh): """decimal hour to unix timestamp""" # return dt.replace(tzinfo=datetime.timezone.utc).timestamp() t0 = datetime.datetime.strptime(day_str, '%Y%m%d') - datetime.datetime(1970, 1, 1) return datetime.datetime.strptime(day_str, '%Y%m%d') + datetime...
f87ec634f49400c178b6cad84f50426f67342868
23,753
from typing import Sequence from typing import Union from pathlib import Path def run(cmd: Sequence[Union[str, Path]], check=True) -> int: """Run arbitrary command as subprocess""" returncode = run_subprocess( cmd, capture_stdout=False, capture_stderr=False ).returncode if check and returnco...
985eea94264b72db88ae23ebcfdb2d7413390488
23,755
def getDict(fname): """Returns the dict of values of the UserComment""" s = getEXIF(fname, COMMENT_TAG) try: s = s.value except Exception: pass return getDictFromString(s)
9601103a03a97964b2b29379ce21e6710de6a376
23,756
from hetmatpy.degree_weight import default_dwwc_method import inspect import functools import time def path_count_cache(metric): """ Decorator to apply caching to the DWWC and DWPC functions from hetmatpy.degree_weight. """ def decorator(user_function): signature = inspect.signature(user_...
0872b15d52fef0289a72d87632c95a676291dffb
23,757
from typing import Mapping from typing import Set import tqdm def get_metabolite_mapping() -> Mapping[str, Set[Reference]]: """Make the metabolite mapping.""" metabolites_df = get_metabolite_df() smpdb_id_to_metabolites = defaultdict(set) for pathway_id, metabolite_id, metabolite_name in tqdm(metaboli...
ceca1f2bfc993249d9424abec0c5e67b1d456af4
23,758
def has_merge_conflict(commit: str, target_branch: str, remote: str = 'origin') -> bool: """ Returns true if the given commit hash has a merge conflict with the given target branch. """ try: # Always remove the temporary worktree. It's possible that we got # interrupted and left it around. T...
2136f1b60201bd33c3e854ed4df372e0196ea62f
23,759
def load_csr(data): """ Loads a PEM X.509 CSR. """ return x509.load_pem_x509_csr(data, default_backend())
edf07190243d7990d2782df240044572243f770b
23,761
def parseIMACS(hdul): """ Parses information from a given HDU, for data produced at IMACS """ start = hdul[0].header['CRVAL1'] step = hdul[0].header['CDELT1'] total = hdul[0].header['NAXIS1'] corr = (hdul[0].header['CRPIX1'] - 1) * step wave = np.arange(start - corr, start + total*st...
35d45a5842977d71375eaa9d07df6051d45ed075
23,762
def boll_cross_func_jit(data:np.ndarray,) -> np.ndarray: """ 布林线和K线金叉死叉 状态分析 Numba JIT优化 idx: 0 == open 1 == high 2 == low 3 == close """ BBANDS = TA_BBANDS(data[:,3], timeperiod=20, nbdevup=2) return ret_boll_cross
8fc68429f5ea94e462327fa57926742161d49911
23,763
from cuml.linear_model import LogisticRegression def rank_genes_groups( X, labels, # louvain results var_names, groups=None, reference='rest', n_genes=100, **kwds, ): """ Rank genes for characterizing groups. Parameters ---------- X : cupy.ndarray of shape (n_cells,...
bd2230d2be098677f62a46becd766edcc1fea36f
23,764
def init_graph_handler(): """Init GraphHandler.""" graph = get_graph_proto() graph_handler = GraphHandler() graph_handler.put({graph.name: graph}) return graph_handler
66b7f9d0b30c435fc3e6fe1152b24d663c31ac6e
23,765
def add_average_column(df, *, copy: bool = False): """Add a column averaging the power on all channels. Parameters ---------- %(df_psd)s An 'avg' column is added averaging the power on all channels. %(copy)s Returns ------- %(df_psd)s The average power across channels h...
0ff995d660ba71bd42ea7ae886b79631e3bd4509
23,766
import fnmatch def _is_globbed(name, glob): """ Return true if given name matches the glob list. """ if not glob: return True return any((fnmatch.fnmatchcase(name, i) for i in glob))
305116367884c8acc9c6f52a73c2cb116abaadbe
23,767
import struct def read_vec_flt(file_or_fd): """[flt-vec] = read_vec_flt(file_or_fd) Read kaldi float vector, ascii or binary input, Parameters ---------- file_or_fd : obj An ark, gzipped ark, pipe or opened file descriptor. Raises ------ ValueError Unsupported data-ty...
f12218f029e18a91666b99e9994ba29d67d62d5a
23,768
def arg_export(name): """Export an argument set.""" def _wrapper(func): _ARG_EXPORTS[name] = func if 'arg_defs' not in dir(func): func.arg_defs = [] return func return _wrapper
a713b22a7fffda50f8a9581362d8fd5ca807cef3
23,769
from typing import OrderedDict def get_od_base( mode = "H+S & B3LYP+TPSS0"): # od is OrderedDict() """ initial parameters are prepared. mode = "H+S & B3LYP+TPSS0" --> ["B3LYP", "TPSS0"] with speration of H and S "H+S & B3LYP" --> ["B3LYP"] with speration of H and S "H+S & TPSSO" --> ["TPSS0"] with sperat...
6a7aa100d8d244d9a0606a08188153e95a0df44b
23,770