content
stringlengths
22
815k
id
int64
0
4.91M
def make_all_figures(close_figs=False): """ Call all the figure generators for this chapter :close_figs: Boolean flag. If true, will close all figures after generating them; for batch scripting. Default=False :return: List of figure handles """ # Find the output directory ...
5,306,500
def write_spark_json(comments_dir, top_words_file, save_file): """ 统计每一个top word的词频随时间的变化,并保存为{'word':[,,]} json格式 :param comments_dir: (str) 包含所有月份的评论top words 词频的文件夹 :param top_words_file: (str) 所有评论中选取的top words的路径 :param save_file: json数据的保存位置 :return: """ # 读取每个月的json存到list里 mon...
5,306,501
def build_cython(c): """Build the cython extension module""" print_banner("Building Cython Module") # Run cython on the pyx file to create a .cpp file invoke.run("cython --cplus -3 cython_example.pyx -o cython_wrapper.cpp") # Compile and link the cython wrapper library compile_python_module("cy...
5,306,502
def exists_lite_runner_bin(): """Returns true iff lite_runner binary exists.""" return os.path.exists(_LITE_RUNNER_BIN)
5,306,503
def run_pcluster_command(*args, **kwargs): """Run a command after assuming the role configured through register_cli_credentials_for_region.""" region = kwargs.get("region") if not region: region = os.environ["AWS_DEFAULT_REGION"] if region in cli_credentials: with sts_credential_provide...
5,306,504
def arguments_from_docstring(doc): """Parse first line of docstring for argument name. Docstring should be of the form ``min(iterable[, key=func])``. It can also parse cython docstring of the form ``Minuit.migrad(self[, int ncall_me =10000, resume=True, int nsplit=1])`` """ if doc is None: ...
5,306,505
def _check_mod_11_2(numeric_string: str) -> bool: """ Validate numeric_string for its MOD-11-2 checksum. Any "-" in the numeric_string are ignored. The last digit of numeric_string is assumed to be the checksum, 0-9 or X. See ISO/IEC 7064:2003 and https://support.orcid.org/knowledgebase/artic...
5,306,506
def fft_convolve3(signal, kernel, conv_mode = CONV_MODE.DEFAULT): """ FFT based Convolution: 3D Parameters ----------- signal: af.Array - A 3 dimensional signal or batch of 3 dimensional signals. kernel: af.Array - A 3 dimensional kernel or batch of 3 dimensional kerne...
5,306,507
def check_en_wik9_dataset(method): """Wrapper method to check the parameters of EnWik9 dataset.""" @wraps(method) def new_method(self, *args, **kwargs): _, param_dict = parse_user_args(method, *args, **kwargs) nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shards', 'shard_id...
5,306,508
def arg_parser(): """Parser for command line arguments.""" description = ("Script to validate that " "election results XML file(s) " "follow best practices") parser = argparse.ArgumentParser(description=description) subparsers = parser.add_subparsers(dest="cmd") parser_valid...
5,306,509
def low_depth_second_order_trotter_error_operator( terms, indices=None, is_hopping_operator=None, jellium_only=False, verbose=False): """Determine the difference between the exact generator of unitary evolution and the approximate generator given by the second-order Trotter-Suzuki expansion....
5,306,510
def prep_metrics(ap_data, dets, img, gt, gt_masks, h, w, num_crowd, image_id, detections): """ postprocess """ # classes [100,], scores [100, ], boxes [100,4], masks [100, H, W] classes, scores, boxes, masks = postprocess(dets, w, h, crop_masks=True, score_threshold=args.threshold) if classes.shape.issp...
5,306,511
def stash(): """ Stash the repository. """ pass
5,306,512
def test_p6(): """ Test some joint and conditional perplexities """ d = D(['00', '11'], [1 / 2] * 2) assert P(d) == pytest.approx(2) assert P(d, [0], [1]) == pytest.approx(1) assert P(d, [1], [0]) == pytest.approx(1)
5,306,513
def get_historical(ticker: str, metric: str) -> pd.DataFrame: """Get historical sentiment data [Source: sentimentinvestor] Parameters ---------- ticker : str Stock metric : str Metric to get Returns ------- pd.DataFrame Dataframe of historical sentiment """ ...
5,306,514
def _calculate_euclidean_similarity(distances, zero_distance): """Calculates the euclidean distance between two sets of detections, and then converts this into a similarity measure with values between 0 and 1 using the following formula: sim = max(0, 1 - dist/zero_distance). The default zero_distance of 2.0...
5,306,515
def setInitialParameters(initialSuggestions): """Initial parameters for optimization problem being solved""" global params params = initialSuggestions sugjson = json.dumps(list(initialSuggestions)) apipath = __SERVER_HOST__ + __SERVER_PARAMETERS_API__ + "/" + str(__SERVER_SECRET__) resp...
5,306,516
def compute_signature_strength(cpds_list, df, metadata_cols = metadata_cols): """Computes signature strength for each compound based on its replicates""" cpds_SS = {} for cpd in cpds_list: cpd_replicates = df[df['pert_iname'] == cpd].copy() cpd_replicates.drop(metadata_cols, axis = 1, i...
5,306,517
def include_all_subfiles(*args): """Slurps up all files in a directory (non recursive) for data_files section Note: Not recursive, only includes flat files Returns: list: all non-directories in a file """ file_list = [] for path_included in args: local_path = path.join...
5,306,518
def test_enum(): """ Can create a class for an enum schema """ registry = Registry() registry.register({ "id": "id", "type": "string", "enum": ["Foo", "Bar"], }) Enum = registry.create_class("id") enum = Enum("Foo") enum.validate() assert_that(calling(E...
5,306,519
def _unpack_value(value): """ Unpack contents if it is pickled to a temporary file. :param value: A non-string variable or a string referring to a pickled file path. :returns: The original value, or the unpacked contents if a valid path was given. """ if isinstance(value, stri...
5,306,520
def join_3_query(): """Finds all players from country X who scored at least one goal in a game played in Y city and Z year.""" desired_country = "Brazil" desired_gameDest = "Europe" desired_gameYear = 2017 sql = text('''SELECT distinct a.name, a.teamID, a.status, a.salary FROM Ath...
5,306,521
def calc_ac_fit(df, objects): """ created dataframe of features for train objects """ object_ids, ac_decay, ac_decay_err, ac_loss, ac_amp, ac_amp_err = ( [], [], [], [], [], [], ) for obj in objects: obj_df = df[(df....
5,306,522
def test_runner_should_continue_running_steps_when_step_is_skipped_or_pending( hook_registry, default_config, mocker ): """The Runner should continue running Steps after a Step is skipped""" # given runner = Runner(default_config, None, hook_registry) runner.run_step = mocker.MagicMock() runner....
5,306,523
def get_forge_plugin_command_names() -> List[str]: """ Returns a list of plugin command names""" return [ get_command_from_config(plugin_config) for plugin_config in get_plugins() ]
5,306,524
async def test_switch_setup_without_discovery_info(hass, config, numato_fixture): """Test handling of empty discovery_info.""" numato_fixture.discover() await discovery.async_load_platform(hass, "switch", "numato", None, config) for entity_id in MOCKUP_ENTITY_IDS: assert entity_id not in hass.st...
5,306,525
def array_to_datetime(array): """ Convert an 1d datetime array from various types into pandas.DatetimeIndex (i.e., numpy.datetime64). If the input array is not in legal datetime formats, raise a "ParseError" exception. Parameters ---------- array : list or 1d array The input da...
5,306,526
def write_seqids_to_fasta(seqids, output_filename, fasta_d): """ Write to fasta: ID --- the sequence id Seq -- the sequence """ with open(output_filename, 'w') as f: for seqid in seqids: r = fasta_d[seqid] f.write(">{0}\n{1}\n".format(r.id, r.seq))
5,306,527
def _save_cover_image(dirname, filename): """Save the cover image to the album folder. :arg str dirname: the album folder name :arg str filename: the cover image file name :return: ``True`` if the cover image was saved, otherwise ``False`` """ image_ext = os.path.splitext(filename)[1] if i...
5,306,528
def then(name, converters=None): """Then step decorator. :param name: Step name or a parser object. :param converters: Optional `dict` of the argument or parameter converters in form {<param_name>: <converter function>}. :return: Decorator function for the step. """ retu...
5,306,529
def get_stored_username(): """get stored username if available""" file_name = 'chapter_10/remember.json' try: with open(file_name) as f_o: usern = json.load(f_o) except FileNotFoundError: return None else: return usern
5,306,530
def evaluate(gt_file, re_file, logger=None): """ This function is reformed from MSCOCO evaluating code. The reference sentences are read from gt_file, the generated sentences to be evaluated are read from res_file """ gts = json.load(open(gt_file, 'r')) scorers = [ (Bleu(4), ["Bleu...
5,306,531
def redis_error_handler(func): """Decorator for returning better errors if Redis is unreachable""" def wrapper(*args, **kwargs): try: if 'body' in kwargs: # Our get/patch functions don't take body, but the **kwargs # in the arguments to this wrapper cause it t...
5,306,532
def find_versions_from_versioncontrol(dependencies): """Determine whether a file is under version control, and if so, obtain version information from this.""" for dependency in dependencies: if dependency.version == "unknown": try: wc = versioncontrol.get_working_copy(...
5,306,533
def clean_log(): """Remove all log files""" log_files = glob.glob('*_LOG_*') for log in log_files: os.remove(log) return
5,306,534
def _remove_readonly(func, path, _): """Clear the readonly bit and reattempt the removal""" os.chmod(path, stat.S_IWRITE) func(path)
5,306,535
def findDistortionCoefficients(filename,Nx,Ny,method='cubic'): """ Fit L-L coefficients to distortion data produced by Vanessa. """ #Load in data d = np.transpose(np.genfromtxt(filename,skip_header=1,delimiter=',')) #Compute angle and radial perturbations x0,y0,z0 = d[2:5] t0 = np.arcta...
5,306,536
def keras_test(func): """Function wrapper to clean up after TensorFlow tests. # Arguments func: test function to clean up after. # Returns A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, **kwargs): output = func(*args, **kwargs) ke...
5,306,537
def drawbox(img,bbox): """ skeleton function which draws bbox on an img :param img: :param bbox: :return: """ return img
5,306,538
def is_valid_route_protection(protection: Any) -> bool: """Checks if the protection text is a valid protection name. Returns True if valid, False if not.""" if not isinstance(protection, str): return False # Once the protection scheme is established, this can be loosened. # return protection...
5,306,539
def test_default_callback(): """Sample request not specifying callback.""" spider = MySpider() request = scrapy.Request('http://example.com/') request_dict = request_to_dict(request, spider) assert isinstance(request_dict, dict) assert request_dict['url'] == 'http://example.com/' assert requ...
5,306,540
def main() -> None: """Start server and train a number of rounds.""" args = parse_args() # Configure logger configure(identifier="server", host=args.log_host) server_setting = get_setting(args.setting).server log(INFO, "server_setting: %s", server_setting) # Load evaluation data (_, _...
5,306,541
def open_CsvDataset(filename, delimiter=',', M='M', T='T', tlabels=False, varnames=False, parameter='climate_var'): """opens a .csv file formatted like n_samples x m_features. returns Xarray DataArray with X=0, Y=0, Samples=N, features=M. Can include labels for each sample, and labels for each feature. """ assert Pa...
5,306,542
def paster(*args, **kwargs): """ Call a paster command. All arguments are parsed and passed on to the command. The ``--config`` option is automatically appended. By default, an ``AssertionError`` is raised if the command exits with a non-zero return code or if anything is written to STDERR. ...
5,306,543
def restart_cmd(jail, soft): """ Looks for the jail supplied and passes the uuid, path and configuration location to stop_jail and start_jail. """ lgr = logging.getLogger('ioc_cli_restart') jails, paths = IOCList("uuid").list_datasets() if jail == "ALL": for j in jails: ...
5,306,544
def parse_coalesce_object_response(coalesce_object_response): """ Parse a response from RpcGetObject. Returns (modification time, inode no., no. writes). """ return (_ctime_or_mtime(coalesce_object_response), coalesce_object_response["InodeNumber"], coalesce_object_response[...
5,306,545
def main(input_filepath, output_file): """ Runs specific data processing and aggregations to turn interim data from (../interim) into the final dataset. Examples / Ideas: - Extract columns from different files in interim data - Aggregate over grouped data """ logger.info("Making final d...
5,306,546
def make_hist_dict( bin_edges: Dict[str, Dict[str, str]], adj: bool, hist_metric_list: List[str] = HISTS, label_delimiter: str = "_", ) -> Dict[str, str]: """ Generate dictionary of Number and Description attributes to be used in the VCF header, specifically for histogram annotations. :para...
5,306,547
def create_running_ema(alpha=0.95, initial=0): """ Returns a function to compute running exponentially weighted averaging Args: alpha (0.95): relative importance of accumulated value initial (0): initial value """ return partial(running_f, f=lambda acc, elem: alpha*a...
5,306,548
def get_tarred_char_dataset( config: dict, shuffle_n: int, global_rank: int, world_size: int, augmentor: Optional['AudioAugmentor'] = None ) -> audio_to_text.TarredAudioToCharDataset: """ Instantiates a Character Encoding based TarredAudioToCharDataset. Args: config: Config of the TarredAudioTo...
5,306,549
def import_flow_env(env_name, render, shared, maddpg, evaluate): """Import an environment from the flow/examples folder. This method imports the flow_params dict from the exp_configs folders in this directory and generates an appropriate FlowEnv object. Parameters ---------- env_name : str ...
5,306,550
def gtf_row_to_bed(row): """ Converts gtf row to bed format: Args: row (pd.Series): One GTF row Returns: pd.Series([chrom, start, end, ensID, "."]) """ # Extract required fields chrom = str(row[0]) strand = row[6] # Take end of transcript for forward/reverse strand if...
5,306,551
def getFileName(prompt): """Prompts the user for a valid file which it returns. """ while True: fileName = input(prompt+" ") if os.path.exists(fileName): return fileName else: print("File not found! Make sure that the file is inside this directory.")
5,306,552
def build_gas_stores(gas_stores, current_timestep): """Set up the initial system from a list of interventions Write in the all interventions with the intervention_name ``gasstore`` to the GasStore table. Arguments --------- gas_stores : list Notes ----- GasStorage" ( Stora...
5,306,553
def mtotal_from_mtotal_source_z(total_mass_source, z): """Return the detector-frame total mass of the binary given samples for the source-frame total mass and redshift """ return _detector_from_source(total_mass_source, z)
5,306,554
def sim_spiketrain(spike_param, n_samples, method, refractory=None, **kwargs): """Simulate a spike train. Parameters ---------- spike_param : float Parameter value that controls the simulated spiking. rate or probability. For `prob` or `binom` methods, this is the probability of spiking...
5,306,555
def weight_mask_variable(var, scope): """Create a mask for the weights. This function adds a variable 'mask' to the graph. Args: var: the weight variable that needs to be masked scope: The variable scope of the variable var Returns: the mask variable of the same size and shape as var, initialized...
5,306,556
def youngest_oldest(_dict): """Return youngest and oldest billionaires.""" oldest = None youngest = float('inf') for person in _dict: if person['age'] < 80: if oldest is not None: if person['age'] > oldest['age']: oldest = person else: ...
5,306,557
def build_optimizer(model: nn.Module, args: Namespace) -> Optimizer: """ Builds an Optimizer. :param model: The model to optimize. :param args: Arguments. :return: An initialized Optimizer. """ if hasattr(model, 'ffn'): ignored_params = list(map(id, model.ffn.parameters())) else...
5,306,558
def mock_request(params: dict = None, data=None, **headers) -> Request: """ Mocks a Request object so the @pre_process decorator can inject it as an APIRequest. :param params: Optional query parameter dict for the request. Will be set to {} if omitted. :param data: Optional data/...
5,306,559
def get_management_token() -> dict: """ Gets a token for contacting the management endpoint of auth0. Returns: dict -- Dictionary with token and expirey information. """ payload = { 'grant_type': 'client_credentials', 'client_id': CLIENT_ID, 'client_secret': CLIENT_S...
5,306,560
def empty_put_with_manifest(cont, obj, headers): """ Perform an empty PUT (headers only) to the empty manifest object. Manifest object's location is dictated by command-line params. python-swiftclient Connection can't take query params, so we need this helper method. """ conn = CONN.http_co...
5,306,561
def test_traefik_api_default(): """ Test default traefik api authentication settings with no overrides """ c = apply_mock_config({}) assert c.TraefikTomlProxy.traefik_api_username == "api_admin" assert len(c.TraefikTomlProxy.traefik_api_password) == 0
5,306,562
def test_to_graph_should_return_identifier() -> None: """It returns an identifier graph isomorphic to spec.""" attribute = Attribute() attribute.identifier = "http://example.com/attributes/1" src = """ @prefix dct: <http://purl.org/dc/terms/> . @prefix rdf: <http://www.w3.org/1999/02/22...
5,306,563
def simulate(t=1000, poly=(0.,), sinusoids=None, sigma=0, rw=0, irw=0, rrw=0): """Simulate a random signal with seasonal (sinusoids), linear and quadratic trend, RW, IRW, and RRW Arguments: t (int or list of float): number of samples or time vector, default = 1000 poly (list of float): polynomial c...
5,306,564
def get_rgb_image(image: Image): """Convert the image to rgb format.""" # logger.debug("Computing rgb image") if image.band == 'rgb': red = image['red'] green = image['green'] blue = image['blue'] rgb = np.ma.dstack([red, green, blue]) else: gray = image[image...
5,306,565
def main(): """Report graph creator command line""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( 'reportfile', type=argparse.FileType('r'), help="test report file generated by `guesslang --test TESTDIR`") parser.add_argument( '-d', '--debug', defaul...
5,306,566
def gen_cookie(username, hash_password): """ Build secure cookie content as a string containing: - content length (excluding length itself) - role_name - 16 first chars of the hash password Part of hash password is there for 2 main reasons: 1/ If the cookie secret key is st...
5,306,567
def line_generic(pos, color=(1, 1, 1, 1), width=0.1, antialias=True, mode='line_strip'): """ Add a pyqtgraph.opengl.GLLinePlotItem to GPGLViewWidget, with exactly the same arguments. For detail, consult documentation of pyqtgraph.opengl.GLLinePlotItem: http://www.pyqtgraph.org/documentation/3dgraphic...
5,306,568
def do_config_set_add(gc, args): """Add a config_set.""" fields = dict(filter(lambda x: x[1] is not None, vars(args).items())) # Filter out values we can't use CREATE_PARAMS = daisyclient.v1.config_sets.CREATE_PARAMS fields = dict(filter(lambda x: x[0] in CREATE_PARAMS, fields.items())) ...
5,306,569
def create_dict(obj, columns): """ Create a dict, given a database record and an ordered list of columns. Mind the order of column names in the columns list """ try: new_obj = {} for col in range(len(columns)): new_obj[columns[col]] = obj[col] return new_obj ...
5,306,570
def filepath_result_format(classifier_name, task, res, filepath): """ Helper function to produce result dictionary using filepath filepath (str) : (e.g. '../../inferred_features/code_ss_w2v_multiclass_7.pkl' """ filepath = filepath.split("/")[-1] dims = filepath.split(".")[0].split("_") if d...
5,306,571
def get_optimisation_status(): """Get the status of an optimisation job.""" opt_job_id = request.args.get('opt-job-id') opt_job = database.opt_jobs.find_one({'_id': ObjectId(opt_job_id)}) return jsonify({'_id': opt_job_id, 'status': opt_job['status']})
5,306,572
def makeCorrelationMatrixFromDictionary(value_dictionary, keys=[], matrix_file_name="temporary_matrix_file.txt", key_file_name="temporary_key_file.txt"): """ Returns numpy.matrix: matrix object of correlation coefficients, symmetric matrix with a diagonal of ones Returns list: list of keys that correspond to the row...
5,306,573
def pad(value, seq: Seq, size: int = None, step: int = None) -> Iter: """ Fill resulting sequence with value after the first sequence terminates. Args: value: Value used to pad sequence. seq: Input sequence. size: Optional minimum size of sequence...
5,306,574
def str_to_state(str_state): """ Reads a sequence of 9 digits and returns the corresponding state. """ assert len(str_state) == 9 and sorted(str_state) == list('012345678') return tuple(int(c) for c in str_state)
5,306,575
def linearly_interpolate(colors: ColorMatrix, count: int): """ Generates :count: colors from this palette, interpolating intermediate colors if necessary. TODO(saumitro): Lift interpolation to perceptual space """ palette_size = len(colors) if count <= palette_size: return colors[:c...
5,306,576
def load_10x_h5(file, genome): """Load count matrix in 10x H5 format Adapted from: https://support.10xgenomics.com/single-cell-gene-expression/software/ pipelines/latest/advanced/h5_matrices Args: file (str): Path to H5 file genome (str): genome, top level h5 group Ret...
5,306,577
def to_dataset_entity_id( full_name: str, platform: DataPlatform, account: Optional[str] = None ) -> EntityId: """ converts a dataset name, platform and account into a dataset entity ID """ return EntityId( EntityType.DATASET, DatasetLogicalID(name=full_name, platform=platform, accou...
5,306,578
def parse_args(): """parsing and configuration""" parser = argparse.ArgumentParser(description="Generate ImageNet10 using BigGAN") # for training generative model parser.add_argument('--gan_type', type=str, default='BigGAN', help='The type of GAN') parser.add_argument('--dataset', type=str, default...
5,306,579
def get_collection_table_name(node, intermine_model): """ Get the table name for this collection :param node: :param intermine_model: :return: (table-name, reference-column-name). table-name will be null if there isn't a collection table for this node """ if 'reverse-reference' in ...
5,306,580
def parse_xml(path: str) -> Element: """Parse an XML file from a path to a GZIP file.""" t = time.time() log.info('parsing xml from %s', path) with gzip.open(path) as xml_file: tree = ET.parse(xml_file) log.info('parsed xml in %.2f seconds', time.time() - t) return tree.getroot()
5,306,581
def get(ctx, # Mandatory main parameter scheduleid): """You can use the GetSchedule method to retrieve information about a scheduled snapshot. You can see information about a specific""" """schedule if there are many snapshot schedules in the system. You also retrieve information about mor...
5,306,582
def apply_qos(): """POST QOS configuration from form data""" find_int_num = [i for i in request.form.get("interface") if i not in string.ascii_letters] find_int_type = [i for i in request.form.get("interface") if i in string.ascii_letters] build_config = BuildConfig.build_interface_qos(''.join(find_int...
5,306,583
def _readdir(DIR): """Implementation of perl readdir in scalar context""" try: result = (DIR[0])[DIR[1]] DIR[1] += 1 return result except IndexError: return None
5,306,584
def Update(version): """Requests an update of the toolchain to the specific hashes we have at this revision. The update outputs a .json of the various configuration information required to pass to vs_env.py which we use in |SetEnvironmentForCPU()|. """ depot_tools_path = FindDepotTools() get_toolchain_arg...
5,306,585
def compute_normalization(data): """ Write a function to take in a dataset and compute the means, and stds. Return 6 elements: mean of s_t, std of s_t, mean of (s_t+1 - s_t), std of (s_t+1 - s_t), mean of actions, std of actions """ l = [] for a in [data['observations'], (data['next_observatio...
5,306,586
def fast_back_test(bars: List[RawBar], init_n: int, strategy: Callable, html_path: str = None, max_bi_count: int = 50, bi_min_len: int = 7, signals_n: int = 0, ): """快速回测系统(暂时仅支持多头交易回...
5,306,587
def test_descriptor_proxy(): """ Test that the descriptor is properly "installed" in the class """ # The test record record = TestRecord() # This must raise exception, since we're inputting wrong data with pytest.raises(ValidationError): record.first_field = 'AAAA' # Test assig...
5,306,588
def test_download_awards_v2_status_endpoint(client, award_data): """Test the transaction status endpoint.""" dl_resp = client.post( "/api/v2/bulk_download/awards", content_type="application/json", data=json.dumps({"filters": {}, "columns": []}) ) resp = client.get("/api/v2/download/status/?fil...
5,306,589
def convert_cidr_to_canonical_format(value): """CIDR is validated and converted to canonical format. :param value: The CIDR which needs to be checked. :returns: - 'value' if 'value' is CIDR with IPv4 address, - CIDR with canonical IPv6 address if 'value' is IPv6 CIDR. :raises: InvalidInpu...
5,306,590
def test_datasaver_multidimarrayparameter_as_array(SpectrumAnalyzer, bg_writing): """ Test that inserting multidim Arrrayparameters as array works as expected """ array_param = SpectrumAnalyzer.multidimspectrum meas = Measurement() meas.register...
5,306,591
def g_xyz_eclip_planet_eqxdate(name, jde): """ Parameters ---------- name : str Name of the planet jde : float Julian Day of the ephemeris Returns ------- np.array[3] """ h_xyz_eclipt_earth = h_xyz_eclip_eqxdate("Earth",jde) h_xyz_eclipt_planet = h_...
5,306,592
def get_cannot_db(state_brief_db): """ Determine for each position register (identified by acceptance_id) the set of position registers. The condition for this is given at the entrance of this file. RETURNS: map: acceptance_id --> list of pattern_ids that it cannot be c...
5,306,593
def _unique_numpy_dtype_string(dtype): """Private function providing a standardized string used to characterize a Numpy dtype """ dt = np.dtype(dtype) try: s = dt[0].str except KeyError: s = dt.str return s[1:]
5,306,594
def iterate_bucket_items(bucket, start_with=""): """ Generator that iterates over all objects in a given s3 bucket See http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.list_objects_v2 for return data format :param bucket: name of s3 bucket :return: dict of metadata for...
5,306,595
def _progress(msg, warn=False): """ Consistent and "pretty" progress logs. """ click.echo(click.style(" -> ", fg="blue"), nl=False) if warn: fg = "red" else: fg = "green" click.echo(click.style(msg, fg=fg))
5,306,596
def debug_on(is_debug): """Sets debug logging flag""" if is_debug: set_level(logging.DEBUG) else: set_level(logging.INFO)
5,306,597
def powsimp(expr, deep=False): """ Usage ===== powsimp(expr, deep) -> reduces expression by combining powers with similar bases and exponents. Notes ===== If deep is True then powsimp() will also simplify arguments of functions. By default deep is set to False. ...
5,306,598
def project_to_finest_grid(*trees): """... """ def single_tree_function(tree): for level in range(tree.max_level): if tree.dimension == 1: for i in range(2**level): index = mesh.z_curve_index(tree.dimension, level, i) ...
5,306,599