content
stringlengths
22
815k
id
int64
0
4.91M
def handle_switches(args, sysroot): """Fetch the targeted binary and determine how to attach gdb. Args: args: Parsed arguments. sysroot: Local sysroot path. Returns: (binary_file, attach_pid, run_cmd). Precisely one of attach_pid or run_cmd will be None. """ device...
5,344,000
def dot2states(dot): """Translate a dot-bracket string in a sequence of numerical states""" dot = dot.replace(".", "0") # Unpaired dot = dot.replace("(", "1") # Paired dot = dot.replace(")", "1") # Paired return np.array(list(dot), dtype=int)
5,344,001
def _create_all_schemata(): """ Create all of the schemata, just in case they haven't yet been created. """ cursor = connection.cursor() cursor.execute("SELECT count(*)>0 FROM information_schema.tables WHERE table_name = 'boardinghouse_schema'") if cursor.fetchone() == (True,): for schem...
5,344,002
def mel_to_hz(mels, htk=False): """Convert mel bin numbers to frequencies Examples -------- >>> librosa.mel_to_hz(3) 200. >>> librosa.mel_to_hz([1,2,3,4,5]) array([ 66.667, 133.333, 200. , 266.667, 333.333]) Parameters ---------- mels : np.ndarray [shape=(n,)],...
5,344,003
def test_outfile_british_american2(): """ Runs on good input """ run(AMERICAN, BRITISH, EXPECTED3)
5,344,004
def _iter_population(draws, tune, popstep, steppers, traces, points): """Iterate a ``PopulationStepper``. Parameters ---------- draws: int number of draws per chain tune: int number of tuning steps popstep: PopulationStepper the helper object for (parallelized) stepping ...
5,344,005
def load_images(images): """ Decodes batch of image bytes and returns a 4-D numpy array. """ import numpy as np batch = [] for image in images: img_np = readImage(image) batch.append(img_np) batch_images = np.concatenate(batch) logger.info('batch_images.shape:%s'%(str(b...
5,344,006
def dumplist(args): """Dumps lists of files based on your criteria""" db = Database() objects = db.objects( protocol=args.protocol, purposes=args.purposes, groups=args.groups, kinds=args.kinds ) output = sys.stdout if args.selftest: from bob.db.base.uti...
5,344,007
def stats_hook(): """ decorator to register a stats hook. :raises InvalidStatsHookTypeError: invalid stats hook type error. :returns: stats hook class. :rtype: type """ def decorator(cls): """ decorates the given class and registers an instance of it into available...
5,344,008
def safe_infer(node, context=None): """Return the inferred value for the given node. Return None if inference failed or if there is some ambiguity (more than one node has been inferred). """ try: inferit = node.infer(context=context) value = next(inferit) except exceptions.Infer...
5,344,009
def start_session(config_path): """Lanuch tmuxp in a new terminal window.""" subprocess.Popen( ["rofi-sensible-terminal", "-e", "tmuxp", "load", str(config_path)], stdout=subprocess.DEVNULL, )
5,344,010
def test_get_order( rotation_matrix, translation_vector, repr_matrix, repr_has_cc, result, numeric ): """ Check that the ``get_order`` method matches the expected result. """ sym_op = sr.SymmetryOperation( rotation_matrix=rotation_matrix, translation_vector=translation_vector, ...
5,344,011
def catch_exception(func): """ Returns: object: """ @functools.wraps(func) def wrapper(*args, **kwargs): worker = kwargs['error_catcher'] try: return func(*args, **kwargs) except Exception as e: print('stdout:', worker.stdout.read().decode("ut...
5,344,012
def RandomCrop(parent, new_shape, name=""): """\ Crop an image layer at a random location with size ``[height, width]``. :param parent: parent layer :param new_shape: [height, width] size :param name: name of the output layer :return: CropRandom layer """ return _eddl.RandomCrop(parent,...
5,344,013
def test_Compile_WrapMethodInClass_syntax_error(): """Test that error is raised if method contains a syntax error.""" with test.Raises(errors.BadCodeException): java.Compile(java.WrapMethodInClass("!@///"))
5,344,014
def run_client(instance): """ Start a client process """ port = [1008, 8989, 9002][instance] cpu = ['(3,4)', '(5,6)', '(7,8)'][instance] # TODO: the following line is an example of code that is not suitable! # should switch to run_udp_app instead of this function # ips = [[_server_ip...
5,344,015
def get_linear_sys(eqns, params): """Gets the linear system corresponding to the symbolic equations Note that this function only work for models where the left-hand side of the equations all contain only linear terms with respect to the given model parameters. For these linear cases, this function will...
5,344,016
def slightly(membership: npt.ArrayLike) -> npt.ArrayLike: """ Applies the element-wise function fn(u) = u^(1/2). :param membership: Membership function to be modified. >>> from fuzzy_expert.operators import slightly >>> slightly([0, 0.25, 0.5, 0.75, 1]) array([0. , 0.16326531, 0.9969618...
5,344,017
def pfxstrokes(fn="string",pc=1,sl=1): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/pfxstrokes.html ----------------------------------------- pfxstrokes is NOT undoable, NOT queryable, and NOT editable. This command will loop through all the Paint Effects strokes, including pfx...
5,344,018
def int_max(int_a, int_b): """ max(a, b) """ if int_a > int_b: return int_a else: return int_b
5,344,019
def extract_depth_map(frame): """ Extract front-view lidar camera projection for ground-truth depth maps """ (range_images, camera_projections, range_image_top_pose) = frame_utils.parse_range_image_and_camera_projection(frame) for c in frame.context.camera_calibrations: if dataset_pb2.CameraName.Name.Nam...
5,344,020
def cross(vect1, vect2): """ Returns cross product of two vectors. Examples ======== >>> from sympy.vector import CoordSys3D >>> from sympy.vector.vector import cross >>> R = CoordSys3D('R') >>> v1 = R.i + R.j + R.k >>> v2 = R.x * R.i + R.y * R.j + R.z * R.k >>> cross(v1, v2) ...
5,344,021
def get_cognates(wordlist, ref): """ Retrieve cognate sets from a wordlist. """ etd = wordlist.get_etymdict(ref=ref) cognates = {} if ref == "cogids": for cogid, idxs_ in etd.items(): idxs, count = {}, 0 for idx, language in zip(idxs_, wordlist.cols): ...
5,344,022
def test_ir_to_rgb_calibration(get_depthcamera): """ Tests the depthcamera's ir_to_rgb_calibration method. """ depthcamera = get_depthcamera depthcamera_model = check_device_types.get_device_model(depthcamera) if depthcamera_model == Devices.depthcamera_g1: with pytest.raises(PySproutEr...
5,344,023
def get_actress_string(_movie, s): """Return the string of the actress names as per the naming convention specified Takes in the html contents to filter out the actress names""" a_list = get_actress_from_html(_movie, s) actress_string = '' # if javlibrary returns no actresses then we'll just ...
5,344,024
def test_shortuuid_uuid(): """Test shortuuid_to_uuid and uuid_to_shortuuid""" uuid = "5CF8D91E-DCEB-4CC3-BFF7-920B05564EB0" shortuuid = "JYsxugP9UjetmCbBCHXcmu" assert uuid_to_shortuuid(uuid) == shortuuid assert shortuuid_to_uuid(shortuuid) == uuid
5,344,025
def get_route_by_id(): """ GET /routes/<id> :return: """ req = client.routes.get(domain=domain, route_id="6012d994e8d489e24a127e79") print(req.json())
5,344,026
def get_lessons_of_day(day): """ Returns the lessons as a string for the given day webelement :param day: day webelement :return: dictionary with day as key and list with lessons as value """ day_lessons = [] to_iterate = day.find_elements_by_class_name('event-content') to_iterate.reve...
5,344,027
def main(season=None): """Get a list of (winner,loser) pairs for every NCAA men's basketball game in the specified season (season==2010 means the 2010-2011 seaon). """ today = datetime.datetime.today().date() if not season: # Figure out what season it is. season = today.year - 1 if t...
5,344,028
async def test_if_fires_on_change_with_template_advanced(hass, start_ha, calls): """Test for firing on change with template advanced.""" context = Context() await hass.async_block_till_done() hass.states.async_set("test.entity", "world", context=context) await hass.async_block_till_done() asser...
5,344,029
def version_map_to_rst(full_version, version_family, ver_map): """ Return a version of the version map that is suitable for printing. """ none_found_msg = '* No SIMP Mapping Data Found for "' + full_version + '"' # Easy cop out if not ver_map: return none_found_msg simp_release_list = __g...
5,344,030
def progressbar(total, alive, desc=None): """ progressbar for single file uploading, downloading, copying :param cpfilepath: checkpoint file :param total: file size :param alive: 0-init state; 1-task complete; 2-task failed :param desc: :return: """ with tqdm(total=total, unit="B",...
5,344,031
def run_command(name, command, cwd, module, logdir, results): """Run a command and log the stdout and stderr. :arg command: command argument list :arg cwd: current directory to run the command :arg module: the ansible module object :arg logdir: where to place stdout and stderr logs :arg results...
5,344,032
def resize_cluster(checkpoint, new_size, debug=True): """Resize cluster to given size. Inputs: checkpoint: A scalar tensor of type string, new peers should be able to restore to this checkpoint. new_size: A scalar tensor of type int32, the new cluster size. Returns: A pair of scalar...
5,344,033
def log_test(): """" Issue logs at each level """ print('Issuing five messages...') for l, n in zip([logger], ['logger']): print(n) l.debug('A debug message') l.info('A info message') l.warning('A warning message') l.error('A error message') l.critical...
5,344,034
def ising_hamiltonian(n_qubits, g, h): """ Construct the hamiltonian matrix of Ising model. Args: n_qubits: int, Number of qubits g: float, Transverse magnetic field h: float, Longitudinal magnetic field """ ham_matrix = 0 # Nearest-neighbor interaction spin_coupling = ...
5,344,035
def declare_eq_bus_vm_approx(model, index_set, PTDF=None, rel_ptdf_tol=None, abs_ptdf_tol=None): """ Create the equality constraints or expressions for voltage magnitude (from PTDF approximation) at the bus """ m = model con_set = decl.declare_set("_con_eq_bus_vm_approx_set", model, index_set)...
5,344,036
def test_main( mock_building_parser, mock_return_logger, config_dict, db_connection, monkeypatch, test_dir, ): """Test main()""" def mock_parser(*args, **kwargs): parser = Namespace( cache_dir=(test_dir / "test_outputs" / "test_outputs_uniprot"), ...
5,344,037
def _slots_from_params(func): """List out slot names based on the names of parameters of func Usage: __slots__ = _slots_from_signature(__init__) """ funcsig = signature(func) slots = list(funcsig.parameters) slots.remove('self') return slots
5,344,038
def gnd_to_wd_id(gnd_id): """ Searches for a Wikidata entry which contains the provided GND ID. Outputs the Wikidata ID (if found). --------- gnd_id : str GND ID of entity. Returns ----------- str. """ url = 'https://query.wikidata.org/bigdata/namespace/wdq/sparq...
5,344,039
def get_instance_category(entry) -> Optional[str]: """Determines the instance category for which the entry was submitted. If it does not match the config of any instance category, returns None. """ instance_categories = RidehailEnv.DIMACS_CONFIGS.ALL_CONFIGS entry_config = entry[...
5,344,040
def extendheader(table, fields): """ Extend header row in the given table. E.g.:: >>> import petl as etl >>> table1 = [['foo'], ... ['a', 1, True], ... ['b', 2, False]] >>> table2 = etl.extendheader(table1, ['bar', 'baz']) >>> table2 +...
5,344,041
def _rzz(theta: float, q0: cirq.Qid, q1: cirq.Qid) -> cirq.OP_TREE: """Implements the Rzz Ising coupling gate (i.e. exp(-1j * theta * zz)) using Sycamore gates. Args: theta: The rotation parameter of Rzz Ising coupling gate. q0: First qubit to operate on q1: Second qubit to operate on ...
5,344,042
def get_teamcount(): """Get a count of teams.""" #FINISHED FOR SASO teamlist = get_list_of_teams() return len(teamlist)
5,344,043
def make_adjacencyW(I, D, sigma): """Create adjacency matrix with a Gaussian kernel. Args: I (numpy array): for each vertex the ids to its nnn linked vertices + first column of identity. D (numpy array): for each data the l2 distances to its nnn linked vertices ...
5,344,044
def blackbody2d(wavelengths, temperature): """ Planck function evaluated for a vector of wavelengths in units of meters and temperature in units of Kelvin Parameters ---------- wavelengths : `~numpy.ndarray` Wavelength array in units of meters temperature : `~numpy.ndarray` ...
5,344,045
def record_metrics(metrics, args): """ Record the metrics recorded in the metrics dictionary to a metrics file """ with open('attacker_metrics/input_reduction_metrics_{}'.format(args.file_num), 'a') as f: f.write("META DATA\n") f.write("---------\n") f.write("Model Name: {}\n".fo...
5,344,046
def bookShop(): """ Este programa resuelve el siguiente ejercicio: Book Shop Link: https://cses.fi/problemset/task/1158 Este programa retorna el máximo número de páginas que se pueden conseguir comprando libros dados el precio y páginas de los libros disponibles y la cantidad de dinero disponible. """ ...
5,344,047
def test_data_modules(dm_cls: Type[LightningDataModule], stratified: bool) -> None: """Test the datamodules.""" dm = _create_dm(dm_cls, stratified) loader = dm.train_dataloader() batch = next(iter(loader)) assert batch.x.size() == torch.Size([BATCHSIZE, *dm.size()]) assert batch.s.size() == torc...
5,344,048
def pdf(x, nu, sigma): """ PDF for the Rice distribution. """ if x <= 0: return mpmath.mp.zero with mpmath.extradps(5): x = mpmath.mpf(x) nu = mpmath.mpf(nu) sigma = mpmath.mpf(sigma) sigma2 = sigma**2 p = ((x / sigma2) * mpmath.exp(-(x**2 + nu**2)/(2*...
5,344,049
def get_310_prob(score_prob_dct: dict) -> typing.Dict[str, float]: """get home win, draw, away win prob""" prob = {} result_dct = get_score_pairs(0) type_dict = ['home_win', 'draw', 'away_win'] for i in type_dict: prob[i] = get_one_prob(score_prob_dct, result_dct, i) sum_value = float...
5,344,050
def test__getBarFCNameNL(): """Test __getBarFCNameNL function.""" tests = {None: None, 0: 'Zware storm', 500: 'Zware storm', 973: 'Zware storm', 974: 'Storm', 981: 'Storm', 989: 'Storm', 990: 'Regen en wind', ...
5,344,051
def load_project_data(storage): """Load project data using provided open_func and project directory.""" # Load items and extractors from project schemas = storage.open('items.json') extractors = storage.open('extractors.json') # Load spiders and templates spider_loader = SpiderLoader(storage) ...
5,344,052
def bidir_bfs(ADT,start,end): """Bidirectional Breadth First Search""" #create queues with rule of first-in-first-out #queue1 for bfs from start #queue2 for bfs from end queue1=[] queue1.append(start) queue2=[] queue2.append(end) visited1=[] visited2=[] ...
5,344,053
def PBH_HASH_update(db, hash_name, hash_field_list): """ Update object in PBH_HASH table """ ctx = click.get_current_context() hash_name_validator(ctx, db.cfgdb_pipe, hash_name) table = str(PBH_HASH_CDB) key = str(hash_name) data = {} if hash_field_list is not None: hash_field_li...
5,344,054
def home(): """ Route to display home page and form to receive text from user for speech synthesis. """ form = TextToSpeechForm() # Instantiates a client client = texttospeech.TextToSpeechClient() # Get the language list voices = client.list_voices() voice_codes_list = list(dict.fr...
5,344,055
def load_c6_file(filename, is_radar): """ Loads ice scattering LUTs from a file (based on Yang et al., JAS, 2013). Parameters ---------- filename: str The name of the file storing the Mie scattering parameters is_radar: bool If True, the first LUT column is treated as the freque...
5,344,056
def gwrite(document: vp.Document, output: typing.TextIO, profile: str): """ Write gcode or other ascii files for the vpype pipeline. The output format can be customized by the user heavily to an extent that you can also output most known non-gcode ascii text files. """ gwrite_config = vp.CONFIG...
5,344,057
def retrieve_latin_text_boxes(data_dir: str, annotation_file: TextIO) -> None: """ Extract the text boxes from the source dataset for which the language is in VALID_LANGUAGES Parameters ---------- data_dir: Directory containing the text boxes. annotation_file: File where the information on each...
5,344,058
def txt_analysis(file_name, pattern, path): """Tries to finds the pattern in the text of UTF-8 encocded files""" try: with open(file_name, "r") as file: text = file.read().lower() counter = text.count(pattern) show(path, file_name, counter) except UnicodeDecodeErr...
5,344,059
def test_draw_out_of_samples(proposal): """Assert populated is set to false when the last sample is used.""" N = 5 proposal.populated = True proposal.indices = [0] proposal.samples = np.array([0, 1, 2, 3, 4]) sample = AnalyticProposal.draw(proposal, 1, N=N) assert sample == 0 assert pr...
5,344,060
def create_datasets(dataset, num_valid=0, max_epochs=1, batch_size=128, cache=True, **kwargs): """ Takes `.tfrecord` files and creates `tf.data.Dataset` objects. If `dataset` is `hdfs://<path>/data/` or `hdfs://<path>/data.tfrecord`, then there should also be a JSON file called `hdfs://<path>/data.json` which ...
5,344,061
def user_int(arg): """ Convert a :class:`~int` to a `USER` instruction. :param arg: Int that represents instruction arguments. :return: Fully-qualified `USER` instruction. """ return str(arg)
5,344,062
def timezoneAdjuster(context, dt): """Convinience: new datetime with given timezone.""" newtz = ITimezoneFactory(context) return dt.astimezone(newtz)
5,344,063
def turn(board, player): """Simulate a single player's turn.""" log.info('Beginning turn of player %s.', player.name) if player.jailed: player.try_jailout(board) else: player.consider_developing(board) diceroll, doubles = roll() player.advance(diceroll, board) if ...
5,344,064
def make_adder(n): """Return a function that takes one argument k and returns k + n. >>> add_three = make_adder(3) >>> add_three(4) 7 """ def adder(k): return k + n return adder
5,344,065
def IsWritable(Feature): """IsWritable(Feature) -> Writable Parameters: Feature: str Return value: Writable: ctypes.c_int""" if _at_camera_handle is not None: return _at_core_lib.AT_IsWritable(_at_camera_handle, Feature) != AT_FALSE else: raise AndorError('Andor libr...
5,344,066
def error(statuscode, cause, message): """ Print a given `message` to standard error and terminate the program with `statuscode` value. It's a good practice to use Unix convention for status code: `2` for command line syntax error and `1` for all other kind of errors. """ print('{0}: {1}: {2...
5,344,067
def playstore_search(text): """ Search on Play Store (https://play.google.com/store) Parameters ----------- text:- The query which you want to search about (str) """ play_store=f"https://play.google.com/store/search?q={text}" open(play_store)
5,344,068
def groupby_apply( keys: torch.Tensor, values: torch.Tensor, bins: int = 95, reduction: str = "mean", return_histogram: bool = False ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Groupby apply for torch tensors Args: keys: tensor of groups (``0`` to ``bins``) values: ...
5,344,069
def cube(x): """return x^3""" return x*x*x
5,344,070
def get_candidados(vetor): """Retorna o dado dos candidatos""" lista_retorno = [] for i in vetor: lista_retorno.append(candidatos[int(i)]) return lista_retorno
5,344,071
def get_fmin_tree(f_df, tree): """ """ f = f_df[f_df['F4ratio']>=0].reset_index() t = copy.deepcopy(tree) i=0 for node in t.traverse(): if node.children: l = node.children[0] r = node.children[1] lleaves = l.get_leaf_names() rleaves = ...
5,344,072
def primes(n): """ Returns a list of primes < n """ n = int(n) sieve = [True] * n for i in np.arange(3, n ** 0.5 + 1, 2, dtype=int): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1) return [2] + [i for i in np.arange(3,n,2) if sieve[i]]
5,344,073
def H_TP(Z, T, P): """ Enthalpy defined by temperature and pressure (reference state at 300 K and 1 bar) Z - array of molar composition T, P - temperature and pressure Units are specified above """ H = RP.ABFLSHdll('TP', T, P*100, Z, 2).h - RP.ABFLSHdll('TP', 300, 100,...
5,344,074
def convert_docx(converter, output_path: pathlib.Path, settings: Settings) -> None: """Convert the xml to docx.""" docx_output_filename = output_path / settings["OutputFormats"]["docx"]["OutputFile"] docx_builder = DocxBuilder(docx_output_filename, pathlib.Path(settings["OutputFormats"]["docx"]["ReferenceFi...
5,344,075
def is_root() -> bool: """ Checks whether the current user is root (or, on Windows, an administrator). """ if os.name == 'nt': try: _dummy = list((Path(os.environ.get('SystemRoot', 'C:\\Windows')) / 'Temp').iterdir()) return True except OSError: retur...
5,344,076
def test_fallback_round_with_input_n_not_int(): """ Feature: JIT Fallback Description: Test round() in graph mode with input x is not int. Expectation: TypeError. """ @ms_function def foo(): x = round(10.123, 1.0) return x with pytest.raises(TypeError) as ex: foo(...
5,344,077
def validate_netmask(s): """Validate that a dotted-quad ip address is a valid netmask. >>> validate_netmask('0.0.0.0') True >>> validate_netmask('128.0.0.0') True >>> validate_netmask('255.0.0.0') True >>> validate_netmask('255.255.255.255') True >>> validate_netmask(BROADCAST)...
5,344,078
def translate(): """ A handler for translating given english word which about digit to chinese character Return: - `JSON` .. code-block # message = isError ? reason : "OK" # output = isError ? '' : <TRANSLATION> { message: string, output: str...
5,344,079
def create_matrix_sars_overlap_between_networks(networks_summary_df, networks_dict): """ Creates matrix where element (i,j) quantifies the number of common SARS-Cov-2 partners in networks i and j divided by the total number of SARS-Cov-2 partners in both networks Args: networks_summary_df: data...
5,344,080
def load_forcings_gauge_metadata(path: str) -> Tuple[float, float, float]: """ Loads gauge metadata from the header of a CAMELS-USE forcings file. Parameters ---------- path: str Path to the forcings file. Returns ------- tuple (gauge latitude, gauge elevation, basin ar...
5,344,081
async def test_restore_state(hass, monkeypatch): """Ensure states are restored on startup.""" config = { "rflink": {"port": "/dev/ttyABC0"}, DOMAIN: { "platform": "rflink", "devices": { "NewKaku_12345678_0": {"name": "l1", "type": "hybrid"}, ...
5,344,082
def transition(measure, N, **measure_args): """ A, B transition matrices for different measures measure: the type of measure legt - Legendre (translated) legs - Legendre (scaled) glagt - generalized Laguerre (translated) lagt, tlagt - previous versions of (tilted) Laguerre with slightly...
5,344,083
def update_standings(season, current_week, matchups): """ Generate scores and results for the current week, update standings. """ for matchup in matchups: scores = matchup.scoreboard.get_score() winner = matchup.scoreboard.get_winner() for team in (matchup.home_team, mat...
5,344,084
def interpolate_coord(df, xcol, ycol, step, distcol='d'): """ Interpolates x/y coordinates along a line at a fixed distance. Parameters ---------- df : pandas.DataFrame xcol, ycol : str Labels of the columns in ``df`` containing the x- and y-coords, respectively. step : int ...
5,344,085
def dnd(dev, cmd, start_hr, start_min, end_hr, end_min): """Query and adjust do-not-disturb mode.""" if cmd == "off": click.echo("Disabling DND..") print(dev.disable_dnd()) elif cmd == "on": click.echo("Enabling DND %s:%s to %s:%s" % (start_hr, start_min, ...
5,344,086
def create_ticket_for_new_issue(obj, issue_tracker_info): """Create new IssueTracker ticket for issue""" builder = issue_tracker_params_builder.IssueParamsBuilder() issue_tracker_params = builder.build_create_issue_tracker_params( obj, issue_tracker_info ) if issue_tracker_params.is_empty(): ...
5,344,087
def test_protocol_version_0(valid_data): """Test whether version 0 raises an exception""" valid_data["version"] = 0 with pytest.raises(IOError): Packet(bitstring.pack(PACKET_FORMAT, **valid_data), "127.0.0.1")
5,344,088
def oven_cook_setting_to_str(cook_setting: OvenCookSetting, units: str) -> str: """Format OvenCookSetting values nicely.""" cook_mode = cook_setting.cook_mode cook_state = cook_mode.oven_state temperature = cook_setting.temperature modifiers = [] if cook_mode.timed: modifiers.append(STA...
5,344,089
def print_location(location: Location) -> str: """Render a helpful description of the location in the GraphQL Source document.""" return print_source_location( location.source, get_location(location.source, location.start) )
5,344,090
def run_metrics(ground_truth, simulation, measurement_name,users=None,repos=None): """ Run all of the assigned metrics for a given measurement. Inputs: ground_truth - DataFrame of ground truth data simulation - DataFrame of simulated data measurement_name - Name of measurement corresponding to...
5,344,091
def setPenColor(c=_DEFAULT_PEN_COLOR): """ Set the pen color to c, where c is an object of class color.Color. c defaults to stddraw.BLACK. """ global _penColor _penColor = c
5,344,092
def checkTrue(comment,res,update=True): """ This method is a pass-through for consistency and updating @ In, comment, string, a comment printed out if it fails @ In, res, bool, the tested value @ In, update, bool, optional, if False then don't update results counter @ Out, res, bool, True if test ...
5,344,093
def compute_votes( candidates, voters, voter_id, node_degree_normalization, ): """Comptue neighbor voting for a given set of candidates and voters Arguments: candidates {np.ndarray} -- genes x cells normalized expression for candidates voters {np.ndarray} -- genes x cells norma...
5,344,094
def drop_second_col(in_list): """ Drop line info, convert into list """ ret = [] log.debug("Drop second col from %r", in_list) for x in in_list: y = x.split(":") lineless = y[0:1] + y[2:] log.debug("Add lineless list: %r", lineless) ret.append(lineless) return ret
5,344,095
def _precompute_cache(x, y, num_classes): """Cache quantities to speed-up the computation of L2-regularized least-sq.""" # Whiten mean = jnp.mean(x, axis=0, keepdims=True) std = jnp.std(x, axis=0, keepdims=True) + 1e-5 x = (x - mean) / std # Add a constant feature for the bias, large so it's almost unregul...
5,344,096
def Usage(): """Print usage.""" print """Usage: cros_check_patches [--board=BOARD] [emerge args] package overlay-dir config.json Given a package name (e.g. 'chromeos') and an overlay directory (e.g. /usr/local/portage/chromiumos), outputs a list of patches applied by that overlay, in the course of building the spe...
5,344,097
def test_dispose(websocket_server): """Observable subscriptions can be disposed using Websockets.""" url_thing_01 = websocket_server.pop("url_thing_01") exposed_thing_01 = websocket_server.pop("exposed_thing_01") prop_name = websocket_server.pop("prop_name_01") @tornado.gen.coroutine def test_...
5,344,098
def show_user(): """Return page showing details: walks, landmarks rated, scores.""" user = User.query.filter_by(user_id=session.get('user_id')).first() ratings = user.ratings # import pdb; pdb.set_trace() walks = user.walks # for walk in walks: # origin = Landmark.query.filter(La...
5,344,099