content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def triplet_margin_loss( anchor, positive, negative, margin=0.1, p=2, use_cosine=False, swap=False, eps=1e-6, scope='', reduction=tf.losses.Reduction.SUM ): """ Computes the triplet margin loss Args: anchor: The tensor containing the anchor embeddings ...
55e85a9ae98ab57458ae1a61a1dbd445deddd7cb
13,900
def f_raw(x, a, b): """ The raw function call, performs no checks on valid parameters.. :return: """ return a * x + b
89bbe9e7a08e3bf4bf37c3efa695ed20fdca95c5
13,901
from pyapprox.cython.barycentric_interpolation import \ def compute_barycentric_weights_1d(samples, interval_length=None, return_sequence=False, normalize_weights=False): """ Return barycentric weights for a sequence of samples. e.g. of seq...
1711328af31b756c040455e0b03363def08e6504
13,902
import collections def _generate_conversions(): """ Generate conversions for unit systems. """ # conversions to inches to_inch = {'microinches': 1.0 / 1000.0, 'mils': 1.0 / 1000.0, 'inches': 1.00, 'feet': 12.0, 'yards': 36.0, ...
8fa4f625e693fe352b2bba0082d0b18c46f5bec1
13,903
def _ifail(repo, mynode, orig, fcd, fco, fca, toolconf): """ Rather than attempting to merge files that were modified on both branches, it marks them as unresolved. The resolve command must be used to resolve these conflicts.""" return 1
278bb52f96e1a82ce9966626be08bc6fdd0df65d
13,904
from typing import Pattern from typing import Optional from typing import Callable from typing import Union import logging def parser( text: str, *, field: str, pattern: Pattern[str], type_converter: Optional[Callable] = None, clean_up: Optional[Callable] = None, limit_size: Optional[int] ...
0b44fecf252399b3109efedffe0f561809982ea6
13,905
import os def checkpoint_metrics_path(checkpoint_path, eval_name, file_name=None): """Gets a path to the JSON of eval metrics for checkpoint in eval_name.""" checkpoint_dir = os.path.dirname(checkpoint_path) checkpoint_name = os.path.basename(checkpoint_path) if eval_name: # This bit of magic is defined b...
e176b873d13ae28f6a53100adba6ca437c4ce805
13,906
def colorize(text='', opts=(), **kwargs): """ Return your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Return the RESET code if no parameters are given. Valid colors: 'black', 'red', 'green', 'yellow', ...
02ad24710413770cebdaa4265a1d40c69212ecc8
13,907
from re import T def get_prediction(img_path, threshold): """ get_prediction parameters: - img_path - path of the input image - threshold - threshold value for prediction score method: - Image is obtained from the image path - the image is converted to image tensor ...
d6df91fb464b072b06ef759ad53aa00fb7d624ec
13,908
def make_fixed_size(protein, shape_schema, msa_cluster_size, extra_msa_size, num_res, num_templates=0): """Guess at the MSA and sequence dimensions to make fixed size.""" pad_size_map = { NUM_RES: num_res, NUM_MSA_SEQ: msa_cluster_size, NUM_EXTRA_SEQ: extra_msa_size,...
f74306815dd7cd5291305c7b5c67cae4625c4d38
13,909
def plot_skymap_tract(skyMap, tract=0, title=None, ax=None): """ Plot a tract from a skyMap. Parameters ---------- skyMap: lsst.skyMap.SkyMap The SkyMap object containing the tract and patch information. tract: int [0] The tract id of the desired tract to plot. title: st...
a8f1b25d8afedfbb0ed643b7954e615932031419
13,910
import json def label(vertex): """ Graph vertex label in dot format """ label = f"{vertex.name} {vertex.state or ''}\n{vertex.traceback or ''}" label = json.dumps(label).replace("\\n", r"\l") return f"[label={label}]"
a8604cfd837afbdba8b8ee7666d81df4b015ad2a
13,911
import six import hashlib def compute_hashes_from_fileobj(fileobj, chunk_size=1024 * 1024): """Compute the linear and tree hash from a fileobj. This function will compute the linear/tree hash of a fileobj in a single pass through the fileobj. :param fileobj: A file like object. :param chunk_siz...
8c6aed21ae59ecb3e5449ee0856be1d032108aa6
13,912
def imshow(axim, img, amp_range=None, extent=None,\ interpolation='nearest', aspect='auto', origin='upper',\ orientation='horizontal', cmap='jet') : """ extent - list of four image physical limits for labeling, cmap: 'gray_r' #axim.cla() """ imsh = axim.imshow(img, interpol...
3483690b01c5d182877c3bf944fa5409d4cb9e69
13,913
def get_total(): """ Return the rounded total as properly rounded string. Credits: https://github.com/dbrgn/coverage-badge """ cov = coverage.Coverage() cov.load() total = cov.report(file=Devnull()) class Precision(coverage.results.Numbers): """ A class for usin...
9df511f0d895721061642c2fb88268490e27cc0b
13,914
def _infer_subscript_list(context, index): """ Handles slices in subscript nodes. """ if index == ':': # Like array[:] return ValueSet([iterable.Slice(context, None, None, None)]) elif index.type == 'subscript' and not index.children[0] == '.': # subscript basically implies ...
bde1de5e7604d51e6c85e429ceb2102d79e91ca6
13,915
def count_by_guess(dictionary, correctly=False): """ Count the number of correctly/incorrectly guessed images for a dataset :param dictionary: :param correctly: :return: """ guessed = 0 for response in dictionary: guessed = guessed + count_by_guess_user(response, correctly) ...
d1328a63d3029707131f1932be1535dabb62ab66
13,916
def get_game_by_index(statscursor, table, index): """ Holds get_game_by_index db related data """ query = "SELECT * FROM " + table + " WHERE num=:num" statscursor.execute(query, {'num': index}) return statscursor.fetchone()
754a83f2281ad095ffc32eb8a03c95490bd5f815
13,917
def create_queue(): """Creates the SQS queue and returns the queue url and metadata""" conn = boto3.client('sqs', region_name=CONFIG['region']) queue_metadata = conn.create_queue(QueueName=QUEUE_NAME, Attributes={'VisibilityTimeout':'3600'}) if 'queue_tags' in CONFIG: conn.tag_queue(QueueUrl=qu...
ae61c542182bc1238b76bf94991e50809bace595
13,918
def db_describe(table, **args): """Return the list of columns for a database table (interface to `db.describe -c`). Example: >>> run_command('g.copy', vector='firestations,myfirestations') 0 >>> db_describe('myfirestations') # doctest: +ELLIPSIS {'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ...
6265a2f6dcc26fcd1fcebb5ead23abfb37cfa179
13,919
def objective_func(x, cs_objects, cs_data): """ Define the objective function :param x: 1D array containing the voltages to be set :param args: tuple containing all extra parameters needed :return: average count rate for 100 shots """ x = np.around(x,2) try: flag_range = 0 ...
677b6455b0db177a3a4f716ced3dd309c711cf74
13,920
def getHPELTraceLogAttribute(nodename, servername, attributename): """ This function returns an attribute of the HPEL Trace Log for the specified server. Function parameters: nodename - the name of the node on which the server to be configured resides. servername - the name of the server w...
8003066ec41ee07dab311690d0687d7f79e6952a
13,921
def dispersionTable(adata): """ Parameters ---------- adata Returns ------- """ if adata.uns["ispFitInfo"]["blind"] is None: raise ("Error: no dispersion model found. Please call estimateDispersions() before calling this function") disp_df = pd.DataFrame({"gene_id": adata...
7f7b4c122ffc42402248ec55155c774c77fbad51
13,922
def L10_indicator(row): """ Determine the Indicator of L10 as one of five indicators """ if row < 40: return "Excellent" elif row < 50: return "Good" elif row < 61: return "Fair" elif row <= 85: return "Poor" else: return "Hazard"
10656a76e72f99f542fd3a4bc2481f0ef7041fa9
13,923
def create_ip_record( heartbeat_df: pd.DataFrame, az_net_df: pd.DataFrame = None ) -> IpAddress: """ Generate ip_entity record for provided IP value. Parameters ---------- heartbeat_df : pd.DataFrame A dataframe of heartbeat data for the host az_net_df : pd.DataFrame Option ...
63deb15081f933b0a445d22eed25646782af4221
13,924
import re def extract_version(version_file_name): """Extracts the version from a python file. The statement setting the __version__ variable must not be indented. Comments after that statement are allowed. """ regex = re.compile(r"^__version__\s*=\s*['\"]([^'\"]*)['\"]\s*(#.*)?$") with open(v...
1cc70ba4bf69656bb8d210a49c236e38eba59513
13,925
def powerlaw_loglike(data, theta): """Return the natural logarithm of the likelihood P(data | theta) for our model of the ice flow. data is expected to be a tuple of numpy arrays = (x, y, sigma) theta is expected to be an array of parameters = (intercept, slope) """ x, y, sigma = data n = ...
98650e66d2a16762b2534be9083b6b92e0d9e9fd
13,926
def get_conv(dim=3): """Chooses an implementation for a convolution layer.""" if dim == 3: return nn.Conv3d elif dim == 2: return nn.Conv2d else: raise ValueError('dim has to be 2 or 3')
4152984ecf7220dc4693013ee567822a2487e225
13,927
import os import errno def resolve_path(path, parent=None): """Resolves the absolute path of the specified file. Args: path (str): Path to resolve. parent (str): The directory containing ``path`` if ``path`` is relative. Returns: The absolute path. Raises: ...
c8088bc2dcee62b0ed12e8b0902a35e2e291313c
13,928
import ipykernel from notebook.notebookapp import list_running_servers import re import requests def notebook_metadata(): """Attempts to query jupyter for the path and name of the notebook file""" error_message = "Failed to query for notebook name, you can set it manually with the WANDB_NOTEBOOK_NAME environm...
47cd98371605240ae52ca90fda23c46b9bde52d0
13,929
async def create_mute_role(bot, ctx): """Create the mute role for a guild""" perms = discord.Permissions( send_messages=False, read_messages=True) mute_role = await ctx.guild.create_role( name='Muted', permissions=perms, reason='Could not find a muted role in the process of muting or...
9128de3a7f4f841e47531699a878a1c18d8be9d5
13,930
import json import uuid def build_request_data(useralias, req_node): """build_request_data :param useralias: user alias for directory name :param req_node: simulated request node """ if "file" not in req_node: return None use_uniques = req_node["unique_names"]...
938c79c290e1e4c086e6d48f71cbd0b965d36b36
13,931
def _get_stmt_lists(self): """ Returns a tuple of the statement lists contained in this `ast.stmt` node. This method should only be called by an `ast.stmt` node. """ if self.is_simple(): return () elif self.is_body(): return (self.body,) elif self.is_body_orelse(): r...
0ec85481bc4261ae77ced0ae32c72081ef80c651
13,932
def get_article(name): """a general function to get an article, returns None if doesn't exist """ article = None if name is not None: try: article = Article.objects.get(name=name) except Article.DoesNotExist: pass return article
d69e801a1d18ccf81753cc35ce2afa645b304fba
13,933
import tempfile import os import shutil def _CreateNginxConfigMapDir(): """Returns a TemporaryDirectory containing files in the Nginx ConfigMap.""" if FLAGS.nginx_conf: nginx_conf_filename = FLAGS.nginx_conf else: nginx_conf_filename = ( data.ResourcePath('container/kubernetes_nginx/http.conf'))...
9f9cde4e270e60ae03e65af61017ead886e89d18
13,934
def abbreviateLab(lab): """Lab names are very long and sometimes differ by punctuation or typos. Abbreviate for easier comparison.""" labAbbrev = apostropheSRe.sub('', lab) labAbbrev = firstLetterRe.sub(r'\1', labAbbrev, count=0) labAbbrev = spacePunctRe.sub('', labAbbrev, count=0) return labAbbrev
dce4a1d0f6302a2968fe701d067b209fb61b8930
13,935
def backproject(depth, intrinsics, instance_mask): """ Back-projection, use opencv camera coordinate frame. """ cam_fx = intrinsics[0, 0] cam_fy = intrinsics[1, 1] cam_cx = intrinsics[0, 2] cam_cy = intrinsics[1, 2] non_zero_mask = (depth > 0) final_instance_mask = np.logical_and(insta...
9828197b646342ec76cc21b1083540d0fe62978f
13,936
def if_any( _data, *args, _names=None, _context=None, **kwargs, ): """Apply the same predicate function to a selection of columns and combine the results True if any element is True. See Also: [`across()`](datar.dplyr.across.across) """ if not args: args = (None,...
41bf4a14cc8b16845f7d0dd8138871a7ccfad66f
13,937
def get_inpgen_para_from_xml(inpxmlfile, inpgen_ready=True): """ This routine returns an python dictionary produced from the inp.xml file, which can be used as a calc_parameters node by inpgen. Be aware that inpgen does not take all information that is contained in an inp.xml file :param inpxmlfile...
e0454061da7c817b4dfe3f1eb0257493dc92437b
13,938
import os def confirm_revocation(cert): """Confirm revocation screen. :param cert: certificate object :type cert: :class: :returns: True if user would like to revoke, False otherwise :rtype: bool """ return util(interfaces.IDisplay).yesno( "Are you sure you would like to revoke ...
d64c64a6426e521fa8d9edc817b44a50fdd75894
13,939
def Gaussian(y, model, yerr): """Returns the loglikelihood for a Gaussian distribution. In this calculation, it is assumed that the parameters are true, and the loglikelihood that the data is drawn from the distribution established by the parameters is calculated Parameters ---------- model...
d9eaa41b95006a9d17907582b804a4921f672141
13,940
def clean_us_demographics(us_demographics_spark, spark_session): """ Clean data from us_demographics Args: us_demographics (object): Pyspark dataframe object spark_session (object): Pyspark session Returns: (object): Pyspark dataframe with cleaned data """ s...
dcf812bf64a2f6c3b908d895488e1a57e1729301
13,941
from datetime import datetime def parse_date(date=None): """ Parse a string in YYYY-MM-DD format into a datetime.date object. Throws ValueError if input is invalid :param date: string in YYYY-MM-DD format giving a date :return: a datetime.date object corresponding to the date given """ if...
a4c6cef85dabd445dd308fdd5f2c20a38accd6de
13,942
def status(): """ Incoming status handler: forwarded by ForwardServerProvider """ req = jsonex_loads(request.get_data()) status = g.provider._receive_status(req['status']) return {'status': status}
3a50ff8d829a7bf37b84871897335345496dbc49
13,943
def get_feature_extractor_info(): """Return tuple of pretrained feature extractor and its best-input image size for the extractor""" return get_pretrained_feature_extractor(), K_MODEL_IMAGE_SIZE
bdec6d5a2d402f659b9a001f4082f6b5e33ca3cc
13,944
import networkx def nx_find_connected_limited(graph, start_set, end_set, max_depth=3): """Return the neurons in end_set reachable from start_set with limited depth.""" reverse_graph = graph.reverse() reachable = [] for e in end_set: preorder_nodes = list( ( network...
4322f4231be73b575d05442f09608c71c3b9f605
13,945
def hexbyte_2integer_normalizer(first_int_byte, second_int_btye): """Function to normalize integer bytes to a single byte Transform two integer bytes to their hex byte values and normalize their values to a single integer Parameters __________ first_int_byte, second_int_byte : int inte...
a3bbe75014b6e08607314b615440039bab245f04
13,946
def wrapAngle(angle): """ Ensures angle is between -360 and 360 arguments: angle - float angle that you want to be between -360 and 360 returns: float - angle between -360 and 360 """ printDebug("In wrapAngle, angle is " + str(angle), DEBUG_INFO) if angle >...
4ec1ee51b895075053468dfa5d09f988d15413d1
13,947
import os def _save_first_checkpoint(keras_model, custom_objects, config): """Save first checkpoint for the keras Estimator. Args: keras_model: an instance of compiled keras model. custom_objects: Dictionary for custom objects. config: Estimator config. Returns: The path where keras model chec...
790cc96785c6a2a66d19af886c82e0dc354704c9
13,948
import logging import os def build_reference_spectrum_list_from_config_file(config): """ Read reference spectrum file glob(s) from configuration file to create and return a list of ReferenceSpectrum instances. :param config: configparser instance :return: list of ReferenceSpectrum instances "...
31d4f54e786846122845b7eb6d73dfa1353ef7d6
13,949
def make_window(signal, sample_spacing, which=None, alpha=4): """Generate a window function to be used in PSD analysis. Parameters ---------- signal : `numpy.ndarray` signal or phase data sample_spacing : `float` spacing of samples in the input data which : `str,` {'welch', 'han...
5ef18c990225b6610ee10c848ab4ee0b2ce0fc9b
13,950
from typing import Dict from typing import Union def set_units( df: pd.DataFrame, units: Dict[str, Union[pint.Unit, str]] ) -> pd.DataFrame: """Make dataframe unit-aware. If dataframe is already unit-aware, convert to specified units. If not, assume values are in specified unit. Parameters ------...
8a0cf821e3e0d1ba7b1b8c3dbdddb5f517ea0acb
13,951
def address_repr(buf, reverse: bool = True, delimit: str = "") -> str: """Convert a buffer into a hexlified string.""" order = range(len(buf) - 1, -1, -1) if reverse else range(len(buf)) return delimit.join(["%02X" % buf[byte] for byte in order])
6b4b8921d6280cd688c3bfcfca82b2b5546001e7
13,952
import re def _highlight(line1, line2): """Returns the sections that should be bolded in the given lines. Returns: two tuples. Each tuple indicates the start and end of the section of the line that should be bolded for line1 and line2 respectively. """ start1 = start2 = 0 match = re.search(r'\S', ...
d9bf7667e24d21e6f91b656af0697765c2b74f55
13,953
import subprocess def get_comrec_build(pkg_dir, build_cmd=build_py): """ Return extended build command class for recording commit The extended command tries to run git to find the current commit, getting the empty string if it fails. It then writes the commit hash into a file in the `pkg_dir` path, ...
f704fecc1c0001c3feeb66ccc4e251c019694c1b
13,954
def get_detected_objects_new(df, siglim=5, Terr_lim=3, Toffset=2000): """ Get a dataframe with only the detected objects. :param df: A DataFrame such as one output by get_ccf_summary with N > 1 :param siglim: The minimum significance to count as detected :param Terr_lim: The maximum number of standa...
7662086053c093b9eb19ffe7c56f5cf7914b1ab8
13,955
def cmp(a, b): """ Python 3 does not have a cmp function, this will do the cmp. :param a: first object to check :param b: second object to check :return: """ # convert to lower case for string comparison. if a is None: return -1 if type(a) is str and type(b) is str: a...
c82837a0d8887f55fdd1175b5d828742529b3e37
13,956
def pe(cmd, shell=True): """ Print and execute command on system """ ret = [] for line in execute(cmd, shell=shell): ret.append(line) print(line, end="") return ret
0a238be68a7c383153834d45fbf3193f9b8c9a72
13,957
import os def create_photo(user_id, text: str, greencolor: bool): # color: tuple(R,G,B) """ :param user_id: int or str :param text: str :param greencolor: bool True = зеленый (204, 255, 204) False = серый (240, 238, 237) """ color = (204, 255, 204) if n...
c06c15f450d614febfc52d3f274e80b6d79d6688
13,958
def crop(image): """ Method to crop out the uncessary white parts of the image. Inputs: image (numpy array): Numpy array of the image label. Outputs: image (numpy array): Numpy array of the image label, cropped. """ image = ImageOps.invert(image) imageBox = image.getbbox() imag...
37a12733bcda66a9da16d72ff3fae749784481a0
13,959
def all_pairs_normalized_distances(X): """ We can't really compute distances over incomplete data since rows are missing different numbers of entries. The next best thing is the mean squared difference between two vectors (a normalized distance), which gets computed only over the columns that tw...
c744c6ac87cbd3760d6512178747ac60794d616a
13,960
import torch def forward_pass(model, target_angle, mixed_data, conditioning_label, args): """ Runs the network on the mixed_data with the candidate region given by voice """ target_pos = np.array([ FAR_FIELD_RADIUS * np.cos(target_angle), FAR_FIELD_RADIUS * np.sin(target_angle) ...
e9644b01ea04b08ae92d50d3c7944e0d72213b2b
13,961
import select from typing import Optional from datetime import datetime import pytz async def get_event_by_code(code: str, db: AsyncSession) -> Event: """ Get an event by its code """ statement = select(Event).where(Event.code == code) result = await db.execute(statement) event: Optional[Event...
592cd6b5aad7b12a98889bf82ea7e32a55b8832e
13,962
def get(name): """Returns an OpDef for a given `name` or None if the lookup fails.""" with _sync_lock: return _registered_ops.get(name)
75e3ba3601f1ad8f67e77046a9b286bee8e60be6
13,963
def angle_detect_dnn(img, adjust=True): """ 文字方向检测 """ h, w = img.shape[:2] ROTATE = [0, 90, 180, 270] if adjust: thesh = 0.05 xmin, ymin, xmax, ymax = int(thesh * w), int(thesh * h), w - int(thesh * w), h - int(thesh * h) img = img[ymin:ymax, xmin:xmax] ##剪切图片边缘 in...
a3fc8513afce26e96a315a606acfd9be9feaa376
13,964
def get_correct_line(df_decisions): """ The passed df has repeated lines for the same file (same chemin_source). We take the most recent one. :param df_decisions: Dataframe of decisions :return: Dataframe without repeated lines (according to the chemin_source column) """ return df_decisions....
989f1aba1c5e0c61f8b7ca1c883baf4dd181ebbc
13,965
def fix_1(lst1, lst2): """ Divide all of the elements in `lst1` by each element in `lst2` and return the values in a list. >>> fix_1([1, 2, 3], [0, 1]) [1.0, 2.0, 3.0] >>> fix_1([], []) [] >>> fix_1([10, 20, 30], [0, 10, 10, 0]) [1.0, 2.0, 3.0, 1.0, 2.0, 3.0] """ out = [] ...
7929cfc19952a829c66c18af967668d1015f8477
13,966
def user_wants_upload(): """ Determines whether or not the user wants to upload the extension :return: boolean """ choice = input("Do you want to upload your extension right now? :") if "y" in choice or "Y" in choice: return True else: return False
67643d1ccf8d1ffe23ddc503cd8e9f4dc4e98707
13,967
def has_genus_flag(df, genus_col="mhm_Genus", bit_col="mhm_HasGenus", inplace=False): """ Creates a bit flag: `mhm_HasGenus` where 1 denotes a recorded Genus and 0 denotes the contrary. Parameters ---------- df : pd.DataFrame A mosquito habitat mapper DataFrame genus_col : str, default=...
7e178f7570f8de436521047e012518e6f5ee6a72
13,968
from typing import Tuple def compass( size: Tuple[float, float] = (4.0, 2.0), layer: Layer = gf.LAYER.WG, port_type: str = "electrical", ) -> Component: """Rectangular contact pad with centered ports on rectangle edges (north, south, east, and west) Args: size: rectangle size ...
fefa0842958fb91b870eb78e2170a81d7c8daaa9
13,969
def get_service(vm, port): """Return the service for a given port.""" for service in vm.get('suppliedServices', []): if service['portRange'] == port: return service
d617771c25c69ee874b0bc64adcc735aa876f929
13,970
async def async_setup_entry(hass, config_entry): """Set up AirVisual as config entry.""" entry_updates = {} if not config_entry.unique_id: # If the config entry doesn't already have a unique ID, set one: entry_updates["unique_id"] = config_entry.data[CONF_API_KEY] if not config_entry.opt...
e09b0c8e499a055123a88503cac4d1d1492a3d53
13,971
def rotation_point_cloud(pc): """ Randomly rotate the point clouds to augment the dataset rotation is per shape based along up direction :param pc: B X N X 3 array, original batch of point clouds :return: BxNx3 array, rotated batch of point clouds """ # rotated_data = np.zeros(pc.shape, dtyp...
f1f84b9dad06bea6c377559d8b4a64be88031847
13,972
import time def alliance_system_oneday(mongohandle, alliance_id, system): """find by corp and system - one day""" allkills = mongohandle.allkills system = int(system) timeframe = 24 * 60 * 60 gmtminus = time.mktime(time.gmtime()) - timeframe cursor = allkills.find({"alliance_id": alliance_id, ...
b951f11f606352dc6614e1ff1c587c3a64ed1ea8
13,973
def slit_select(ra, dec, length, width, center_ra=0, center_dec=0, angle=0): """ :param ra: angular coordinate of photon/ray :param dec: angular coordinate of photon/ray :param length: length of slit :param width: width of slit :param center_ra: center of slit :param center_dec: center of s...
a3047a59bbc8566d261f1d52f92b437ad2b26d52
13,974
def login(): """ Logs in user """ req = flask.request.get_json(force=True) username = req.get('username', None) password = req.get('password', None) user = guard.authenticate(username, password) ret = {'access_token': guard.encode_jwt_token(user)} return ret, 200
b577c7982bf65d3a24cfd3f116f5cb128079cd1f
13,975
def statuses_filter(auth, **params): """ Collect tweets from the twitter statuses_filter api. """ endpoint = "https://stream.twitter.com/1.1/statuses/filter.json" if "follow" in params and isinstance(params["follow"], (list, tuple)): params["follow"] = list_to_csv(params["follow"]) if ...
e81f85d5c747a4bcca8fc9b3b82d362905404452
13,976
def adjust_hue(image, hue_factor): """Adjusts hue of an image. The image hue is adjusted by converting the image to HSV and cyclically shifting the intensities in the hue channel (H). The image is then converted back to original image mode. `hue_factor` is the amount of shift in H channel and must...
52390b83a60cc8f23632f198a558b518d687f94e
13,977
import json import requests import time def lambda_handler(event, context): """Sample pure Lambda function Parameters ---------- event: dict, required API Gateway Lambda Proxy Input Format Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-int...
05b5da6e2c2aff16c43a3822978f0cd800370bed
13,978
def compareDict(a, b): """ Compare two definitions removing the unique Ids from the entities """ ignore = ['Id'] _a = [hashDict(dict(x), ignore) for x in a] _b = [hashDict(dict(y), ignore) for y in b] _a.sort() _b.sort() return _a == _b
19f0340064c95584a4e80ecb4a090c25944f6923
13,979
import traceback import time def create_twitter_auth(cf_t): """Function to create a twitter object Args: cf_t is configuration dictionary. Returns: Twitter object. """ # When using twitter stream you must authorize. # these tokens are necessary for user authe...
0eff78ce2dba182d739cc2bb082d5053a6a8847a
13,980
def _project(doc, projection): """Return new doc with items filtered according to projection.""" def _include_key(key, projection): for k, v in projection.items(): if key == k: if v == 0: return False elif v == 1: return...
0f2cd190e73b39ceeec0f850054baab1dd357587
13,981
import random def random_swap(words, n): """ Randomly swap two words in the sentence n times Args: words ([type]): [description] n ([type]): [description] Returns: [type]: [description] """ def swap_word(new_words): random_idx_1 = random.randint(0, l...
d6916404c363176f13010d006cd61354dcd4e16e
13,982
def get_dist_for_angles(dict_of_arrays, clusters, roll, pitch, yaw, metric='3d', kind='max'): """ Calculate a single distance metric for a combination of angles """ if (dict_of_arrays['yaw_corr'] == 0).all(): rot_by_boresight = apply_boresight_same(dict_of_arrays, roll, pitch, yaw) else:...
4db8a68cebc845de942817eb9eb28e57d2db5cc4
13,983
import asyncio async def stream(): """Main streaming loop for PHD""" while True: if phd_client.is_connected and manager.active_connections: response = await phd_client.get_responses() if response is not None: # Add to the websocket queue # If it ...
19e1934e8cb48fa66f8ab3f61ca013fd19b040fc
13,984
def filter_camera_angle(places, angle=1.): """Filter pointclound by camera angle""" bool_in = np.logical_and((places[:, 1] * angle < places[:, 0]), (-places[:, 1] * angle < places[:, 0])) return places[bool_in]
9956c5b001989c5f64d935087a1e13ffbc6469b7
13,985
def load_nifti(path: str) \ -> tuple[np.ndarray, np.ndarray, nib.nifti1.Nifti1Header]: """ This function loads a nifti image using the nibabel library. """ # Extract image img = nib.load(path) img_aff = img.affine img_hdr = img.header # Extract the actual data in a numpy arra...
9e76e3f6e6d200b3cd3be34b3780f8fe84cad53e
13,986
def f5_list_policy_hostnames_command(client: Client, policy_md5: str) -> CommandResults: """ Get a list of all policy hostnames. Args: client (Client): f5 client. policy_md5 (str): MD5 hash of the policy. """ result = client.list_policy_hostnames(policy_md5) table_name = 'f5 da...
38263c85480ba5d7de8a21509820052444b4cdab
13,987
def predict(m, count, s, A): """predict the chain after s calculate the probability of a m-length chain, then return chains. CAUTION the number of chains maybe less then count args: m: the length of predict chain count: the number of predict chain s: the last element of the...
f45acc67c97204efdabb48f29d73277fb4b75967
13,988
import mimetypes import gzip import os def read_lengths_from_fastx_file(fastx_file): """ @param fastx_file: file path @type fastx_file: str @rtype: dict[str, int] """ file_type = mimetypes.guess_type(fastx_file)[1] if file_type == 'gzip': f = gzip.open(fastx_file, "rt") elif n...
6aef86176269674a96a707bc5f7cbb9798237f57
13,989
def f_multidim(anchors, basis, distance_measurements, coeffs): """ :param anchors: anchors dim x N :param basis: basis vectors K x M :param distance_measurements: matrix of squared distances M x N :param coeffs: coefficient matrix dim x K :return: vector of differences between estimate distanc...
cd9f7fa67e6cbf3cfb5fe14e53b019713c56aa26
13,990
def getHomography(indict, outdict, outsize=None): """Returns a transformation to go from input pts to output pts using a homography. 'indict' and 'outdict' should contain identical keys mapping to 2-tuples. We create A: x1 y1 1 0 0 0 -x1*x1' -y1*x1' 0 0 0 x1 y1 1 -x1*y1' -y1*y1' ...
709fad7ffba7047e8d2c15e79611c3ac897733b7
13,991
def variables_to_restore(scope=None, strip_scope=False): """Returns a list of variables to restore for the specified list of methods. It is supposed that variable name starts with the method's scope (a prefix returned by _method_scope function). Args: methods_names: a list of names of configurable methods...
bc1f433b6a67898d8c010a56c6c51821f50df81a
13,992
def from_strings(data, gaps="-", length=None, dtype=np.int8): """Convert a series of strings to an array of integer encoded alleles. Parameters ---------- data : array_like, str Sequence of strings of alleles. gaps : str, optional String of symbols to be interpreted as gaps in the s...
7405e208613aa75b132f686fcf5fe7451a4160cc
13,993
def get_relationship_targets(item_ids, relationships, id2rec): """Get item ID set of item IDs in a relationship target set""" # Requirements to use this function: # 1) item Terms must have been loaded with 'relationships' # 2) item IDs in 'item_ids' arguement must be present in id2rec # ...
55542448af0eb2b46442bff0e0464361b669241a
13,994
def cli(ctx, newick, analysis_id, name="", xref_db="null", xref_accession="", match_on_name=False, prefix=""): """Load a phylogenetic tree (Newick format) into Chado db Output: Number of inserted trees """ return ctx.gi.phylogeny.load_tree(newick, analysis_id, name=name, xref_db=xref_db, xref_accessio...
9b68dec5584a692f2fe04746d9bb179c9e002682
13,995
def roll_neighbors(sites, site, dims=None, radius=1): """ N-dimensional pixel neighborhood for periodic images on regular grids """ index = np.unravel_index(site, dims=dims) neighs = sites.take(nbr_range+index, axis=0, mode='wrap') return neighs.flatten()
e653604c07f4824ef766c3a7f41a6c6c8a35bad0
13,996
import os def extract_node_name(path, ignore_missing_nodes=False): """extracts the token after the 'nodes'""" tokens = path.split(os.sep) last_nodes_index = -1 for i, token in enumerate(tokens): if token == "nodes": last_nodes_index = i if last_nodes_index == -1: if ign...
0d81e46ef2812e5b087fdef5264ad20a3f3bef2d
13,997
import scipy import os import tqdm def run_model(model, raw_cohort, delta_encoder): """ Run the given model using the given cohort and experimental settings contained in args. This function: (1) balanced the dataset (2) splits the cohort intro training:development:testing sets at the patient-leve...
94aec871db5b4e57014444d57fb1ef6844f516a1
13,998
import requests import json def folder0_content(folder0_id, host, token): """ Modules ------- request, json ---------- Parameters ---------- folder0_id : Onedata folder level 0 id containing the data to publish. host : OneData provider (e.g., ceta-ciemat-02.datahub.egi.eu). tok...
8ce6ae617666f936643b9599ae115e140b30bd2b
13,999