content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import warnings def disable_warnings_temporarily(func): """Helper to disable warnings for specific functions (used mainly during testing of old functions).""" def inner(*args, **kwargs): warnings.filterwarnings("ignore") func(*args, **kwargs) warnings.filterw...
5e19b8f51ca092709a1e1a5d6ff0b2543a41e5e1
17,200
def progress_bar(progress): """ Generates a light bar matrix to display volume / brightness level. :param progress: value between 0..1 """ dots = list(" " * 81) num_dots = ceil(round(progress, 3) * 9) while num_dots > 0: dots[81 - ((num_dots - 1) * 9 + 5)] = "*" num_dots -= ...
88986ecc505cf786e197d8ad55cd70b21fa3aa27
17,201
def get_context_command_parameter_converters(func): """ Parses the given `func`'s parameters. Parameters ---------- func : `async-callable` The function used by a ``SlasherApplicationCommand``. Returns ------- func : `async-callable` The converted function. ...
294706230f95745dbd50681cafc066a5d226880d
17,202
def norm(x): """Normalize 1D tensor to unit norm""" mu = x.mean() std = x.std() y = (x - mu)/std return y
ea8546da2ea478edb0727614323bba69f6af288d
17,203
def honest_propose(validator, known_items): """ Returns an honest `SignedBeaconBlock` as soon as the slot where the validator is supposed to propose starts. Checks whether a block was proposed for the same slot to avoid slashing. Args: validator: Validator known_items (Dict): Kn...
c6b0403b15154e3e3b19547770a162e2ac05501b
17,204
import re def formatKwargsKey(key): """ 'fooBar_baz' -> 'foo-bar-baz' """ key = re.sub(r'_', '-', key) return key
24c79b37fdd1cd6d73ab41b0d2234b1ed2ffb448
17,205
import dateutil def mktimestamp(dt): """ Prepares a datetime for sending to HipChat. """ if dt.tzinfo is None: dt = dt.replace(tzinfo=dateutil.tz.tzutc()) return dt.isoformat(), dt.tzinfo.tzname(dt)
2f444d0ea27a3afbed68742bade8833a49e191e4
17,206
import os def load_and_assign_npz_dict(name='model.npz', sess=None): """Restore the parameters saved by ``tl.files.save_npz_dict()``. Parameters ---------- name : a string The name of the .npz file. sess : Session """ assert sess is not None if not os.path.exists(name): ...
b5c2a0d1878117cb7e6461e0615457ee92501823
17,207
def build_accuracy(logits, labels, name_scope='accuracy'): """ Builds a graph node to compute accuracy given 'logits' a probability distribution over the output and 'labels' a one-hot vector. """ with tf.name_scope(name_scope): correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(la...
53f5f78a8c07c691e20d14c416c1fe21a2547bc6
17,208
import json import os def generate_markdown_files(domain, mitigations, side_nav_data, side_nav_mobile_data, notes): """Responsible for generating shared data between all mitigation pages and begins mitigation markdown generation """ data = {} if mitigations: data['domain'] = domain.s...
8a30af0868b541c8771019c57d42d33a842050bc
17,209
def compute_mp_av(mp, index, m, df, k): """ Given a matrix profile, a matrix profile index, the window size and the DataFrame that contains the timeseries. Create a matrix profile object and add the corrected matrix profile after applying the complexity av. Uses an extended version of the apply_av funct...
cc89d34dd145339c99d1ded8ced9af853c061124
17,210
import logging def read_burris(fh): """ Read Burris formatted file, from given open file handle. Accepts comma or tab-separated files. Parameters ---------- fh : TextIOWrapper open file handle Returns ------- ChannelList """ all_survey_data = ChannelList() ...
4519cf73be5663a70e76e083aa9f735f427248a6
17,211
import re def _remove_invalid_characters(file_name): """Removes invalid characters from the given file name.""" return re.sub(r'[/\x00-\x1f]', '', file_name)
49a9f668e8142855ca4411921c0180977afe0370
17,212
def get_ops(): """ Builds an opcode name <-> value dictionary """ li = ["EOF","ADD","SUB","MUL","DIV","POW","BITAND","BITOR","CMP","GET", \ "SET","NUMBER","STRING","GGET","GSET","MOVE","DEF","PASS", \ "JUMP","CALL","RETURN","IF","DEBUG","EQ","LE","LT","DICT", \ "LIST","NONE","LEN...
6cd9e4014a124faa6be6dfc36b9f77a22df1ccfb
17,213
def load_actions( file_pointer, file_metadata, target_adim, action_mismatch, impute_autograsp_action ): """Load states from a file given metadata and hyperparameters Inputs: file_pointer : file object file_metadata : file metadata row (Pandas) target_adim ...
0b8b5dc259fa0645069cc57b4510355ec6897ab6
17,214
def send_message(hookurl: str, text: str) -> int: """ Send a message on the channel of the Teams. The HTTP status is returned. parameters ---------- hookurl : str URL for the hook to the Teams' channel. text : str text to send. returns ------- int HTTP...
8ffef50d745fafd125b556e9fb1ceff2cb438a4e
17,215
def np_fft_irfftn(a, *args, **kwargs): """Numpy fft.irfftn wrapper for Quantity objects. Drop dimension, compute result and add it back.""" res = np.fft.irfftn(a.value, *args, **kwargs) return Quantity(res, a.dimension)
fbfdfe470f09106e9589709ebae5fa19ba8a2732
17,216
def get_codec_options() -> CodecOptions: """ Register all flag type registry and get the :class:`CodecOptions` to be used on ``pymongo``. :return: `CodecOptions` to be used from `pymongo` """ return CodecOptions(type_registry=TypeRegistry(type_registry))
a0acd3e719ae0a4be463c71cba5eb86914348248
17,217
def get_frame_lims(x_eye, y_eye, x_nose, y_nose, view, vertical_align='eye'): """Automatically compute the crop parameters of a view using the eye and nose and reference. Note that horizontal/vertical proportions are currently hard-coded. Parameters ---------- x_eye : float x position of t...
20b3c5d74b7d4dd4b2b63c9d32f7325a199d3dee
17,218
import os def write_curies(filepaths: dict, ontoid: str, prefix_map: dict, pref_prefix_map: dict) -> bool: """ Update node id field in an edgefile and each corresponding subject/object node in the corresponding edges to have a CURIE, where the prefix is the ontology ID and the class is ...
d574142a634b9a4998f8b887e4bc309661c5625e
17,219
def split(time: list, value: list, step, group_hours, region=None, whole_group=False): """ Split and group 'step' number of averaged values 'hours' apart :param time: time per value (hour apart) :param value: values corresponding to time :param step: number of group times set for each index ...
a8f8cf51d241a532e6a925d4323abb281215f543
17,220
def launch_ebs_affinity_process(instanceid, instance_infos, ebs_configs): """ Manage the ebs affinity process. :param instanceid string The instance id :param instance_infos dict Informations about the instance :param ebs_config dict The EBS parameters :return None """ ...
ec30f4748417cee8f9fe96c2c47cf78dd10be59f
17,221
def get_all(isamAppliance, check_mode=False, force=False): """ Retrieve a list of mapping rules """ return isamAppliance.invoke_get("Retrieve a list of mapping rules", "/iam/access/v8/mapping-rules")
e48aa65f5212ea32e84c40e326633cf2971d378a
17,222
def get_oyente(test_subject=None, mutation=None): """ Run the Oyente test suite on a provided script """ is_request = False if not test_subject: test_subject = request.form.get('data') is_request = True o = Oyente(test_subject) info, errors = o.oyente(test_subject) if len(errors) > 0: errors = [{'lin...
f264262c22314ac26b56369f4d7741effb4cf09e
17,223
def search_for_example(search_string: str) -> tuple: """Get the Example for a Particular Function""" function = match_string(search_string) if function: function = function.strip() sql = f"SELECT example, comment FROM example WHERE function='{function}'" data = execute(sql) ...
16eb034369954017b1b51a206d48af40f5768ef6
17,224
def WildZumba(x,c1=20,c2=0.2,c3=2*np.pi) : """ A separable R**n==>R function, assumes a real-valued numpy vector as input """ return -c1 * np.exp(-c2*np.sqrt(np.mean(x**2))) - np.exp(np.mean(np.cos(c3*x))) + c1 + np.exp(1)
589f90f174d61269c2c019ef678f51c498c68ff8
17,225
def import_xlsx(filename, skip_variation=False): """Импортирует параметры пиков, хроматограммы и варьируемых параметров, если они указаны. Parameters ---------- filename : str Имя xlsx файла. skip_variation : bool, default = False Пропустить блок Variation даже если он есть. Re...
75b32618274fb2ab7ede9f525856fdc13e8c97ee
17,226
from typing import Union from typing import Optional def _get_dataset_builder( dataset: Union[str, tfds.core.DatasetBuilder], data_dir: Optional[str] = None) -> tfds.core.DatasetBuilder: """Returns a dataset builder.""" if isinstance(dataset, str): dataset_builder = tfds.builder(dataset, data_dir=data...
0f17169541604e69a614ddfeee4c8a963834ed8e
17,227
def write_bbox(scene_bbox, out_filename): """Export scene bbox to meshes Args: scene_bbox: (N x 6 numpy array): xyz pos of center and 3 lengths out_filename: (string) filename Note: To visualize the boxes in MeshLab. 1. Select the objects (the boxes) 2. Filters -> Po...
c7504260306495e6252569a3cb83f61ca084de26
17,228
def label_rotate(annot, rotate): """ anti-clockwise rotate the occ order annotation by rotate*90 degrees :param annot: (H, W, 9) ; [-1, 0, 1] :param rotate: value in [0, 1, 2, 3] :return: """ rotate = int(rotate) if rotate == 0: return annot else: annot_rot = np.rot9...
e37a2e9dddc5f19898691fe22d02978d1954d435
17,229
def allocate_available_excess(region): """ Allocate available excess capital (if any). """ difference = region['total_revenue'] - region['total_cost'] if difference > 0: region['available_cross_subsidy'] = difference region['deficit'] = 0 else: region['available_cross_s...
19a3d7fbc776ae5b5b47ecfc32db14bf4abd949e
17,230
def items(dic): """Py 2/3 compatible way of getting the items of a dictionary.""" try: return dic.iteritems() except AttributeError: return iter(dic.items())
2664567765efe172591fafb49a0efa36ab9fcca8
17,231
import json import binascii def new_settingsresponse_message(loaded_json, origin): """ takes in a request - executes search for settings and creates a response as bytes :param loaded_json: :param origin: is this a response of drone or groundstation :return: a complete response packet as bytes ...
812444353a50ffeb468398d8681e81a74cb9d7e9
17,232
def list_icmp_block(zone, permanent=True): """ List ICMP blocks on a zone .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewlld.list_icmp_block zone """ cmd = "--zone={0} --list-icmp-blocks".format(zone) if permanent: cmd += " --permanent" ...
9f0f8c2e7a688263ddd31c8384babba25e2300e6
17,233
def dependencies_found(analysis_id, execution_id): """ Installation data from buildbot. Requires a JSON list of objects with the following keys: * installer: The system used to install the dependency. * spec: The full specification used by the user to request the package. ...
8983e53dd558b42272d4886412e918e7b192754e
17,234
def set_augmentor(): """ Set the augmentor. 1. Select the operations and create the config dictionary 2. Pass it to the Augmentor class with any other information that requires 3. Return the instance of the class. :return: """ config = {'blur': {'values': ('gaussian', 0.7, 1.0), 'prob': ...
77c64cec87af2d41a4cc6dc55600ab5eaedad247
17,235
def get_global_event_logger_instance(): """Get an event logger with prefilled fields for the collection. This returns an options configured event logger (proxy) with prefilled fields. This is almost CERTAINLY the event logger that you want to use in zaza test functions. :returns: a configured Log...
66228b15dd4d1ac9468834124e4ba073a846580f
17,236
def plot_market_entry(cat_entry_and_exit_df, cat_entry_and_exit_df_2): """ returns a plot with the entry and exit of firms per category """ # get the limits so everything is on the same scale df = pd.concat([cat_entry_and_exit_df, cat_entry_and_exit_df_2]) limits = [-df.exit.max() - 0.3, df.entr...
c1b1ad00c1dbdde804e4d594dda4ae6525c7779f
17,237
import io def find_elements_by_image(self, filename): """ Locate all the occurence of an image in the webpage. :Args: - filename: The path to the image to search (image shall be in PNG format). :Returns: A list of ImageElement. """ template = cv2.imread(filename, cv2.IMREAD_U...
23137766b68068c8cb78bb57127bfa6040bace70
17,238
from typing import Set from typing import Sequence def compile_tf_signature_def_saved_model( saved_model_dir: str, saved_model_tags: Set[str], module_name: str, exported_name: str, input_names: Sequence[str], output_names: Sequence[str]) -> Modules: """Compiles a SignatureDef SavedModel to each backend ...
ed1a1efc28c9ae473d76c700ab7781f141fc3765
17,239
def origtime2float(time): """ converts current datetime to float >>> import datetime >>> t = datetime.datetime(2010, 8, 5, 14, 45, 41, 778877) >>> origtime2float(t) 53141.778876999997 """ t3fmt = time.strftime("%H:%M:%S:%f") return time2float(t3fmt)
03cadf1f686fde1dd46cbb52fd71adcc2f06585c
17,240
def discrete_fourier_transform1(freq, tvec, dvec, log=False): """ Calculate the Discrete Fourier transform (slow scales with N^2) The DFT is normalised to have the mean value of the data at zero frequency :param freq: numpy array, frequency grid calculated from the time vector :param tvec: numpy a...
b5e1bafe1ba2b8863ac97bb95c204ca84877b8fd
17,241
from typing import List def ngram_overlaps(a: List[str], b: List[str], threshold: int = 3) -> List[int]: """ Compute the set over overlapping strings in each set based on n-gram overlap where 'n' is defined by the passed in threshold. """ def get_ngrams(text): """ Get a set of all...
87621e28a4a5d2cba5bb66c6bfa9834c711a7ecf
17,242
def ssq_cwt(x, wavelet='morlet', scales='log', nv=None, fs=None, t=None, ssq_freqs=None, padtype='symmetric', squeezing='sum', difftype='direct', difforder=None, gamma=None): """Calculates the synchrosqueezed Continuous Wavelet Transform of `x`. Implements the algorithm described in Sec....
8af5caea64e9a861f7702f52c50681e61322658c
17,243
import random import logging import time def request_retry_decorator(fn_to_call, exc_handler): """A generic decorator for retrying cloud API operations with consistent repeatable failure patterns. This can be API rate limiting errors, connection timeouts, transient SSL errors, etc. Args: fn_to_cal...
0813cc19d9826275917c9eb701683a73bfe597f9
17,244
import logging import os def lambda_handler(event, context): """ 1. Receive from data from the lambda event. 2. DynamoDB: Stores incomming form data 3. Discord: Posts notification to a channel 4. Mailgun: sends notification args: - event: Event data that has trigged the lambda functio...
1cecfe77c6d845976372003d1f465c5d9e5ad2a1
17,245
import json async def establish_async_connection(config: json, logger: AirbyteLogger) -> AsyncConnection: """ Creates an async connection to Firebolt database using the parameters provided. This connection can be used for parallel operations. :param config: Json object containing db credentials. ...
696334cdce9e04ef8f5d42ceafbf1031b063b074
17,246
def _wrap_with_before(action, responder, resource=None, is_method=False): """Execute the given action function before a responder method. Args: action: A function with a similar signature to a resource responder method, taking (req, resp, resource, params) responder: The responder m...
96d4e6640f85bf920a5cc35ed02926ca5f3be7e9
17,247
from datetime import datetime def last_day_of_month(d): """ From: https://stackoverflow.com/a/43088/6929343 """ if d.month == 12: return d.replace(day=31) return d.replace(month=d.month+1, day=1) - datetime.timedelta(days=1)
a97ce3bdbcd9d5cb707919750ecc818de04deb7e
17,248
def plot_landscape(landscape): """ Plot all landscapes for a given (set of) diagrams Inputs: ------- landscape (list): Output of one iteration of persim.to_landscape() Outputs: -------- Plots for each landscape in the list Returns: -------- None """ # ...
0583f3d8c25079720e586d297396d04ab39dc7f5
17,249
import google def get_access_token(): """Return access token for use in API request. Raises: requests.exceptions.ConnectionError. """ credentials, _ = google.auth.default(scopes=[ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform...
907aacd6d9976390b2896149179c84ea9bd3d0fc
17,250
from typing import List from typing import Dict def _singleInstrumentParametersToJson(instrument: InstrumentBase, get: bool = False, addPrefix: str = '', includeMeta: List[str] = [], ...
44b5b77f261a5774438aaeda25b7576d9b9b9274
17,251
def unknown_action(player: Player, table: dynamodb.Table) -> ActionResponse: """ Do nothing because the action could not be resolved. In the message list, returns a message saying the action was bad. :return: Original inputs matching updated inputs, and a message """ message = ["Action could no...
ea2a03d140eea2853b77da492ea0f403fc9c6ad9
17,252
def forecast_marginal_bindglm(mod, n, k, X=None, nsamps=1, mean_only=False): """ Marginal forecast function k steps ahead for a binomial DGLM """ # Plug in the correct F values F = update_F(mod, X, F=mod.F.copy()) # F = np.copy(mod.F) # if mod.nregn > 0: # F[mod.iregn] = X.reshape(mo...
dc8c82fc17465c4a22e7bc5d46cf9b5abd9abd54
17,253
def import_file(isamAppliance, id, filename, check_mode=False, force=False): """ Importing a file in the runtime template files directory. """ warnings = [] check_file = _check(isamAppliance, id) if check_file != None and force == False: warnings.append("File {0} exist.".format(id)) ...
3978e5476a7344ef4c92d2cec3852a57850380df
17,254
def get_func_from_attrdict(func_name : str, attrdict : AttrDict) -> ObjectiveFunction1D: """ Given a string func_name, attempts to find the corresponding entry from attrdict. :param func_name :param attrdict :returns Objective Function """ for key, val in attrdict.items(): if val.n...
bb4b03371d5fbb642864d7c9e77d4172fee92315
17,255
from fdk import runner import io def event_handle(handle_code): """ Performs HTTP request-response procedure :param handle_code: customer's code :type handle_code: fdk.customer_code.Function :return: None """ async def pure_handler(request): log.log("in pure_handler") heade...
03ca9cff4b7993e92c146565cb697a080d40c5ef
17,256
import torch def load_precomputed_embeddings(det_df, seq_info_dict, embeddings_dir, use_cuda): """ Given a sequence's detections, it loads from disk embeddings that have already been computed and stored for its detections Args: det_df: pd.DataFrame with detection coordinates seq_info_d...
685eb63ca23d634345304575a148e72a8172567e
17,257
def _model_gpt(size=0, dropout_rate=0.0, attention_dropout_rate=0.0): """Configs for a variety of Transformer model sizes.""" num_layers = [1, 3, 6, 12, 24, 36, 48][size] dim = [64, 128, 512, 768, 1024, 1280, 1600][size] num_heads = int(dim / 64) # Always dim 64 per head return _transformer( emb_dim=di...
7bc9eab929b8c48ca4b8ff671e9e0885c0d2bc44
17,258
def test_module(client, demisto_args: dict): """ Test the OMWS Client connection by attempting to query a common username """ d = client.query_profile_data("maneenus") if d: return 'ok' else: raise DemistoException("Incorrect or empty API response")
59e653c8fb5c40ee84a5945e5e4b0410418248ec
17,259
def as_string(raw_data): """Converts the given raw bytes to a string (removes NULL)""" return bytearray(raw_data[:-1])
6610291bb5b71ffc0be18b4505c95653bdac4c55
17,260
import seaborn import matplotlib def plot_series_statistics(observed=None, expected=None, total_stdev=None, explained_stdev=None, color_set='Set2', xscale="linear", ...
0e940011e2a00b41bf1303604ff13c6d8c152327
17,261
import math def generate_trapezoid_profile(max_v, time_to_max_v, dt, goal): """Creates a trapezoid profile with the given constraints. Returns: t_rec -- list of timestamps x_rec -- list of positions at each timestep v_rec -- list of velocities at each timestep a_rec -- list of accelerations a...
5851cfab06e20a9e79c3a321bad510d33639aaca
17,262
import logging def main(args): """ Main function of PyGalGen generator Parameters ---------- args : list of command line arguments: Returns ------- Error code """ logging.basicConfig(level=logging.DEBUG) parser = define_default_params() pipeline = PipelineExecutor(par...
4ee6dcfb0b2897b34e36966256e8b7990dbc2760
17,263
def query_pypi(spec_pk): """ Query one spec of package on PyPI""" spec = Spec.objects.get(pk=spec_pk) logger.debug('[PYPI] Fetching data for %s' % spec) pkg_data = PyPI().get_info(spec.name, spec.version) if not pkg_data: logger.debug('[PYPI] Errored %s ' % spec) spec.status = 'erro...
e306ac77792653a3c106d8094c00e06994329952
17,264
import logging def get_logger(name: str, format_str: str = aps_logger_format, date_format: str = aps_time_format, file: bool = False) -> logging.Logger: """ Get logger instance Args: name: logger name format_str|date_format: to configure logging...
06d673473c7014d6373003bf924fdf2dc9965baf
17,265
import torch def to_tensor(args, device=None): """Convert an arg or sequence of args to torch Tensors """ singleton = not isinstance(args, (list, tuple)) if singleton: args = [args] tensor_args = [] for arg in args: if isinstance(arg, torch.Tensor): tensor_args.app...
d85d842c095aa3c942f94e61c79d2bbeb49bc41d
17,266
def main(self): """ to run: kosmos 'j.data.bcdb.test(name="meta_test")' """ bcdb, _ = self._load_test_model() assert len(bcdb.get_all()) == 0 assert len(bcdb.meta._data["url"]) == 7 s = list(j.data.schema._url_to_md5.keys()) assert "despiegk.test" in s m = bcdb.model_get(u...
7f88d33bd6cc2df5284201d859718a8a06e6a4e4
17,267
def snake_head_only(): """ |===========| |···········| |···········| |···········| |···········| |···········| |···········| |·······o···| |···········| |···········| |···········| |···········| |===========| """ return Snake.from_dict( **{ ...
c08ffd0a86ec9d5a40d2649dd63a2b60019a6791
17,268
import six def str_to_bool(s): """Convert a string value to its corresponding boolean value.""" if isinstance(s, bool): return s elif not isinstance(s, six.string_types): raise TypeError('argument must be a string') true_values = ('true', 'on', '1') false_values = ('false', 'off',...
c228321872f253ce3e05c6af9284ec496dea8dcf
17,269
def id_feat_pred_mz_rt(cursor, mz, rt, ccs, tol_mz, tol_rt, tol_ccs, esi_mode, norm='l2'): """ id_feat_pred_mz_rt description: identifies a feature on the basis of predicted m/z and retention time parameters: cursor (sqlite3.Cursor) -- cursor for querying lipids.db mz (float) -- m/z ...
72818a631b155e1c50d53b26c1749bf8f68767f7
17,270
import os import re import sys def help(user_display_name, module_file_fullpath, module_name): """Generate help message for all actions can be used in the job""" my_path = os.path.dirname(module_file_fullpath) my_fname = os.path.basename(module_file_fullpath) my_package = module_name.rsplit(u'.')[-2]...
d76d0a2c07f7d60d1f9409281dc699d402fa1dd7
17,271
def Arrow_bg(self): """ The function that will create the background for the dropdown arrow button. For internal use only. This function is therefore also not imported by __init__.py """ #Just leave the making of the buttons background to the default function. Not gonna bother re-doing that here (be...
4b09c197666aa5ea15713d98ae7c38e1b0ffa0e0
17,272
def _is_debugging(ctx): """Returns `True` if the current compilation mode produces debug info. rules_apple specific implementation of rules_swift's `is_debugging`, which is not currently exported. See: https://github.com/bazelbuild/rules_swift/blob/44146fccd9e56fe1dc650a4e0f21420a503d301c/swift/intern...
f2468f394d4cb6ef545df06af5e78e0f4f1c1525
17,273
def get_bounds_5km_to_1km( itk_5km, isc_5km ) : """ return the 1km pixel indexes limits in the 5km pixel [ itk_5km, isc_5km ] footprint """ # set the (track,scan) indexes of the 5km pixel in the 5km grid itk_1km = itk_5km_to_1km ( itk_5km ) isc_1km = isc_5km_to_1km ( isc_5km ) # set the 1k...
7fd175787f075d7ed9b3e8ed04565f38877de1e4
17,274
import torch def batch_hard_triplet_loss(labels, embeddings, margin, squared=False): """Build the triplet loss over a batch of embeddings. For each anchor, we get the hardest positive and hardest negative to form a triplet. Args: labels: labels of the batch, of size (batch_size,) embedding...
37d20237580463e668cee77c96f732f2d0211aef
17,275
def categorical_sample_logits(logits): """ Samples (symbolically) from categorical distribution, where logits is a NxK matrix specifying N categorical distributions with K categories specifically, exp(logits) / sum( exp(logits), axis=1 ) is the probabilities of the different classes Cleverly ...
f93752b11de02b1b61f60b3ff5c12dd9c15f7d8f
17,276
def sort_results(boxes): """Returns the top n boxes based on score given DenseCap results.json output Parameters ---------- boxes : dictionary output from load_output_json n : integer number of boxes to return Returns ------- sorted dictionary """ r...
20f30e5846de4ce46073c3d32573d283576489e0
17,277
from datetime import datetime def get_date(d : str) -> datetime.datetime: """A helper function that takes a ModDB string representation of time and returns an equivalent datetime.datetime object. This can range from a datetime with the full year to second to just a year and a month. Parameters ...
44fb951ecb96102c631f88dc888aac11d11c8bad
17,278
def var_policer(*args): """Returns a variable policer object built from args.""" return VarPolicer(args)
a346e041118f1be2ed6b0acd2c9e3d04603031df
17,279
def winner(board): """ Returns the winner of the game, if there is one. """ #looking horizontal winner i = 0 while i < len(board): j = 1 while j <len(board): if board[i][j-1]==board[i][j] and board[i][j] == board[i][j+1]: return board[i][j] ...
31ab2cf04dfe269598efdd073762505643563a96
17,280
import signal def freqz_resp_list(b, a=np.array([1]), mode='dB', fs=1.0, n_pts=1024, fsize=(6, 4)): """ A method for displaying digital filter frequency response magnitude, phase, and group delay. A plot is produced using matplotlib freq_resp(self,mode = 'dB',Npts = 1024) A method for displaying...
207ad7ad59a3260df9d5df80c1b8e1bee4c33a3e
17,281
import socket def _nslookup(ipv4): """Lookup the hostname of an IPv4 address. Args: ipv4: IPv4 address Returns: hostname: Name of host """ # Initialize key variables hostname = None # Return result try: ip_results = socket.gethostbyaddr(ipv4) if len(...
7771887dbfcd60e73b8fce0ce4029fcd7058a7d1
17,282
def get_service_node(service): """ Returns the name of the node that is providing the given service, or empty string """ node = rosservice_get_service_node(service) if node == None: node = "" return node
7a8df548e119e8197f92340d228fdc7855494670
17,283
import warnings from io import StringIO def _download_nasdaq_symbols(timeout): """ @param timeout: the time to wait for the FTP connection """ try: ftp_session = FTP(_NASDAQ_FTP_SERVER, timeout=timeout) ftp_session.login() except all_errors as err: raise RemoteDataError('Er...
9b34571086ac3e738e29b3ed130ab2d0c7303657
17,284
def sessions(request): """ Cookies prepeocessor """ context = {} return context
562f4e9da57d3871ce780dc1a0661a34b3279ec5
17,285
import logging def dynamax_mnn(src: nb.typed.Dict, trg: nb.typed.Dict, src_emb: np.ndarray, trg_emb: np.ndarray, src_k: np.ndarray, trg_k: np.ndarray) -> np.ndarray: """ Run Dynamax-Jaccard in both directions and infer mutual neighbors. :param src nb.typed.Dict: src_id2poi...
174f603df09cbe7a8ee91de29de48ccaf2573b31
17,286
def resnet152(pretrained=False, progress=True, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet152', DistillerBott...
5e3435eea1a18c028d422abef57d9e88d88e609f
17,287
import torch def _load_model(featurizer_path): """Load the featurization model Parameters ---------- featurizer_path: str Path to the saved model file Returns ------- The loaded PyTorch model """ # load in saved model ...
21c29c9320b482bb33e82f97723d04bb53364ba1
17,288
def grid0_baseline(num_runs, render=True): """Run script for the grid0 baseline. Parameters ---------- num_runs : int number of rollouts the performance of the environment is evaluated over render : bool, optional specifies whether to use the gui during e...
8cb8a01309bb8ea3aae467d8a6c8a81ce295ab94
17,289
def read_aims(filename): """Method to read FHI-aims geometry files in phonopy context.""" lines = open(filename, 'r').readlines() cell = [] is_frac = [] positions = [] symbols = [] magmoms = [] for line in lines: fields = line.split() if not len(fields): con...
bcf5f00e57ed249c10667ad0b883986cb1b36865
17,290
def test(model, issue_batches): """ return accuracy on test set """ session = tf.get_default_session() num_correct = 0 num_predict = 0 for epoch, step, eigens, labels in issue_batches: feeds = { model['eigens']: eigens, } guess = session.run(model['gues...
0d8ae672766567a6665089c2d7d5004e25d80755
17,291
def evaluate_sample(ResNet50_model, X_train, Y_train, X_val_b,Y_val_b,X_data,Y_data,checkpoint_path): """ A function that accepts a labeled-unlabeled data split and trains the relevant model on the labeled data, returning the model and it's accuracy on the test set. """ # shuffle the training set: ...
c5f86feede372f078e9c88bac688c790de6578d6
17,292
import six import base64 def Base64WSEncode(s): """ Return Base64 web safe encoding of s. Suppress padding characters (=). Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type unicode to string type first. @param s: string to encode as Base64 @type s: string @retur...
cb28001bddec215b763936fde4652289cf6480c0
17,293
def onlyWikipediaURLS(urls): """Some example HTML page data is from wikipedia. This function converts relative wikipedia links to full wikipedia URLs""" wikiURLs = [url for url in urls if url.startswith('/wiki/')] return ["https://en.wikipedia.org"+url for url in wikiURLs]
df9ecbb73dfc9a764e4129069a4317517830307a
17,294
def get_image_filename_index(): """ Obtain a mapping of filename -> filepath for images :return: """ index_path = osp.join(SEG_ROOT, 'privacy_filters', 'cache', 'fname_index.pkl') if osp.exists(index_path): print 'Found cached index. Loading it...' return pickle.load(open(index_p...
002b6fd4dea1b00bb758377e71de0e67f5d979d3
17,295
def merge_coordinates(coordinates, capture_size): """Merge overlapping coordinates for MIP targets. Parameters ---------- coordinates: python dictionary Coordinates to be merged in the form {target-name: {chrom: chrx, begin: start-coordinate, end: end-coordinate}, ..} capture_size: ...
8af4a34fc8ce1a01ddcd4d4f257815ef5f852911
17,296
def Emojify_V2(input_shape, word_to_vec_map, word_to_index): """ Function creating the Emojify-v2 model's graph. Arguments: input_shape -- shape of the input, usually (max_len,) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation word_t...
111a0c97e9a8c75aa6a7191ee89cbda69a84794c
17,297
import fcntl import os def SetFdBlocking(fd, is_blocking): """Set a file descriptor blocking or nonblocking. Please note that this may affect more than expected, for example it may affect sys.stderr when called for sys.stdout. Returns: The old blocking value (True or False). """ if hasattr(fd, 'file...
58d1496152cc752b59e8abc0ae3b42387a2f8926
17,298
def de_parser(lines): """return a dict of {OfficalName: str, Synonyms: str, Fragment: bool, Contains: [itemdict,], Includes: [itemdict,]} from DE lines The DE (DEscription) lines contain general descriptive information about the sequence stored. This information is generally sufficient to identify ...
d22158e365c52976ed638c27a0a85d8a047d743d
17,299