content
stringlengths
22
815k
id
int64
0
4.91M
def std_of_displacements(stops, distf=lambda a, b: geodesic(a, b).meters): """ Compute standard deviation of displacements feature from stops. The standard deviation of distances between subsequent stops. :param stops: dataframe of stops. :param distf: distance function of the form: ((lat, lon),(l...
5,304,800
def main(args): """The main process of profile-based features. :param args: an object of the arguments. """ file_list = args.inputfiles label_list = args.labels output_format = args.f if len(file_list) == 0: print 'Input files not found.' return False if outpu...
5,304,801
def test_lead(): """Can get leading values with function""" df = tp.Tibble({'x': range(3)}) actual = df.mutate(lead_null = tp.lead(col('x')), lead_default = tp.lead('x', default = 1)) expected = tp.Tibble({'x': range(3), 'lead_null': [1, 2, None], ...
5,304,802
def class_amount(data_amount: int) -> int: """Compute class amount (k) of a data size""" return ceil(1 + 3.3 * log10(data_amount))
5,304,803
def step_impl_my_open_threads_count_are_counted_by_ru(context, business_id): """access the messages_count endpoint to get the count of my unread conversations""" url_args = f"?is_closed=false&my_conversations=true&business_id={business_id}" _step_impl_get_threads_count(context, url_args)
5,304,804
def _wrap_coord(tensors): """wrap positions to unit cell""" cell = tf.gather_nd(tensors['cell'], tensors['ind_1']) coord = tf.expand_dims(tensors['coord'], -1) frac_coord = tf.linalg.solve(tf.transpose(cell, perm=[0, 2, 1]), coord) frac_coord %= 1 coord = tf.matmul(tf.transpose(cell, perm=[0, 2,...
5,304,805
def save_data(df, database_filename): """ Input: 1. df: the cleaned dataframe, which is generated by the clean data function 2. database_filename: name of the database file Output: Saved database file Process: 1. Create engine for saving dataframe 2. Use ...
5,304,806
def two_linear_model_loss_regularized_dy1dx_lp(w0, w1, x, y, reg_coeff, norm_type): """Penalize by ||dy1/dx||, optimal when first layer is fixed.""" dy1_dx_f = jax.grad(two_linear_model_y1_mean, argnums=2) dy1_dx = dy1_dx_f(w0, w1, x) loss = two_linear_model_loss(w...
5,304,807
def register_type(implementation, rdtype, rdtype_text, is_singleton=False, rdclass=dns.rdataclass.IN): """Dynamically register a module to handle an rdatatype. *implementation*, a module implementing the type in the usual dnspython way. *rdtype*, an ``int``, the rdatatype to register...
5,304,808
def test_statuses(get_resource_status: MagicMock): """Should execute statuses on bundle resources.""" bundle = kuber.from_file(os.path.join(MY_DIRECTORY, "test-get.yaml")) bundle.statuses() assert get_resource_status.call_count == len(bundle.resources)
5,304,809
def test_generic_ansible(): """ Scenario: Given valid arguments, mock events from ansible-runner, ensure context/readable output matches expectations Given: - valid host args for single windows host 123.123.123.123 - valid username / password - command win-audit-policy-system - args subcate...
5,304,810
def mask_elon(aia_cumul8, hmi_dat): """ Masking for elongation algorithm. Parameters ---------- aia_cumul8 : list Cumulative ribbon masks, c=8. hmi_dat : list SDO/HMI image data for flare. Returns ------- aia8_pos_2 : list Contains only the positive cumulati...
5,304,811
def _validate_pad(padtype, padlen, x, axis, ntaps): """Helper to validate padding for filtfilt""" if padtype not in ['even', 'odd', 'constant', None]: raise ValueError(("Unknown value '%s' given to padtype. padtype " "must be 'even', 'odd', 'constant', or None.") % ...
5,304,812
def generate_fc2_filedata(filepath_tests): """Generate a `SinglefileData` instance with fc2.hdf5 file.""" def _generate_fc2_filedata(structure_id: str = "NaCl-64"): if structure_id == "NaCl-64": filepath = os.path.join( filepath_tests, "parsers", ...
5,304,813
def get_supported_languages(): """Return the list of supported language. """ if getattr(PARSER, 'filename', None): return list(sorted(lang for lang in PARSER.sections())) return list(sorted(DEFAULT.keys()))
5,304,814
def createCFileBuilders(env): """This is a utility function that creates the CFile/CXXFile Builders in an Environment if they are not there already. If they are there already, we return the existing ones. This is a separate function because soooo many Tools use this functionality. The ret...
5,304,815
def get_requirements(integration: Integration, packages: set[str]) -> set[str]: """Return all (recursively) requirements for an integration.""" ensure_cache() all_requirements = set() to_check = deque(packages) while to_check: package = to_check.popleft() if package in all_requir...
5,304,816
def timestr_mod24(timestr): """ Given a GTFS HH:MM:SS time string, return a timestring in the same format but with the hours taken modulo 24. """ try: hours, mins, seconds = [int(x) for x in timestr.split(":")] hours %= 24 result = "{:02d}:{:02d}:{:02d}".format(hours, mins, s...
5,304,817
def set_ext_api(file_path): """Smart Function to set Extension.""" ext = file_path.split('.')[-1] if ext == 'plist': return 'plist' elif ext == 'xml': return 'xml' elif ext in ['sqlitedb', 'db', 'sqlite']: return 'db' elif ext == 'm': return 'm' else: ...
5,304,818
def gen_ipc_path(base_mac, pipe) -> Path: """ Builds a path that should represent some RX pipe """ base_path = Path("/tmp/ripple_ipc/rx") base_path.mkdir(exist_ok=True) return _gen_ipc_path(base_path, base_mac, pipe)
5,304,819
def _get_cert_dates(pem_cert): """Returns the dates in the cert""" cert = x509.load_pem_x509_certificate(pem_cert.encode(), default_backend()) logger.debug( "Certificate with serial '%s', has not before: '%s' and not after: '%s' (UTC)", cert.serial_number, cert.not_valid_before, ...
5,304,820
def animations(): """animations() -> tuple Returns a list of animatable things the user wants to work on. If this is a command being executed from a menu item in a curve editor, a list of the names of all selected curves is returned. If this list is empty a "No curves selected" error is produced. If this is a comm...
5,304,821
def updateByManifest(path, dryRun=False): """ Attempts to update only the recently updated datafiles by using a manifest file. Returns False if updating failed and a full update should be performed; returns True if updating was a success. """ say("Updating via manifest...") say("Gathering l...
5,304,822
def toggle_language(n_clicks, target_lang): """ Toggles the language between English and Chinese. Args: n_clicks (int): Number of times the button has been clicked. target_lang (str): The target language to change to (children attribute of #toggle-language element) """ if target_lan...
5,304,823
def create_handler(event, context): """ Called when CloudFormation custom resource sends the create event """ return create_processing_job(event)
5,304,824
def finish_multiplier(): """Starts at 1.5x in the middle of the grid, increases to linearly to 2x for 1st and last place.""" multiplier_floor = 1.15 current_position = ir.car_position() grid_size = ir.field_size() mid_positions = grid_size/2 if grid_size % 2 == 1: mid_positions = [mid_p...
5,304,825
def combined_roidb(split, task, num_im, num_val_im): """ Combine multiple roidbs """ imdb = get_vg_imdb(split, task, num_im, num_val_im) print('Loaded dataset `{:s}` for training'.format(imdb.name)) roidb = get_training_roidb(imdb) return imdb, roidb
5,304,826
def gen_payment_op( dest: xdr_type.AccountID, src: Optional[xdr_type.AccountID] = None, amount: int = 10 ) -> xdr_type.Operation: """Generate a payment operation. """ body = xdr_pack.nullclass() body.type = xdr_const.PAYMENT body.paymentOp = xdr_type.PaymentOp( destination=dest, ...
5,304,827
def _get_copyrights_from_files(license_files): """ Get all of the copyright notifications from a list of files. """ copyright_notices = [] for license_file in license_files: # If the license_file is a folder, skip it if not os.path.isfile(license_file): continue #...
5,304,828
def get_affine_transform(center, scale, rot, output_size, shift=np.array([0, 0], dtype=np.float32), inv=False): """ adapted from CenterNet: https://github.com/xingyizhou/CenterNet/blob/master/src/lib/utils/image.py center: ndarray: (cx, cy) scale: (w, h) rot: angle in deg output_size: int or (w,...
5,304,829
def hostip(req=None, black_list=None, pref_list=None, logger=None): """ Look up the ip number for a given requested interface name. If interface is not given, do some magic. """ # we only determine hostip once global _hostip if _hostip: return _hostip # List of interfaces that ...
5,304,830
def test_sgf(filename): """Parses a sgf file to a game dict. Args: filename: str, path of the sgf file Returns: None if one of these to Errors occurs: * sgf contains no moves, affects about 1% of files in KGS dataset * move in the sgf breaks the minigo ko rule, affects about...
5,304,831
def dtex_cii_1(tcii, tau_cii, tbg): """ """ return np.power(tex_cii(tcii, tau_cii, tbg), 2.) * 1./(1 + tstar*(1. - np.exp(-tau_cii))/(tcii + J(tbg)))
5,304,832
def test_async_dump_bin(): """ Feature: async dump on Ascend in npy format Description: test async dump with file_format = "bin" Expectation: dump data are generated as protobuf file format (suffix with timestamp) """ run_async_dump("test_async_dump_bin")
5,304,833
def get_pragma_spec(source: str) -> Optional[NpmSpec]: """ Extracts pragma information from Vyper source code. Args: source: Vyper source code Returns: NpmSpec object or None, if no valid pragma is found """ pragma_match = next(re.finditer(r"(?:\n|^)\s*#\s*@version\s*([^\n]*)", source), ...
5,304,834
def git_log(start, end, workingdir=None): """Run a ``git log`` command that will provide a nicely formatted list of commits between ``start`` and ``end`` times. If ``workingdir`` is provided, change to that directory before running the command.""" if workingdir: olddir = os.getcwd() os.c...
5,304,835
def parse_time(input_time): """Parse an Atom time stamp.""" parsed = None try: parsed = timezone.make_aware(timezone.datetime(*input_time[:-3]), timezone.utc) except (pytz.NonExistentTimeError, pytz.AmbiguousTimeError): added_hour = (timezone.datetime...
5,304,836
def run_and_save_simulation( n_agents, parameter_market, parameter_deviation, super_star_tuples ): """ Load the needed data, run the simulation and save the simulation data. Args: n_agents (integer): Number of agents in the markets. parameter_market (dict): Explained somewhere else ...
5,304,837
def test_multi_mws_preserve_order(client: FlaskClient): """test Router.route with multiple middlewares (order preserving)""" resp = client.post('/multi-mws') assert resp.status_code == 401 assert not resp.json.get('success') assert resp.json.get('message') == 'unauthorized access'
5,304,838
def test_check_messages(load_mock, forward_mock, mark_mock, reply_mock, settings_mock): """ Messages should be forwarded evenly across recipients. """ # Arrange messages = MESSAGES_RESPONSE['value'] settings_mock.FORWARD_TO = [ ('Bender', 'bender@planetexpress.com'), ('Zoidberg',...
5,304,839
def add_solution( respy_obj, periods_rewards_systematic, states_number_period, mapping_state_idx, periods_emax, states_all, *args, ): """Add solution to class instance.""" respy_obj.unlock() respy_obj.set_attr("periods_rewards_systematic", periods_rewards_systematic) respy_ob...
5,304,840
def sinusoid(t,A,P,phi,offset): """ A simple sinusoid model """ return A*np.sin(2.*np.pi*t/P + phi)+offset
5,304,841
def sanitize_bucket_and_host(bucket): # type: (str) -> Tuple[str, str] """ if bucket is in following format : 'xxx.amazonaws.com/bucket_name', Returns a 2-values tuple ('bucket_name', 'xxx.amazonaws.com') """ # first case: we got a "<host>/<bucket_name>" input if "/" in bucket: host,...
5,304,842
def _compute_embedding_grad_sample( layer: nn.Embedding, A: torch.Tensor, B: torch.Tensor, batch_dim: int = 0 ) -> None: """ Computes per sample gradients for ``nn.Embedding`` layer Parameters ---------- layer : nn.Embedding Layer A : torch.Tensor Activations B : torch.T...
5,304,843
def test_recordmodel(mock_program_dao): """Get a record model instance for each test function.""" dut = mock_program_dao.do_select_all(RAMSTKMechanismRecord, _all=False) yield dut # Delete the device under test. del dut
5,304,844
def config_to_file(): """Outputs the current configuration in .arc file format""" config_items = [ [name, getattr(config, name)] for name in Config.__dataclass_fields__ # pylint: disable=no-member ] print("\n".join(f"{name}={value}" for name, value in config_items))
5,304,845
def move_roles_to_base_role_config_group(resource_root, service_name, role_names, cluster_name="default"): """ Moves roles to the base role config group. The roles can be moved from any role config group belonging to the same service. The role type of the roles may vary. Each role will be moved to its c...
5,304,846
def stamp_allowing_unusual_version_table( config: Config, revision: str, sql: bool = False, tag: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> None: """ Stamps the Alembic version table with the given revision; don't run any migrations. This ...
5,304,847
def when(*contexts: Context): """Returns a function wrapper. A function decorated with `when` will exit early if any supplied context in `contexts` is active. The first supplied context to block will be reported as a message. Consider supplying permanent conditions first. For example, to block a function wh...
5,304,848
def color_wipe(unused_addr, red, green, blue, wait_ms=3): """Wipe color across display a pixel at a time.""" logger.info(f'Color {red} {green} {blue}') color = Color(red, green, blue) for i in range(strip.numPixels()): strip.setPixelColor(i, color) strip.show() time.sleep(wait_ms...
5,304,849
def read(filename: PathLike, **kwargs) -> Union[MuData, AnnData]: """ Read MuData object from HDF5 file or AnnData object (a single modality) inside it This function is designed to enhance I/O ease of use. It recognises the following formats: - FILE.h5mu - FILE.h5mu/MODALITY - FIL...
5,304,850
def bash(): """bash commands group.""" pass
5,304,851
def group_nodes(graph: ModuleGraph) -> Iterator[Tuple[str, str, Sequence[BaseNode]]]: """ Detect groups of reachable nodes in the graph. This function groups nodes in two ways: - Group all nodes related to a particular distribution - Group all nodes in the same stdlib package Args: graph...
5,304,852
def rename_local_repo(old, new, project): """ Renames local repositories: - Rename the git dir - Change remote origin (svn or git) - Change commit notification ML - Change PR notification ML """ # First, rename the dir on the box. Fall flat on our behind if this fails. ...
5,304,853
def highlight_regex(str_, pat, reflags=0, color='red'): """ FIXME Use pygments instead """ import re matches = list(re.finditer(pat, str_, flags=reflags)) colored = str_ for match in reversed(matches): start = match.start() end = match.end() colored_part = ub.color_te...
5,304,854
def get_environment(env_name: str) -> Environment: """ Get environment for given env name :return: Environment or None """ _check_active_client() envs = _merlin_client.list_environment() # type: ignore for env in envs: if env.name == env_name: return env return None
5,304,855
def cluster_otus(workflow, method, fasta_file, reference_fasta, output_folder): """ Cluster the otus with usearch Args: workflow (anadama2.workflow): an instance of the workflow class. method (string): tools for sequence analysis - usearhc(default) or vsearch fasta_file (string): th...
5,304,856
def __add_dhcpd_file(subnet_list): """ to generate local dhcpd.conf file """ print" " logger.info("addDhcpdFile function") common_str = """ ddns-update-style none; default-lease-time 1600; max-lease-time 7200; authoritative; log-facility local7; allow booting; allow bootp; option option-...
5,304,857
def get_mirtarbase(): """Get generic mirtarbase entry.""" return _get_data(mirtarbase.Mirtarbase)
5,304,858
def build_postprocessor(): """Build the default postprocessors.""" processor = PostProcessor() # processor.reg.add(function, name, priority) return processor
5,304,859
def mod(source): """Create kernel module shared among multiple tests.""" return source.get_module_for_symbol("snd_request_card")
5,304,860
def load_data(data_file, one_hot: bool = True, one_hot_dim: int = None, code_map=None): # TODO: remove the radii selection lines # TODO: Currently the one-hot encoding is done in memory all at once. Potentially it needs to be moved to a custom DataLoader like ExpertTrajectory above """For Arash's format ...
5,304,861
def getAvailableTimesOnDate(client, date): """Function that first loads the page for a date and then returns the list of free time slots on that day.""" loadDate(client, date) return getAvailableTimes(client.html)
5,304,862
def show_main_colors(main_colors: np.ndarray): """Plot main colors Args: main_colors (np.ndarray): Main colors """ _, axes = plt.subplots(1, len(main_colors), figsize=(15, 2)) for k in range(len(axes)): axes[k].imshow([[np.mean(main_colors, axis=2)[k] / 256]]) axes[k].set_ax...
5,304,863
def run_gui(sim): """ Encapsulate frame """ gui = ApocalypseGUI(sim) gui.start()
5,304,864
def make_utf8(x): """Encode a string as UTF8 Respect both python2 and python3.""" if isinstance(x, six.text_type): return x elif isinstance(x, six.binary_type): return x.decode('utf8') else: raise ValueError('Expected string type, got type %s' % str(type(x)))
5,304,865
def forward_step(data_iterator, model, input_tensor): """Forward step.""" args = get_args() timers = get_timers() # Get the batch. timers('batch-generator').start() query_tokens, query_mask, \ context_tokens, context_mask, context_indices = get_ict_batch(data_iterator) timers('batch-gen...
5,304,866
def load_savedmodel(savedmodel_dir: str) -> Tuple[tf.compat.v1.Session, Dict[str, any]]: """ Loads a Lobe exported Tensorflow SavedModel and returns the session with the model loaded and our signature file. """ # make sure our exported SavedModel folder exists model_path = os.path.realpath(savedmodel_dir) if not...
5,304,867
def main(): """ Função principal. A função somente faz chamadas á outras funções. """ valor_area = float(input('Área(m²): ')) __calcula_quantidade_tinta(area=valor_area)
5,304,868
def recorder(event_loop) -> AsyncAWSXRayRecorder: """An X-Ray recorder with local-only, stubbed, segment collection.""" xray_recorder = get_new_stubbed_recorder() xray_recorder.configure( service="test", sampling=False, context=AsyncContext(loop=event_loop) ) with patch("xraysink.asgi.middl...
5,304,869
def _join_subpath(root: Path, source: Union[str, Path], destination: Path) -> Path: """ Appends to destination, source-relative path to root. Written for use with os.walk() to match subfolders during walk. For example: root = 'R:/Documents/School/Math source = 'R:/Docum...
5,304,870
def makepath(subsystem, group, pseudofile=None): """Pieces together a full path of the cgroup. """ mountpoint = _get_mountpoint(subsystem) group = group.strip('/') if pseudofile: return os.path.join(mountpoint, group, pseudofile) return os.path.join(mountpoint, group)
5,304,871
def srt_formatter(subtitles, padding_before=0, padding_after=0): """ Serialize a list of subtitles according to the SRT format, with optional time padding. """ sub_rip_file = pysrt.SubRipFile() for i, ((start, end), text) in enumerate(subtitles, start=1): item = pysrt.SubRipItem() it...
5,304,872
def file_copy(file_path_source, file_path_destination): """Copies a file from `file_path_source` to `file_path_destination`""" copyfile(file_path_source, file_path_destination)
5,304,873
def are_in_same_quarter(first: datetime.date, second: datetime.date) -> bool: """Find out if two dates are in the same quarter. Args: first (datetime.date): The first date. second (datetime.date): The second date. Returns: bool: True if the dates aare in the same quarter. """ ...
5,304,874
def get_plot_colours(n: int = 10, colourmap: Optional[str] = None) -> List[Tuple[float]]: """ Return iterable list of RGB colour values that can be used for custom plotting functions Returns a list of RGB colours values, potentially according to a specified colourmap. If n is low enough, will use the c...
5,304,875
def get_output_file_globbing_template(output_dir: Path, file_prefix: str, file_suffix: str) -> Path: """ Returns a canonical path with the given parameters where the start and end times are replaced with a globbing expression (?). :param output_dir: the path for the globbing expression :param file_...
5,304,876
def evaluate_reaction_rate(results, cell, nuc, rxn): """ Evaluates a single nuclide reaction rate in a single cell from a results list. Parameters ---------- results : list of Results The results to extract data from. Must be sorted and continuous. cell : str Cell name to evaluate ...
5,304,877
def roundFloatsInDict(data, decimals): """Recursively rounds all floats in the dictionary to the specified decimal digits. If a float value is smaller than 10e-decimals it is set to zero. Args: data(dict): data dictionary decimals(int): number of decimals floats should be rounded to R...
5,304,878
def _get_vuln_info_from_cve(full_cve): """Return the vulnerable configurations of operating system and software for a given CVE. Args: full_cve (dict): Full CVE data as a JSON dictionary from API call. Returns (dict, dict): ({os: [version,]}, {software: [version,]) """ vulnerable_confi...
5,304,879
def toggle_results_visible(session, context, poll): """Change the results visible settings of a poll.""" if poll.created: return i18n.t('callback.poll_already_created', locale=context.user.locale) poll.results_visible = not poll.results_visible open_anonymization_settings(context.query.message...
5,304,880
def fnCalculate_DatetimeEpoch(timevec, index, timestamp): """ Find the datetime object for the time index. Created: 24 May 2017 in testepochfunc.py Edited: 29.08.17: Commented out everything, better to use datetime methods. As set up originally, results would be im...
5,304,881
def fetchFTPURL(remote_file:URIType, cachedFilename:AbsPath, secContext:Optional[SecurityContextConfig]=None) -> Tuple[Union[URIType, ContentKind], List[URIWithMetadata]]: """ Method to fetch contents from ftp :param remote_file: :param cachedFilename: :param secContext: """ parsedInpu...
5,304,882
def plot_prediction(args: dict, index: int): """ Plots image located at <index> in dataset found in <args.folder> and prints the true and predicted labels. :param args: Dictionary of training specifications detailed in main.py. :param index: Index of image data to plot. :return: None """ ...
5,304,883
def compute_stage4(lon, lat, year): """Build a daily dataframe for the stage4 data""" nc = netCDF4.Dataset("/mesonet/data/stage4/%s_stage4_hourly.nc" % (year,)) lons = nc.variables["lon"][:] lats = nc.variables["lat"][:] dist = ((lons - lon) ** 2 + (lats - lat) ** 2) ** 0.5 (yidx, xidx) = np.unr...
5,304,884
def celery_place_order(data, staff_id): """使用Celery + djcelery实现快递异步下单 使用djcelery可以在任务中方便的直接操作Django数据库, 而且最终的任务可以在Django的后台中查看和修改相关的任务""" # 创建快递操作对象 express = ProjectExpress() result = express.place_order(request_data=data) if result.get('Success'): ExpressInfo.objects.create( ...
5,304,885
def measure_torsion_angles(residues): """Calculates the dihedral angles for a list of backbone atoms. Parameters ---------- residues : [ampal.Residue] List of `Residue` objects. Returns ------- torsion_angles : (float, float, float) One triple for each residue, containing t...
5,304,886
def constant_time_compare(x, y): """ Compares two byte strings in a way such that execution time is constant regardless of how much alike the input values are, provided that they are of the same length. Comparisons between user input and secret data such as calculated HMAC values needs to be ex...
5,304,887
def check_epic_key (db, cl, nodeid, new_values) : """ Ensure that the epic_key matches the format of keys in Jira """ if 'epic_key' in new_values : r = re.compile (r'^[A-Z][0-9A-Z_]+[0-9A-Z]-[0-9]+$') k = new_values ['epic_key'] if k is not None and not r.search (k) : epi...
5,304,888
def get_objective_sbml_fbc_ids(model_source): """ Get the SBML-FBC id of the active objective Args: model_source (:obj:`str`): path to model Returns: :obj:`tuple`: * :obj:`str`: SBML-FBC id of the active objective * :obj:`list` of :obj:`str`: SBML-FBC id of the obj...
5,304,889
def isNOAAACE(filename): """ Checks whether a file is NOAA ACE format. """ try: tempf = open(filename, 'rt') temp1= tempf.readline() temp2= tempf.readline() temp3= tempf.readline() except: return False try: if not temp1.startswith(':'): ...
5,304,890
def uiNewRadioButtons(): """ Creates a new radio buttons. :return: uiRadioButtons """ clibui.uiNewRadioButtons.restype = ctypes.POINTER(uiRadioButtons) return clibui.uiNewRadioButtons()
5,304,891
def gradient_binarizing_scalers(grads_and_vars, clip_factor): """ Get the scalers.""" gradients, variables = zip(*grads_and_vars) scalers = [] for gradient in gradients: if gradient is None: scalers.append(None) continue if (clip_factor > 1.0e-5): mea...
5,304,892
def test_connect_to_broker(): """Test that our broker connection is working fine. This doens't need to run in a RasPi. """ client, connection = connect_to_broker( client_id='test_client', host=HOST, port=PORT, keepalive=KEEPALIVE ) assert client is not None as...
5,304,893
def cov_spk_ker(spk, object=False, time_format='TDB', support_ker ='', report=False, unload=True): """ Provides time coverage summary for a given object for a given SPK file. Several options are available. This function is based on the following SPICE API: http://naif.jpl.nasa.gov/p...
5,304,894
def _str2bool(string): """Converts either 'true' or 'false' (not case-sensitively) into a boolean.""" if string is None: return False else: string = string.lower() if string == 'true': return True elif string == 'false': return False else: raise ValueError( 'String should either...
5,304,895
def _get_alpha_bar_from_time(t): """ Noise scheduling method proposed by Nichol et. al to avoid too noisy image especially for smaller resolution. This strategy creates beta as follows: alpha_bar(t) = f(t) / f(0) f(t) = cos((t / T + s) / (1 + s) * PI / 2) ** 2 beta(t) = 1 - alpha_ba...
5,304,896
def decrementAny(tup): """ the closest tuples to tup: decrementing by 1 along any dimension. Never go into negatives though. """ res = [] for i, x in enumerate(tup): if x > 0: res.append(tuple(list(tup[:i]) + [x - 1] + list(tup[i + 1:]))) return res
5,304,897
def _delete_folder(path): """Internal method which won't trigger the callback""" with fslock: if os.path.exists(path): shutil.rmtree(path)
5,304,898
def mock_open(mock=None, read_data=''): """ A helper function to create a mock to replace the use of :func:`open()`. It works for :func:`open()` called directly or used as a context manager. :param mock: mock object to configure, by default a :class:`~asynctest.MagicMock` object is ...
5,304,899