content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def reverse_list_iterative(head): """ Reverse a singly linked list by iterative method :param head: head node of given linked list :type head: ListNode :return: head node of reversed linked list :rtype: ListNode """ curr = head prev = None while curr is not None: tmp = c...
c6795a6bc3356955a939396feafc1fb7d745333f
78,540
def contloc(df, column, target_set): """return rows of df where all members of target_set are in column""" return df.loc[df[column].apply(are_in(target_set))]
dbedfd5df38479ad7e977f5490003cff6eb9d55e
78,542
import hashlib def md5sum(fname): """Calculate the MD5 sum of a file""" hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest()
07f405cbf235d21ea8216f6e894076543c772b98
78,544
def main(doc=None): """Remove empty headings from Vimwiki file. Pandoc filter using panflute """ newdoc = pf.load() for i in range(5): newdoc = pf.run_filter(action, prepare=prepare, finalize=finalize, doc=newdoc) return pf.dump(newdoc)
222b6bb3efe975b6480337a86e6034bf237e661f
78,546
from typing import List from operator import or_ from operator import and_ def get_prev_track_entries(session: Session, entries: List[Track]): """ Gets the previous state of tracks in the database given a list of tracks. Args: session: (DB) sqlalchemy scoped db session entries: (List<Trac...
9cd9e32c5b1003f642034136efbb787b2429a084
78,547
def _get_classifier_block(in_channels, out_channels, kernel_size, stride, activation, se, bn_momentum, bn_track_running_stats, *args, **kwargs): """ Construct the classifier block """ block = nn.Linear(in_channels, out_channels) return block
7ee12afd5fbf127f773db17488c5f0f6f1cf6c41
78,548
import scipy def dlqr(A, B, Q, R): """Solve the discrete time lqr controller. returns state-feedback law: u[k] = -K x[k] for discrete-time state-space mode: x[k+1] = A x[k] + B u[k] by minimizing cost function: sum x[k].T*Q*x[k] + u[k].T*R*u[k] and returns infinite horizon solution S """ ...
becb24d187f77addc2a721be5752f730e3c74337
78,549
def tilt(image): """Shift image so the maximum value is in the centre. Parameters ---------- image: (sz,sz) array The image to be shifted. Returns ---------- result: (sz,sz) array The shifted image. """ """maxTargCoords = np.where(target==np.max(target)) maxPSFCoords = np.where(PSF...
a27f98872a6ac01ce2c28820c24943aebdbf5959
78,550
def _simplify_ternary_conditional(expression): """Return the `if_true` clause if the predicate of the TernaryConditional is a TrueLiteral. Args: expression: TernaryConditional to be simplified. Returns: the if_true expression of the given TernaryConditional, if the predicate is True, an...
653917b97d94378b7c9c19f1393cf5121b5b2973
78,551
def v2rdm_cvvxpy(one_body_ints, two_body_ints, Na, Nb): """ Generate a cvxpy Problem corresponding the variational 2-RDM method Note: if you are using with integrals generated from OpenFermion you need to reorder the 2-body ints before passing to this function. this can be accomplished by changing ...
75a2a556cc009a5f303975fd5e8d66f0b45d0944
78,552
def process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (dictionary) raw structured data to process Returns: List of dictionaries. Structured data with the following schema: [ { "netid": string, ...
958058d67b03663afab5058c98fb16f0d3d2bd51
78,553
def runacq(binary_name, mpiprocs, iterations=None, isserial=False, isintel=False): """ Run and Acquire: scriptable, parametrized, parallel execution of binaries. """ # Preallocation retlist = [] # What the function should return execution_lol = [] # Execution List Of Lists (a.k.a a "trace") gnuti...
917cde1534194d66af6304efd7eff086c9005b3a
78,554
def _nway_groups(*factors, values, levels=None): """ Parameters ---------- factors : one or more 1-d sequences of values The factors (i.e. the independent variables) to be analyzed. Generally these should be integers or categorical values. values : 1-d sequence The values ass...
49fec112bf8934813f109b46a3391e5bd3e3b05b
78,555
def make_map(npix,npix_star,dRRs,angle): """ makes the stick ring and rotates it to a given angle npix - number of pixels in the ring map npix_star - number of pixels in the stellar map dRRs - the half width of the ring in pixels angle - the rotation from the vertical axis of the rings outpu...
39f8f54c50485a9271809fca33e8934eab68fb57
78,556
def fw_sfm(n, f): """Implementation of the Fujishige-Wolfe minimum norm algorithm for SFM. Maintains a vector x explicitly and as a minimal affine combination given by a list of tuples (lambda, vector). The programming logic mainly follows the paper of Chakrabarty et al. and the original paper by W...
690407d70c8a1b0dc56ab8f294638d21115f7408
78,557
import csv from pathlib import Path from typing import List def get_samples_from_table(filename:Path)->List[SampleReads]: """ Reads a tab-delimited file of samples and extracts the read filenames. Should have the columns 'sampleName', 'readForward', 'readReverse' """ samples = list() with filename.open() as ...
b31598050e66200b73407faf55c7e6a7bb54ab75
78,558
def get_event_list(config): """Get a dict of supported events from device.""" eventinstances = session_request( config.session.post, device_event_url.format(proto=config.web_proto, host=config.host, port=config.port), auth=config.session.auth, headers=headers, data=reques...
dae84bffa493ccaae7a9f81c83c760b2e37f1328
78,559
def get_boosting_parameter_suggestions(trial: Trial) -> dict: """ Get parameter sample for Boosting (like XGBoost, LightGBM) Args: trial(trial.Trial): Returns: dict: parameter sample generated by trial obj """ return { # L2 正則化 'reg_lambda': trial.suggest_loguni...
0172d4afa5c72cf01be018118e8a272ff4c6aa8b
78,560
def getplain(formula): """ Method to make a chemical formula more readable for embedding in filenames Examples: CH3COOHv=0 -> CH3COOH g-CH3CH2OH -> CH3CH2OH (CH3)2COv=0 -> (CH3)2CO cis-CH2OHCHOv= -> CH2OHCHO g'Ga-(CH2OH)2 -> (CH2OH)2 Paramete...
2680228632f58fb3712fd5ffcc183aa270b8bd81
78,561
import decimal def RichardsonExtrapolation(fh, fhn, n, k): """Compute the Richardson extrapolation based on two approximations of order k where the finite difference parameter h is used in fh and h/n in fhn. Inputs: fh: Approximation using h fhn: Approximation using h/n n: divisor of h ...
899514b887020980a3bceb4a0dcfd0abcffd1063
78,562
def read_ephem_file(infile): """Read the ephem file.""" name, ra, dec, epoch, period = [], [], [], [], [] with open(infile, 'r') as f: for line in f: data = line.split() name.append(data[0]) ra.append(float(data[1])) dec.append(float(data[2])) ...
4a49db0803352a74adfddab84e9c8e2c44c26756
78,563
import oci def get_authenticated_client(token_path, client, file_location=None, profile_name=None): """ Get an an authenticated OCI client. Example: get_authenticated_client(token_path, oci.object_storage.ObjectStorageClient) """ if not in_dataflow(): # We are running locally, use our AP...
982ec421420c27456038340133f3d4d864d87b24
78,564
def beam_waist(wavelength,divergence, msquared=1.0): """Compute the beam waist from wavelength, divergence, and m-squared value. Parameters ---------- wavelength : float The wavelength in meters divergence : float The half divergenence in rad msquared : float, o...
a807fe174afe883ac2e72eb82b62a67c20e4ea39
78,565
def evaluate_xcoms(source, task_instance, context=None): """ Takes in an object (or container) and returns the same thing but with XComParameters evaluated :param source: The object (or container) that (may) have XComParameters :param task_instance: The task instance whose asking :param context: Op...
3dbe557c18b273dfbc5f243432de1187af340d72
78,568
def phrasify(repo_data, scale): """ Convert the repo data into a bunch of musical phrase patterns and clips. For each commit, create a phrase clip out of each unique sha or filepath part (i.e. "/home/user/bin" becomes ['home', 'user', 'bin']). Each phrase clip is a short sequence notes. Also f...
354d053a6563c28d2219a41884397055e267e417
78,569
def load_annotations( samples, anno_key, unexpected="prompt", cleanup=False, **kwargs ): """Downloads the labels from the given annotation run from the annotation backend and merges them into the collection. See :ref:`this page <loading-annotations>` for more information about using this method to ...
1d5b5171108d977603d33bb81c23fd310be44614
78,570
def hex_str_to_int(value: str) -> int: """ convert a hexadecimal string to integer '0x1b1b' -> 6939 """ return int(value, 16)
6c7187fb94528a0342b28e4633d03ba797d9d354
78,571
def generate(model, origin_inputs, seq_length, end_token=50256): """ TopK for text generation Inputs: model: the model for inferencing origin_inputs: the original inputs based on which the model will continue writing seq_length: seq_length for the model end_token: end of sen...
be3df08f62ad2fc21e4ec45c8027140dd9720993
78,574
async def async_unload_entry(hass: HomeAssistant, entry: config_entries.ConfigEntry): """Unload the config entry and stop discovery process.""" await async_stop_discovery_service(hass) return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
d556d5f257a44e9b9dde0f2e99473c5c4d5e9e4d
78,575
import re def _tokenize(text, is_comment_line=False): """ :param text: :param is_comment_line: :return: """ tokens = [] # check multi-line comment : /* comment */ while len(text) > 0: # comment end (*/) if is_comment_line: match = re.search(pattern.COMMENT...
3ee8dcb44d82fd2c21f573aad57f7d14101dd1a2
78,576
def draw_mesh2d(m: Mesh2D, **kwargs) -> SvgPlot: """Support for two-dimensional meshes.""" if "boundaries_only" in kwargs: facets = m.facets[:, m.boundary_facets()] else: facets = m.facets p, width, height, stroke = points_to_figure(m.p.copy(), kwargs) color = kwargs["color"] if "col...
6561a69f5576c0e8a48e6bbbc516f3e038156162
78,577
def get_articles(conn, page, order='score:'): """ get_articles @param conn: @param page: @param order: @return: """ start = max(page-1, 0) * ARTICLES_PER_PAGE end = start + ARTICLES_PER_PAGE - 1 ids = conn.zrevrangebyscore(order, start, end) pipeline = conn.pipeline() a...
24aca2089c7630004c9ba0688cadf5f40eb7caf3
78,578
def ProfileCurve(type=0, a=0.25, b=0.25): """ ProfileCurve( type=0, a=0.25, b=0.25 ) Create profile curve Parameters: type - select profile type, L, H, T, U, Z (type=int) a - a scaling parameter (type=float) b - b sca...
e9f31502138355be5abac65452ff79ce169cdcd6
78,579
def smooth (x,width=5,window='hanning'): """ Derived from https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html """ if x.ndim != 1 : raise ValueError ('smooth only accepts 1 dimension arrays.') if x.size < width : raise ValueError ('Input vector needs to be bigger than window size.') if width < 3 : re...
f730a4a36e696e37ff9f3bbf140879216db23474
78,580
def sigmoid(x): """ (function) sigmoid ------------------ The sigmoid function Parameter --------- - x : input value(s) Return ------ - sigmoid function output value(s) """ return 1 / (1 + np.exp(-x))
d3582abd40e8dd585e62f0fa38c7d6ffe264c946
78,581
def lovasz_hinge_flat(logits, labels): """ Binary Lovasz hinge loss logits: [P] Variable, logits at each prediction (between -\infty and +\infty) labels: [P] Tensor, binary ground truth labels (0 or 1) ignore: label to ignore """ def compute_loss(): labelsf = tf.cast(labels, l...
cdd2fd2278ff58cf986c7ccde7b90d7a03f5a49a
78,582
def color(color_): """Utility for ability to disabling colored output.""" return color_
ab99444124a14e64857226cb6d163f81e65d3eff
78,583
import heapq def sort_streams(*args): """ args is a list of iterables, The smallest item is yielded each time. """ streams = [zip(c, repeat(c.service)) for c in args] return heapq.merge(*streams)
19178bc88d21250e54b7968e5d3608757ec4c855
78,584
def get_contacts(filename): """ Return two lists names, emails containing names and email addresses read from a file specified by filename. """ names = [] emails = [] with open(filename, mode='r', encoding='utf-8') as contacts_file: for a_contact in contacts_file: na...
cffc2561ac5c393291451e0eba3df91ff3e7cd25
78,585
def nll(y_true, y_pred): """ Negative log likelihood (Bernoulli). """ # keras.losses.binary_crossentropy gives the mean # over the last axis. we require the sum return tf.reduce_sum(tf.metrics.binary_crossentropy(y_true, y_pred), axis=-1)
0f9f327fcaa44a34fd93cae9216314e9973c1891
78,586
import joblib def loadTrainingFeatures(file, model_type, downsample, features_type): """ Counterpart to saveTrainingFeatures, this function loads features and labels for training. Arguments: file -- string containing the location of the file that will be read model_type -- string containi...
35368f7c5d8c094d962f4781b4c9cb879a1a7e0b
78,587
def login(): """ Login Page, Associated to login.html """ if 'username' in session: flash(u"Already logged in", 'error') return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): if form.password.data == globalsettings.password: session['usern...
8086205c450cc787651334a8a26dd4f0ef68a539
78,589
def centers_cutouts(subsize, ysize, xsize, log=None, get_remainder=False): """Function that determines the input image indices (!) of the centers (list of nsubs x 2 elements) and cut-out regions (list of nsubs x 4 elements) of image with the size xsize x ysize. Subsize is the fixed size of the subi...
0557a471fa0a5832581db60704150e1c2238a740
78,590
def mongoDeleteCol(col): """删除指定集合col""" mycol = db[col] return mycol.drop()
862af25816b49222b22181129211dad6dfb8d27f
78,591
def estimate_transport(transplants): """ This function computes transport statistics for organs traveling between DSAs @Input: @transplants: data frame containing number of organs being transported from DSA i to DSA j across 5 years 5 replications @Output: @distances: average di...
8963da9cad46ef720a47c2b73f27b72914a9a4bd
78,592
import re def fOrteStripped(LDSResBaseType,OrteIDs): """ returns Orte stripped """ if LDSResBaseType == 'SEG': # 'Objects.3S_FBG_SEG_INFO.3S_L_6_MHV_02_FUD.In.'] orteStripped=[] for OrtID in OrteIDs: pass m=re.search(Lx.pID,OrtID+'dummy') ortStri...
357f40e797dc65fa0ab8f28833536ee7820f35a3
78,593
def _cmds(): """ :returns: all the supported commands :rtype: dcos.cmds.Command """ return [ cmds.Command( hierarchy=['job', 'run'], arg_keys=['<job-id>'], function=_run), cmds.Command( hierarchy=['job', 'kill'], arg_keys...
e1e96890139e771f53490b2cdf76dd9285e0a9f7
78,594
def calculate_sift(images): """ 计算每一张图片的sift特征值 :param images 一个图片集合的可迭代对象 :return: 一个列表 [ SIFTFeature(), ... ] """ answer = [] for image in images: sift_detector = cv2.xfeatures2d.SURF_create() # 调用SIFT key_points = si...
285920fea79153856c867c7d3fea9a37c2812b08
78,595
def _check_package(pkg): """ Checks if a package is installed and signed :param str pkg: name of package """ return has_package(InstalledRedHatSignedRPM, pkg)
29a07c5a0adaefff6b2823612d2cbc4855f71cae
78,596
def fan_data_fixture(): """Load fan MQTT data and return it.""" return load_fixture("ozw/fan_network_dump.csv")
38e32efe58272db66925fac9cf59ce5869e5f7b1
78,597
def poseFromROSPoseMsg(msg): """ :param msg: A populated ROS Pose message. :return: (pos, quat), where pos is a 3-element list of positions [x, y, z], and quat is a 4-element list of quaternion elems [w, x, y, z] """ pos = [msg.position.x, msg.position.y, msg.position.z] quat = [msg...
328d9ae08f1d7c8113f86c8f0b27edac40d8fc1b
78,598
import json def open_map_file(difficulty): """This function opens the map file listed in the info.dat file for the specificed difficulty level.""" with open('./temporary/info.dat', 'rb') as i: info = json.load(i) for x in info['_difficultyBeatmapSets']: if x['_beatmapCharacteristicName'].c...
301716cd4c75f2843a75d04c6e0118bcbd76e065
78,599
def atom_degree_one_hot(atom, allowable_set=None, encode_unknown=False): """One hot encoding for the degree of an atom. Note that the result will be different depending on whether the Hs are explicitly modeled in the graph. Parameters ---------- atom : rdkit.Chem.rdchem.Atom RDKit atom...
091ad22a3713f3b4ff8fc5117734be3c75b68fde
78,600
def _is_a_tab(knob): """Helper function to check if a knob is a tab. This is _not_ perfect, we use a lazy check to see if the flag to save is set. Tab knobs (and group end variants) have the DO_NOT_WRITE flag set to be True. """ return isinstance(knob, nuke.Tab_Knob) and knob.getFlag(nuke.DO_NO...
2349b563da11e51fbecaf93e7d7e967631f18917
78,601
import types def create_batch(autocommit=False, **batch_settings): """Return a batch object suitable for testing. Args: autocommit (bool): Whether the batch should commit after ``max_latency`` seconds. By default, this is ``False`` for unit testing. batch_settings (dic...
8ae5b82fb188be0d8d6f15663c051e4f0c219427
78,602
def aggregated_comparitive_iou(boxes1, boxes2=None, iou_type=0, beta=0.6): """Calculates the IOU between two set of boxes. Similar to bbox_overlap but far more versitile. Args: boxes1: a `Tensor` of shape [batch siz...
fea0cc2bf59829405bec4d6b05d4c2ed37a3f215
78,603
def _cluster_quality_gev(data, clusters, clustering, sd=None): """Global Variance Explained (GEV) """ if sd is None: sd = np.std(data, axis=1) map_corr = _correlate_vectors(data.T, clusters[clustering].T) gev = np.sum((sd * map_corr) ** 2) / np.sum(sd ** 2) return gev
eb1575e53b9efde57b96b982e6a159186c4ba845
78,604
def Poly4Asymmetric(t, duration, A, B, C, D, Cf=None, time_argument_is_f=False): """Transfer coil function, standard one segment Cf, if not None, should be a list or tuple, the first element of which is a Cf function for scaling the time coordinate, and the other elements the arguments to be passed...
4963cfa02610df45f837922039e980d290f9ad51
78,605
async def validation_exception_handler(request: Request, ex: 'RequestValidationError'): """Exception handler for all RequestValidationError raised by pydantic :param request: starlette request :param ex: actual Validation exception :return: json response representing the error """ return JSONRe...
1231c70aee8fc4ebc33ce048fcf9fc1751d17c55
78,606
def replace_classprops(func: astroid.FunctionDef): """Replace ``classproperty`` decorated methods. As discussed in https://github.com/PyCQA/pylint/issues/1694, pylint does not understand the ``@classproperty`` decorator, and so mistakes the method as a function, rather than an attribute of the class. I...
b152991834b67054991bba3d2226ea2b19688962
78,607
def get_auth_stdin(refresh_token_filename): """Simple wrapper for :func:`get_auth` that prompts the user using stdin. Args: refresh_token_filename (str): Path to file where refresh token will be cached. Raises: GoogleAuthError: If authentication with Google fails. """ r...
7382947f7a41e162213ed29ff4f418fd0a64a8cb
78,608
def compare_dicts(before, after): """ Comparing 2 dicts and providing diff list of [added items, removed items] Args: before (dict): Dictionary before execution after (dict): Dictionary after execution Returns: list: List of 2 lists - ('added' and 'removed' are lists) """ ...
26bf3b345d07d656eed2e2cc634072c459c4a5c0
78,609
def unit_sphere_projection(tensor_var): """ Unit sphere normalisation of a tensor. Parameters ---------- tensor_var : tf.Tensor Embeddings tensor. Returns ------- tf.Tensor Embedding matrix with the unit sphere normalisation applied. """ return tensor_unit_norm(tens...
6a2da97b5894edc5d4ab94d15e1f838a288a0669
78,610
def root_mean_squared_percentage_error(y_true: np.ndarray, y_pred: np.ndarray): """ Root Mean Squared Percentage Error Note: result is NOT multiplied by 100 """ y_true = flatten_values(y_true) y_pred = flatten_values(y_pred) percentage_error = (y_true - y_pred) / y_true square_percentag...
ca021a1b842090b1afa8ac5fd8b16e6e8d903f1b
78,611
def make_conv_relu_tests(options): """Make a set of tests to do conv_relu.""" return make_conv_activation_tests(tf.nn.relu)(options)
ffd7008ef3887234e859c8ac783cf3d3b5b99123
78,614
def str_str(haystack, needle): """ Solution 1 超时 """ if needle is None or len(needle) == 0: return 0 if len(haystack) < len(needle): return -1 for i in range(len(haystack)): if needle[0] != haystack[i]: continue j = 0 while j < len(needle):...
8e90ed2c7c4f4a880594f66487742cc939480aa8
78,616
def getNormalDataIterator(batchSize, sequenceLength: int, includeData=False, includeLabel=False, cols=None, extra=None): """ :param includeData: If False, will only iterate through the labels :param includeLabel: If true, will return tuple (train batch, label batch) when iterated through. Otherwise will exc...
8ff1f4f8c54e50e879753a6f90cdaeace34448cf
78,618
def obd_file_with_valid_speed(obd_file): """ Check if the given obd file has valid speed column. The file might be empty. The speed column might be empty. """ if not file_populated(obd_file): return False time_speed = read_raw_obd(obd_file) if not time_speed[0][1].strip(): r...
45f48b23ce42e452bc45b582942723b9eb2a0453
78,619
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {'user': user} if not username: return None warn_setting('SOCIAL_AUTH_CREATE_USERS', 'create_user') if not ge...
73e3e4c25ea1b02f05c259cf45a0b290271e225c
78,620
def _rpt_curve(xDataSrc, yDataSrc): """ Набирает строку для записи в файл """ result = ' db ' resultList = list('') # итоговая кривая proc2shim = kMaxSpeed_/100.0 for i in range(len(xDataSrc)): value = int(xDataSrc[i]) resultList.append(value) # читаем проценты и перево...
ad8fd000ceeb71c2a5f1ee6decc703c7ce0f70e9
78,621
from typing import OrderedDict def merge_io_formats(wps_formats, cwl_formats): # type: (List[ANY_Format_Type], List[ANY_Format_Type]) -> List[ANY_Format_Type] """ Merges I/O format definitions by matching ``mime-type`` field. In case of conflict, preserve the WPS version which can be more detailed (f...
e681ebe0fbaaabc4cb41124cfac815a19356fa8a
78,622
def construct_weights(phy, weights_fn, write=True): """ Given some binary phylip infile file path, compute the character-wise log frequencies and translate to the phylip scaling (0-Z) for the weights file. """ aln = AlignIO.read(phy, "phylip") df = pc.from_bioalignment(aln) abund = df.app...
92495345c5c6ffdf37914923aeb8780dae4a8fe0
78,624
def _get_corrected_type(defined_type, value): # type: (str, Any) -> str """Returns the corrected type according to `defined_type` and `value`. For lists we recurisively find types for the underlying elements and pick a "smallest common denominator" type. If the expected type is integer, we make sure that th...
a5b633e648d18b3afaab40acf8118dcd0f279d42
78,625
from datetime import datetime import copy def team_cumul_mileage(): """ """ teams = meta.scoped_session().query(Team).all() # @UndefinedVariable q = text( """ select team_id, ride_date, points, (@total_points := @total_points + points) AS cumulative_points, ...
543efcda839f63c568dad23a8a3454b8041294fe
78,626
import json def ajx_set_attempt_proceed_to_checkout(request, attempt_id, checkin_id): """ View function responsible for mark an attempt to checkout process """ if not request.is_ajax(): return HttpResponse(status=400) rpc_client = BalaioRPC() rpc_response = rpc_client.call('proceed_to...
0c45371d9f5da9ca4c9d10a80bdec604d007c0f3
78,627
def get_password_data(): """ Gets the password for a specified instance. @return: Response. """ helpers.require_parameters(['InstanceId']) response = _get_password_data_request() return _get_password_data_format_response(response)
d0d7075e22876e89843933eed5b9cc770a50d0ca
78,629
def is_mcode_set1(*args): """ is_mcode_set1(mcode) -> bool """ return _ida_hexrays.is_mcode_set1(*args)
c99c9486440087acf15700cb57d2e8f275bd09c3
78,630
def nin(x, num_units, **kwargs): """ a network in network layer """ s = int_shape(x) x = tf.reshape(x, [np.prod(s[:-1]),s[-1]]) x = wndense(x, num_units, **kwargs) return tf.reshape(x, s[:-1]+[num_units])
be02519a1a40dae0a6a65beb09a34fdc5be81c3f
78,632
def invertedresidualflownet_bn(data=None): """FlowNetS model architecture from the "Learning Optical Flow with Convolutional Networks" paper (https://arxiv.org/abs/1504.06852) Args: data : pretrained weights of the network. will create a new one if not set """ model = InvertedResidualFlowNe...
d5ea5353620c9478ab06c421292b2c0915b8e1a4
78,634
def memoized(fget): """ Return a property attribute for new-style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned, preventing the need to call the getter any more. Parameters ---------- fget: function The getter met...
9fa61406e15f71f7cee7fa4aae93bad0d0270b7e
78,635
def make_integer(value): """Returns a number in a string format like "10,000" as an integer.""" return int(value.replace(",", ""))
9999c3476afa70366275402b2d327a9e42dfe4d7
78,636
def coordinate_map(center_pixel): """ A coordinate map. """ return DashedRingMap(center_pixel, 2.5)
7e135b1a638bd3de1c26f6695f2655b7b9ab69ee
78,637
import re import tensorflow as tf def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path): """ Load tf checkpoints in a pytorch model """ try: except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see " ...
ff781e758f78d850caae1a561f00f6e2d4fc1c90
78,638
def plot_ratio_from_HWU(path, ax, hwu_variable, hwu_numerator, hwu_denominator, *args, **opts): """INPUT: - path can be a path to HwU or an HwUList instance - ax is the matplotlib frame where to do the plot - hwu_variable is the histograms to consider - hwu_numerator is the numerator of ...
49e33dde9f19422a724bb00ae5dfc5f469fb8180
78,641
async def get_pokemon(id: int): """ ## Retrieves a Pokemon by ID. Path Parameters --------------- id: int Pokemon ID. Body Parameters --------------- None Returns ------- id: int Pokemon ID. name: str Name ...
300c344076c9d1ab45bf10e2a2b617a52a6c4a98
78,643
from typing import Optional import torch import math def reference_butterfly_layout_for_testing( out_features: int, in_features: int, block_size: int = 256, butterfly_size: int = 64, n_factors: Optional[int] = None, stretch: bool = False, ) -> torch.IntTensor: """ Get a matrix [num_out...
c32089af6bea7a59b7103be1bcb5f001d95a3b6e
78,644
def images_rescale(arFrames): """ Rescale array of images (rgb 0-255) to [-1.0, 1.0] :param arFrames: Array of frames. :return: Array of rescaled frames. """ ar_fFrames = arFrames / 127.5 ar_fFrames -= 1. return ar_fFrames
63f823b529a39300e15245e2326edf3b1497edb5
78,645
def developer_token() -> str: """The developer token that is used to access the Adwords API""" return 'ABCDEFEGHIJKL'
f35bdffe3cf127731a9bf86e79e5c6fbe5a021d0
78,646
def control_change(chan, ctrl, val): """ Creates a control change message. Parameters ---------- chan : 0-15 The midi channel of the message. ctrl : byte The controller number. val : byte The controller value. """ return [kCtrlChange | chan, ctrl, val]
6b4a826a05a186cfe909b647c39fc375957f218a
78,647
def affichage_menu_jeu(screen, var): """ Affiche le menu du jeu (Paul) """ screen.fill(COLOR["SILVER"]) plateau = show_table(screen) screen.blit(plateau, (0, 0)) pygame.display.flip() return var
336ba94d6bf8b5cfb4bab0bbc62becb9f42e17f8
78,649
def create_convert_apds_filenames(from_date, to_date): """ Create the list of filenames output by convert_apt_data.py. """ return [create_apds_flights_filename(from_date, to_date), create_apds_positions_filename(from_date, to_date), create_apds_events_filename(from_date, to_date)]
e0dfaac9ae356c8d806749610519b9475abcaf98
78,650
def get_course_topics(request, course_key, topic_ids=None): """ Returns the course topic listing for the given course and user; filtered by 'topic_ids' list if given. Parameters: course_key: The key of the course to get topics for user: The requesting user, for access control t...
75528c28ac48143a7b7124037fce37a7e9709be7
78,651
def get_mfa_session(taws_access_key_id,taws_secret_access_key,tmfaarn,tmfa_token): """ using MFA, connect and get temp access creds/sessions """ sts = boto3.client('sts', aws_access_key_id=taws_access_key_id, aws_secret_access_key=taws_secret_access_key) try: tempcredentials = sts.get_session_token(...
16d1c7518dc7801e55b388d49c3f97fc6f1ba88b
78,652
def norm(v): """ Returns scaled v, normalized to magnitude 1.0. """ return scale(v, 1.0/mag(v))
e151abecd8c84eae5b41d495076e7bcc635b9979
78,653
from typing import List def compress_pulses(schedules: List[Schedule]) -> List[Schedule]: """Optimization pass to replace identical pulses. Args: schedules: Schedules to compress. Returns: Compressed schedules. """ existing_pulses = [] new_schedules = [] for schedule in...
37ddfd18728db590ec7430063415e9f81ecf30bc
78,654
import platform def is_linux(): """ détermine si le système actuel est linux """ return platform.system().lower() == "linux"
40098b70535d5725b13358ee00a84b5783d1d397
78,655
def scale_matrix(mat): """Scale matrix values within [-1, 1] range""" return (mat*2/np.max(mat) - 1)
f522b7cc2b08638e6931d0552c7c2e4eddb7d58a
78,656
def get_advanced_hunting_request(query): """Retrieves results according to query. Args: query (str): Query to do advanced hunting on Returns: dict. Advanced hunting results """ cmd_url = '/advancedqueries/run' json = { 'Query': query } response = http_request('P...
3cb1f5b22536adabac7b1543e06df03877cbe204
78,657
def get_parent_relative_joint_locations(joints_xyz, axis=0, sk_data=psk_data): """ Assumed shape: [#limbs, X, ...] """ limb_parents = sk_data.limb_parents joints_xyz = joints_xyz.swapaxes(0, axis) limb_rel_preds = joints_xyz - joints_xyz[limb_parents] return limb_rel_preds.swapaxes(0, axis)
34d16813026d2b02b1fdd6074e7dc54567a5c48b
78,658
def imresize_like(img, target, interpolation='bilinear', return_scale=False): """ Resize an image to the same size of a given image. Args: img (:obj:`np.ndarray`): The input image. target (:obj:`np.ndarray`): The target image. interpolation (str | int, optional): Interpolation metho...
08e29c54a634caa14a5c9eeabfc1ee4e0b2144b1
78,659