content
stringlengths
22
815k
id
int64
0
4.91M
def load_spectr_folder(path, result_format="xy"): """ Load a folder containing demod scope files. Return a list of 6 elements (one pere demod), which are either ``None``, if there's not data for this demod, or contain that demod's trace. """ data=[] for demod in range(1,7): file_path=os...
5,354,600
def play_game(player_count: int, board: BattleshipBoard) -> None: """Play a game of Battleship with a given number of players.""" os.system("clear") total_guesses = 0 won_game = False while total_guesses < GUESSES_COUNT * player_count: # determine the current player and the remaining gue...
5,354,601
def make_row(filename, num_cols, col_names): """ Given a genome file, create and return a row of kmer counts to be inerted into the mer matrix. """ # Filepath thefile = str(filename[0]) # Get the genome id from the filepath genomeid = filename[0].split('/')[-1] genomeid = genomeid.s...
5,354,602
def analytic_overlap_NM( DQ: float, w1: float, w2: float, n1: int, n2: int ) -> float: """Compute the overlap between two displaced harmonic oscillators. This function computes the overlap integral between two harmonic oscillators with frequencies w1, w2 that are dis...
5,354,603
def init_manager(mocker): """Fixture to initialize a style constant.""" mocker.patch.object(manager.StyleManager, "__init__", lambda x: None) def _create(): return manager.StyleManager() return _create
5,354,604
def GaussLegendre(f, n): """Gauss-Legendre integration on [-1, 1] with n points.""" x, w = numint.GaussLegendre(n) I = np.dot(f(x), w) return I
5,354,605
def directory_item_groups( items: List[Item], level: int ) -> Dict[str, List[Item]]: """Split items into groups per directory at the given level. The level is relative to the root directory, which is at level 0. """ module_items = OrderedDict() for item in items: module_items.setdefault(...
5,354,606
def mergeSort(x): """ Function to sort an array using merge sort algorithm """ if len(x) == 0 or len(x) == 1: return x else: middle = len(x)//2 a = mergeSort(x[:middle]) b = mergeSort(x[middle:]) return merge(a,b)
5,354,607
async def join( db, query: Union[dict, str], document: Optional[Dict[str, Any]] = None, session: Optional[AsyncIOMotorClientSession] = None, ) -> Optional[Dict[str, Any]]: """ Join the otu associated with the supplied ``otu_id`` with its sequences. If an OTU is passed, the document will not...
5,354,608
def cp_solve(V, E, lb, ub, col_cov, cuts=[], tl=999999): """Solves a partial problem with a CP model. Args: V: List of vertices (columns). E: List of edges (if a transition between two columns is allowed). col_cov: Matrix of the zone coverages of the columns (c[i][j] == 1 if ...
5,354,609
def file_exists(path: Text): """ Returns true if file exists at path. Args: path (str): Local path in filesystem. """ return file_io.file_exists_v2(path)
5,354,610
def _get_page_num_detail(): """ 东方财富网-数据中心-特色数据-机构调研-机构调研详细 http://data.eastmoney.com/jgdy/xx.html :return: int 获取 机构调研详细 的总页数 """ url = "http://data.eastmoney.com/DataCenter_V3/jgdy/xx.ashx" params = { "pagesize": "5000", "page": "1", "js": "var SZGpIhFb", "p...
5,354,611
def different_name(name: str) -> Iterator[str]: """Look for new names that don't conflict with existing names.""" yield name for n in itertools.count(2): yield name + str(n)
5,354,612
def freeze_session( session, keep_var_names=None, output_names=None, clear_devices=True): """ Freezes the state of a session into a pruned computation graph. """ graph = session.graph with graph.as_default(): freeze_var_names = list(set(v.op.name for v in tf.g...
5,354,613
def send_mail(subject, body, recipient_list, bcc_list=None, from_email=None, connection=None, attachments=None, fail_silently=False, headers=None, cc_list=None, dc1_settings=None, content_subtype=None): """ Like https://docs.djangoproject.com/en/dev/topics/email/#send-mail Attachment is a list...
5,354,614
def distinct_by_t(func): """ Transformation for Sequence.distinct_by :param func: distinct_by function :return: transformation """ def distinct_by(sequence): distinct_lookup = {} for element in sequence: key = func(element) if key not in distinct_lookup: ...
5,354,615
def test_parse_sections_exception(iniparse_tester, info, expected): """ Tests our base function used to parse sections before we do any processing Ensures: * we can handle comments around sections. * caps issues """ iniparse_tester.run_parsing_test(parse_sections, info, expected, Exce...
5,354,616
def are_datasets_created(path, number_of_datasets, suffix='parts'): """Checks existence and reads the dataset ids from the datasets file in the path directory """ dataset_ids = [] try: with open("%s%sdataset_%s" % (path, os.sep, suffix)) as datasets_file: for line in datasets...
5,354,617
def _get_partition_info(freq_unit): """ 根据平台单位获取tdw的单位和格式 :param freq_unit: 周期单位 :return: tdw周期单位, 格式 """ if freq_unit == "m": # 分钟任务 cycle_unit = "I" partition_value = "" elif freq_unit == "H": # 小时任务 cycle_unit = "H" partition_value = "YYYYMM...
5,354,618
def metadata_property(k: str) -> property: """ Make metadata fields available directly on a base class. """ def getter(self: MetadataClass) -> Any: return getattr(self.metadata, k) def setter(self: MetadataClass, v: Any) -> None: return setattr(self.metadata, k, v) return prop...
5,354,619
def write_case_to_yaml(yamFile, data): """ Write the test case to yaml. param: yamFile: Yaml file path. return: There is no. """ with io.open(yamFile, 'w', encoding='utf-8') as fp: ordered_dump(data, fp, Dumper=yaml.SafeDumper, allow_unicode=True, default_flow...
5,354,620
def test_empty_pop(): """ test for pop on empty stack""" with pytest.raises(IndexError): empty = Stack() empty.pop()
5,354,621
def _single_saver(save, pack, outfile, binary, ext, **kwargs): """Call a font saving function, providing a stream.""" # use standard streams if none provided if not outfile or outfile == '-': outfile = sys.stdout.buffer if len(pack) == 1: # we have only one font to deal with, no need to ...
5,354,622
def adjust_contrast(img, contrast_factor): """Adjust contrast of an RGB image. Args: img (Tensor): Image to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while...
5,354,623
async def handle_private_message_only(ctx, exc, calls=0): """ Exception handler for :exc:`~discord.ext.commands.PrivateMessageOnly`. Informs the user that the command can only be used in private messages. Has a cooldown of 10 seconds per user. """ if calls > 0: return ...
5,354,624
def license_wtfpl(): """ Create a license object called WTF License. """ return mixer.blend(cc.License, license_name="WTF License")
5,354,625
def _add_embedding_column_map_fn( k_v, original_example_key, delete_audio_from_output, audio_key, label_key, speaker_id_key): """Combine a dictionary of named embeddings with a tf.train.Example.""" k, v_dict = k_v if original_example_key not in v_dict: raise ValueError( f'Orig...
5,354,626
def modelf(input_shape): """ Function creating the model's graph in Keras. Argument: input_shape -- shape of the model's input data (using Keras conventions) Returns: model -- Keras model instance """ X_input = Input(shape = input_shape) ### START CODE HERE ### ...
5,354,627
def test_perform_prevalidation_option(postgres, db_conn, tmpdir, monkeypatch, mocked_config): """Test pre-validation is not performed if option is turned off in the config.""" files_to_zip = ['unittest_data/operator/operator1_with_rat_info_20160701_20160731.csv'] zip_files_to_tmpdir(files_to_zip, tmpdir) ...
5,354,628
def merge_parameters(col_orig, col_new, klass, name_attr="name", value_attr="value"): """This method updates col_orig removing any that aren't in col_new, updating those that are, and adding new ones using klass as the constructor col_new is a dict col_orig is a list klass is a type """ ...
5,354,629
def get_mbed_official_psa_release(target=None): """ Creates a list of PSA targets with default toolchain and artifact delivery directory. :param target: Ask for specific target, None for all targets. :return: List of tuples (target, toolchain, delivery directory). """ psa_targets_release_li...
5,354,630
def diff_files(expectfile, actualfile): """Diff the files, and display detailed output if any""" cmd = ['diff', '-wB', expectfile, actualfile] proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sys.stderr) (stdout, _unused) = proc.communicate() if isi...
5,354,631
def assignSentenceIds(tokLayer: TokenLayer): """ propagate sentence IDs to the given layer from a higher layer """ if not tokLayer: return for tok in tokLayer: currSentId = None if tok.linksHigher and not isinstance(tok.linksHigher[0], DeletionToken): currSentId...
5,354,632
def match_l2(X, Y, match_rows=False, normalize=True): """Return the minimum Frobenius distance between X and Y over permutations of columns (or rows).""" res = _match_factors(X, Y, l2_similarity, match_rows) res['score'] = np.sqrt(-res['score']) if normalize: res['score'] = res['score'] / np.lin...
5,354,633
def subparser(subparsers): """Define the `kevlar mutate` command-line interface.""" desc = 'Apply the specified mutations to the genome provided.' subparser = subparsers.add_parser('mutate', description=desc) subparser.add_argument('-o', '--out', metavar='FILE', help='output...
5,354,634
def doNMFDriedger(V, W, L, r = 7, p = 10, c = 3, plotfn = None, plotfnw = None): """ Implement the technique from "Let It Bee-Towards NMF-Inspired Audio Mosaicing" :param V: M x N target matrix :param W: An M x K matrix of template sounds in some time order\ along the second axis :param ...
5,354,635
def extract_red(image): """ Returns the red channel of the input image. It is highly recommended to make a copy of the input image in order to avoid modifying the original array. You can do this by calling: temp_image = np.copy(image) Args: image (numpy.array): Input RGB (BGR in OpenCV) image. ...
5,354,636
def _cleaned_data_to_key(cleaned_data): """ Return a tuple representing a unique key for the cleaned data of an InteractionCSVRowForm. """ # As an optimisation we could just track the pk for model instances, # but that is omitted for simplicity key = tuple(cleaned_data.get(field) for field in DU...
5,354,637
def add_xspice_to_circuit(part, circuit): """ Add an XSPICE part to a PySpice Circuit object. Args: part: SKiDL Part object. circuit: PySpice Circuit object. """ # The device reference is always the first positional argument. args = [_get_spice_ref(part)] # Add the pins to...
5,354,638
def schedule_for_cleanup(request, syn): """Returns a closure that takes an item that should be scheduled for cleanup. The cleanup will occur after the module tests finish to limit the residue left behind if a test session should be prematurely aborted for any reason.""" items = [] def _append_clea...
5,354,639
async def startup_event(): """Startup event. This is called after the server is started and: - connects to the database - loads roles """ retry_interval = 5 while True: try: await Postgres.connect() except Exception as e: msg = " ".join([str(k...
5,354,640
def build_cooccurrences(sequences: List[List[int]], cache: defaultdict, window=3): """ It updates a shared cache for by iteratively calling 'bigram_count' :param sequences: The input sequences :param cache: The current cache :param window: The size of window to look around a central word """ ...
5,354,641
def unpickle_context(content, pattern=None): """ Unpickle the context from the given content string or return None. """ pickle = get_pickle() if pattern is None: pattern = pickled_context_re match = pattern.search(content) if match: return pickle.loads(base64.standard_b64deco...
5,354,642
def ask_openid(request, openid_url, redirect_to, on_failure=None, sreg_request=None): """ basic function to ask openid and return response """ on_failure = on_failure or signin_failure trust_root = getattr( settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/' ) if xri.ide...
5,354,643
def get_accuracy_ANIL(logits, targets): """Compute the accuracy (after adaptation) of MAML on the test/query points Parameters ---------- logits : `torch.FloatTensor` instance Outputs/logits of the model on the query points. This tensor has shape `(num_examples, num_classes)`. target...
5,354,644
def stream_logger(): """ sets up the logger for the Simpyl object to log to the output """ logger = logging.Logger('stream_handler') handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(asctime)s %(message)s')) logger.addHandler(handler) return logger
5,354,645
def sql_coordinate_frame_lookup_key(bosslet_config, coordinate_frame): """ Get the lookup key that identifies the coordinate fram specified. Args: bosslet_config (BossConfiguration): Bosslet configuration object coordinate_frame: Identifies coordinate frame. Returns: coordinate...
5,354,646
def entry_from_resource(resource, client, loggers): """Detect correct entry type from resource and instantiate. :type resource: dict :param resource: One entry resource from API response. :type client: :class:`~google.cloud.logging.client.Client` :param client: Client that owns the log entry. ...
5,354,647
def make_preprocesser(training_data): """ Constructs a preprocessing function ready to apply to new dataframes. Crucially, the interpolating that is done based on the training data set is remembered so it can be applied to test datasets (e.g the mean age that is used to fill in missing values for '...
5,354,648
def get_breakeven_prob(predicted, threshold = 0): """ This function calculated the probability of a stock being above a certain threshhold, which can be defined as a value (final stock price) or return rate (percentage change) """ predicted0 = predicted.iloc[0,0] predicted = predicted.iloc[-1] p...
5,354,649
def test_comoving_vol_init_invalid_cosmology(comoving_vol_converter): """Test the init method when an invalid cosmology is given""" with pytest.raises(RuntimeError) as excinfo: ComovingDistanceConverter.__init__( comoving_vol_converter, cosmology='Planck' ) assert 'Could not get ...
5,354,650
def trim_whitespace(sub_map, df, source_col, op_col): """Trims whitespace on all values in the column""" df[op_col] = df[op_col].transform( lambda x: x.strip() if not pd.isnull(x) else x) return df
5,354,651
def beneficiary(): """ RESTful CRUD controller """ # Normally only used in Report # - make changes as component of Project s3db.configure("project_beneficiary", deletable = False, editable = False, insertable = False, ) li...
5,354,652
def test__hr_grad(): """ test automech.py hr_scan """ tsks = '\tspc hr_grad runlvl=lvl_scf inplvl=lvl_scf tors_model=1dhrfa' drivers = '\tes' # Format the run.dat with the run-save dir paths with open(RUN_TEMP_PATH, 'r') as file_obj: run_str = file_obj.read() with open(RUN_DAT_...
5,354,653
def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg() #cfg.merge_from_file(args.config_file) #cfg.merge_from_file(model_zoo.get_config_file("/data/mostertrij/tridentnet/detectron2/configs/COCO-Detection/my_script_faster_rcnn_X_101_32x8d_FPN_3x.yaml")) cfg.merge_fr...
5,354,654
def get_distinct_quotation_uid(*args, **kwargs): """ 获取用户 :param args: :param kwargs: :return: List """ field = 'uid' return map(lambda x: getattr(x, field), db_instance.get_distinct_field(Quotation, field, *args, **kwargs))
5,354,655
def present_from(ref: pathlib.Path, obs: pathlib.Path) -> pathlib.Path: """Build a somehow least surprising difference folder from ref and obs.""" ref_code = ref.parts[-1] if obs.is_file(): return pathlib.Path(*obs.parts[:-1], f'diff-of-{obs.parts[-1]}') present = pathlib.Path(*obs.parts[:-1], ...
5,354,656
def dataQ_feeding(filename_queue, feat_dim, seq_len): """ Reads and parse the examples from alignment dataset Args: filename_queue: A queue of strings with the filenames to read from. Returns: An object representing a single example, with the following fields: MFCC sequence: 200 * 39 d...
5,354,657
def dummy_backend(_, **kwargs): """ Dummy backend always returning stats with 0 """ return _default_statement()
5,354,658
def comp_mass(self): """Compute the mass of the Frame Parameters ---------- self : Frame A Frame object Returns ------- Mfra: float Mass of the Frame [kg] """ Vfra = self.comp_volume() # Mass computation return Vfra * self.mat_type.struct.rho
5,354,659
def write_DS9reg(x, y, filename=None, coord='IMAGE', ptype='x', size=20, c='green', tag='all', width=1, text=None): """Write a region file for ds9 for a list of coordinates. Taken from Neil Crighton's barak.io Parameters ---------- x, y : arrays of floats, shape (N,) The c...
5,354,660
def bug_xmltoolkit3(): """ Check that close doesn't accept optional argument >>> parser = sgmlop.XMLParser() >>> parser.feed("foo") 0 >>> parser.close("bar") Traceback (most recent call last): TypeError: close() takes exactly 0 arguments (1 given) >>> parser.close() 0...
5,354,661
def checkInputDataValid(lstX:list=None,lstY:list=None,f:object=None)->(int,tuple): """ :param lstX: :param lstY: :param f: :return: int, (int,list, int,int) """ ret=-1 rettuple=(-1,[],-1,-1) if lstX is None or lstY is None: msg = "No input lists of arrays" msg2log(No...
5,354,662
def parseManualTree(node): """Parses a tree of the manual Main_Page and returns it through a list containing tuples: [(title, href, [(title, href, [...]), ...]), ...]""" if node.nodeType != Node.ELEMENT_NODE: return [] result = [] lastadded = None for e in node.childNodes: if e.nodeType ...
5,354,663
def test_rf_frequency_view(exopy_qtbot, root_view, task_workbench): """Test SetRFFrequencyTask widget outisde of a LoopTask. """ task = SetRFFrequencyTask(name='Test') root_view.task.add_child_task(0, task) show_and_close_widget(exopy_qtbot, RFFrequencyView(task=task, root=root_view))
5,354,664
def main(): """ Main program entry point. """ config_manager.register(MainConfig) parser = argparse.ArgumentParser(description='Bandit and Bayesian Optimization Experimental Framework.') parser.add_argument("task", type=parse_task) parser.add_argument("experiment", nargs='?') parser.add...
5,354,665
def _create_hub_module(save_path): """Create a TensorFlow Hub module for testing. Args: save_path: The directory path in which to save the model. """ # Module function that doubles its input. def double_module_fn(): w = tf.Variable([2.0, 4.0]) x = tf.compat.v1.placeholder(dtype=tf.float32) hu...
5,354,666
def validation_by_method(mapping_input: Union[List, Dict[str, List]], graph: nx.Graph, kernel: Matrix, k: Optional[int] = 100 ) -> Tuple[Dict[str, list], Dict[str, list]]: """Repeated holdout validation by diffustion...
5,354,667
async def test_async_setup_raises_entry_not_ready(opp: OpenPeerPower): """Test that it throws ConfigEntryNotReady when exception occurs during setup.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"}, ) config_entry.add_to_op...
5,354,668
def headnode_connect_network(headnode, hnic, network): """Connect a headnode's hnic to a network. Raises IllegalStateError if the headnode has already been started. Raises ProjectMismatchError if the project does not have access rights to the given network. Raises BadArgumentError if the network ...
5,354,669
def get_about_agent(): """ This method returns general information of the agent, like the name and the about. Args: @param: token: Authentication token. """ data = request.get_json() if "token" in data: channel = get_channel_id(data["token"]) if channel is not None: ...
5,354,670
def add_namespace(tree, new_ns_name, new_ns_uri): """Add a namespace to a Schema. Args: tree (etree._ElementTree): The ElementTree to add a namespace to. new_ns_name (str): The name of the new namespace. Must be valid against https://www.w3.org/TR/REC-xml-names/#NT-NSAttName new_ns_ur...
5,354,671
def RZ(angle, invert): """Return numpy array with rotation gate around Z axis.""" gate = np.zeros(4, dtype=complex).reshape(2, 2) if not invert: gate[0, 0] = np.cos(-angle/2) + np.sin(-angle/2) * 1j gate[1, 1] = np.cos(angle/2) + np.sin(angle/2) * 1j else: gate[0, 0] = np.cos(-an...
5,354,672
def _create_unicode(code: str) -> str: """ Добавление экранизирующего юникод кода перед кодом цвета :param code: Код, приоритетно ascii escape color code :return: """ return u'\u001b[{}m'.format(code)
5,354,673
def compact_axis_angle_from_matrix(R): """Compute compact axis-angle from rotation matrix. This operation is called logarithmic map. Note that there are two possible solutions for the rotation axis when the angle is 180 degrees (pi). We usually assume active rotations. Parameters ---------- ...
5,354,674
def _generate_IPRange(Range): """ IP range to CIDR and IPNetwork type Args: Range: IP range Returns: an array with CIDRs """ if len(Range.rsplit('.')) == 7 and '-' in Range and '/' not in Range: if len(Range.rsplit('-')) == 2: start_ip, stop_ip = Range.rspli...
5,354,675
def is_dict_homogeneous(data): """Returns True for homogeneous, False for heterogeneous. An empty dict is homogeneous. ndarray behaves like collection for this purpose. """ if len(data) == 0: return True k0, v0 = next(iter(data.items())) ktype0 = type(k0) vtype0 = type(v0) i...
5,354,676
def translate(item: Union[Callable[P, T], Request]) -> Union[Generator[Any, Any, None], Callable[P, T]]: """Override current language with one from language header or 'lang' parameter. Can be used as a context manager or a decorator. If a function is decorated, one of the parameters for the function must...
5,354,677
def get_all(isamAppliance, check_mode=False, force=False, ignore_error=False): """ Retrieving the current runtime template files directory contents """ return isamAppliance.invoke_get("Retrieving the current runtime template files directory contents", "/mga/template_f...
5,354,678
def build_path(dirpath, outputfile): """ Build function """ #some checks if not path.exists(dirpath): print("Path does not exist!") return 1 if not path.isdir(dirpath): print("Path is not folder") return 1 #for now SQLite try: output = cr...
5,354,679
def print_symbols(f, name, node, level=0, *, tree_parser_doc, tree_parser_xpath, ignore_dirs_for_coverage): """ Prints C++ code for relevant documentation. """ indent = ' ' * level def iprint(s): f.write((indent + s).rstrip() + "\n") name_var = name if not node.f...
5,354,680
def prepare_seed(seed): """Set Random Seed""" print("Random Seed: ", seed) mindspore.set_seed(seed)
5,354,681
def partitioned_cov(x, y, c=None): """Covariance of groups. Partition the rows of `x` according to class labels in `y` and take the covariance of each group. Parameters ---------- x : array_like, shape (`n`, `dim`) The data to group, where `n` is the number of data points and `...
5,354,682
def _fix_importname(mname): """ :param mname: """ mname = os.path.normpath(mname) mname = mname.replace(".", "") mname = mname.replace("-", "") mname = mname.replace("_", "") mname = mname.replace(os.path.sep, "") mname = mname.replace(os.path.pathsep, "") return mname
5,354,683
def main(args, out, err): """ This wraps GURepair's real main function so that we can handle exceptions and trigger our own exit commands. This is the entry point that should be used if you want to use this file as a module rather than as a script. """ cleanUpHandler = BatchCaller(args.ve...
5,354,684
def getSymbolData(symbol, sDate=(2000,1,1), adjust=False, verbose=True, dumpDest=None): """ get data from Yahoo finance and return pandas dataframe Parameters ----------- symbol : str Yahoo finanance symbol sDate : tuple , default (2000,1,1) start date (y,m,d) adju...
5,354,685
def generateLouvainCluster(edgeList): """ Louvain Clustering using igraph """ Gtmp = nx.Graph() Gtmp.add_weighted_edges_from(edgeList) W = nx.adjacency_matrix(Gtmp) W = W.todense() graph = Graph.Weighted_Adjacency( W.tolist(), mode=ADJ_UNDIRECTED, attr="weight", loops=False) # ig...
5,354,686
def exprvars(name, *dims): """Return a multi-dimensional array of expression variables. The *name* argument is passed directly to the :func:`pyeda.boolalg.expr.exprvar` function, and may be either a ``str`` or tuple of ``str``. The variadic *dims* input is a sequence of dimension specs. A dime...
5,354,687
def cell_segmenter(im, thresh='otsu', radius=20.0, image_mode='phase', area_bounds=(0,1e7), ecc_bounds=(0, 1)): """ This function segments a given image via thresholding and returns a labeled segmentation mask. Parameters ---------- im : 2d-array Image to be segmente...
5,354,688
def generate_report(start_date, end_date): """Generate the text report""" pgconn = get_dbconn('isuag', user='nobody') days = (end_date - start_date).days + 1 totalobs = days * 24 * 17 df = read_sql(""" SELECT station, count(*) from sm_hourly WHERE valid >= %s and valid < %s GROUP by ...
5,354,689
def whole(eventfile,par_list,tbin_size,mode,ps_type,oversampling,xlims,vlines): """ Plot the entire power spectrum without any cuts to the data. eventfile - path to the event file. Will extract ObsID from this for the NICER files. par_list - A list of parameters we'd like to extract from the FITS file ...
5,354,690
def handle_postback(): """Handles a postback.""" # we need to set an Access-Control-Allow-Origin for use with the test AJAX postback sender # in normal operations this is NOT needed response.set_header('Access-Control-Allow-Origin', '*') args = request.json loan_id = args['request_token'] m...
5,354,691
def metadata_mogrifier(folder): """Utility function transforming metadata stored in txt file into a format usable by :py:class:`Metadata <livius.video.processing.jobs.meta.Metadata>` usable one. This is just an example reading 2 files in a JSON format and creating the appropriate metadata input for the...
5,354,692
def process_responses(response_queue, msg_in): """ Pulls responses off of the queue. """ log_name = '{0} :: {1}'.format(__name__, process_responses.__name__) logging.debug(log_name + ' - STARTING...') while 1: stream = '' # Block on the response queue try: res = r...
5,354,693
def selfcal_apcal(imc, trial='1'): """ Self Calibration. Apply the calibration from the phase only solution """ flagmanager(imc.vislf, mode='restore', versionname='startup') applycal(vis=imc.vislf, spwmap=np.zeros(54), interp='linearPDperobs', gaintable=[imc.path_base+...
5,354,694
def get_bb_bev_from_obs(dict_obs, pixor_size=128): """Input dict_obs with (B,H,W,C), return (B,H,W,3)""" vh_clas = tf.squeeze(dict_obs['vh_clas'], axis=-1) # (B,H,W,1) # vh_clas = tf.gather(vh_clas, 0, axis=-1) # (B,H,W) vh_regr = dict_obs['vh_regr'] # (B,H,W,6) decoded_reg = decode_reg(vh_regr, pixor_size...
5,354,695
def get_hard_edges(obj): """ :param str obj: :returns: all hard edges from the given mesh in a flat list :rtype: list of str """ return [obj + '.e[' + str(i) + ']' for i, edgeInfo in enumerate(cmds.polyInfo(obj + '.e[*]', ev=True)) if edgeInfo.endswith('Hard\n')]
5,354,696
def make_system(l=70): """ Making and finalizing a kwant.builder object describing the system graph of a closed, one-dimensional wire with l number of sites. """ sys = kwant.Builder() lat = kwant.lattice.chain() sys[(lat(x) for x in range(l))] = onsite sys[lat.neighbors()] = hopping return sys.finalized()
5,354,697
def jsontabledump(f: TextIO, c: Tuple[str, Dict[str, Tuple[str, str]]], name: str) -> None: """ Dump table schema to the given file. :param f: File object to dump the table to. :param c: Table schema. :param name: Table name. """ f.write("{}\n---------\n".format(name)) f.write("\n" + c[0...
5,354,698
def _gen_test_methods_for_rule( rule: Type[CstLintRule], fixture_dir: Path, rules_package: str ) -> TestCasePrecursor: """Aggregates all of the cases inside a single CstLintRule's VALID and INVALID attributes and maps them to altered names with a `test_` prefix so that 'unittest' can discover them later on and...
5,354,699