content
stringlengths
22
815k
id
int64
0
4.91M
def ADOSC( frame, fast=3, slow=10, high_col="high", low_col="low", close_col="close", vol_col="Volume", ): """Chaikin A/D oscillator""" return _frame_to_series( frame, [high_col, low_col, close_col, vol_col], talib.ADOSC, fast, slow )
42,800
def file_name_error(file_name): """ Function that returns an error message for missing files. """ if file_name=='' or file_name[0][0]=='-': print 'ERROR! Input file name not specified.' exit(-1) elif os.path.isfile(file_name)==False: print 'ERROR! Input file name [%s] does not exist.' %...
42,801
def op_scr( gep: pd.DataFrame, gross_tp: pd.DataFrame, ul_exp: float, bscr: float ): """ SCR Op Risk module Inputs: - Gross EP last 12m and 12m prior - Gross TP: BEL should be positive - BSCR """ op_premiums = 0.04 * (gep.at['life_all', 'gep_last12m'] - ...
42,802
def ensure_admins(admin_password_list): """ Setup given list of users as admins. """ os.makedirs(STATE_DIR, mode=0o700, exist_ok=True) if not admin_password_list: return logger.info("Setting up admin users") config_path = CONFIG_FILE if os.path.exists(config_path): with ...
42,803
def parse_voyager_sclk(sclk, planet=None): """Convert a Voyager clock string (FDS) to a numeric value. Typically, a partition number is not specified for FDS counts. However, if it is, it must be compatible with the planetary flyby. The partition number is 2 for Jupiter and Saturn, 3 for Uranus, a...
42,804
def format_url(url): """ Formats url by adding 'http://' if necessary and deleting 'www.' :param url: ulr to article or domain :return: formatted url e.g. the following urls: 'http://www.google.pl/', 'google.pl/', 'google.pl/', 'www.google.pl/', 'http://google.pl/...
42,805
def append(arr, values, axis=None): """Append to the end of an array along axis (ravel first if None) """ arr = asanyarray(arr) if axis is None: if arr.ndim != 1: arr = arr.ravel() values = ravel(values) axis = arr.ndim-1 return concatenate((arr, values), axis=axi...
42,806
def volo_d4_448(pretrained=False, **kwargs): """ VOLO-D4 model, Params: 193M """ model_args = dict(layers=(8, 8, 16, 4), embed_dims=(384, 768, 768, 768), num_heads=(12, 16, 16, 16), **kwargs) model = _create_volo('volo_d4_448', pretrained=pretrained, **model_args) return model
42,807
def generate_train_test(path): """ Split all .asm.vec files into training samples and test samples. :param path: The path of all .asm.vec files. """ train_path = '/'.join(path.split('/')[:-1]) + "/train/" test_path = '/'.join(path.split('/')[:-1]) + "/test/" dirs = os.listdir(path) for ...
42,808
def rec_hasattr(obj, attr): """ Recursive hasattr. :param obj: The top-level object to check for attributes on :param attr: Dot delimited attribute name Example:: rec_hasattr(obj, 'a.b.c') """ try: reduce(getattr, attr.split('.')...
42,809
def test_run_script(setup_test_data): """ Test that the populate_reporting_agency_tas script acts as expected """ call_command("populate_reporting_agency_overview") results = ReportingAgencyOverview.objects.filter(fiscal_year=2019, fiscal_period=3, toptier_code="987").all() assert len(results) == 1 ...
42,810
def _add_project_entry(projName, scriptName): """Add project to rootPathsRel and rootPathAbs. Args: projName -- __name__ of the project class scriptName -- __name__ of the script in which the project class was defined """ relPath = os.path.dirname(_scriptPathsRel[scriptName]) absPat...
42,811
def find_svos(tokens): """ Extracts all the subject-verb objects in a list of tokens. :param tokens: the parsed list. :return: a list of the subject verb objects. """ svos = [] verbs = [tok for tok in tokens if tok.pos_ == "VERB" and tok.dep_ != "aux"] for verb in verbs: subs, ve...
42,812
def githooks(): """Manage Git hooks for Renku repository."""
42,813
def def_axiom(arg1): """ def-axiom rule prove propositional tautologies axioms. for reason that prove need propositional logic decision procedure, currently use proofterm.sorry """ # Ts = analyze_type(arg1) # if IntType in Ts: # pt = refl(arg1).on_rhs( # top_conv(rewr_con...
42,814
def not_shiptoast_check(self, message): """Checks whether the message object is not in a shiptoast chat.""" if (message.channel.id in self.settings["shiptoast"]) or (message.channel.name in self.settings["shiptoast"]): return False else: return True
42,815
def jaccard_distance_loss(y_true, y_pred, smooth=100): """ Jaccard = (|X & Y|)/ (|X|+ |Y| - |X & Y|) = sum(|A*B|)/(sum(|A|)+sum(|B|)-sum(|A*B|)) """ intersection = tf.reduce_sum(tf.math.abs(y_true * y_pred), axis=-1) sum_ = tf.reduce_sum(tf.math.abs(y_true) + tf.math.abs(y_pred), axis=-1...
42,816
def DiscoverConnect(sources, target_attributes, allowed_links, chain_attribute, chain_filters, link_type, max_length, connect_function = None, debug = None): """ sources - ModelList of elements to start from target_attributes - list of attributes (pairs) to detect target attributes allowed_links - list of attribute...
42,817
def main(): """ Read the Boot Artifact ID from the /proc/cmdline and report it to the BOS API. This reports the booted 'state' of the node to BOS. """ component = read_identity() try: sleep_time = get_value_from_proc_cmdline('bos_update_frequency') except KeyError: sleep_time...
42,818
def unshare_document(token, docid, userid): """ Unshares a document from another user. :param token: The user JWT token. :type token: str :param docid: The DocID of the document. :type docid: str :param userid: The UserID of the user to be unshared fr...
42,819
def AlterNChannels(layer2alter_id, new_n_channels, old_model): """ Function to increase number of channels Args: layer2alter_id: layer to change new_n_channels: number of channels for the altered layer old_model: model before mutation Returns: Returns mutated model ...
42,820
def predict_to_file(in_file, out_file): """预测到文件 可以提交到 https://www.cluebenchmarks.com/ner.html """ fw = open(out_file, 'w', encoding='utf-8') with open(in_file) as fr: for l in tqdm(fr): l = json.loads(l) l['label'] = {} for start, end, label in NER.recogn...
42,821
def generate_bins(bins, values=None): """Compute bin edges for numpy.histogram based on values and a requested bin parameters Unlike `range`, the largest value is included within the range of the last, largest value, so generate_bins(N) with produce a sequence with length N+1 Arguments: bins (...
42,822
def makeRollAnswerStr( roll_res, mention_str ): """Formats an answer string depending on the roll result. If provided with an invalid roll result, returns 'None'.""" answer = None if roll_res == None: answer = "Invalid dice expression !" elif len(roll_res)==2: #either threshold or success ro...
42,823
def ECSPower(min, max, size): """ on modélise l'eau du réseau comme une fonction sinusoidale de période annuelle cette fonction est complètement calée sur un fichier météo qui commence au 1er janvier mais qui peut être pluriannuel min : température minimale d'injection de l'eau du réseau dans ...
42,824
def __create_notification(title: str, content: str) -> Dict[str, Any]: """ Creates a notification "object" from the given title and content. :params title: The title of the notification. :params content: The content of the notification. :returns A dictionary representing a notification "object". ...
42,825
def readme(): """Read and patch README.""" readme_text = read('README.rst') # PyPI does not accept :class: references. return readme_text.replace(':class:`base64io.Base64IO`', '``base64io.Base64IO``')
42,826
def generator_dcgan(noise_dim, img_source_dim,img_dest_dim, bn_mode,deterministic,pureGAN,inject_noise,wd, model_name="generator_dcgan"): """DCGAN generator based on Upsampling and Conv2D Args: noise_dim: Dimension of the noise input img_dim: dimension of the image output bn_mode: keras...
42,827
def get_ironic_client(): """Get Ironic client instance.""" kwargs = {'os_password': CONF.ironic.os_password, 'os_username': CONF.ironic.os_username, 'os_tenant_name': CONF.ironic.os_tenant_name, 'os_auth_url': CONF.ironic.os_auth_url, 'os_endpoint_type': '...
42,828
def emg21(peak_index, x_pos, amp, init_pars=pars_dict, vary_shape_pars=True, index_first_peak=None): """ Hyper-EMG(2,1) lmfit model (single-peak fit model with two exponential tails on the left and one exponential tail on the right) Parameters ---------- peak_index : int Inde...
42,829
def _wait_and_retry(provider, job_id, poll_interval, retries, job_descriptor, summary): """Wait for job and retry any tasks that fail. Stops retrying an individual task when: it succeeds, is canceled, or has been retried "retries" times. This function exits when there are no tasks running ...
42,830
def process_evaluation(evaluation, codec, tree_bits, name, trajectory_dict): """ Adds to trajectory_dict the mappings from start/end positions to the various metrics stored for the associated codebook """ test_trajectories = evaluation.pop('test') train_trajectories = evaluation.pop('train') ...
42,831
def summarize_2_dual_3(package_list): """ Given list of packages, return counts of (py3-only, dual-support, py2-only) """ py3 = 0 dual = 0 py2 = 0 for pkg in package_list: if pkg['status'] == 'py3-only': py3 += 1 elif pkg['status'] in PY2_STATUSES: dua...
42,832
def get_invalid_resumes(): """ Loads invalid json resumes for unit tests, returning a list of TestSchemaFile """ folder = os.path.join(RESUME_DIR, 'invalid') return [ TestSchemaFile( invalid_resume_filename, json.load( open(os.path.join(folder, invalid_resume_...
42,833
def get_exppath(tag, name=None, override=False, prompt=False, root='~'): """ Specific path for experiments results Parameters ---------- tag: string specific tag for the task you are working on name: string name of the folder contains all the results (NOTE: the name can has subfolder) ove...
42,834
def login(session, init_url): """ steps: 1. GET init_url -> forward to sso_url 2. GET sso_url -> get sid_url 3. POST sid_url -> submit login data 4. POST sid_url -> get assert_url and assert_data 5. POST assert_url -> redirect to init_url, login OK! """ # 1. GET in...
42,835
def isPTSF(p, T=[]): """ >>> from common.production import Production >>> p = Production(['A'], [['\\"a\\"', '\\"b\\"'],['\\"cde\\"']]) >>> isPTSF(p) True >>> p = Production(['A'], [['\\"a\\"', '\\"b\\"'],['\\"cde\\"']]) >>> isPTSF(p, ['a', 'b', 'c', 'd', 'e']) True >>> p = Product...
42,836
def __generate_all_seq(length): """ Generate all sequence with length """ for sequence in itertools.product(["A", "C", "T", "G"], repeat=length): yield "".join(sequence)
42,837
def new_getvalue( state, name, p): """ Called every time a node value is used in an expression. It will override the value for the current step only. Returns random values for the node states """ global TARGETS value = util.default_get_value( state, name, p ) if name in TARGETS: ...
42,838
def csv_find(filein, data): """Finds and returns the row number of the element given, in a CSV file.""" if not os.path.isfile(filein): return(-1) with open(filein, 'rt') as fi: reader = csv.reader(fi, delimiter=',') for row in reader: hashout = row[1] # location of hash ...
42,839
def informe_ministerios(): """ Listado de personas """ check_edit_or_admin() roles = db.session.query(Rol).filter(Rol.tipo_rol == 'M')\ .join(relacion_miembros_roles, relacion_miembros_roles.c.id_rol == ...
42,840
def merge_regions_and_departments(regions, departments): """Merge regions and departments in one DataFrame. The columns in the final DataFrame should be: ['code_reg', 'name_reg', 'code_dep', 'name_dep'] """ return pd.merge(left=regions[["code", "name"]], right=departments[['regi...
42,841
def updateResourceJsons(swagger,examplesDict,dirName): """ Update the Resource JSON file to include examples in other folder """ try: # Iterate through all resources in the output folder for id in range(len(swagger['tags'])): resourceName = swagger['tags'][id]['name'] ...
42,842
def watch(name, plural, namespace=None, timeout_seconds=600, version=constants.TEKTON_VERSION): """Watch the created or patched tekton objects in the specified namespace""" if namespace is None: namespace = utils.get_default_target_namespace() tbl = TableLogger( columns='NAME,SUCCEEDED,REA...
42,843
def modification_proposes(doc, data): """7. С учётом п.5 предложения по модификации системы (с обоснованием в плане стоимости, сложности и проч.);""" pass
42,844
def add_input_gfa(parser): """Add the input_gfa parser""" parser.add_argument( '--input-gfa', '-i', type=str, required=True, help='Input splice graph in GFA1 format (the results from ' 'build_splicegraph)', dest='gfa1', metavar='FILE' )
42,845
def sign(x): """Sign function. :return -1 if x < 0, else return 1 """ if x < 0: return -1 else: return 1
42,846
def set_default_dataseg(*args): """ set_default_dataseg(ds_sel) Set default value of DS register for all segments. @param ds_sel (C++: sel_t) """ return _ida_segregs.set_default_dataseg(*args)
42,847
def plt_ts_comp4ARNA_flights_PHYSICAL_VARS(dpi=320, show_plot=False, inc_GEOSChem=False, RunSet=None, res='4x5', just_plot_GEOS_Chem=False, flight_n...
42,848
def get_sms_history(key: str): """ Get SMS history. :param str key: Authentication key. :return: List of SMSHistoryItems. """ session = get_session(key) url = f"{SITE_BASE_URL}/index.php?page=10&lang=en" response = session.get(url) pages = bs(response.text, "html.parser").find_all...
42,849
def core_rotd(sym_factor, flux_file_name, stoich): """ Writes the string that defines the `Core` section for a variational reaction-coordinate transition-state theory model of a transition state for a MESS input file by formatting input information into strings a filling Mako template. ...
42,850
def last_gen(genobj): """ 迭代一个生成器对象,返回最后一个元素 :param genobj: :return: """ for i in genobj: last_e = i return last_e
42,851
def downloadsrtm(xy_range): """ Downlaods SRTM v4.1 tiles2 as bytestream and saves them to TILES_DIR. :param xy_range: The range of tiles2 in x and y as per grid in http://srtm.csi.cgiar.org/SELECTION/inputCoord.asp in 'minx, maxx, miny, maxy. :type xy_range: comma-separated range s...
42,852
def get_section_name_mapping(lattice): """.""" lat = lattice[:] section_map = ['' for i in range(len(lat))] # find where the nomenclature starts counting and shift the lattice: start = _pyaccel.lattice.find_indices(lat, 'fam_name', 'start')[0] b1 = _pyaccel.lattice.find_indices(lat, 'fam_name',...
42,853
def from_quaternion(quaternions, name=None): """Converts quaternions to Euler angles. Args: quaternions: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "euler_from_quaternion". Returns: A tensor of sh...
42,854
def is_polygonal(n, num): """ Predicate for if num is a n-gonal number. Works for all n >= 3 and num >= 1. """ if n < 3 or num < 1: return False t = int((sqrt(8*num*(n-2) + (n-4)**2) + (n-4)) / (2 * (n-2))) return poly(n, t) == num
42,855
def instance_segmentation(): """Segment object instances in images.""" cli = FlashCLI( InstanceSegmentation, InstanceSegmentationData, default_datamodule_builder=from_pets, default_arguments={ "trainer.max_epochs": 3, }, ) cli.trainer.save_checkpoint(...
42,856
def map2pix(geoTransform, x, y): """ transform map coordinates to local image coordinates Parameters ---------- geoTransform : tuple, size=(6,1) georeference transform of an image. x : np.array, size=(m), ndim={1,2,3}, dtype=float horizontal map coordinate. y : np.array, size=(m...
42,857
def fk_plaintext_dict_from_db_record(session,element,db_record,excluded=None): """Return a dictionary of <name>:<value> for any <name>_Id that is a foreign key in the <element> table, excluding any foreign key in the list <excluded>""" fk_dict = {} fk_df = dbr.get_foreign_key_df(session,element) if ...
42,858
def checkmarkers(tubemarker, tubechecker): """Check for required markers in each tube The tube-specific markers that are to be merged are desceribed in constants.py Args: tubemarker: required markers for that tube tubechecker: markers in the given tube that needs to be validated Retu...
42,859
def _in_Kexp(z): """ Returns true if z is in the exponential cone """ alpha, beta, delta = z if ((beta > 0) and (delta > 0) and (np.log(delta) >= np.log(beta) + alpha / beta)) \ or ((alpha <= 0) and (np.abs(beta) < 1e-12) and (delta >= 0)): return True else: retur...
42,860
def split_blocks(bytestring, block_size): """Splits bytestring in block_size-sized blocks. Raises an error if len(string) % blocksize != 0. """ if block_size == 1: return map(b_chr, bytearray(bytestring)) rest_size = len(bytestring) % block_size if rest_size: raise ValueError(...
42,861
def put_newest_oldest_files(f, author, path_earliest_latest, n_files, is_newest): """Write a report of files that were least recently changed by `author` (`is_newest` is False), or was first most least recently changed by `author` in current revision. f: file handle to write to path_earlies...
42,862
def pearson_correlation(trajectory_data): """ Calculates the Pearson Correlation Matrix for node pairs Usage: node_correlation, node_variance, node_average = pearson_correlation(trajectory_data) Arguments: trajectory_data: multidimensional numpy array; first index (rows) correspond to ti...
42,863
def dglstep(q,maxf=10000,replfunc=None): """returns: next dgl step, function that was replaced, with what""" #choose rnd func to replace allfunc=q.listfunc() f=random.choice(list(allfunc)) par=q.findparamforfunc(f) #choose replacement function global pdgl r=None shallreplace=True while r is None:...
42,864
def main(): """ifstat main loop""" f_netdev = open("/proc/net/dev", "r") # We just care about ethN interfaces. We specifically # want to avoid bond interfaces, because interface # stats are still kept on the child interfaces when # you bond. By skipping bond we avoid double counting. f_n...
42,865
def upper_band(df: 'Dataframe', metric_col: str, rolling_window: Optional[int] = 20) -> pd.DataFrame: """Calculates the lower bound of a stock's price movements. Args: df: the dataframe to append a column onto metric_col: the column to calculate over (usually the 'Close' price) rolling_...
42,866
def reparametisation_trick(mu, log_var, device): """ :param mu: The mean of the latent variable to be formed (nbatch, n_z) :param log_var: The log variance of the latent variable to be formed (nbatch, n_z) :param device: CPU or GPU :return: latent variable (nbatch, n_z) """ noise = torch.no...
42,867
def classify_dataset_ion_images(db, ds, services_config, overwrite_existing=False): """Classifies all dataset ion images. Args: db (sm.engine.db.DB): database connection ds (sm.engine.dataset.Dataset): target dataset services_config (dict): configuration for services overwrite_e...
42,868
def test_create_mask_for_gaussian2d_type( mask_type, center_fractions, accelerations, expected_mask_func, x, seed, half_scan_percentage, scale ): """ Test that the function returns gaussian 2D masks Args: mask_type: The type of mask to be created center_fractions: The center fractions o...
42,869
def process_gaf_input(gaf_file_path, gaf_file_cache, ignore_cache, node_lengths, edge_lengths, num_jobs): """ The current implementation only works if the GAF file has an informative MAPQ column """ segment_re = re.compile(SEGMENT_ORIENTATION_SYMBOLS) process_read_aln = fnt.partial(process_read_alig...
42,870
async def prefix_wrapper_async_callable(prefix_factory, re_flags, message): """ Function to execute asynchronous callable prefix. This function is a coroutine. Parameters ---------- prefix_factory : `async-callable` Async callable returning the prefix. re_flags : `int` ...
42,871
def draw_mask(img0, img1, mask, size=14, downscale_ratio=1): """ Args: img: color image. mask: 14x28 mask data. size: mask size. Returns: display: image with mask. """ resize_imgs = [] resize_imgs.append(cv2.resize( img0, (int(img0.shape[1] * downscale_rat...
42,872
def serialize( obj: object, worker: AbstractWorker = None, simplified: bool = False, force_full_simplification: bool = False, ) -> bin: """This method can serialize any object PySyft needs to send or store. This is the high level function for serializing any object or collection of objects ...
42,873
def sine_data_generation(no, seq_len, dim): """Sine data generation. Args: - no: the number of samples - seq_len: sequence length of the time-series - dim: feature dimensions Returns: - data: generated data """ # Initialize the output data = list() # Generate sine ...
42,874
def apply_wilcoxon_test(wide_optimal, dep_var, OVRS_NAMES, alpha): """Performs a Wilcoxon signed-rank test""" pvalues = [] for ovr in OVRS_NAMES: mask = np.repeat(True, len(wide_optimal)) pvalues.append( wilcoxon( wide_optimal.loc[mask, ovr], wide_optimal.loc[mas...
42,875
def init_premailer() -> None: """Construct the :class:`premailer.Premailer` object used to prepare mails HTML body.""" global _premailer class_files_contents = [] for file in class_files: with open(file, "r") as fp: class_files_contents.append(fp.read()) scheme = flask.curr...
42,876
def get_accuracy(targets, outputs, k=1, ignore_index=None): """ Get the accuracy top-k accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ...
42,877
def set_viewport_min_height(height: int): """Sets the viewport's minimum height. Returns: None """ internal_dpg.configure_viewport(0, min_height=height)
42,878
def cameraPs2Ts(cameraPOs): """ convert multiple POs to Ts. ---------- input: cameraPOs: list / numpy output: cameraTs: list / numpy """ if type(cameraPOs) is list: N = len(cameraPOs) else: N = cameraPOs.shape[0] cameraT_list = [] for _cameraPO in ...
42,879
def dimerization_worker(primer_1, primer_2): """ Returns the total number of complementary bases and the longest run of complementary bases (weighted by HYBRID_SCORES), the median length of all runs and the array of complementary bases. """ p1 = [set(AMB[i]) for i in primer_1] p2 = [set(AMB[i])...
42,880
def load_dataset(ds, elsize=[], axlab='', outlayout='', dtype='', dataslices=None, uint8conv=False): """Load data from a proxy and select/transpose/convert/....""" slices = get_slice_objects(dataslices, ds.shape) data = slice_dataset(ds, slices) if list(axlab) != lis...
42,881
def assignUnknownCluster(clustermap, elementmap): """ Assigns unknown cluster to the element, if parent is None. Args: clustermap (ClusterMap): cluster map elementmap (ElementMap): element map """ misc.checkTypeAgainst(type(clustermap), ClusterMap, __file__) misc...
42,882
def _interpret_err_lines(err_specs, ncols, names=None): """Give list of column names from the READ SERR and TERR commands Parameters ---------- err_specs : dict ``{'serr': [n0, n1, ...], 'terr': [n2, n3, ...]}`` Error specifications for symmetric and two-sided errors ncols : int ...
42,883
def import_config_cmd(): """Import a teamocil/tmuxinator config.""" pass
42,884
def mro_hasattr(cls: type, attr: str) -> bool: """Check if an attribute exists in a type's class hierarchy Args: cls (type): The type attr (str): The attribute Returns: bool: True if has the attribute. Raises: TypeError: Not called on a type """ if not isinsta...
42,885
def get_channel_number_from_frequency(frequency): """gets the 802.11 channel for a corresponding frequency in units of kilohertz (kHz). does not support FHSS.""" try: return _20MHZ_CHANNEL_LIST.get(frequency, "Unknown") except KeyError: return "Unknown"
42,886
def diurnal_cycle(data, var, stat, stat_config): """ Calculate diurnal cycle """ # Type of diurnal cycle; amount or frequency dcycle_stat = stat_config[stat]['dcycle stat'] # Threshold; must be defined for frequency in_thr = stat_config[stat]['thr'] if in_thr is not None: if var...
42,887
def fetch_single_minutely_equity(code, start, end): """ 从本地数据库读取单个股票期间分钟级别交易明细数据 **注意** 交易日历分钟自9:31~11:30 13:01~15:00 在数据库中,分钟级别成交数据分日期存储 Parameters ---------- code : str 要获取数据的股票代码 start_date : datetime-like 自开始日期(包含该日) end_date : datetime-like ...
42,888
def launch_about_window(event): """ it will create and launch credit window """ About.about.create_About(root, root)
42,889
def aggregate_components_from_owners(root): """Traverses the given dir and parse OWNERS files for team and component tags. Args: root (str): the path to the src directory. Returns: A pair (data, warnings) where data is a dict of the form {'component-to-team': {'Component1': 'team1@chr...', ...}, ...
42,890
def verifyactions(actions, state, ctxs): """Verify that there exists exactly one action per given changeset and other constraints. Will abort if there are to many or too few rules, a malformed rule, or a rule on a changeset outside of the user-given range. """ expected = set(c.node() for c in c...
42,891
def method2(): """Provide an examples of doc strings that are too long. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. """ # noqa W505: doc line too long (127 > 100 characters) (auto-generated noqa) return 7
42,892
def get_parent_compartment_ocid(teamname): """ Retrieves the OCID for the compartment based on the team name (assuming the model of root -- team -- individual structure of compartments. Args: teamname (str): name of the team level compartment Returns: str: The OCId or None - None is only returne...
42,893
def list_files_path(path): """ List files from a path. :param path: Folder path :type path: str :return: A list containing all files in the folder :rtype: List """ return sorted_alphanumeric([path + f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])
42,894
def set_recommended_watch_points(session_id): """Set recommended watch points.""" body = _read_post_request(request) request_body = body.get('requestBody') if request_body is None: raise ParamMissError('requestBody') set_recommended = request_body.get('set_recommended') reply = _wrap_re...
42,895
def active_power(sensecli): """return the realtime current active power consumption """ api = sensecli.api click.echo(api.active_power)
42,896
def epochJulian2JD(Jepoch): """ ---------------------------------------------------------------------- Purpose: Convert a Julian epoch to a Julian date Input: Julian epoch (nnnn.nn) Returns: Julian date Reference: See JD2epochJulian Notes: e.g. 1983.99863107 converts into 2445700.5 Inverse of ...
42,897
def set_bcr(bcr, val, unit, now: datetime): """Set the values in the specified BCR structure. :param val: The numeric value. :param unit: The value's unit. :param now: The timestamp for the value. """ bcr.actVal = int(val) bcr.units.value = unit write_timestamp(bcr.t, now)
42,898
def _isfile(path): """Variant of os.path.isfile that is somewhat type-resilient.""" if not path: return False return os.path.isfile(path)
42,899