content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cmd_issuer_hash(cert): """Returns hash of certificate issuer. """ return cert.get_issuer().hash()
d35d35c39ba9c33c5b0015bb9f4d4ddf433cd71d
3,627,500
def linearly_enhancing_details(alphas, numOfScales=2, window_scale=3): """ :param alphas: the high frequency component of the image calculated with Shearlet transformation. i * j * (kl) array, where i, j are equal to the height and width of the original image, kl is ...
bdba70e9b8d63da29c8a87c09857f6698dcd12fb
3,627,501
def strip_c(buf, dia): """This is the ugliest python function I've ever written and I'm ashamed that it exists. Can you tell that it's an almost line for line translation of a C program? The two embedded functions were macros. """ pos = bytes(buf, 'ascii', errors='replace') single_q = double_q =...
0d23d9826fdbba09b06d3a866d54bcda13d43509
3,627,502
def map_bool(to_bool) -> bool: """Maps value to boolean from a string. Parameters ---------- to_bool: str Value to be converted to boolean. Returns ------- mapped_bool: bool Boolean value converted from string. Example ------- >>> boolean_string = "True" # can ...
4e3bb175f653174a56cb6ddc72ba7bcc56755826
3,627,503
def _format_koff_text(properties, timeunit): """Format text for koff plot. """ tu = "ns" if timeunit == "ns" else r"$\mu$s" text = "{:18s} = {:.3f} {:2s}$^{{-1}} $\n".format("$k_{{off1}}$", properties["ks"][0], tu) text += "{:18s} = {:.3f} {:2s}$^{{-1}} $\n".format("$k_{{off2}}$", properties["ks"][1], t...
c657173779a7e63c149de364c3b5d3dfb27b4618
3,627,504
def annotate_heatmap(im, data=None, valfmt="{x:.2f}", textcolors=("black", "white"), threshold=None, **textkw): """ A function to annotate a heatmap. Parameters ---------- im The AxesImage to be labeled. data Data used to annotate. If No...
2409be396c214db7f9fb7e31254bbc6ebe3aca33
3,627,505
def fmt_val(val, shorten=True): """Format a value for inclusion in an informative text string. """ val = repr(val) max = 50 if shorten: if len(val) > max: close = val[-1] val = val[0:max-4] + "..." if close in (">", "'", '"', ']', '}', ')'): ...
c8a10f187d971f8b3f4222549375642b6c12a6a6
3,627,506
from typing import List def start_nodes(aliases: List[str] = [], ssh_config_file: str = DEFAULT_CHAOS_SSH_CONFIG_FILE) -> bool: """ Start indy-node service on a list of nodes. :param aliases: A list of nodes. Required. :type aliases: List[str] :param ssh_config_file: The relative ...
0b9fb3e3fd21e56b571a554577309a2495a73165
3,627,507
def get_rms_radius(ts): """ Calculate the RMS radius at the different iterations of the timeseries. """ r = [] for iteration in ts.iterations: x, w = ts.get_particle( ['x', 'w'], iteration=iteration ) r.append( np.sqrt( np.average( x**2, weights=w ) ) ) return( 1.e-6*np.array(r) ...
f5d7fcbb90e2f29d7e2a38427f7fdb5aea53c962
3,627,508
def encode_function_data(function=None, *args): """Encodes the function call so we can work with an initializer. Args: initializer ([brownie.network.contract.ContractTx], optional): The initializer function we want to call. Example: `box.store`. Defaults to None. args (Any, opt...
645f663e29672e96ce1cd18c727c4ed56b7d93db
3,627,509
def analyzeTarget(obj, targetPath): """ This function is used (more during the development cycle than in the runtime application) to analyze the difference between the vertex positions of a mesh object and those recorded in a file on disk. The result is a representation of each vertex displacemen...
2534ddf77ae356fbd189052890ab5e3c6b2b1dc0
3,627,510
def generate_ranklist(data, rerank_lists): """ Create a reranked lists based on the data and rerank documents ids. Args: data: (Raw_data) the dataset that contains the raw data rerank_lists: (list<list<int>>) a list of rerank list in which each el...
3ad3431efff6a7ad81b649a8654d5ec30184de74
3,627,511
def is_merge_brances_has_written(from_branch, to_branch, merge_msg="auto merge"): """ returns True, if merge is successful and it has modified some untracked_files return False, if there is nothing to merge """ for line in git("merge", from_branch, to_branch, "-m", merge_msg, _iter=True, _tty_out=F...
59d4580127d4627b5edc7478d7588710874ff693
3,627,512
def desktop_extra_assigner(self, user): """Assign the extra packages name of the selected desktop. Arguments --------- user: "Dictionary containing user's answers" Returns ------- "String containing question for the desktop extras" """ choice = ['Gnome extra', ...
529910c70e7dfd83ab58a4937668d35607457271
3,627,513
from typing import Dict from typing import Tuple from typing import List def _get_openmm_parameters( force: openmm.Force, ) -> Dict[Tuple[int, ...], List[Tuple[unit.Quantity, ...]]]: """Returns the parameters stored in a given force. Args: force: The force to retrieve the parameters from. Re...
12178a67b060f85da83929465a359d3f377c9a90
3,627,514
def create_scene(info, color="cpk", scale=1.0, show_bonds=False): """Create a fresnel.Scene object. Adds geometries for particles, bonds, and box (or boundingbox). Parameters ---------- info : list List containing N, types, typeids, positions, N_bonds, bonds, box color : str, default "...
1be9e76c7eb1379a516fbdc1bace26891648f505
3,627,515
from bs4 import BeautifulSoup def crawl_malware_domains(url): """ This function crawls the malware domain indicator and returns all the dataset links to be downloaded and scraped later. @param url (string) url of the indicator web page @return """ print('Crawling site: ...
93c518d7db9140951b6133b8157e87e0a7205577
3,627,516
import asyncio def ip_address_middleware(get_response): """A Middleware to attach the IP Address and if its Routable to the request object. """ if asyncio.iscoroutinefunction(get_response): async def middleware(request): client_ip, is_routable = get_client_ip(request) ...
e31213ef515d9b747e77a9b5f257ee6b394d8526
3,627,517
from datetime import datetime def parse_datetime(datetime_str: Text) -> datetime.datetime: """ form string parse datetime """ for str_format in cfg.datetime_str_formats: try: datetime_object = datetime.datetime.strptime(datetime_str, str_format) return datetime_object e...
860c24a80d8e8f555f554d4343f7f37357a0673e
3,627,518
import re import logging def get_gpu(): """Returns video device as listed by WMI. Not cached as the GPU driver may change underneat. """ wbem = _get_wmi_wbem() if not wbem: return None, None _, pythoncom = _get_win32com() dimensions = set() state = set() # https://msdn.microsoft.com/library/aa...
cb2ca5c26d9df4788d1f5596922ab97107649578
3,627,519
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None): """ Search nodes matching `filter_` but stop at `maxlevel` or `stop`. Return tuple with matching nodes. Args: node: top node, start searching. Keyword Args: filter_: function called with every...
f7b8d5694c0d17de1476145aa8c603c3f7074bca
3,627,520
from typing import Union from typing import Iterable from typing import Mapping from typing import Optional from typing import Hashable def concat( objs: Union[ Iterable[FrameOrSeriesUnion], Mapping[Optional[Hashable], FrameOrSeriesUnion] ], axis=0, join="outer", ignore_index: bool = False...
5574293208e2b1b7a61733ffd48af04be55c639e
3,627,521
import random import string def create_hash(): """ Creates a unique hash for each URL. :return: Hash """ _hash = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) if UrlShortenModel.find_by_hash(_hash): create_hash() return _hash
36467353abe2a6f59746ff4bb403de74b2e6f2d5
3,627,522
def str_or_list_like(x): """Determine if x is list-list (list, tuple) using duck-typing. Here is a set of Attributes for different classes | x | type(x) | x.strip | x.__getitem__ | x.__iter__ | | aa | <class 'str'> | True | True ...
5ea7a6ff90f702c766401d0a973ac02347c66ade
3,627,523
from typing import Optional def get_carrier_gateway(carrier_gateway_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCarrierGatewayResult: """ An example resource schema demonstrating some basic constructs and validation rules. :param str carr...
ab70ed301bf14e47347a7d260f68594f6507c67b
3,627,524
def _bootstrap_dm(ids, dm, new_names=None): """Makes a bootstrapped distance matrix Parameters ---------- ids: array-like A list of ids in the distance matrix. These do not have to be unique. dm : DistanceMatrix The distance matrix object to resample. new_names: array_li...
8f1ad0203f43a5033d83e21fbb7eb3d6082e0d57
3,627,525
def ai(listAI, listHuman, list_all): """ AI计算落子位置 """ if len(listHuman) == 0: next_point[0] = 7 next_point[1] = 7 else: #listAI = listai #listHuman = listhuman for i in range(len(listAI)): listAIAndHuman.append(listAI[i]) for i in range(len(listHuman)): listAI...
869f77276f0a4ed92fd1be820329e44a750bb568
3,627,526
import os def readprobes(path, probes_name="probes", time_name="0", name="U"): """read the data contained in the force file . create the forces variables in the Forcesfile object Args: path: str\n probes_name: str\n time_name: str ('latestTime' and 'mergeTime' are supported)\n ...
a3345bc0aafdf00291193b17ecab66189b386924
3,627,527
import itertools def list_as_range_strings(values): """ Format a list of single-range strings from a list of values; sorts input. :param values: :return: """ values.sort() # make sure numbers are consecutive value_groups = itertools.groupby(values, lambda n, c=itertools.count(): n - next(...
d4b8da4a1d6c501705cade252cff11eb7c898a9a
3,627,528
def squared_distance(v: Vector, w: Vector) -> float: """Computes (v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2""" return sum_of_squares(subtract(v, w))
889f77eebc691d4d1f0f49e357ae06506f0eb5e0
3,627,529
def fp2tan(xfp, yfp): """ Convert focal plane to tangent plane coordinates Args: xfp, yfp: CS5 focal plane coordinates in mm return xtan, ytan where xtan=sin(theta)*cos(phi), ytan=sin(theta)*sin(phi) """ #- phi=0 aligned with +xtan = -RA = +HA = +xfp phi = np.arctan2(yfp, xfp) ...
97bbc6730a9321a18cbf0d60ab0393ee16a04d42
3,627,530
def bounding_box(fixtures, pose): """Get the axis aligned bounding box of the fixtures Args: fixtures (iterable): an iterable containing the fixtures to bound pose (tuple): an (x, y, theta) tuple. All fixtures will be transformed by this pose before the bounding box is c...
eaf8f6cfca0e97550a8579e7db3b99fd8ed8306f
3,627,531
def dir_key(dir_name): """ Used for sorting """ p = parse_dir(dir_name) if p is None: return 0 abits, wbits, r = p return 1000*abits + 100*wbits + int(100*r)
f8fc4af4f3fe1db6bf7a8e18d3e0fa9041729a31
3,627,532
def get_impact_from_xmlfile(element): """Gets the impact value of a step/testcase/suite from the testcase.xml/testsuite.xml/project.xml file """ return TCOBJ.get_impact_from_xmlfile(element)
9925c26956aaeb17672dabf5bb124830e0f2d32d
3,627,533
def readlist(infile): """Read each row of file as an element of the list""" with open(infile, 'r') as f: list_of_rows = [r for r in f.readlines()] return list_of_rows
50ea79f3c64e5e90a0f8b3bfd4cd8108304d57b2
3,627,534
def is_indvar(expr): """ An individual variable must be a single lowercase character other than 'e', followed by zero or more digits. :param expr: str :return: bool True if expr is of the correct form """ assert isinstance(expr, string_types), "%s is not a string" % expr return INDVAR_R...
4e9bd018da3950adb68d93ec36bdfafb8a7219c5
3,627,535
from scipy import signal def estimate_ringing_samples(system, max_try=100000): """Estimate filter ringing. Parameters ---------- system : tuple | ndarray A tuple of (b, a) or ndarray of second-order sections coefficients. max_try : int Approximate maximum number of samples to try....
689d1afb7fe99136fa3741099cb68af11151f437
3,627,536
def read_popularity(path): """ :param path: a path of popularity file. A file contains '<id>,<rank>' rows. :return: a set of popularity object ids """ ids = set() for line in open(path): try: ident = int(line.split(",", maxsplit=1)[0]) except (AttributeError, IndexErr...
a97f20b129bd7849a4bf9a91d40c23ad664b500b
3,627,537
def classify(tree, input): """classify the input using the given decision tree""" # if this is a leaf node, return its value if tree in [True, False]: return tree # otherwise find the correct subtree attribute, subtree_dict = tree subtree_key = input.get(attribute) # None if input is mi...
66b7558ac8658aa83b1796c17a637daa5a2309bb
3,627,538
def fmt_null_obj(obj): """将空对象转为空字符串(obj) \t\t@param: obj 传入对象 """ if not __check_null(obj): return '' if type(obj) in (list, tuple): # Change 'None' to '' obj_new = __fmt_null_ListTuple(obj) elif type(obj) == dict: # Change None's value to '' obj_new = __fmt_null...
fc52615d2db94485c9431a89c18c1b93fe6c7cb0
3,627,539
def email_loeschen(request): """ Dekrementiert die Anzahl der Formulare für eine E-Mail in der mitgliedBearbeitenView oder mitgliedErstellenView nach Löschen eines Formulars. Aufgaben: * Erfassen der Anzahl der E-Mails * Rechteeinschränkung: Nur angemeldete Nutzer können den Vorgang auslösen ...
46b6dd6d0e4728563e6f7e5530a9f1ebefb28141
3,627,540
def extendDynaForm(dynaform, dynainclude=None, dynaexclude=None, dynaproperties=None, append=False): """Extends an existing dynaform. If any of dynainclude, dynaexclude or dynaproperties are not present, they are retrieved from dynaform (if present in it's Meta class). While it is rather u...
656d0d86ffb5bb2f9141f1f5e2ecf616d9c56535
3,627,541
def _parse_write_checkpoint(write_checkpoint): """ Returns the appropriate value of ``write_checkpoint``. """ if isinstance(write_checkpoint, bool): if not write_checkpoint: write_checkpoint = "NONE" else: write_checkpoint = "ALL" if write_checkpoint.upper() not in ("...
752db50a4782fb13584ee0daf691f37edcb095eb
3,627,542
def compute_shape_features(df_samples, sig, center='trough'): """Compute shape features for each spike. Parameters --------- df_samples : pandas.DataFrame Contains cycle points locations for each spike. sig : 1d array Voltage time series. center : {'trough', 'peak'} Cent...
54605acbfa0b96aa1430401cc3aa3c0a2a2a1626
3,627,543
def uCSIsCyrillic(code): """Check whether the character is part of Cyrillic UCS Block """ ret = libxml2mod.xmlUCSIsCyrillic(code) return ret
e099fce1c26940bc7e5facc8ef783da5d9478126
3,627,544
def ping(): """ Send a ping query --- tags: - ping parameters: - in: query name: time description: timestamp required: false type: integer - in: states name: states description: states required: false type: string responses: 200: description: pong received """ ret...
21acff6108a07bf5f982260409843dc05662aa31
3,627,545
import string def names_to_usernames(names): """ Take the given list of names and convert it to usernames. "John Doe" -> "john.doe" Each name is stripped before conversion, then split by spaces. If the name contains anything except letters and spaces, raise an exception. If duplicate names...
0156f8402541e64dc1ed2b62d21bfcfbda55f167
3,627,546
def measurement_chain_with_equipment() -> MeasurementChain: """Get a default measurement chain with attached equipment.""" source = SignalSource( "Current measurement", output_signal=Signal(signal_type="analog", units="V"), error=Error(Q_(1, "percent")), ) ad_conversion = SignalT...
e9a673a37baf07cbe5a6e284755c66d9bf51e5c9
3,627,547
def get_all(): """ Get All Profiles --- /api/users/profiles_all: get: summary: Get all profiles Function security: - APIKeyHeader: [] tags: - Profile responses: '200': description: Returns all profiles '400': description: Us...
ae3f780a045b4c3d5b0430c38b411ead8de8fb13
3,627,548
import numpy def compose_matrix(scale=None, shear=None, angles=None, translate=None, perspective=None): """Return transformation matrix from sequence of transformations. """ M = numpy.identity(4) if perspective is not None: P = numpy.identity(4) P[3, :] = perspective...
95ae6e3ec348a49c15607e5e9e1f35c0a393b66f
3,627,549
def value_to_cpp(type_, value): """ Convert a python value into a string representing that value in C++. This is equivalent to primitive_value_to_cpp but can process arrays values as well Warning this still processes only primitive types @param type_: a ROS IDL type @type type_: builtin.str ...
c771656e3163efb1c077b22a1832a7e78440f132
3,627,550
def make_reference(x, crop_size, ref_type): """ ref_type: {'bmf', 'bt'} bmf: Ball-Mid-Frame, normalize by where the ball is at mid-frame tb: Track-Ball, normalize by where the ball is at each frame """ print('Running DataUtils:make_reference') assert(crop_size[0] % 2 == ...
10627c3c1174129ed1e90e44d348a87b1a5dacdf
3,627,551
def vessel_tip_coupling_data_to_str(data_list): """A list of vessel tip data elements is converted into a string.""" s = [] for v in data_list: s.append('VesselTipData(') s.append(' p = Point(x={}, y={}, z={}),'.format(v.p.x, v.p.y, v.p.z)) s.append(' vertex_id = {},'.format(v.vert...
6768afa9497e5343bc20736a963d81c7ec298867
3,627,552
def user_labels_insert(*args): """ user_labels_insert(map, key, val) -> user_labels_iterator_t Insert new (int, qstring) pair into user_labels_t. @param map (C++: user_labels_t *) @param key (C++: const int &) @param val (C++: const qstring &) """ return _ida_hexrays.user_labels_insert(*args)
9c255306ee2e42e947e4f9d939681a79e090e1d4
3,627,553
def RequestReasonInterceptor(): """Returns an interceptor that adds a request reason header.""" return HeaderAdderInterceptor(_GetRequestReasonHeader)
c85b4b1c2a4e893610df17bdfabda7effbfeed54
3,627,554
from typing import Union from typing import Dict from typing import Set from typing import Any def mem_usage_pd(pd_obj: Union[pd.DataFrame, pd.Series], index: bool = True, deep: bool = True, details: bool = True) -> Dict[str, Union[str, Set[Any]]]: """ Calculate the memory usage of a pandas o...
793a75301da3bb7e9ff784db55a26afdc347180c
3,627,555
import re def LF_DG_METHOD_DESC(c): """ This label function is designed to look for phrases that imply a sentence is description an experimental design """ #TODO FIX for words that change the sentence menaing from methods to results if "we found" in get_tagged_text(c): return 0 i...
00a4816ebf04d26cdcc3a444749cd65b1a06d827
3,627,556
import torch def gumbel_binary(theta, temperature=0.5, hard=False): """theta is a vector of unnormalized probabilities Returns: A vector that becomes binary as the temperature --> 0 """ u = Variable(torch.rand(theta.size())) z = theta + torch.log(u / (1 - u)) a = F.sigmoid(z / temperat...
530eff4fb887b863c65c2e2a669953f49b0b83db
3,627,557
import re def price_quantity_us_number(price): """Extract the numeric quantity of the price, assuming the number uses dot for decimal and comma for thousands, etc.""" p = re.sub('[^0-9.]', '', price.strip()) return p
9e35d8096bd3edfe80b6fae6ab0641107828a50b
3,627,558
import typing import re def build_global_regexes() -> typing.Dict[str, typing.Pattern]: """ Returns a list where each element is a tuple of ``(label, possible_regexes)``. """ nums = r'-?\d+' ip_atom = r'(({0})|({0}:)|(:{0})|({0}:{0})|({0}-{0})|(:))?'.format(nums) ip = r'^{0}(,{0})*$'.forma...
43ce3ef0b0bdd6afee39e1cb710272eab859e123
3,627,559
import os def register_api(provider: str, api_dir: str = '.') -> object: """ decorator for registering api of the domain :param provider: :type provider: :param api_dir: :type api_dir: :return: :rtype: """ def generate(cls): if context['register_api']: imp...
a25409aa1f7e0aa63fd669f0fd9e510ea0c433fc
3,627,560
def _ratio_sample_rate(ratio): """ :param ratio: geodesic distance ratio to Euclid distance :return: value between 0.008 and 0.144 for ration 1 and 1.1 """ return 20 * (ratio - 0.98) ** 2
1cd2989937a992e2f558b01be6fadebc66c50782
3,627,561
def normalize_boolean(val): """Returns None if val is None, otherwise ensure value converted to boolean""" if val is None: return val else: return ensure_boolean(val)
c9cfb505fb4ace5c01ab06ff3c218cbb73cf915f
3,627,562
def make_braced_expr(tokens): """Make a braced expr from a recursive, nested list of tokens.""" result = "" for e in tokens[1:-1]: if isinstance(e, list): result += "".join([getattr(t, 'value', t) for t in flatten(e)]) else: result.append(e.value) contents = ''....
d928ae98b067bc79ac7284adffedd637cbeb750d
3,627,563
def basic_stats(G, area=None, clean_intersects=False, tolerance=15, circuity_dist="gc"): """ Calculate basic descriptive metric and topological stats for a graph. For an unprojected lat-lng graph, tolerance and graph units should be in degrees, and circuity_dist should be 'gc'. For a projected graph, ...
5f35239c7b5b572b39ce515d1a841d0e910d70fe
3,627,564
from typing import Counter def trip_finder(hand): """ Takes a 5-card hand, concats, only takes ranks If we get 3 of a kind only, returns list: [6, trip rank, 0, 0, 0, 0] """ cards = ''.join(hand)[::2] if Counter(cards).most_common(1)[0][1] == 3: if Counter(cards).most_common(2)[1][1] == 1: return [6, Coun...
42281d141bdb41e0c745610257cc4376a6262d64
3,627,565
def crossfadein(clip, duration): """ Makes the clip appear progressively, over ``duration`` seconds. Only works when the clip is included in a CompositeVideoClip. """ newclip = clip.copy() newclip.mask = clip.mask.fx(fadein, duration) return newclip
74c40f98c3c55069b132a306b2b6f6f763caccd4
3,627,566
import torch import time def get_feats(model, loader, logger, opt): """Obtain features and labels for all samples in data loader using current model. """ batch_time = AverageMeterV2('Time', ':6.3f') progress = ProgressMeter( len(loader), [batch_time], prefix='Test: ') # s...
91a053de5bbc188eb461fea10b2b650084eda8c6
3,627,567
from .mastercatalog import MasterCatalog def match(*args, verbose=True, threshold=0.036*u.arcsec): """ Find sources that match up between any number of dendrocat objects. Parameters ---------- *args : `~dendrocat.Radiosource`, `~dendrocat.Mastercatalog`, or `~astropy.table.Table` object ...
43cc2064a7f5cad7a421496f79a6f4549eb5a0ff
3,627,568
import re def show_user(func): """Register a function to be displayed to the user as an option""" global USER_FUNCTIONS try: key = re.search(r'\[(.+?)\]', func.__doc__).group(1) except AttributeError as e: key = func.__name__ print(e) USER_FUNCTIONS[key] = func retur...
1d9f0dd8217f7d493bed48a32c01453f7e1473b5
3,627,569
def check_balancing_time_gran(param_name, granmap, entity, comp='coarser', find_EC_=lambda x, y: y[-1]): """check if given granularity map specifies granularity appropriately as specified by c...
3e47918769fcdd770e09feca0ea1c281c8b7797a
3,627,570
def plot_integer_part(xs, ns, alpha, show=True): """Plot the integer part of real numbers mod alpha.""" fig = plt.figure() ax = plt.gca() xmin, xmax = alpha * (xs[0] // alpha), alpha * (xs[-1] // alpha) + alpha newxticks = np.linspace(xmin, xmax, int((xmax - xmin) // alpha) + 1) ax.xaxis.set_ma...
97107a6087f99fb9f6f39f58b26b0617a6f182fe
3,627,571
def array_to_sentence(vocab_dict, array: np.array, cut_at_eos=True): """ Converts an array of IDs to a sentence, optionally cutting the result off at the end-of-sequence token. :param array: 1D array containing indices :param cut_at_eos: cut the decoded sentences at the first <eos> :return: lis...
dd0fbe2426f429ef71325cfbebbe365c7e8a1cd7
3,627,572
import keras def make_time_scheme(dt, trend): """ Implémentation d'un schéma de RK4 sous forme de réseau de neurones """ state = keras.layers.Input(shape = trend.input_shape[1:]) # k1 k1 = trend(state) # k2 _tmp_1 = keras.layers.Lambda(lambda x : 0.5*dt*x)(k1) input_k2 = keras....
3777638ea910687d4e084133d0fb8c5268cb329a
3,627,573
def print_parameters(opt): """ Generate a string with the options pretty-printed (used in the --verbose mode). """ return str(cg.ParamBlock(opt, ''))
670b984d1cac8b0379d5200ca8ae1256935f0962
3,627,574
import os def read_scores(scores_dir, targets): """ Return a pandas DataFrame containing scores of all decoys for all targets in <targets>. Search in <scores_dir> for the label files. """ frames = [] for target in targets: df = pd.read_csv(os.path.join(scores_dir, '{:}.dat'.format(targ...
6100085100c546149df67fb8fb8dba776644009d
3,627,575
def compute_regularizer_fft(n, weight_tv, weight_l2): """Precompute 2D filter regularizer (total variation + L2) in Fourier domain. This function implements w^2 in eq. 23 of the paper: Fast Fourier Color Constancy, Barron and Tsai, CVPR 2017 https://arxiv.org/abs/1611.07596 Args: n: specifies the square...
74e481ca0517d984d443dafb04749ae68983e231
3,627,576
from pathlib import Path from typing import Optional import json async def read_data(*, file_path: Path) -> Optional[Box]: """Return the data read from file_path.""" if not file_path.is_file(): return None lock = FileLock(f"{file_path.as_posix()}.lck") with lock.acquire(): async with a...
0cb963cd42a199c18d71ff8e916269155e287cff
3,627,577
def savefacedata(request): """Save face data""" if request.method == "GET": return render(request, "savefacedata.html", {"form": FaceDataForm()}) else: try: fd = get_object_or_404(FaceData, user=request.user) form = FaceDataForm(request.POST, request.FILES, instance=f...
cf8d046ca5d754de96a2caa986cd506d4590c68b
3,627,578
import urllib def addToCal(url, date_from, date_end, summary): """ Add entry in calendar to period date_from, date_end """ vcal_entry = """BEGIN:VCALENDAR VERSION:2.0 PRODID:Pyvac Calendar BEGIN:VEVENT SUMMARY:%s DTSTART;VALUE=DATE:%s DTEND;VALUE=DATE:%s END:VEVENT END:VCALENDAR """ client = caldav.DAVC...
5d0914167ce26202f2ddf1b75550957798d55fb1
3,627,579
import os def get_bool_from_environment(env, default): """Read an environment variable as a boolean. :param env: the environment variable name :param default: the default value :return: """ try: v = os.environ[env].lower() if v == 'true': v = True elif v ==...
73bde49b05b09db598438c8e604b110d1b753688
3,627,580
def SetIamPolicy(zone_ref, policy): """Set Iam Policy request.""" set_iam_policy_req = dataplex_api.GetMessageModule( ).DataplexProjectsLocationsLakesZonesSetIamPolicyRequest( resource=zone_ref.RelativeName(), googleIamV1SetIamPolicyRequest=dataplex_api.GetMessageModule() .GoogleIamV1SetIamPolic...
f2bbf272084aa874fbb39ccbf9742090445d55f2
3,627,581
def sticky_attribute_assignment(trackable, name, value): """Adds dependencies, generally called from __setattr__. This behavior is shared between Trackable and Model. Respects NoDependency indicators, but otherwise makes trackable objects out of common data structures and tracks objects by their attribute nam...
b8070181ec4c73aee852b164044e4a3c61e021d5
3,627,582
def raw_to_pos_prob(raw): """Raw model output to positive class probability""" probs_pos_class = [] for out in raw: out = np.array(out) if len(out.shape) == 1: # This is typical style of outputs. probs_pos_class.append(softmax(out)[1]) elif len(out.shape) == 2...
0a75cd13afdaf32a45cd6f871d95ef5acdfb18bc
3,627,583
def is_tt_object(arg) -> bool: """Determine whether the object is a `TT-Tensor`, `TT-Matrix` or `WrappedTT` with one of them. :return: `True` if `TT-object`, `False` otherwise :rtype: bool """ return is_tt_tensor(arg) or is_tt_matrix(arg)
57c560ae04da2d3e493b940a29db8a6627c703de
3,627,584
def get_nltk_builder(languages): """Returns a builder with stemmers for all languages added to it. Args: languages (list): A list of supported languages. """ #all_stemmers = [] all_stopwords_filters = [] all_word_characters = set() for language in languages: if language == ...
ad7624ff6701826ec04961b559ef771fe7b294a8
3,627,585
from shapely.geometry import Point def from_edge_geoms_to_node_geoms(edge_network,logger = None): """ Infer the coordinates of the nodes from a DataFrame that describes the coordinates of the edges as Linestrings. This assumes that coords in the linestring are in the direction 'from' to 'to' the edge ID ...
6a679f1cc04046b59b2a0a96e454a1be9907b4d8
3,627,586
import _datetime from datetime import datetime def from_timestamp( timestamp, tz=UTC ): # type: (Union[int, float], Union[str, _Timezone]) -> DateTime """ Create a DateTime instance from a timestamp. """ dt = _datetime.datetime.utcfromtimestamp(timestamp) dt = datetime( dt.year, dt.m...
1342dc14559265d3d9902d2dd4c8b4c7ba03a438
3,627,587
def _check_shape_(joint_positions): """ should be (7, <nb frames>, 38, 2) 7 for the images, some should be 0 because it didn't record the images for these points 1000 for the nb of frames 38 for the features (some for the legs, antennae ...) check skeleton.py in semigh's code 2 for the pose dimensio...
de7f5924f3da6a6f8dc390c5bf22fe7155b256a8
3,627,588
def image_read(path): """ Simple abstraction over imread Parameters ---------- path : string Path to be loaded Returns ------- image : opencv image """ if CV_V3 or CV_V4: return cv2.imread(path, cv2.IMREAD_GRAYSCALE) else: return cv2.imread(path, cv2...
9b0c98697850fac2e5452d09156e590f5e3462ce
3,627,589
def mpg(miles, gallons): """Write a program that will compute MPG for a car. Prompt the user to enter the number of miles driven and the number of gallons used. Print a nice message with the answer.""" miles = float(miles) / gallons km = miles * 0.425 print miles, "mpg or in km/liter:", km r...
c3e79b6b828c6f1d4b900bb92d3057165c302780
3,627,590
def add_genesets_name(df: pd.DataFrame) -> pd.DataFrame: """ Add genesets names. Used for genesets analysis. """ # if 'geneset' not in df.columns: genesets = df.index.map(lambda s: s.split("_")[0]) df.insert(loc=0, column="geneset", value=genesets) return df
5c0c46c475fbf8b152b2d6adcdb6d7ebea74661f
3,627,591
import sys import os import json def write_index_files(files, regex, hdrnum, print_trace, content_mode="translated", outpath=None, outstream=sys.stdout, errstream=sys.stderr): """Process each file and create JSON index file. The index file will have common information in the toplevel. ...
1cff92ab3dfac39a5dc4a795b622e30413b58480
3,627,592
def set_relation_hierarchy(items_query, type_relation): """ Запись иерархических связей и пререквизитов """ try: for key,value in items_query.items(): names = value.split(', ') items_set = Items.objects.filter(name__in = names) item1 = Items.objects.get(na...
8a75ba57cd503057a2411a4e570e150054cffda2
3,627,593
import unittest def makeTestSuiteV201004(): """Set up test suite using v201004. Returns: TestSuite test suite using v201004. """ suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(ReportServiceTestV201004)) return suite
3ffe1ebcbcd3446d7cf1d81f9c6f31a026f8936b
3,627,594
def copy_data_to_csv(data=[]): """ 将从飞书下载的数据存储到csv模板里 :param data: :return: """ csv_path = cfg.excel_path try: csv_df = open_excel(csv_path) data_fmt = [str(item[0]) for item in data] csv_df["完成情况"] = data_fmt # 保存 csv_df.to_excel(csv_path, index=Fa...
13c6ec903211f329a7e9caf55ae21f472e94c87e
3,627,595
def add(x, y): """add `x` and `y`.""" return x + y
5651ff2331c1298377db3836af534c7cce37e1fa
3,627,596
def beale(position): """ optimum at (3.0, 0.5) = 0 :param position: :return: """ x, y = position return (1.5 - x + x * y) ** 2 + (2.25 - x + x * y ** 2) ** 2 + (2.625 - x + x * y ** 3) ** 2
bb5bc6d50b793155f81fdd75f8a1be8889ab7839
3,627,597
def cvReleaseHist(*args): """cvReleaseHist(PyObject obj)""" return _cv.cvReleaseHist(*args)
408fa751003d9384b8027165fbd8b6561b8459f5
3,627,598
def naive_log_ctz(x: int) -> int: """Count trailing zeros, in a O(log(zeros)) steps. Args: x: An int. Returns: The number of trailing zeros in x, as an int. This implementation is much faster than the naive linear implementation, as it performs a logarithmic number of steps relati...
dfa4c0fb890bbb13803c653a3f7f65b25bb3158f
3,627,599