content
stringlengths
22
815k
id
int64
0
4.91M
def py_cpu_nms(dets, thresh): """Pure Python NMS baseline.""" x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) ## index for dets order = scores.argsort()[::-1] keep = [] while order.size > 0: i...
36,200
def photo_handler(message): """ Handler for a photo content type. """ process_photo(message)
36,201
def _list_news(): """List the content of type ``content_type``.""" folder = os.path.join(PATH, g.project_name, "news") if not os.path.isdir(folder): raise NotFound filenames = {} for user in os.listdir(folder): news = os.listdir(os.path.join(folder, user)) for filename in new...
36,202
def _split_iterators(iterator, n=None): """Split itererator of tuples into multiple iterators. :param iterator: Iterator to be split. :param n: Amount of iterators it will be split in. toolz.peak can be used to determine this value, but that is not lazy. This is basically the same as x, y, z = zip(*a)...
36,203
def get_league_listing(**kwargs): """ Get a list of leagues """ return make_request("GetLeaguelisting", **kwargs)
36,204
async def perhaps_this_is_it( disc_channel: disnake.TextChannel = commands.Param(lambda i: i.channel), large: int = commands.Param(0, large=True), ) -> PerhapsThis: """This description should not be shown Parameters ---------- disc_channel: A channel which should default to the current one - us...
36,205
def enable() -> None: """ Enable automatic garbage collection. """ ...
36,206
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv parser = E.ArgumentParser(description=__doc__) parser.add_argument("--version", action='version', version="1.0") parser.add_argument("-b", "...
36,207
def maybe_setup_moe_params(model_p: InstantiableParams): """Convert a FeedforwardLayer to a MoE Layer for StackedTransformer.""" if model_p.cls == layers.StackedTransformerRepeated: model_p = model_p.block if model_p.num_experts == 0: return model_p ff_p = model_p.transformer_layer_params_tpl.tr_fflay...
36,208
def verify_message( message ): """Verifies that a message is valid. i.e. it's similar to: 'daily-0400/20140207041736'""" r = re.compile( "^[a-z]+(-[0-9])?-([a-z]{3})?[0-9]+/[0-9]+" ) return r.match( message )
36,209
def get_all_unicode_chars(): """Get all unicode characters.""" all_unicode_chars = [] i = 0 while True: try: all_unicode_chars.append(chr(i)) except ValueError: break i += 1 return all_unicode_chars
36,210
def displayString(q=1,d=1,ex=1,k=1,r=1,v="string"): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/displayString.html ----------------------------------------- displayString is NOT undoable, queryable, and NOT editable. Assign a string value to a string identifier. Allows you def...
36,211
def get_east_asian_width_property(value, binary=False): """Get `EAST ASIAN WIDTH` property.""" obj = unidata.ascii_east_asian_width if binary else unidata.unicode_east_asian_width if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['eastasianwidth'].get(negate...
36,212
def ModifyListRequest(instance_ref, args, req): """Parse arguments and construct list backups request.""" req.parent = instance_ref.RelativeName() if args.database: database = instance_ref.RelativeName() + '/databases/' + args.database req.filter = 'database="{}"'.format(database) return req
36,213
def output_encoding(outfile=None): """Determine the encoding to use for output written to `outfile` or stdout.""" if outfile is None: outfile = sys.stdout encoding = ( getattr(outfile, "encoding", None) or getattr(sys.__stdout__, "encoding", None) or locale.getpreferredencodi...
36,214
def day_start(src_time): """Return the beginning of the day of the specified datetime""" return datetime(src_time.year, src_time.month, src_time.day)
36,215
def _construct_corrections_dict(file): """Construct a dictionary of corrections. Given the name of a .ifa corrections file, construct a dictionary where the keys are wavelengths (represented as integers) and the values are measures of the instrument sensitivity (represented as floats). Intensi...
36,216
def get_activation_func(activation_label): """ Returns the activation function given the label Args: activation_label: Name of the function """ if activation_label == 'sigmoid': return tf.nn.sigmoid elif activation_label == 'identity': return tf.identity elif activation_l...
36,217
def sim_share( df1, df2, group_pop_var1, total_pop_var1, group_pop_var2, total_pop_var2, ): """Simulate the spatial population distribution of a region using the CDF of a comparison region. For each spatial unit i in region 1, take the unit's percentile in the distribution, and swap the group share wit...
36,218
def SetFileExecutable(path): """Sets the file's executable bit. Args: path: The file path. """ st = os.stat(path) os.chmod(path, st.st_mode | stat.S_IXUSR)
36,219
def test_get_command_bad_id() -> None: """It should raise if a requested command ID isn't in state.""" command = create_completed_command(command_id="command-id") subject = get_command_view(commands_by_id=[("command-id", command)]) with pytest.raises(errors.CommandDoesNotExistError): subject.ge...
36,220
def fixextensions(peeps, picmap, basedir="."): """replaces image names with ones that actually exist in picmap""" fixed = [peeps[0].copy()] missing = [] for i in range(1, len(peeps)): name, ext = peeps[i][2].split(".", 1) if (name in picmap): fixed.append(peeps[i].copy()) ...
36,221
def do_divide(data, interval): """ 使用贪心算法,得到“最优”的分段 """ category = [] p_value, chi2, index = divide_data(data, interval[0], interval[1]) if chi2 < 15: category.append(interval) else: category += do_divide(data, [interval[0], index]) category += do_divide(data, [index,...
36,222
def opened_bin_w_error(filename, mode="rb"): """ This context ensures the file is closed. """ try: f = open(filename, mode) except IOError as err: yield None, err else: try: yield f, None finally: f.close()
36,223
def test_is_question(): """Function does some tests to the is_question function""" assert isinstance(is_question('lol'), bool) assert is_question('test?') == True assert callable(is_question)
36,224
def get_config(key_path='/'): """ Return (sub-)configuration stored in config file. Note that values may differ from the current ``CONFIG`` variable if it was manipulated directly. Parameters ---------- key_path : str, optional ``'/'``-separated path to sub-configuration. Default is...
36,225
def find_cloudtrails(ocredentials, fRegion, fCloudTrailnames=None): """ ocredentials is an object with the following structure: - ['AccessKeyId'] holds the AWS_ACCESS_KEY - ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY - ['SessionToken'] holds the AWS_SESSION_TOKEN - ['AccountNumber'] holds the account ...
36,226
def evaluate(sess, logits, loss, labels, img_name, dataset): """ Trains the network Args: sess: TF session logits: network logits """ conf_mat = np.ascontiguousarray( np.zeros((FLAGS.num_classes, FLAGS.num_classes), dtype=np.uint64)) loss_avg = 0 for i in trange(dataset.num_examples()): ...
36,227
def run_worker(queues): """Run service workers.""" from renku.service.jobs.queues import QUEUES from renku.service.worker import start_worker if not queues: queues = os.getenv("RENKU_SVC_WORKER_QUEUES", "") queues = [queue_name.strip() for queue_name in queues.strip().split(",") if queu...
36,228
def _get_options(): """ Function that aggregates the configs for sumo and returns them as a list of dicts. """ if __mods__['config.get']('hubblestack:returner:sumo'): sumo_opts = [] returner_opts = __mods__['config.get']('hubblestack:returner:sumo') if not isinstance(returner_opt...
36,229
def maybe_unzip(local_archive='\\'.join([os.getcwd(), 'data', 'dataset.zip']), unzip_path='\\'.join([os.getcwd(), 'data', 'unzipped_dataset'])): """Unzip the specified local zip archive to the specified folder. Args: local_archive (:obj:`str`): the full path to the zip archive, including it...
36,230
def convert_boolean(value: Any) -> Optional[bool]: """Convert a value from the ToonAPI to a boolean.""" if value is None: return None return bool(value)
36,231
def Split4(thisBrep, cutters, normal, planView, intersectionTolerance, multiple=False): """ Splits a Brep into pieces using a combination of curves, to be extruded, and Breps as cutters. Args: cutters (IEnumerable<GeometryBase>): The curves, surfaces, faces and Breps to be used as cutters. Any othe...
36,232
def generate_passwords_brute_force(state): """ String Based Generation :param state: item position for response :return: """ if state is None: state = [0, 0] k, counter = state password = '' i = counter while i > 0: r = i % base password = alphabet[r] + pa...
36,233
def main() -> None: """Start maruberu server.""" options.parse_command_line(final=False) if pathlib.Path(options.conf).is_file(): options.parse_config_file(options.conf, final=False) options.parse_command_line() else: options.parse_command_line() logging.warning("conf '{}...
36,234
def tparse(instring: str, lenout: int = _default_len_out) -> Tuple[float, str]: """ Parse a time string and return seconds past the J2000 epoch on a formal calendar. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tparse_c.html :param instring: Input time string, UTC. :param lenout: A...
36,235
def _init_density_est_data_stub(num_time_steps_block: int, max_num_walkers: int, cfc_spec: CFCSpec) -> DensityExecData: """Stub for the init_density_est_data function (p.d.f.).""" pass
36,236
def release(ctx, version, skip_release_notes=False): """Tag a new release.""" status = run("git status --porcelain", hide=True).stdout.strip() if status != "": raise Exit(message="git checkout not clean, cannot release") version = semver.parse_version_info(version) is_patch_release = versio...
36,237
def align_decision_ref(id_human, title): """ In German, decisions are either referred to as 'Beschluss' or 'Entscheidung'. This function shall align the term used in the title with the term used in id_human. """ if 'Beschluss' in title: return id_human return id_human.replace('Be...
36,238
def get_headers(soup): """get nutrient headers from the soup""" headers = {'captions': [], 'units': []} footer = soup.find('tfoot') for cell in footer.findAll('td', {'class': 'nutrient-column'}): div = cell.find('div') headers['units'].append(div.text) headers['captions'].append...
36,239
def table2rank(table, transpose=False, is_large_value_high_performance=True, add_averaged_rank=False): """ transform a performance value table to a rank table :param table: pandas DataFrame or numpy array, the table with performance values :param transpose: bool, whether to transpose table (default: Fal...
36,240
def test_device_section_method_failed(flask_app, db): # pylint: disable=unused-argument """ To verify that registration section method is working properly and response is correct""" headers = {'Content-Type': 'multipart/form-data'} rv = flask_app.get('{0}/{1}'.format(DEVICE_REGISTRATION_SECTION_A...
36,241
def F_z_i(z, t, r1, r2, A): """ Function F for Newton's method :param z: :param t: :param r1: :param r2: :param A: :return: F: function """ mu = mu_Earth C_z_i = c2(z) S_z_i = c3(z) y_z = r1 + r2 + A * (z * S_z_i - 1.0) / np.sqrt(C_z_i) F = (y_z / C_z_i) ** 1....
36,242
def sigma_clip(array,nsigma=3.0,MAD=False): """This returns the n-sigma boundaries of an array, mainly used for scaling plots. Parameters ---------- array : list, np.ndarray The array from which the n-sigma boundaries are required. nsigma : int, float The number of sigma's away fro...
36,243
def main(): """example code lives in one function""" # grab a token token = oauth2_wrappers.gen_token() # set up our simple query string # # field names and matchTypes are documented at # https://app.swaggerhub.com/apis-docs/datafinnovation/clientapi/1.0/ query_dict = { "fields"...
36,244
def points_distance(xyz_1, xyz_2): """ :param xyz_1: :param xyz_2: :return: """ if len(xyz_1.shape) >= 2: distance = np.sqrt(np.sum((xyz_1 - xyz_2)**2, axis=1)) else: distance = np.sqrt(np.sum((xyz_1 - xyz_2)**2)) return distance
36,245
def test_fastparcel_transition_point_mixed(): """Test FastParcel._transition_point for mixed moist/dry descent.""" z_init = 3000*units.meter t_initial = -2*units.celsius q_initial = 0.004751707262581661*units.dimensionless l_initial = 2e-3*units.dimensionless rate = 0.5/units.km theta_e = sy...
36,246
def ensure_society(sess: SQLASession, name: str, description: str, role_email: Optional[str] = None) -> Collect[Society]: """ Register or update a society in the database. For existing societies, this will synchronise member relations with the given list of admins. """ try: ...
36,247
async def test_form_login_failed(hass): """Test we handle invalid auth error.""" result = await test_external_url_callback(hass) flow_id = result["flow_id"] with patch( "custom_components.tesla_custom.config_flow.TeslaAPI.connect", return_value={}, ): result = await hass.conf...
36,248
def odd_numbers_list(n): """ Returns the list of n first odd numbers """ return [2 * k - 1 for k in range(1, n + 1)]
36,249
def domain_delete(domainName): # noqa: E501 """domain_delete Remove the domain # noqa: E501 :param domainName: :type domainName: str :rtype: DefaultMessage """ return 'do some magic!'
36,250
def ParseDate(s): """ ParseDate(s) -> datetime This function converts a string containing the subset of ISO8601 that can be represented with xs:dateTime into a datetime object. As such it's suitable for parsing Collada's <created> and <modified> elements. The date must be of the form '-'? yyy...
36,251
def kinetic_energy(atoms): """ Returns the kinetic energy (Da*angs/ps^2) of the atoms. """ en = 0.0 for a in atoms: vel = v3.mag(a.vel) en += 0.5 * a.mass * vel * vel return en
36,252
async def cat(ctx): """gives you a cute cat image!""" embed = discord.Embed() catimg = await alex_api.cats() embed = discord.Embed(title= ('CUTY CATTY'),timestamp=datetime.datetime.utcnow(), color=discord.Color.green()) embed.set_footer(text=ctx.author.name , icon_url=ctx.author.avatar_url) ...
36,253
def boxes_intersect(boxes, box): """Determine whether a box intersects with any of the boxes listed""" x1, y1, x2, y2 = box if in_box(boxes, x1, y1) \ or in_box(boxes, x1, y2) \ or in_box(boxes, x2, y1) \ or in_box(boxes, x2, y2): return True return False
36,254
def cumulative_mean_normalized_difference_function(df, n): """ Compute cumulative mean normalized difference function (CMND). :param df: Difference function :param n: length of data :return: cumulative mean normalized difference function :rtype: list """ # scipy method c...
36,255
def configure(app): """ init babel :param app: :return: """ babel.init_app(app)
36,256
def add_spaces_old(spaces: Iterable["zfit.Space"]): """Add two spaces and merge their limits if possible or return False. Args: spaces: Returns: Union[None, :py:class:`~zfit.Space`, bool]: Raises: LimitsIncompatibleError: if limits of the `spaces` cannot be merged because they...
36,257
def minimal_subject_transformer(index, minimal_subject, attributes, subject_types, subject_type_is, center, radius): """Construct the JSON object for a MinimalSubject.""" subdomain, type = minimal_subject.subdomain, minimal_subject.type # Gather all the attributes values...
36,258
def _check_archive_dir(): """ Checks that the purported archive directory appears to contain a Vesper archive. """ _check_database() _check_preferences() _check_presets()
36,259
def beta_avg_inv_cdf(y, parameters, res=0.001): """ Compute the inverse cdf of the average of the k beta distributions. Parameters ---------- y : float A float between 0 and 1 (the range of the cdf) parameters : array of tuples Each tuple (alpha_i, beta_i) i...
36,260
def check_overwrite(file_path, overwrite=False): """ Defines the behavior for the overwrite argument for all output types. Arguments --------- file_path: str Exact file path overwrite: bool True: Structure files will be overwritten in the dir_path False: Exception wi...
36,261
def _aprime(pHI,pFA): """recursive private function for calculating A'""" pCR = 1 - pFA # use recursion to handle # cases below the diagonal defined by pHI == pFA if pFA > pHI: return 1 - _aprime(1-pHI ,1-pFA) # Pollack and Norman's (1964) A' measure # formula from Grier 1971 i...
36,262
def requires_testing_data(func): """Skip testing data test.""" return _pytest_mark()(func)
36,263
def mfcc_derivative_loss(y, y_hat, derivative_op=None): """ Expects y/y_hat to be of shape batch_size x features_dim x time_steps (default=128) """ if derivative_op is None: derivative_op = delta_matrix() y_derivative = tf.matmul(y, derivative_op) y_hat_derivative = tf.matmul(y_hat, deri...
36,264
def get_representative_terms( abilities_corpus: Iterable[str], skills_corpus: Iterable[str] ) -> Tuple[list, list]: """Return representative terms in order of importance from the abilities and skills corpora. Parameters ---------- abilities_corpus : Iterable[str] Iterable containing th...
36,265
def get_tags_from_playbook(playbook_file): """Get available tags from Ansible playbook""" tags = [] playbook_path = os.path.dirname(playbook_file) with open(playbook_file) as playbook_fp: playbook = yaml.safe_load(playbook_fp) for item in playbook: if 'import_playbook' in ite...
36,266
def get_mprocess_names_type1() -> List[str]: """returns the list of valid MProcess names of type1. Returns ------- List[str] the list of valid MProcess names of type1. """ names = ( get_mprocess_names_type1_set_pure_state_vectors() + get_mprocess_names_type1_set_kraus_ma...
36,267
def LoadAI(FileName): """LoadSC: This loads an IGOR binary file saved by LabView. Loads LabView Scope data from igor and extracts a bunch of interesting information (inf) from the data header""" IBWData = igor.LoadIBW(FileName); # I am going to store the experimental information in a dictionary ...
36,268
def accept_message_request(request, user_id): """ Ajax call to accept a message request. """ sender = get_object_or_404(User, id=user_id) acceptor = request.user if sender in acceptor.profile.pending_list.all(): acceptor.profile.pending_list.remove(sender) acceptor.profile.conta...
36,269
def cache_response(method, url, data, params, response): """ Caches the response in cache index """ logger.info("Caching response") response_json = response.__dict__ res = {} for key in ["content", "text", "json", "html"]: if key in response_json: res[key] = response_json...
36,270
def pytz_timezones_from_utc_offset(tz_offset, common_only=True): """ Determine timezone strings corresponding to the given timezone (UTC) offset Parameters ---------- tz_offset : int, or float Hours of offset from UTC common_only : bool Whether to only return common zone na...
36,271
def _sympysage_rf(self): """ EXAMPLES:: sage: from sympy import Symbol, rf sage: _ = var('x, y') sage: rfxy = rf(Symbol('x'), Symbol('y')) sage: assert rising_factorial(x,y)._sympy_() == rfxy.rewrite('gamma') sage: assert rising_factorial(x,y) == rfxy._sage_() """ ...
36,272
def validate_token_parameters(params): """Ensures token precence, token type, expiration and scope in params.""" if 'error' in params: raise_from_error(params.get('error'), params) if not 'access_token' in params: raise MissingTokenError(description="Missing access token parameter.") i...
36,273
def get_feature_gated_capabilities(request=None): """Return the capabilities gated behind enabled features. Args: request (django.http.HttpRequest, optional): The HTTP request from the client. Yields: tuple: A 3-tuple of the following: * The category of the cap...
36,274
def test_chip64_skip_next_if_unequal(): """ Tests the c64.skip_next_if_unequal() method, ensures that the code_ptr is appropriately modified. """ c64 = chip64.Chip64() c64.registers[0] = 0 c64.registers[1] = 1 c64.skip_next_if_unequal(0, 1) assert c64.code_ptr == 2 c64.reset() c...
36,275
def plotting_data_for_inspection(xdata,ydata,plot_title,plot_xlabel,plot_ylabel,filename_for_saving,folder_to_save, block_boolean): """ Plots data for user to look at within program parameters ---------- xdata,ydata: x and y data to be plotted plot_xlabel,plot_ylabel: label x and y axes in plo...
36,276
def run_sax_on_sequences(rdd_sequences_data, paa, alphabet_size): """ Perform the Symbolic Aggregate Approximation (SAX) on the data provided in **ts_data** :param rdd_sequences_data: rdd containing all sequences: returned by function *sliding_windows()*: *sequences_data* contain a list of all seq : tu...
36,277
def TC_analysis(EC_dict, target_substrate, filenamechoice, smilesFile, inchiFile): """This function carries out similarity indexing on the substrates of enzymes of interest. Arguments: EC_dict -- dictionary of EC numbers with the relevant substrates target_substrate -- SMILES string of the substrate ...
36,278
def attack_speed(game: FireEmblemGame, unit: ActiveUnit, weapon: Union[ActiveWeapon, None]) -> int: """ Calculates and returns the unit's Attack Speed, based on the AS calculation method of the current game, the unit's stats, the given weapon's Weight. If the weapon is None, always returns the unit's ba...
36,279
def test_nr_cfg_inline_commands_plugin_scrapli(): """ ret should look like:: nrp1: ---------- ceos1: ---------- scrapli_send_config: ---------- changed: True diff:...
36,280
def set_pow_ref_by_upstream_turbines_in_radius( df, df_upstream, turb_no, x_turbs, y_turbs, max_radius, include_itself=False): """Add a column called 'pow_ref' to your dataframe, which is the mean of the columns pow_%03d for turbines that are upstream and also within radius [max_radius] of the turbi...
36,281
def load_block_production(config: ValidatorConfig, identity_account_pubkey: str): """ loads block production https://docs.solana.com/developing/clients/jsonrpc-api#getblockproduction """ params = [ { 'identity': identity_account_pubkey } ] return smart_rpc_call(co...
36,282
def get_object(dic, img_width, img_height, center,z,angle): """ Move the UR3 robot to get the object. Parameters ---------- dic : dict Dictionnary of positions. img_width : int Width size of the image. In pixel. img_height : int Height size of the image. In pixel. ...
36,283
def run_doxygen(*, conf: DoxygenConfiguration, root_dir: Path) -> int: """Run Doxygen. Parameters ---------- conf A `DoxygenConfiguration` that configures the Doxygen build. root_dir The directory that is considered the root of the Doxygen build. This is the directory where ...
36,284
def remove_metatlas_objects_by_list(object_list, field, filter_list): """ inputs: object_list: iterable to be filtered by its attribute values field: name of attribute to filter on filter_list: strings that are tested to see if they are substrings of the attribute value returns filte...
36,285
def test_remove_with_index(): """ Tests removing an item using index """ # Arrange component1 = KiCadComponent({ "name": "TestComponent1" }) component2 = KiCadComponent({ "name": "TestComponent2" }) component3 = KiCadComponent({ "name": "TestComponent3" }) expected = [component1, componen...
36,286
def sync_database_account_data_resources( neo4j_session: neo4j.Session, subscription_id: str, database_account_list: List[Dict], azure_update_tag: int, ) -> None: """ This function calls the load functions for the resources that are present as a part of the database account response (like cors polic...
36,287
async def subscriber_callback(protocol): """ Receives the data from the publisher. """ msg = await protocol.recvfrom() data = np.frombuffer(msg, dtype=np.float64) # print("Received the data from the publisher.") # print(data) position = np.array([[data[0]], [data[1]], [data[2]]], dtyp...
36,288
def resnet_encoder(inputs, input_depth=16, block_type='wide', activation_fn=tf.nn.relu, is_training=True, reuse=None, outputs_collections=None, scope=None): """Defines an encoder network based on resnet...
36,289
def execute_stored_proc(cursor, sql): """Execute a stored-procedure. Parameters ---------- cursor: `OracleCursor` sql: `str` stored-proc sql statement. """ stored_proc_name, stored_proc_args = _sql_to_stored_proc_cursor_args(sql) status = cursor.callproc(stored_proc_name, pa...
36,290
def copy_dimensions(fi, fo, removedim=[], renamedim={}, changedim={}, adddim={}): """ Create dimensions in output file from dimensions in input file. Parameters ---------- fi : file_handle File handle of opened netcdf input file fo : file_handle File handle o...
36,291
def no_order_func_nb(c: OrderContext, *args) -> Order: """Placeholder order function that returns no order.""" return NoOrder
36,292
def test_print_version(): """CoreMS version""" rv, out = getstatusoutput(f'{prg} {directory}') assert rv == 0 assert re.findall("CoreMS version", out)
36,293
def test_async_add_opp_job_schedule_coroutinefunction(loop): """Test that we schedule coroutines and add jobs to the job pool.""" opp = MagicMock(loop=MagicMock(wraps=loop)) async def job(): pass ha.OpenPeerPower.async_add_opp_job(opp, ha.OppJob(job)) assert len(opp.loop.call_soon.mock_cal...
36,294
def get_queued(): """ Returns a list of notifications that should be sent: - Status is queued - Has scheduled_time lower than the current time or None """ return PushNotification.objects.filter(status=STATUS.queued) \ .select_related('template') \ .filter(Q(scheduled_time__lte=...
36,295
def address_family(config): """Gets AF neighbor config""" check_options = neigh_options(config) print(f"{'Neighbor: ':>20}{config.get('id', {}):<10}") print(f"{'Next-Hop-Self: ':>20}{check_options[0][0]}") print(f"{'Route-Reflector: ':>20}{check_options[1][0]}") print(f"{'Route-Map: ':>2...
36,296
def hue_of_color(color): """ Gets the hue of a color. :param color: The RGB color tuple. :return: The hue of the color (0.0-1.0). """ return rgb_to_hsv(*[x / 255 for x in color])[0]
36,297
def recent_tracks(user, api_key, page): """Get the most recent tracks from `user` using `api_key`. Start at page `page` and limit results to `limit`.""" return requests.get( api_url % (user, api_key, page, LastfmStats.plays_per_page)).json()
36,298
def extract_hdf5_frames(hdf5_frames): """ Extract frames from HDF5 dataset. This converts the frames to a list. :param hdf5_frames: original video frames :return [frame] list of frames """ frames = [] for i in range(len(hdf5_frames)): hdf5_frame = hdf5_frames[str(i)] assert l...
36,299