content
stringlengths
22
815k
id
int64
0
4.91M
def parse(data): """ Parses the input of the Santander text file. The format of the bank statement is as follows: "From: <date> to <date>" "Account: <number>" "Date: <date>" "Description: <description>" "Amount: <amount>" "Balance: <amount>" <second_tra...
5,330,200
def solve_duffing(tmax, dt_per_period, t_trans, x0, v0, gamma, delta, omega): """Solve the Duffing equation for parameters gamma, delta, omega. Find the numerical solution to the Duffing equation using a suitable time grid: tmax is the maximum time (s) to integrate to; t_trans is the initial time perio...
5,330,201
def create_prog_assignment_registry(): """Create the registry for course properties.""" reg = FieldRegistry( 'Prog Assignment Entity', description='Prog Assignment', extra_schema_dict_values={ 'className': 'inputEx-Group new-form-layout'}) # Course level settings. course_op...
5,330,202
def _read_one_cml(cml_g, cml_id_list=None, t_start=None, t_stop=None, column_names_to_read=None, read_all_data=False): """ Parameters ---------- cml_g cml_id_list t_start t_stop column_names_to_rea...
5,330,203
def get_commands(): """ returns a dictionary with all the az cli commands, keyed by the path to the command inside each dictionary entry is another dictionary of verbs for that command with the command object (from cli core module) being stored in that """ # using Microsoft VSCode tooling ...
5,330,204
def test_getNum(): """Test fcn that returns selected nums[i]""" new_num = 321 i = 2 u = Blockchain().address(0) # btw, this account is no longer owner c = Contract('test') c.connect() c.run_trx(u, 'storeNum', i, new_num) assert c.call_fcn('getNum', i) == new_num
5,330,205
def calculate_keypoints(img, method, single_channel, graphics=False): """ Gray or single channel input https://pysource.com/2018/03/21/feature-detection-sift-surf-obr-opencv-3-4-with-python-3-tutorial-25/ """ if single_channel=='gray': img_single_channel = single_channel_gray(img) ...
5,330,206
def plot_pos_neg( train_data: pd.DataFrame, train_target: pd.DataFrame, col1: str = 'v5', col2: str = 'v6' ) -> None: """ Make hexbin plot for training transaction data :param train_data: pd.DataFrame, features dataframe :param train_target: pd.DataFrame, target dataframe...
5,330,207
def open_w_lock (file_name, mode = "r", bufsize = -1) : """Context manager that opens `file_name` after successfully locking it. """ with lock_file (file_name) : with open (file_name, mode, bufsize) as file : yield file
5,330,208
def raffle_form(request, prize_id): """Supply the raffle form.""" _ = request prize = get_object_or_404(RafflePrize, pk=prize_id) challenge = challenge_mgr.get_challenge() try: template = NoticeTemplate.objects.get(notice_type='raffle-winner-receipt') except NoticeTemplate.DoesNotExist:...
5,330,209
def is_rldh_label(label): """Tests a binary string against the definition of R-LDH label As defined by RFC5890_ Reserved LDH labels, known as "tagged domain names" in some other contexts, have the property that they contain "--" in the third and fourth characters but which otherwise co...
5,330,210
def offence_memory_patterns(obs, player_x, player_y): """ group of memory patterns for environments in which player's team has the ball """ def environment_fits(obs, player_x, player_y): """ environment fits constraints """ # player have the ball if obs["ball_owned_player"] == obs["activ...
5,330,211
def get_mem() -> int: """Return memory used by CombSpecSearcher - note this is actually the memory usage of the process that the instance of CombSpecSearcher was invoked.""" return int(psutil.Process(os.getpid()).memory_info().rss)
5,330,212
def load_parameters(directory_name): """ Loads the .yml file parameters to a dictionary. """ root = os.getcwd() directory = os.path.join(root, directory_name) parameter_file_name = directory parameter_file = open(parameter_file_name, 'r') parameters = yaml.load(parameter_file, Loader=yam...
5,330,213
def aggregated_lineplot_new(df_agg,countries,fill_between=('min','max'),save=False,fig=None,ax=None,clrs='default'): """ Creates an aggregates lineplot for multiple countries Arguments: *df_agg* (DataFrame) : contains the aggregated results, either relative (df_rel) or absolute (df_abs) *co...
5,330,214
def _stat_categories(): """ Returns a `collections.OrderedDict` of all statistical categories available for play-by-play data. """ cats = OrderedDict() for row in nfldb.category.categories: cat_type = Enums.category_scope[row[2]] cats[row[3]] = Category(row[3], row[0], cat_type, ...
5,330,215
def rsafactor(d: int, e: int, N: int) -> List[int]: """ This function returns the factors of N, where p*q=N Return: [p, q] We call N the RSA modulus, e the encryption exponent, and d the decryption exponent. The pair (N, e) is the public key. As its name suggests, it is public and is used to ...
5,330,216
def integrate_prob_current(psi, n0, n1, h): """ Numerically integrate the probability current, which is Im{psi d/dx psi^*} over the given spatial interval. """ psi_diff = get_imag_grad(psi, h) curr = get_prob_current(psi, psi_diff) res = np.zeros(psi.shape[0]) with progressbar.Prog...
5,330,217
def getFile(path): """ 指定一个文件的路径,放回该文件的信息。 :param path: 文件路径 :return: PHP-> base64 code """ code = """ @ini_set("display_errors","0"); @set_time_limit(0); @set_magic_quotes_runtime(0); $path = '%s'; $hanlder = fopen($path, 'rb'); $res = fread($hanlder, filesize($path)); fc...
5,330,218
def _load(): """Load the previous state of the repository.""" if not os.path.exists(CONFIG_PATH): print("[x] No config file available.") return with open(CONFIG_PATH) as file_handle: try: CONFIG.update(json.load(file_handle)) except ValueError: print(...
5,330,219
def rgc(tmpdir): """ Provide an RGC instance; avoid disk read/write and stay in memory. """ return RGC(entries={CFG_GENOMES_KEY: dict(CONF_DATA), CFG_FOLDER_KEY: tmpdir.strpath, CFG_SERVER_KEY: "http://staging.refgenomes.databio.org/"})
5,330,220
def test_riid_generator_length(): """The RIID generator length should be a non-zero length string.""" assert isinstance(config.riid_generator_length, int) assert 0 < config.riid_generator_length
5,330,221
def execlog(command): # logs commands and control errors """ controling the command executions using os.system, and logging the commands if an error raise when trying to execute a command, stops the script and writting the rest of commands to the log file after a 'Skipping from here' note. """ global skipping t...
5,330,222
def simulate_quantities_of_interest_superoperator(tlist, c_ops, noise_parameters_CZ, fluxlutman, fluxbias_q1, amp, sim_step, verbose: bool=True): """ Calculates the propagator and the quantities of intere...
5,330,223
def setup_logging(loglevel): """Setup basic logging Args: loglevel (int): minimum loglevel for emitting messages """ logformat = '[%(asctime)s] %(levelname)s:%(name)s: %(message)s' logging.basicConfig(level=loglevel, stream=sys.stdout, format=logformat, datefmt='%Y-%m...
5,330,224
def test_query_with_parquet(sdc_builder, sdc_executor, cluster, database): """Validate end-to-end case with stopping the pipeline and executing the map/reduce job after it read all the data from database. Addresses Hive drift synchronization solution in parquet data format. The pipeline looks like: jdb...
5,330,225
def __polyline(): """Read polyline in from package data. :return: """ polyline_filename = resource_filename( 'cad', join(join('data', 'dxf'), 'polyline.dxf')) with open(polyline_filename, 'r') as polyline_file: return polyline_file.read()
5,330,226
def create_identity_split(all_chain_sequences, cutoff, split_size, min_fam_in_split): """ Create a split while retaining diversity specified by min_fam_in_split. Returns split and removes any pdbs in this split from the remaining dataset """ dataset_size = len(all_chain_seq...
5,330,227
def get_SNR(raw, fmin=1, fmax=55, seconds=3, freq=[8, 13]): """Compute power spectrum and calculate 1/f-corrected SNR in one band. Parameters ---------- raw : instance of Raw Raw instance containing traces for which to compute SNR fmin : float minimum frequency that is used for fitt...
5,330,228
def get_all_child_wmes(self): """ Returns a list of (attr, val) tuples representing all wmes rooted at this identifier val will either be an Identifier or a string, depending on its type """ wmes = [] for index in range(self.GetNumberChildren()): wme = self.GetChild(index) if wme.IsI...
5,330,229
def scan_image_directory(path): """Scan directory of FITS files to create basic stats. Creates CSV file ready to be read by pandas and print-out of the stats if less than 100 entries. Parameters ---------- path : str, pathlib.Path Returns ------- pd.DataFrame DataFrame con...
5,330,230
def print_configure_help_info(): """ print configuration tips """ sys.stdout.write('Please run the command first: duedge configure ') sys.stdout.write('--access-key=<your access-key> ') sys.stdout.write('--secret-key=<your secret-key> ') sys.stdout.write('to initialize local user configurati...
5,330,231
def test_function3(): """tests the key guessing function""" basepath = os.path.join(os.getcwd(), "MusicXML_files") filenames = os.listdir(basepath) for filename in filter(lambda s: s.endswith(".mxl"), filenames): m = MusicXMLExtractor(os.path.join(basepath, filename)) m.read_xml_...
5,330,232
def load_mat(filename): """ Reads a OpenCV Mat from the given filename """ return read_mat(open(filename, 'rb'))
5,330,233
def data_consist_notebook(table1, table2, key1, key2, schema1, schema2, fname, output_root=''): """ Automatically generate ipynb for checking data consistency Parameters ---------- table1: pandas DataFrame one of the two tables to compare table2: pandas DataFrame one of the two ...
5,330,234
def preprocess_fmri(rawdata=None): """example of a preprocessing function Args: rawdata (pyrsa.data.dataset.Dataset): the neural data Returns: preprocessed neural data in format of measurements, descriptors, obs_descriptors, channel_descriptors Example:...
5,330,235
def connected_components(image, threshold, min_area, max_area, max_features, invert=False): """ Detect features using connected-component labeling. Arguments: image (float array): The image data. \n threshold (float): The threshold value. \n ... Returns: features (pa...
5,330,236
def reduce_scan(row, params, **kwargs): """ Reduce scan-mode grism data .. warning:: This function is not yet implemented. It will raise an exception. Parameters ---------- row : abscal.common.exposure_data_table.AbscalDataTable Single-row table of the exposure to be ex...
5,330,237
def module(spec): """ Returns the module at :spec: @see Issue #2 :param spec: to load. :type spec: str """ cwd = os.getcwd() if cwd not in sys.path: sys.path.append(cwd) return importlib.import_module(spec)
5,330,238
def transform_digits_to_string(labels: Tuple[str], coefficients, offset: Fraction) -> str: """Form a string from digits. Arguments --------- labels: the tuple of lablels (ex.: ('x', 'y', 'z') or ('a', 'b', 'c'))) coefficients: the parameters in front of label ...
5,330,239
def match_peaks_with_mz_info_in_spectra(spec_a, spec_b, ms2_ppm=None, ms2_da=None): """ Match two spectra, find common peaks. If both ms2_ppm and ms2_da is defined, ms2_da will be used. :return: list. Each element in the list is a list contain three elements: m/z from spec 1; i...
5,330,240
def make_recsim_env( recsim_user_model_creator: Callable[[EnvContext], AbstractUserModel], recsim_document_sampler_creator: Callable[[EnvContext], AbstractDocumentSampler], reward_aggregator: Callable[[List[AbstractResponse]], float], ) -> Type[gym.Env]: """Creates a RLlib-ready gym.Env class given RecS...
5,330,241
def test_dpp_auth_resp_retries(dev, apdev): """DPP Authentication Response retries""" check_dpp_capab(dev[0]) check_dpp_capab(dev[1]) dev[0].set("dpp_resp_max_tries", "3") dev[0].set("dpp_resp_retry_time", "100") logger.info("dev0 displays QR Code") addr = dev[0].own_addr().replace(':', '')...
5,330,242
def set_default_subparser(self, name, args=None): """ see http://stackoverflow.com/questions/5176691/argparse-how-to-specify-a-default-subcommand """ subparser_found = False for arg in sys.argv[1:]: if arg in ['-h', '--help']: # global help if no subparser break else: ...
5,330,243
def unflatten(dictionary, delim='.'): """Breadth first turn flattened dictionary into a nested one. Arguments --------- dictionary : dict The dictionary to traverse and linearize. delim : str, default='.' The delimiter used to indicate nested keys. """ out = defaultdict(di...
5,330,244
def read_array(dtype, data): """Reads a formatted string and outputs an array. The format is as for standard python arrays, which is [array[0], array[1], ... , array[n]]. Note the use of comma separators, and the use of square brackets. Args: data: The string to be read in. dtype: The data...
5,330,245
def in_ipynb(): """ Taken from Adam Ginsburg's SO answer here: http://stackoverflow.com/a/24937408/4118756 """ try: cfg = get_ipython().config if cfg['IPKernelApp']['parent_appname'] == 'ipython-notebook': return True else: return False except Name...
5,330,246
def load_bioschemas_jsonld_from_html(url, config): """ Load Bioschemas JSON-LD from a webpage. :param url: :param config: :return: array of extracted jsonld """ try: extractor = bioschemas.extractors.ExtractorFromHtml(config) filt = bioschemas.filters.BioschemasFilter(confi...
5,330,247
def pformat(dictionary, function): """Recursively print dictionaries and lists with %.3f precision.""" if isinstance(dictionary, dict): return type(dictionary)((key, pformat(value, function)) for key, value in dictionary.items()) # Warning: bytes and str are two kinds of collections.Container, but w...
5,330,248
def _tonal_unmodulo(x): """ >>> _tonal_unmodulo((0,10,0)) (0, -2, 0) >>> _tonal_unmodulo((6,0,0)) (6, 12, 0) >>> _tonal_unmodulo((2, 0)) (2, 0) """ d = x[0] c = x[1] base_c = MS[d].c # Example: Cb --- base=0 c=11 c-base=11 11 - 12 = -1 if c - base_c > 6: ...
5,330,249
def get_ncopy(path, aboutlink = False): """Returns an ncopy attribute value (it is a requested count of replicas). It calls gfs_getxattr_cached.""" (n, cc) = getxattr(path, GFARM_EA_NCOPY, aboutlink) if (n != None): return (int(n), cc) else: return (None, cc)
5,330,250
def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir, jpeg_data_tensor, bottleneck_tensor): """Ensures all the training, testing, and validation bottlenecks are cached. Because we're likely to read the same image multiple times (if there are no distortions applied during train...
5,330,251
def has_three_or_more_vowels(string): """Check if string has three or more vowels.""" return sum(string.count(vowel) for vowel in 'aeiou') >= 3
5,330,252
def write_to_xlsx( fund_infos: list[FundInfo], xlsx_filename: Path, logger: Logger = Logger.null_logger(), ) -> None: """ Structuralize a list of fund infos to an Excel document. Input: a list of fund infos, and an Excel filename. """ # TODO profile to see whether and how much setting ...
5,330,253
def lbfgs_inverse_hessian_factors(S, Z, alpha): """ Calculates factors for inverse hessian factored representation. It implements algorithm of figure 7 in: Pathfinder: Parallel quasi-newton variational inference, Lu Zhang et al., arXiv:2108.03782 """ J = S.shape[1] StZ = S.T @ Z R = jnp...
5,330,254
def get_geojson_observations(properties: List[str] = None, **kwargs) -> Dict[str, Any]: """ Get all observation results combined into a GeoJSON ``FeatureCollection``. By default this includes some basic observation properties as GeoJSON ``Feature`` properties. The ``properties`` argument can be used to over...
5,330,255
def createFilter(fc, Q, fs): """ Returns digital BPF with given specs :param fc: BPF center frequency (Hz) :param Q: BPF Q (Hz/Hz) :param fs: sampling rate (Samp/sec) :returns: digital implementation of BPF """ wc = 2*pi*fc num = [wc/Q, 0] den = [1, wc/Q, wc**2] dig_tf = sign...
5,330,256
def delete_tc_policy_class(device, parent, classid, namespace=None): """Delete a TC policy class of a device. :param device: (string) device name :param parent: (string) qdisc parent class ('root', 'ingress', '2:10') :param classid: (string) major:minor handler identifier ('10:20') :param namespace...
5,330,257
def create_uno_struct(cTypeName: str): """Create a UNO struct and return it. Similar to the function of the same name in OOo Basic. Returns: object: uno struct """ oCoreReflection = get_core_reflection() # Get the IDL class for the type name oXIdlClass = oCoreReflection.forNam...
5,330,258
def get_dir(): """Return the location of resources for report""" return pkg_resources.resource_filename('naarad.resources',None)
5,330,259
def p_atl_suite(p) : """ atl_suite : NEWLINE INDENT atl_line_stmts DEDENT """ p[0] = p[3]
5,330,260
async def multiwalk(ip, community, oids, port=161, timeout=6, fetcher=multigetnext): # type: (str, str, List[str], int, int, Callable[[str, str, List[str], int, int], List[VarBind]]) -> Generator[VarBind, None, None] """ Executes a sequence of SNMP GETNEXT requests and returns an async_g...
5,330,261
def checkout_commit(repo, commit_id): """ Context manager that checks out a commit in the repo. """ current_head = repo.head.commit if repo.head.is_detached else repo.head.ref try: repo.git.checkout(commit_id) yield finally: repo.git.checkout(current_head)
5,330,262
def SoftCrossEntropyLoss(input, target): """ Calculate the CrossEntropyLoss with soft targets :param input: prediction logicts :param target: target probabilities """ total_loss = torch.tensor(0.0) for i in range(input.size(1)): cls_idx = torch.full((input.size(0),), i, dtype=torch....
5,330,263
def test_base_mult_list_is_empty_without_base_lists(): """ test baseMultList.is_empty is True when there are no baseLists """ assert base_mult_list.is_empty() is True
5,330,264
def composite_layer(inputs, mask, hparams): """Composite layer.""" x = inputs # Applies ravanbakhsh on top of each other. if hparams.composite_layer_type == "ravanbakhsh": for layer in xrange(hparams.layers_per_layer): with tf.variable_scope(".%d" % layer): x = common_layers.ravanbakhsh_set_l...
5,330,265
def edit_expense(expense_id, budget_id, date_incurred, description, amount, payee_id): """ Changes the details of the given expense. """ query = sqlalchemy.text(""" UPDATE budget_expenses SET budget_id = (:budget_id), date_incurred = (:date_incurred), description = (:description), ...
5,330,266
def get_mnist_iterator(batch_size, input_shape, num_parts=1, part_index=0): """Returns training and validation iterators for MNIST dataset """ get_mnist_ubyte() flat = False if len(input_shape) == 3 else True train_dataiter = mx.io.MNISTIter( image="data/train-images-idx3-ubyte", l...
5,330,267
def dataset(): """Get data frame for test purposes.""" return pd.DataFrame( data=[['alice', 26], ['bob', 34], ['claire', 19]], index=[0, 2, 1], columns=['Name', 'Age'] )
5,330,268
def main(number_sites_along_xyz=10, steps=25000, external_field_sweep_start=1, external_field_sweep_end=11, temperature_sweep_start=1, temperature_sweep_end=11): """Run simulation over a sweep of temperature and external field values. Parameters ---------- number_sites_along_xyz : int...
5,330,269
def get_consumer_key(): """This is entirely questionable. See settings.py""" consumer_key = None try: loc = "%s/consumer_key.txt" % settings.TWITTER_CONSUMER_URL url = urllib2.urlopen(loc) consumer_key = url.read().rstrip() except (urllib...
5,330,270
def write_validation3_set_to_file(file, outfile): """ 单独写标签3.0体系到文件 """ tag3 = ["社会", "体育", "娱乐", "财经", "时政", "科技", "时尚", "教育", "情感", "文化", "旅游", "美食", "宠物", "星座命理", "搞笑", "壁纸头像", "生活", "职场", "小说", "国际", "房产", "汽车", "军事", "游戏", "动漫", "育儿", "健康", "历史", "儿童", "知识", "其他...
5,330,271
def disconnect() -> Tuple[str, int]: """Deletes the DroneServerThread with a given id. Iterates over all the drones in the shared list and deletes the one with a matching drone_id. If none are found returns an error. Request: drone_id (str): UUID of the drone. Response: Tuple[str,...
5,330,272
def add_company(context: Context, company: Company): """Will add an Company to Scenario Data. :param context: behave `context` object :param company: an instance of Company Tuple """ assert isinstance( company, Company ), "Expected Company named tuple but got '{}' instead".format(type(c...
5,330,273
def get_graph_feature(x, k=20, idx=None, x_coord=None): """ Args: x: (B, d, N) """ batch_size = x.size(0) num_points = x.size(2) x = x.view(batch_size, -1, num_points) if idx is None: if x_coord is None: # dynamic knn graph idx = knn(x, k=k) else: ...
5,330,274
def get_markers( image_array: np.ndarray, evened_selem_size: int = 4, markers_contrast_times: float = 15, markers_sd: float = 0.25, ) -> np.ndarray: """Finds the highest and lowest grey scale values for image flooding.""" selem = smo.disk(evened_selem_size) evened = sfi.rank.mean_bilateral( ...
5,330,275
def pd_bigdata_read_csv(file, **pd_read_csv_params): """ 读取速度提升不明显 但是内存占用显著下降 """ reader = pd.read_csv(file, **pd_read_csv_params, iterator=True) loop = True try: chunk_size = pd_read_csv_params['chunksize'] except: chunk_size = 1000000 chunks = [] while loop: ...
5,330,276
def PCA(Y_name, input_dim): """ Principal component analysis: maximum likelihood solution by SVD Adapted from GPy.util.linalg Arguments --------- :param Y: NxD np.array of data :param input_dim: int, dimension of projection Returns ------- :rval X: - Nxinput_dim np.array of dimensionality reduced data W - i...
5,330,277
def data_cache_path(page, page_id_field='slug'): """ Get (and make) local data cache path for data :param page: :return: """ path = os.path.join(CACHE_ROOT, '.cache', 'data', *os.path.split(getattr(page, page_id_field))) if not os.path.exists(path): sh.mkdir('-p', path) return pa...
5,330,278
def _get_sequence(value, n, channel_index, name): """Formats a value input for gen_nn_ops.""" # Performance is fast-pathed for common cases: # `None`, `list`, `tuple` and `int`. if value is None: return [1] * (n + 2) # Always convert `value` to a `list`. if isinstance(value, list): pass elif isin...
5,330,279
def make_linear(input_dim, output_dim, bias=True, std=0.02): """ Parameters ---------- input_dim: int output_dim: int bias: bool std: float Returns ------- torch.nn.modules.linear.Linear """ linear = nn.Linear(input_dim, output_dim, bias) init.normal_(linear.weight, ...
5,330,280
def matnorm_logp_conditional_col(x, row_cov, col_cov, cond, cond_cov): """ Log likelihood for centered conditional matrix-variate normal density. Consider the following partitioned matrix-normal density: .. math:: \\begin{bmatrix} \\operatorname{vec}\\left[\\mathbf{X}_{i j}\\right] \\\...
5,330,281
def get_map_folderpath(detectionID): """ Make sure map directory exists and return folder location for maps to be saved to. """ homedir = os.path.dirname(os.path.abspath(__file__)) if not os.path.exists('map'): os.makedirs('map') detection_folder = 'map/'+str(detection...
5,330,282
def get_next_by_date(name, regexp): """Get the next page by page publishing date""" p = Page.get(Page.name == name) query = (Page.select(Page.name, Page.title) .where(Page.pubtime > p.pubtime) .order_by(Page.pubtime.asc()) .dicts()) for p in ifilter(lambda x: regexp.m...
5,330,283
def relative_performance(r_df, combinations, optimal_combinations, ref_method='indp', ref_jt='nan', ref_at='nan', ref_vt='nan', cost_type='Total', deaggregate=False): """ This functions computes the relative performance, relative cost, and univeral relative measure :cite:`Talebiyan2...
5,330,284
def generate_raw_mantissa_extraction(optree): """ generate an operation graph to extraction the significand field of floating-point node <optree> (may be scalar or vector). The implicit bit is not injected in this raw version """ if optree.precision.is_vector_format(): base_precision = o...
5,330,285
def read_temp_f(p): """ read_temp_f Returns the temperature from the probe in degrees farenheit p = 1-Wire device file """ lines = read_temp_raw(p) while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw(p) equals_pos = lines[1].find('t=') if ...
5,330,286
def count_parameters(model, trainable_only=True, is_dict=False): """ Count number of parameters in a model or state dictionary :param model: :param trainable_only: :param is_dict: :return: """ if is_dict: return sum(np.prod(list(model[k].size())) for k in model) if ...
5,330,287
def send_mail(text, to_addr, account): """ Send the email using msmtp. account is the account in .msmtprc """ # check_call does not take input in Python 3.4. # But check_output does?? dummy = subprocess.check_output( ['msmtp', '-d', '-a', account, to_addr], input=text.encode() )
5,330,288
def setup_conf(conf=cfg.CONF): """Setup the cfg for the status check utility. Use separate setup_conf for the utility because there are many options from the main config that do not apply during checks. """ common_config.register_common_config_options() neutron_conf_base.register_core_common_co...
5,330,289
def release_kind(): """ Determine which release to make based on the files in the changelog. """ # use min here as 'major' < 'minor' < 'patch' return min( 'major' if 'breaking' in file.name else 'minor' if 'change' in file.name else 'patch' for file in pathlib.Pat...
5,330,290
def assert_array_equal(x: List[list], y: List[list]): """ usage.scipy: 1 """ ...
5,330,291
def edit_text_file(filepath: str, regex_search_string: str, replace_string: str): """ This function is used to replace text inside a file. :param filepath: the path where the file is located. :param regex_search_string: string used in the regular expression to find what has to be replaced. :param re...
5,330,292
def test_parent_dataset_links(some_interdeps): """ Test that we can set links and retrieve them when loading the dataset """ links = generate_some_links(3) ds = DataSet() for link in links: link.head = ds.guid ds.set_interdependencies(some_interdeps[1]) ds.parent_dataset_link...
5,330,293
def find_sums(sheet): """ Tallies the total assets and total liabilities for each person. RETURNS: Tuple of assets and liabilities. """ pos = 0 neg = 0 for row in sheet: if row[-1] > 0: pos += row[-1] else: neg += row[-1] return pos, neg
5,330,294
def read_links(title): """ Reads the links from a file in directory link_data. Assumes the file exists, as well as the directory link_data Args: title: (Str) The title of the current wiki file to read Returns a list of all the links in the wiki article with the name title """ with...
5,330,295
def test_compile_model_from_params(): """Tests that if build_fn returns an un-compiled model, the __init__ parameters will be used to compile it and that if build_fn returns a compiled model it is not re-compiled. """ # Load data data = load_boston() X, y = data.data[:100], data.target[:...
5,330,296
def writeFEvalsMaxSymbols(fevals, maxsymbols, isscientific=False): """Return the smallest string representation of a number. This method is only concerned with the maximum number of significant digits. Two alternatives: 1) modified scientific notation (without the trailing + and zero in th...
5,330,297
def closedcone(r=1, h=5, bp=[0,0,0], sampH=360, sampV=50, fcirc=20): """ Returns parametrization of a closed cone with radius 'r' and height 'h at basepoint (bpx,bpy,bpz), where 'sampH' and 'sampV' specify the amount of samples used horizontally, i.e. for circles, and vertically, i.e. for height,...
5,330,298
def E_lndetW_Wishart(nu,V): """ mean of log determinant of precision matrix over Wishart <lndet(W)> input nu [float] : dof parameter of Wichart distribution V [ndarray, shape (D x D)] : base matrix of Wishart distribution """ if nu < len(V) + 1: raise ValueError, "dof parameter n...
5,330,299