content
stringlengths
22
815k
id
int64
0
4.91M
def test_staled_job(): """Verify that we can check if a job is staled.""" job = JobProgress({}, amount=1) assert job.is_staled is False job.state = states.STARTED job.add_one_success() assert job.is_staled is False # delete the heartbeat key. job.backend.client.delete(job.backend._get_...
5,290,300
def get_time_ms(frame, position): """Get time in ms and string based on the finishing position :param frame: A frame from AsyncVideoCapture / cv2.VideoCapture :type frame: numpy.ndarray :param position: Position 1-4 :type position: int :return: Time in milliseconds, time as string :rtype: (...
5,290,301
def _extract_license_outliers(license_service_output): """Extract license outliers. This helper function extracts license outliers from the given output of license analysis REST service. :param license_service_output: output of license analysis REST service :return: list of license outlier package...
5,290,302
def maxout(x, pool_size, axis=1): """Maxout activation function. It accepts an input tensor ``x``, reshapes the ``axis`` dimension (say the size being ``M * pool_size``) into two dimensions ``(M, pool_size)``, and takes maximum along the ``axis`` dimension. Args: x (:class:`~chainer.Variab...
5,290,303
def test_fpga_drivers_base(): """ Test accelize_drm.fpga_drivers.FpgaDriverBase. """ from tests.fpga_drivers import FpgaDriverBase from ctypes import c_uint32 library = 'fpga_library.so' fpga_slot_id = 5 base_address = 0x10 fpga_image = 'fpga_image' class Fpga: """Fake ...
5,290,304
def GetNumDistinctChromeVersions(db, build_config, start_date, end_date): """Get the number of distinct chrome versions. This represents the number of successful chrome uprevs. Args: db: cidb.CIDBConnection object. build_config: Name of build config of master builder. start_date: datetime.datetime o...
5,290,305
def install_pip(): """ Install pip using apt-get install. """ #we need to upgrade pip package using pip itself return apt_get_install("python-pip") + pip_install("pip")
5,290,306
def runProcess(exe, working_dir): """ Function that opens a command line and runs a command. Captures the output and returns. Input: - exe: str, string of the command to be run. ! REMEMBER TO ESCAPE CHARS! - working_dir: str, directory where the cmd should be executed ...
5,290,307
def get_os(): """ Determines the type of operating system being used. Needed for when we are loading & saving local files later Parameters ------------ none Returns ------------ os_type : str Type of OS the script is running on Ex: 'linux' is the script is running ...
5,290,308
def center(map, object): """ Center an ee.Image or ee.Feature on the map. Args: map: The map to center the object on. object: The ee.Image or ee.Feature to center. Returns: The provided map. """ coordinates = object.geometry().bounds().coordinates().getInfo()[0] ...
5,290,309
def login_user(): """ Login user in api :return: token """ print('Login') auth = request.authorization # print(request.authorization) if not auth or not auth.username or not auth.password: return make_response('could not verify', 401, {'WWW.Authentication': 'Basic realm: "login r...
5,290,310
def main(): """ Parse CL arguments and run evalutation on the given reference and hypothesis files. """ example = 'Evaluate the performance of a denormalizer.' parser = argparse.ArgumentParser(description=example) add_args(parser) args = parser.parse_args() if args.outfile != sys....
5,290,311
def normalized_diff(b1, b2): """Take two numpy arrays and calculate the normalized difference. Math will be calculated (b1-b2) / (b1+b2). Parameters ---------- b1, b2 : arrays with the same shape Math will be calculated (b1-b2) / (b1+b2). Returns ---------- n_diff : ndarray wit...
5,290,312
def StyledItemDelegateSetModelData(cls, delegate, editor, model, index): # type: (Type[QtWidgets.QStyledItemDelegate], QtWidgets.QStyledItemDelegate, QtWidgets.QWidget, QtCore.QAbstractItemModel, QtCore.QModelIndex) -> Any """PySide appears to force types that can behave as lists (ie. GfMatrix*, GfVec*) to ...
5,290,313
def read_expected_result(test_name): """ :param test_name: :return: """ data_file_path = path.join( get_test_data_prefix(test_name), "Result.xlsx" ) return pd.read_excel( data_file_path, sheet_name=None )
5,290,314
def print_vals(errors, epsilon): """ Prints latest error, guessing rate and learning rate to console, if possible. """ try: print("Error: " + str(errors[-1][0]) + ", Epsilon: " + '{0:05f}'.format(epsilon)) except IndexError: pass
5,290,315
def ConvertTrace(lines, load_vaddrs, more_info): """Convert strings containing native crash to a stack.""" start = time.time() chunks = [lines[i: i+_CHUNK_SIZE] for i in xrange(0, len(lines), _CHUNK_SIZE)] pool = multiprocessing.Pool(processes=_DEFAULT_JOBS) useful_log = itertools.chain(*pool.map(PreProcessL...
5,290,316
def get_json_file_path(): """Opens dialog box for user to choose where to save the measurements. Uses default directory in case of failure. Requires very hacky work-around of installing tk and tcl in NX directories""" try: import tkinter as tk from tkinter import filedialog ...
5,290,317
def clean_fund_nav(date_str): """ wind数据库中存在部分数据净值记录前后不一致的问题 比如:某日记录净值 104,次一后期净值变为 1.04 导致净值收益率走势出现偏差 此脚本主要目的在于对这种偏差进行修正 :param date_str: :return: """ sql_str = """select fn_before.wind_code, fn_before.nav_date nav_date_before, fn_after.nav_date nav_date_after, fn_before.nav_a...
5,290,318
def dash_subprocess(): """ Start a Dash server with subprocess.Popen and waitress-serve. :Example: .. code-block:: python def test_application(dash_subprocess): # consider the application file is named `app.py` dash_subprocess('app') .. seealso:: :py:class:`pytest...
5,290,319
def parse_config_string(config_string, issue_warnings=True): """ Parses a config string (comma-separated key=value components) into a dict. """ config_dict = {} my_splitter = shlex.shlex(config_string, posix=True) my_splitter.whitespace = "," my_splitter.whitespace_split = True for kv_pa...
5,290,320
def dump_sections(path, bank_size=0x4000, initial_bank=0, last_bank=None, separator="\n\n"): """ Returns a str of assembly source code. The source code delineates each SECTION and includes bytes from the file specified by baserom. """ if not last_bank: last_bank = calculate_bank_quantity(pat...
5,290,321
def create_node_private_key_file(): """ Create the node's private key file. The example of the configuration file is located in the tests fixture folder. """ fixture_file_path = os.getcwd() + '/tests/fixtures/validator.priv' pathlib.Path(NODE_PRIVATE_KEY_DIRECTORY_PATH).mkdir(parents=True, exi...
5,290,322
def train(estimator_specs): """Train your model defined by ``estimator_specs``. Here is where all the main flow is defined to train your model. The following steps take place: * Read the dataset (from tf-records or csv) into `tf.data.Dataset <https://www.tensorflow.org/api_docs/python/tf/data/Dataset>...
5,290,323
def security(session): """Package Security Report (badge)""" logs = reports_path / "security.log" report = reports_path / "security.json" with logs.open("w") as handler: session.run("bandit", "-v", "-f", "json", "-o", str(report), "-r", package_name, stdout=handler) with ...
5,290,324
def load_data_clf(ds_name): """ Load the data for classification by the specified dataset name. Parameters ---------- ds_name : str Returns ------- data : DataFrame """ ds_load_func = None if ds_name in DS_LOAD_FUNC_CLF.keys(): ds_load_func = DS_LOAD_FUNC_CLF[ds_na...
5,290,325
def parse_file_name(file_name): """ <Purpose> Parses a file name to identify its module and its descriptor <Arguments> file_name: the name of the test file <Exceptions> InvalidTestFileError: if you provide a test file which does not follow the naming convention of 'ut_<module>_<descriptor>...
5,290,326
def _proto_builder_test_impl(ctx): """The implementation of the 'proto_builder_test' rule. Tests the files generated by the 'proto_builder' rule. The test performs a textual comparison of the generated source and header with the expected source and header respectively. Args: ctx: The current...
5,290,327
def _make_nxm_w (*args, **kw): """ Make a simple wildcarded NXM entry class """ t = _fix_types(kw.pop('type', _nxm_maskable_numeric_entry)) ok = False for tt in t: if _issubclass(tt, _nxm_maskable): ok = True break if not ok: t.insert(0, _nxm_maskable) return _make_nxm(*args, type=t...
5,290,328
def gasfrac_hess(mstar, fgas, weight, label, output, mmin=8.5, mmax=11.7, nmbins=16, fgasmin=0.0, fgasmax=1.0, nfbins=10, pmax=1.0, pmin=0.01): """ Plot _conditional_ distribution of gas fraction vs. stellar mass. Ported from an IDL code, should be cleaned....
5,290,329
def process_datasets(dataset_class, dataset_args, unc_model, device, test_fn=test_unc_model, N=1000, **forward_kwargs): """ calls test_fn(unc_model, dataset) for every dataset in datasets """ results = {} for name in dataset_args: print("Testing", name) print(N) dataset = dat...
5,290,330
def accuracy_metric(actual, predicted, correct=0) -> float: """calculate accuracy of the dataset comparing the actual test label vs the predicted label""" for i in range(len(actual)): if actual[i] == predicted[i]: correct += 1 return correct / len(actual) * 100.0
5,290,331
def get_test_case( data: pd.DataFrame, model: Any, key: str, add: ARITHEMETIC_OPERATIONS = None, multiply: ARITHEMETIC_OPERATIONS = None, ) -> SCORES: """ Helper method to create the different test cases that alter the keys in a dictionary """ # Create a deepcopy of the data whic...
5,290,332
def realign_mol(mol,conf,coord_Map, alg_Map, mol_template, maxsteps): # RAUL: This function requires a clear separation between minimization and alignment. """ Minimizes and aligns the molecule provided freezing the atoms that match the mol_template. Parameters ---------- mol : rdkit.Chem.Mol...
5,290,333
def measure_shadow_work(simulation, n_steps): """Run the simulation for n_steps and return a vector of the shadow work accumulated during integration. * Check whether simulation.integrator has bookkeeping variables W_shad and/or heat. * If only W_shad is available, measure shadow work as W_shad * I...
5,290,334
async def _reduce(out, fn, ch, init): """Reduce items from channel.""" acc = init async for x in ch: acc = fn(acc, x) await out.put(acc) out.close()
5,290,335
def github_archive(name, repo_name, commit, sha256 = None, kind = "zip"): """Defines a GitHub commit-based repository rule.""" project = repo_name[repo_name.index("/"):] http_archive( name = name, sha256 = sha256, strip_prefix = "{project}-{commit}".format(project = project, commit =...
5,290,336
def cumulative_cross_corr(I1, I2): """ doing normalized cross correlation on distance imagery :param I1: NP.ARRAY (_,_) binary array :param I2: NP.ARRAY (_,_) binary array :return result: NP.ARRAY (_,_) similarity surface ...
5,290,337
def getGbdbTables(database, tableset): """ Remove tables that aren't pointers to Gbdb files.""" sep = "','" tablestr = sep.join(tableset) tablestr = "'" + tablestr + "'" hgsqlOut = qaUtils.callHgsql(database, "select table_name from information_schema.columns where\ ...
5,290,338
def four_bar_plane_truss(num_samples: int = 100, distribution: str = "lhs") -> list: """Four bar plane truss problem. As found in Multiobjective structural optimization using a microgenetic algorithm. Parameters ---------- x : list or ndarray Should have 4 elements Returns ------- ...
5,290,339
def parseFile (pomFile): """ Parses a pom.xml file and returns a Maven object or None """ with open (pomFile, 'rb') as f: return parseString (f.read()) return None
5,290,340
def register_error_handlers(a=app): """Register error handlers.""" # @see https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-error-handling @a.errorhandler(500) def handle_internal(error): db.session.rollback() flash(_('Error: %s') % error, 'error') return rend...
5,290,341
def evaluations_to_columns(evaluation): """Convert the results of :meth:`metrics.ScoringMixIn.evaluate` to a pandas DataFrame-ready format Parameters ---------- evaluation: dict of OrderedDicts The result of consecutive calls to :meth:`metrics.ScoringMixIn.evaluate` for all given dataset types ...
5,290,342
def get_metric(name: str, **kwargs) -> abc.Callable: """Returns metric function for given metric name Parameters ---------- name : str Metric name kwargs : any Additional keyword-arguments for metric Returns ------- metric : callable Metric callable or partial c...
5,290,343
def resource_exists(env, resource): """Checks for resource existence without actually instantiating a model. :return: `True` if the resource exists, `False` if it doesn't and `None` in case no conclusion could be made (i.e. when `IResourceManager.resource_exists` is not ...
5,290,344
def run_dqmc(p, unequal_time=True, callback=None, progress=False, *args, **kwargs): """Runs a DQMC simulation. Parameters ---------- p : Parameters The input parameters of the DQMC simulation. unequal_time : bool If `True`, unequal-time measurements will be performed. callback :...
5,290,345
def iter_upoints(vs): """Iterate through all untyped points in an N-dimensional space. Parameters ---------- vs : [Variable] """ for num in range(1 << len(vs)): yield num2upoint(num, vs)
5,290,346
def he_init(m): """He weight initialization """ if type(m) == nn.Conv2d: torch.nn.init.kaiming_uniform_(m.weight) elif type(m) == nn.Linear: torch.nn.init.kaiming_uniform_(m.weight)
5,290,347
def merge(left: list, right: list) -> list: """Merges 2 sorted lists (left and right) in 1 single list, which is returned at the end. Time complexity: O(m), where m = len(left) + len(right).""" mid = [] i = 0 # Used to index the left list. j = 0 # Used to index the right list. while i < ...
5,290,348
def replace(i_list: list, target: int,new_value: int)-> list: """ Replace all the target value with a new value :param i_list: the list to be analyzed :param value: the value to replace :param target: the value to be replaced :return: the new list """ return list(map(lambda value: new_va...
5,290,349
def run(shower_source, pipeline): """Attaches the pipeline to the event generator, and then runs it.""" shower_source.attach(pipeline) with click.progressbar(shower_source) as events: for event in events: event.notify()
5,290,350
def single(request, id, template_name="microblogging/single.html"): """ A single tweet. """ tweet = get_object_or_404(Tweet, id=id) return render_to_response(template_name, { "tweet": tweet, }, context_instance=RequestContext(request))
5,290,351
def generate_responses(prompt, pipeline, seed=None, debug=False, **kwargs): """Generate responses using a text generation pipeline.""" if seed is not None: set_seed(seed) outputs = pipeline(prompt, **kwargs) responses = list(map(lambda x: clean_text(x['generated_text'][len(prompt):]), outputs))...
5,290,352
def astropy_tabular_data(*args, **kwargs): """ Build a data set from a table. We restrict ourselves to tables with 1D columns. All arguments are passed to astropy.table.Table.read(...). """ result = Data() with warnings.catch_warnings(): warnings.simplefilter("ignore") ...
5,290,353
def words_cmp(a, b): """ word比较器 :param a: (word, 词频) :param b: (word, 词频) :return: [-1|0|1] """ a_word, a_freq = a b_word, b_freq = b if a_freq != b_freq: return b_freq - a_freq elif a_word != b_word: return -1 if a_word < b_word else 1 else: return 0
5,290,354
def _load_data(args): """Load data from path.""" if args.data_format == 'CULANE': return vega.dataset("AutoLaneDataset", dataset_format="CULane", data_path=args.data_path, mode="test", batch_size=args.batch_size).loader elif args.data_format == 'COCO': return ...
5,290,355
def extract_u_nk(xvg, T): """Return reduced potentials `u_nk` from a Hamiltonian differences XVG file. Parameters ---------- xvg : str Path to XVG file to extract data from. T : float Temperature in Kelvin the simulations sampled. Returns ------- u_nk : DataFrame ...
5,290,356
def start_data_collection_by_agent_ids(agentIds=None): """ Instructs the specified agents or connectors to start collecting data. See also: AWS API Documentation Exceptions :example: response = client.start_data_collection_by_agent_ids( agentIds=[ 'string', ] ...
5,290,357
def group(query, fields=None, step=None): """Group results by `fields` and/or `step`.""" if fields is None: fields = [] if isinstance(fields, string_types): fields = [fields] fields = ['"%s"' % f for f in fields] if step: fields.insert(0, 'time(%s)' % step) return '%s GRO...
5,290,358
def register_thermoml_property( thermoml_string, supported_phases, property_class=None, conversion_function=None ): """A function used to map a property from the ThermoML archive to an internal `PhysicalProperty` object of the correct type. This function takes either a specific class (e.g. `Density`) ...
5,290,359
def first_level_directory(path): """Return the first level directory of a path. >>> first_level_directory('home/syt/work') 'home' >>> first_level_directory('/home/syt/work') '/' >>> first_level_directory('work') 'work' >>> :type path: str :param path: the path for which we want...
5,290,360
def get_plugin_option(name, options): """ Retrieve option name from options dict. :param options: :return: """ for o in options: if o.get('name') == name: return o['value']
5,290,361
def verify_uri( endpoint_context: EndpointContext, request: Union[dict, Message], uri_type: str, client_id: Optional[str] = None, ): """ A redirect URI MUST NOT contain a fragment MAY contain query component :param endpoint_context: An EndpointContext instance :param request: Th...
5,290,362
def run_cc(hf): """ Run and return a restricted CCSD calculation on mol, with HF molecular orbital coefficients in the RHF object hf. """ if type(hf) == SCF_TYPES['RHF']: calc_cls = cc.CCSD elif type(hf) == SCF_TYPES['UHF']: calc_cls = cc.UCCSD else: raise NotImplemen...
5,290,363
def contains( name, value, count_lt=None, count_lte=None, count_eq=None, count_gte=None, count_gt=None, count_ne=None, ): """ Only succeed if the value in the given register location contains the given value USAGE: .. code-block:: yaml foo: check....
5,290,364
async def top_salty(): """ ### Returns top 10 saltiest user - Takes `/top_salty` ### Response `id` - userid `username` - username `saltiness` - saltiness `salty_description` = salty description """ QUERY = "SELECT * FROM users ORDER BY saltiness limit 10" pg_conn=db_conec...
5,290,365
def to_datetime( arg: List[ Literal[ "1950-01-05 00:40:00", "1950-01-04 00:30:00", "1950-01-03 00:20:00", "1950-01-02 00:10:00", "1950-01-01 00:00:00", ] ] ): """ usage.statsmodels: 1 """ ...
5,290,366
def thai_strftime( datetime: datetime.datetime, fmt: str, thaidigit: bool = False ) -> str: """ Convert :class:`datetime.datetime` into Thai date and time format. The formatting directives are similar to :func:`datatime.strrftime`. This function uses Thai names and Thai Buddhist Era for these dire...
5,290,367
def test_p2p_service_discovery2(dev): """P2P service discovery with one peer having no services""" dev[2].p2p_listen() for dst in [ "00:00:00:00:00:00", dev[0].p2p_dev_addr() ]: ev = run_sd(dev, dst, "02000001") if "0b5f6166706f766572746370c00c000c01" not in ev: raise Exception("...
5,290,368
def register_to_sys_with_admin_list(class_inst, admin_list=None, is_normal_admin_needed=False): """ :param class_inst: model class :param admin_list: admin class :param is_normal_admin_needed: is normal admin registration needed :return: """ if admin_list is None: admin_class = get_v...
5,290,369
async def test_user_adds_unusable_device(opp, airplay_device): """Test that it is not possible to add pure AirPlay device.""" result = await opp.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) result2 = await opp.config_entries.flow.async_configure( ...
5,290,370
def dot_product(t1, t2, keep_dims=False, name=None, reduction_dim=None): """Computes the dot product of t1 and t2. Args: t1: A rank 2 tensor. t2: A tensor that is the same size as t1. keep_dims: If true, reduction does not change the rank of the input. name: Optional name for this op. reduction...
5,290,371
def writeMonthlyTeX(panchangam, template_file): """Write out the panchangam TeX using a specified template """ day_colours = {0: 'blue', 1: 'blue', 2: 'blue', 3: 'blue', 4: 'blue', 5: 'blue', 6: 'blue'} month = {1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY...
5,290,372
def assert_boolean(raw_val): """ Assert that the value is boolean. :return The value if it is boolean, otherwise raise an exception """ return assert_type(raw_val, bool)
5,290,373
def classic_vs_bayesian_normal(mu, sigma, num_points, prior): """ Compute both classical and Bayesian inference processes over the range of data sample sizes (num_points) for a normal distribution with parameters mu,sigma for comparison. Args: mu (scalar): the mean parameter of the normal distribution ...
5,290,374
def get_canonical_synonym(key): """Returns canonical synonym for key, else just key. """ if key == 'SAMPLE': return MELTED_SCHEMA_KEY__ES_LABEL return key
5,290,375
def get_batch_pipe(data, neox_args): """A modification of get_batch() to work with the latest batch instead of an iterator.""" # Items and their type. keys = ["text"] datatype = torch.int64 tokens, labels, loss_mask, attention_mask, position_ids = _get_batch( neox_args, neox_args.tokenizer,...
5,290,376
def compute_precision(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(k=maxk, dim=1, largest=True, sorted=True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) ...
5,290,377
def get_landmark_model(output_size) -> torch.nn.Module: """Build the convolutional network model with Keras Functional API. Args: output_size: the number of output node, usually equals to the number of marks times 2 (in 2d space). Returns: a model """ model = torch.nn.Sequential( ...
5,290,378
def isPerfectSquare(p: int) -> bool: """Checks if given number is a perfect square. A perfect square is an integer that is a square of another integer. Parameters: p: int number to check Returns: result: bool True if number is a perfect square F...
5,290,379
def frequencies_for_cutoffs(col, cutoffs): """ Sets cutoffs for the frequencies """ # Sets each frequency to 0 by default freqs = [0] * len(cutoffs) for el in col: for i in range(len(cutoffs)): if el <= cutoffs[i]: freqs[i] += 1 break return freqs
5,290,380
def main(): """Execute Main program.""" if len(sys.argv) != 2: print(r"Usage: python buildscripts\make_vcxproj.py FILE_NAME") return with ProjFileGenerator(sys.argv[1]) as projfile: with open("compile_commands.json", "rb") as sjh: contents = sjh.read().decode('utf-8') ...
5,290,381
def find(user_id, session): """ Find all the history. :param user_id: history user_id :param session: session :return: history data. """ result = [] fetch = session.query(KMHistory) for history in fetch.filter_by(user_id=user_id).all(): result.append(history) return resul...
5,290,382
def fetch(url, data='', agent=None, referrer=None, charset=None, verbose=0, cookiejar={}, type=None, method=None, accept_language=None): """Make an HTTP or HTTPS request. If 'data' is given, do a POST; otherwise do a GET. If 'agent', 'referrer' and/or 'accept_language' are given, include them as...
5,290,383
def emolument_new_view(request): """ Add new emolument """ # Check authorization if not Utils.has_permission(request, request.registry.settings['affaire_facture_edition']): raise exc.HTTPForbidden() params = request.params data = json.loads(params['data']) emolument_affaire_id =...
5,290,384
def display(auth_context): """ View function for displaying the checkout page. Parameters: auth_context (dict): The authentication context of request. See middlewares/auth.py for more information. Output: Rendered HTML page. """ products = [] # Pre...
5,290,385
def golden_ratio(n): """returns the Golden Ratio to an accuracy of `n` decimal places Examples -------- >>> print(golden_ratio(20)) 1.61803398874989484820 >>> print(golden_ratio(50)) 1.61803398874989484820458683436563811772030917980576 """ x = _sym.symbols('x') gr = [sol for sol...
5,290,386
async def _is_new_version_available() -> bool: """Return `True` if a newer archive of the repo at http://github.com/zwave-js/node-zwave-js is available.""" file_updated_at = _load_db_from_file().get(UPDATED_AT) if file_updated_at is None: _LOGGER.debug("File has not yet been created") return...
5,290,387
def totalbp(file): """Count total number of sequenced base pairs""" with open(file, 'r') as Infile: loci = '' Count = 0 Loci_count = 0 start = False for line in Infile: #count first locus if Loci_count == 0: ...
5,290,388
def _raw_data_verifier(tmp_dir, test_mode=False): """Raw data verifier for DEAP dataset.""" preproc_python_dir = os.path.join(DEFAULT_DEAP_ROOT, "preproc_python/*") files = get_input_file_paths(preproc_python_dir, True, 1) for file in files: if not file.endswith(".dat"): raise ValueError("Expected fil...
5,290,389
def setup(hass, config): """Setup the MySensors component.""" import mysensors.mysensors as mysensors version = config[DOMAIN].get(CONF_VERSION) persistence = config[DOMAIN].get(CONF_PERSISTENCE) def setup_gateway(device, persistence_file, baud_rate, tcp_port, in_prefix, out_...
5,290,390
def parseArguments(): """ I haven't taken the time to learn getopt, so I use regular expressions. """ options[ 'graffle' ] = 'OmniGraffle 5' options[ 'dbhost' ] = 'localhost' options[ 'dbport' ] = 5432 options[ 'dbuser' ] = '' options[ 'dbpass' ] = '' options[ 'dbname' ] = '' options[ 'schema' ] = 'public' ...
5,290,391
def putEntry(key, value, keyColor=bold, valueColor=black): """ Write a key value pair to the console in a nicely formatted way """ putln("{}{}: {}{}".format(keyColor, key, valueColor, value)) clear()
5,290,392
def oppositeFunction(basef): """ the opposite of a function """ if isinstance(basef, FitnessEvaluator): if isinstance(basef, FunctionEnvironment): ''' added by JPQ ''' if isinstance(basef, MultiObjectiveFunction): res = MultiObjectiveFunction() else: ...
5,290,393
def entry_point(): """Entry point for the application activate by command sapera in terminal """ args = sys.argv[1:] # todo add [options] if os.name == "nt": # for windows os.system("cls") else: # linux or mac os.system("clear") if len(args) == 1: if args[0] ...
5,290,394
def test_frontend_can_handle_unhandled_service_initialization_exceptions(): """When a service crashes on initialization an exception should be thrown.""" transport = mock.Mock() fe = workflows.frontend.Frontend( transport=transport, service=assert_single_call_only(ServiceCrashingOnInit) ) t...
5,290,395
def _state(base, kwargs): """Gets version and package_data. Writes MANIFEST.in. Args: base (dict): our base params Returns: dict: base updated """ state = {} sha = '\n' if not 'version' in kwargs: state['version'], s = _version(base) if s: sha = ...
5,290,396
def main(): """Change input text to all caps or all lower""" args = get_args() # set the file handle to either the supplied outfile or stdout out_fh = open(args.outfile, 'wt') if args.outfile else sys.stdout # write to the file handle the args,text which is text from a file # or supplied text ...
5,290,397
def cell(n): """Format a cell""" return '{:3} {:5}'.format( n, 'SPACE' if n == 32 else 'DEL' if n == 127 else chr(n) if n >= 33 else 'NA')
5,290,398
def shape_arrays_for_pcolor_plotting(ps, indexing_list_indep_vars, ordered_params, dep_var_mgf): """ """ X = ps.get_mgf_arr(ordered_params[0].name)[ tuple(indexing_list_indep_vars)] Y = ps.get_mgf_arr(ordered_params[1].name)[ tuple(indexing_list_indep_vars)] Z = None if (np.shape(d...
5,290,399