content
stringlengths
22
815k
id
int64
0
4.91M
def dump_file( file_name: str, data: pd.DataFrame, header: typing.Optional[typing.List[str]] = None, vertical: bool = True ) -> None: """ Dump a file with or without a header to an output file. Arguments: file_name - Name of the output file data - Pandas datafram...
31,600
def read_and_download_profile_information(id): """ linke: https://developer.apple.com/documentation/appstoreconnectapi/read_and_download_profile_information :param id: bundle_id :return: 请求结果 """ data = { "fields[certificates]": "certificateType", "fields[devices]": "platform", ...
31,601
def test_vso_attribute_parse(): """Make sure that Parsing of VSO attributes from HEK queries is accurate""" h = hek.HEKClient() hek_query = h.query(hekTime, hekEvent) vso_query = hek2vso.vso_attribute_parse(hek_query[0]) # Checking Time # TODO # Checking Observatory assert vso_query[1]...
31,602
def get_config(node): """Get the BIOS configuration. The BIOS settings look like:: {'EnumAttrib': {'name': 'EnumAttrib', 'current_value': 'Value', 'pending_value': 'New Value', # could also be None 'read_only': False, ...
31,603
def plot_neural_reconstruction_traces( traces_ae, traces_neural, save_file=None, xtick_locs=None, frame_rate=None, format='png'): """Plot ae latents and their neural reconstructions. Parameters ---------- traces_ae : :obj:`np.ndarray` shape (n_frames, n_latents) traces_neural : :obj...
31,604
def get_only_metrics(results): """Turn dictionary of results into a list of metrics""" metrics_names = ["test/f1", "test/precision", "test/recall", "test/loss"] metrics = [results[name] for name in metrics_names] return metrics
31,605
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: ? Space Complexity: ? """ if nums == None: return 0 if len(nums) == 0: return 0 pass
31,606
def find_tags_containing(project, commit): """Find all tags containing the given commit. Returns the full list and a condensed list (excluding tags 'after' other tags in the list).""" tags = run_list_command(['git', 'tag', '--contains', commit], project) # The packaging projects had a different format for ...
31,607
def setup_nupack_input(**kargs): """ Returns the list of tokens specifying the command to be run in the pipe, and the command-line input to be given to NUPACK. Note that individual functions below may modify args or cmd_input depending on their specific usage specification. """ # Set up terms of command-line ...
31,608
def rebuild_current_distribution( fields: np.ndarray, ics: np.ndarray, jj_size: float, current_pattern: List[Union[Literal["f"], str]], sweep_invariants: List[Union[Literal["offset"], Literal["field_to_k"]]] = [ "offset", "field_to_k", ], precision: float = 100, n_points:...
31,609
def main(): """Make a jazz noise here""" args = get_args() random.seed(args.seed) # nice simple solution # new_text = '' # for char in args.text: # new_text += choose(char) # print(new_text) # list comprehension # print(''.join([choose(char) for char in args.text])) # map pr...
31,610
def get_LCA(index, item1, item2): """Get lowest commmon ancestor (including themselves)""" # get parent list from if item1 == item2: return item1 try: return LCA_CACHE[index][item1 + item2] except KeyError: pass parent1 = ATT_TREES[index][item1].parent[:] parent2 = AT...
31,611
def select_workspace_access(cursor, workspace_id): """ワークスペースアクセス情報取得 Args: cursor (mysql.connector.cursor): カーソル workspace_id (int): ワークスペースID Returns: dict: select結果 """ # select実行 cursor.execute('SELECT * FROM workspace_access WHERE workspace_id = %(workspace_id)s', ...
31,612
def pkcs7_unpad(data): """ Remove the padding bytes that were added at point of encryption. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 """ if isinstance(data, str): return data[0:-ord(data[-1])] else: ...
31,613
def leveinshtein_distance(source,target): """ Implement leveintein distance algorithm as described in the reference """ #Step 1 s_len=len(source) t_len=len(target) cost=0 if(s_len==0): return t_len if(t_len==0): return s_len print("Dimensions:\n\tN:%d\n\tM:%d"%(s_len,t_len)) #Step 2 matrix...
31,614
def minus (s): """ заменить последний минус на равенство """ q = s.rsplit ('-', 1) return q[0] + '=' + q[1]
31,615
def _chk_y_path(tile): """ Check to make sure tile is among left most possible tiles """ if tile[0] == 0: return True return False
31,616
def json_project_activities(request): """docstring for json_project_activities""" timestamp = int(request.GET['dt']) pid = int(request.GET['id']) project = get_object_or_404(Project, id=pid) items = project.items(timestamp) objs = [] for item in items: ...
31,617
def to_complex_matrix(matrix: np.ndarray) -> List: """ Convert regular matrix to matrix of ComplexVals. :param matrix: any matrix. :return: Complex matrix. """ output: List[List] = matrix.tolist() for i in range(len(matrix)): for j in range(len(matrix[i])): if type(matri...
31,618
def skipIfDarwin(func): """Decorate the item to skip tests that should be skipped on Darwin.""" return skipIfPlatform( lldbplatform.translate( lldbplatform.darwin_all))(func)
31,619
def load_dataframe(csv_path: PathLike) -> Tuple[str, pd.DataFrame]: """Returns a tuple (name, data frame). Used to construct a data set by `load_dataframes_from_directory`. See: load_dataframes_from_directory Dataset """ return Path(csv_path).stem, pd.read_csv(csv_path)
31,620
def polar(z): # real signature unknown; restored from __doc__ """ polar(z) -> r: float, phi: float Convert a complex from rectangular coordinates to polar coordinates. r is the distance from 0 and phi the phase angle. """ pass
31,621
def VerifyReleaseChannel(options): """Verify that release image channel is correct. ChromeOS has four channels: canary, dev, beta and stable. The last three channels support image auto-updates, checks that release image channel is one of them. """ return GetGooftool(options).VerifyReleaseChannel( opt...
31,622
def make_start_script(cmd, repo, anaconda_path, env, install_pip=(), add_swap_file=False): """ My basic startup template formatter Parameters ---------- cmd : str The actual command to run. repo : str The repository anaconda_path : str The anaconda ...
31,623
def main(argv=sys.argv): """Main method called by the eggsecutable.""" try: utils.vip_main(ModelicaAgent) except Exception as ex: log.exception(ex)
31,624
def radius_hpmap(glon, glat, R_truncation, Rmin, Npt_per_decade_integ, nside=2048, maplonlat=None): """ Compute a radius map in healpix Parameters ---------- - glon/glat (deg): galactic longitude and latitude in degrees - R_truncation (quan...
31,625
def convert_grayscale_image_to_pil(image): """Converts a 2D grayscale image into a PIL image. Args: image (numpy.ndarray[uint8]): The image to convert. Returns: PIL.Image: The converted image. """ image = np.repeat(image[:, :, None], 3, 2) image_pil = Image.fromarray(image).co...
31,626
async def test_add_run_task() -> None: """It should be able to add a task for the "run" phase.""" run_result = False async def run_task() -> None: nonlocal run_result run_result = True subject = TaskQueue() subject.add(phase=TaskQueuePhase.RUN, func=run_task) subject.start() ...
31,627
def delete_group(group_id, tasks=False, cached=Conf.CACHED): """ Delete a group. :param str group_id: the group id :param bool tasks: If set to True this will also delete the group tasks. Otherwise just the group label is removed. :param bool cached: run this against the cache backend :retu...
31,628
def alphanum_key(string): """Return a comparable tuple with extracted number segments. Adapted from: http://stackoverflow.com/a/2669120/176978 """ convert = lambda text: int(text) if text.isdigit() else text return [convert(segment) for segment in re.split('([0-9]+)', string)]
31,629
def merge_data(attribute_column, geography, chloropleth, pickle_dir): """ Merges geometry geodataframe with chloropleth attribute data. Inputs: dataframe or csv file name for data desired to be choropleth Outputs: dataframe """ gdf = load_pickle(pickle_dir, geography) chloropleth = load_pick...
31,630
def get_ls8_image_collection(begin_date, end_date, aoi=None): """ Calls the GEE API to collect scenes from the Landsat 7 Tier 1 Surface Reflectance Libraries :param begin_date: Begin date for time period for scene selection :param end_date: End date for time period for scene selection ...
31,631
def multi_halo(n_halo): """ This routine will repeat the halo generator as many times as the input number to get equivalent amount of haloes. """ r_halo = [] phi_halo = [] theta_halo = [] for i in range(n_halo): r, theta,phi = one_halo(100) r_halo.append(r) theta...
31,632
def allocation_proportion_of_shimenwpp(): """ Real Name: Allocation Proportion of ShiMenWPP Original Eqn: Allocation ShiMen WPP/Total WPP Allocation Units: m3/m3 Limits: (None, None) Type: component Subs: None """ return allocation_shimen_wpp() / total_wpp_allocation()
31,633
def update_cfg(base_cfg, update_cfg): """used for mmcv.Config or other dict-like configs.""" res_cfg = copy.deepcopy(base_cfg) res_cfg.update(update_cfg) return res_cfg
31,634
def check(conn, command, exit=False, timeout=None, **kw): """ Execute a remote command with ``subprocess.Popen`` but report back the results in a tuple with three items: stdout, stderr, and exit status. This helper function *does not* provide any logging as it is the caller's responsibility to do s...
31,635
def domains_configured(f): """Wraps API calls to lazy load domain configs after init. This is required since the assignment manager needs to be initialized before this manager, and yet this manager's init wants to be able to make assignment calls (to build the domain configs). So instead, we check...
31,636
def test_append(dataset, append_args, n_files): """ Note: ETL will fail for append, because... it's a text file. But also because the destination will likely be removed before the ETL actually places the new node there. """ # TimeSeries package to append into... pkg = TimeSeries(...
31,637
def add_modified_tags(original_db, scenarios): """ Add a `modified` label to any activity that is new Also add a `modified` label to any exchange that has been added or that has a different value than the source database. :return: """ # Class `Export` to which the original database is passe...
31,638
def stats_start(server): """Fills in global_member_times and server_wl dictionaries. Creates and populates a table in the database if no such table exists for this server. Args: server (Server): Server object described in the Discord API reference page. We populate glob...
31,639
def get_sub_bibliography(year, by_year, bibfile): """Get HTML bibliography for the given year""" entries = ','.join(['@' + x for x in by_year[year]]) input = '---\n' \ f'bibliography: {bibfile}\n' \ f'nocite: "{entries}"\n...\n' \ f'# {year}' out = subprocess.run(['...
31,640
def import_tep_sets(lagged_samples: int = 2) -> tuple: """ Imports the normal operation training set and 4 of the commonly used test sets [IDV(0), IDV(4), IDV(5), and IDV(10)] with only the first 22 measured variables and first 11 manipulated variables """ normal_operation = import_sets(0) t...
31,641
def to_fgdc(obj): """ This is the priamry function to call in the module. This function takes a UnifiedMetadata object and creates a serialized FGDC metadata record. Parameters ---------- obj : obj A amg.UnifiedMetadata class instance Returns ------- : str A strin...
31,642
def compute_iqms(settings, name='ComputeIQMs'): """ Workflow that actually computes the IQMs .. workflow:: from mriqc.workflows.functional import compute_iqms wf = compute_iqms(settings={'output_dir': 'out'}) """ workflow = pe.Workflow(name=name) inputnode = pe.Node(niu.IdentityI...
31,643
def get_nbest_bounds_from_membership(membership_logits, n_best_size=1): """ Return possible inclusive start, exclusive end indices given a list of membership logits. :param membership_logits: :return: two lists, each of length n (in nbest) """ # TODO: include heuristic for choosing bounds (not j...
31,644
def GetDepthFromIndicesMapping(list_indices): """ GetDepthFromIndicesMapping ========================== Gives the depth of the nested list from the index mapping @param list_indices: a nested list representing the indexes of the nested lists by depth @return: depth """ ...
31,645
def lowpassIter(wp, ws, fs, f, atten=90, n_max=400): """Design a lowpass filter using f by iterating to minimize the number of taps needed. Args: wp: Passband frequency ws: Stopband frequency fs: Sample rate f: Function to design filter atten: desired attenuation (dB...
31,646
def evaluate_themes( ref_measurement: Measurement, test_measurement: Measurement, themes: Union[FmaskThemes, ContiguityThemes, TerrainShadowThemes], ) -> Dict[str, float]: """ A generic tool for evaluating thematic datasets. """ values = [v.value for v in themes] n_values = len(values) ...
31,647
def test_global_averaging(): """Test that `T==N` and `F==pow2(N_frs_max)` doesn't error, and outputs close to `T==N-1` and `F==pow2(N_frs_max)-1` """ if skip_all: return None if run_without_pytest else pytest.skip() np.random.seed(0) N = 512 params = dict(shape=N, J=9, Q=4, J_fr=5, Q...
31,648
def test_remove_legacy_lb_backend(mocker, ip_load_balancing_array): """ Test lb.legacy.remove-backend task without error """ mocker.patch( 'ovh_api_tasks.api_wrappers.ip.get_ip_lb_services', return_value=ip_load_balancing_array) mocker.patch( 'ovh_api_tasks.api_wrappers.ip....
31,649
def poly_coefficients(df: np.ndarray,z: np.ndarray,cov: np.ndarray) -> np.ndarray: """ Calculate the coefficients in the free energy polynomial Parameters ---------- df : [2,iphase] Difference between next and current integration points z: np.ndarray [2,iphase] Conjugate v...
31,650
def NoneInSet(s): """Inverse of CharSet (parse as long as character is not in set). Result is string.""" return ConcatenateResults(Repeat(NoneOf(s), -1))
31,651
def _read_part(f, verbose): """Reads the part name and creates a mesh with that name. :param f: The file from where to read the nodes from. :type f: file object at the nodes :param verbose: Determines what level of print out to the console. :type verbose: 0, 1 or 2 :return: Nothing, but has the...
31,652
async def get_prefix(bot, message): """Checks if the bot has a configuration tag for the prefix. Otherwise, gets the default.""" default_prefix = await get_default_prefix(bot) if isinstance(message.channel, discord.DMChannel): return default_prefix my_roles = [role.name for role in message.guild...
31,653
def test_render_parameter_header_description(testrenderer): """Header parameter's 'description' is rendered.""" markup = textify( testrenderer.render_parameter( { "name": "X-Request-Id", "in": "header", "description": "A unique request identif...
31,654
def fileprep(f, plate=None, ifu=None, smearing=None, stellar=False, maxr=None, cen=True, fixcent=True, clip=True, remotedir=None, gal=None, galmeta=None, rootdir=None): """ Function to turn any nirvana output file into useful objects. Can take in `.fits`, `.nirv`, `dynesty.NestedSampler`_, ...
31,655
def HA19(request): """ Returns the render for the sdg graph """ data = dataFrameHA() figure = px.bar(data, x = "Faculty", y = "HA 19", labels = {"Faculty":"Faculties", "HA19":"Number of Modules Corresponding to HA 19"}) figure.write_image("core/static/HA19.png") return render(re...
31,656
def student_stop_eligibility_plots(input_directory): """ Create a distribution plot of the number of stop options for """ f = [stop_eligibility_counts(os.path.join( input_directory, 'student-stop-eligibility-{}.csv'.format(s))) for s in ['25', '40', '50', '100', '82']] fig, ax = plt....
31,657
def test_enrich_asset_properties(properties, properties_to_enrich_dict: Dict, expected): """ Given: - Properties of an asset. - Dict containing properties keys to enrich, and the new names of the enrichment as corresponding values. When: - Case a: Basic enrichment of properties have been ask...
31,658
def merge( left: pandas.core.frame.DataFrame, right: pandas.core.frame.DataFrame, how: Literal["right"], left_index: bool, right_index: bool, ): """ usage.dask: 4 """ ...
31,659
def beta(data, market, periods, normalize = False): """ .. Beta Parameters ---------- data : `ndarray` An array containing values. market : `ndarray` An array containing market values to be used as the comparison when calculating beta. periods : `int` Number ...
31,660
def h2orapids(): """ Python API test: h2o.rapids(expr) """ rapidTime = h2o.rapids("(getTimeZone)")["string"] print(str(rapidTime))
31,661
def save_hints_trigger_problem(sender, **kwargs): """save Hints of a TriggerProblem""" if hasattr(kwargs['instance'], 'hints_info'): logger.debug('Saving hints: %s %s', str(sender), str(kwargs['instance'])) save_hints(kwargs['instance'])
31,662
def run(config_name="maestral"): """ This is the main interactive entry point which starts the PyQt5 GUI. :param str config_name: Name of Maestral config to run. """ QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_UseHig...
31,663
def set_process_name(name: str) -> None: """Set a name for this process.""" setproctitle(name)
31,664
def transmission(ctx): """Podcust tools for transmission container image.""" # We can only use ctx.obj to create and share between commands. ctx.obj = TransmissionCust() click.echo("Initializing Podman Custodian Transmission class.")
31,665
def test_index_entry(): """ Test the construction of the list of blocks from text. """ text_list = ("Line one \u00B6.", "Line two. ") entry = search_builder.IndexEntry() entry.text_list.extend(text_list) text = """Line one . Line two.""" nt.assert_equal(text, entry.text)
31,666
def heading_from_to(p1: Vector, p2: Vector) -> float: """ Returns the heading in degrees from point 1 to point 2 """ x1 = p1[0] y1 = p1[1] x2 = p2[0] y2 = p2[1] angle = math.atan2(y2 - y1, x2 - x1) * (180 / math.pi) angle = (-angle) % 360 return abs(angle)
31,667
def delivery_report(err, msg): """ Reports the failure or success of a message delivery. Args: err (KafkaError): The error that occurred on None on success. msg (Message): The message that was produced or failed. Note: In the delivery report callback the Message.key() and Mess...
31,668
def selSPEA2Diverse(individuals, k): """Apply SPEA-II selection operator on the *individuals*. Usually, the size of *individuals* will be larger than *n* because any individual present in *individuals* will appear in the returned list at most once. Having the size of *individuals* equals to *n* will hav...
31,669
def utilization_to_states(state_config, utilization): """ Get the state history corresponding to the utilization history. Adds the 0 state to the beginning to simulate the first transition. (map (partial utilization-to-state state-config) utilization)) :param state_config: The state configuration. ...
31,670
def post_captcha(captcha, cookie, id): """Envia o captcha reconhecido para permitir o download. Parameters ---------- captcha : str, captcha reconhecido coookie : str, cookie com as informacoes da sessao id : str, id do CV Notes ----- Esse endpoint retorna um json, com {'estado': '...
31,671
def com_google_fonts_check_iso15008_interword_spacing(font, ttFont): """Check if spacing between words is adequate for display use""" l_intersections = xheight_intersections(ttFont, "l") if len(l_intersections) < 2: yield FAIL,\ Message('glyph-not-present', "There...
31,672
async def get_pipeline_run_log( organization: str = Path(None, description="Name of the organization"), pipeline: str = Path(None, description="Name of the pipeline"), run: str = Path(None, description="Name of the run"), start: int = Query(None, description="Start position of the log"), download: b...
31,673
def generate_person(results: Dict): """ Create a dictionary from sql that queried a person :param results: :return: """ person = None if len(results) > 0: person = { "id": results[0], "name": results[1].decode("utf-8"), "img_url": results[2].deco...
31,674
def XOR(args): """ Another way of finding the XOR of functions. Just pass the sequence of BFs as args. """ standard_op(args, "%")
31,675
def test_get_required_with_fx(): """Test getting required variables for derivation with fx variables.""" variables = get_required('ohc', 'CMIP5') reference = [ {'short_name': 'thetao'}, {'short_name': 'volcello', 'mip': 'fx'}, ] assert variables == reference
31,676
def paliindrome_sentence(sentence: str) -> bool: """ `int` """ string = '' for char in sentence: if char.isalnum(): string += char return string[::-1].casefold() == string.casefold()
31,677
def get_default_pool_set(): """Return the names of supported pooling operators Returns: a tuple of pooling operator names """ output = ['sum', 'correlation1', 'correlation2', 'maximum'] return output
31,678
def _sys_conf_tpf_stub(actual_state_data: StateData, next_state_data: StateData, cfc_spec: CFCSpec): """Stub for the transition probability function.""" pass
31,679
def virtual_networks_list_all(**kwargs): """ .. versionadded:: 2019.2.0 List all virtual networks within a subscription. CLI Example: .. code-block:: bash salt-call azurearm_network.virtual_networks_list_all """ result = {} netconn = __utils__["azurearm.get_client"]("network...
31,680
def variantNameTextChanged(variantName): """ Reacts to the variant name being changed by the user by editing the text. """ # The text field cannot be empty. Reset to default value if it is. if not variantName: cmds.textField('variantNameText', edit=True, text=kDefaultCacheVariantName) el...
31,681
def generate_state_matrix(Hprime, gamma): """Full combinatorics of Hprime-dim binary vectors with at most gamma ones. :param Hprime: Vector length :type Hprime: int :param gamma: Maximum number of ones :param gamma: int """ sl = [] for g in range(2,gamma+1): for s in combinatio...
31,682
def excel_file2(): """Test data for custom data column required fields.""" return os.path.join('test', 'data', 'NADataErrors_2018-05-19_v1.0.xlsx')
31,683
def playfair_decipher(message, keyword, padding_letter='x', padding_replaces_repeat=False, letters_to_merge=None, wrap_alphabet=KeywordWrapAlphabet.from_a): """Decipher a message using the Playfair cipher.""" column_order = list(range(5)) row_order = list(range(5...
31,684
def test_fails_null_index(driver, function_store): """ Since we do not allow NULL values in queries, it should be banned from index columns in the first place. """ df = pd.DataFrame( { "x": [0, 1, 2, 3], "p": [0, 0, 1, 1], "v": [10, 11, 12, 13], "i...
31,685
def create_role(role_name): """Create a role.""" role_dict = { "Version" : "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Principal" : { "Service" : "lambda.amazonaws.com" }, "Action" : "sts:Ass...
31,686
def show_file_statuses(file_statuses, verbose=False) -> None: """Helper function to print ignored, missing files""" ignored = [] missing = [] downloaded = [] for status, short_filepath in file_statuses: if status == "IGNORE": ignored.append(short_filepath) elif status == ...
31,687
def evaluate_field(record, field_spec): """ Evaluate a field of a record using the type of the field_spec as a guide. """ if type(field_spec) is int: return str(record[field_spec]) elif type(field_spec) is str: return str(getattr(record, field_spec)) else: return str(fiel...
31,688
def project_points(X, K, R, T, distortion_params=None): """ Project points from 3d world coordinates to 2d image coordinates """ x_2d = np.dot(K, (np.dot(R, X) + T)) x_2d = x_2d[:-1, :] / x_2d[-1, :] if distortion_params is not None: x_2d_norm = np.concatenate((x_2d, np.ones((1, x_2d.sha...
31,689
def test_add(c, x1, y1, x2, y2, x3, y3): """We expect that on curve c, (x1,y1) + (x2, y2 ) = (x3, y3).""" p1 = Point(c, x1, y1) p2 = Point(c, x2, y2) p3 = p1 + p2 assert p3.x() == x3 and p3.y() == y3
31,690
def project_exists(response: 'environ.Response', path: str) -> bool: """ Determines whether or not a project exists at the specified path :param response: :param path: :return: """ if os.path.exists(path): return True response.fail( code='PROJECT_NOT_FOUND', me...
31,691
def rate_multipressure(qD, delta_p, B, mu, perm, h): """Calculate Rate as Sum of Constant Flowing Pressures""" import numpy as np return ((.007082 * perm * h) / (B * mu)) * (np.sum(qD * delta_p))
31,692
def osculating_elements_of(position, reference_frame=None, gm_km3_s2=None): """Produce the osculating orbital elements for a position. `position` is an instance of :class:`~skyfield.positionlib.ICRF`. These are commonly returned by the ``at()`` method of any Solar System body. ``reference_frame`` is an...
31,693
def main(): """ perform automatic calibration of pygama DataSets. command line options to specify the DataSet are the same as in processing.py save results in a JSON database for access by other routines. """ run_db, cal_db = "runDB.json", "calDB.json" par = argparse.ArgumentParser(descript...
31,694
def iterate_docker_images(path: str = os.path.join(ROOT, "docker_images.csv")) -> Iterator[Tuple[Optional[str], ...]]: """ Iterates over the known Docker images. :return: An iterator over the following fields of the known Docker images: - name - version ...
31,695
def rename_actions(P: NestedDicts, policy: DetPolicy) -> NestedDicts: """ Renames actions in P so that the policy action is always 0.""" out: NestedDicts = {} for start_state, actions in P.items(): new_actions = copy.copy(actions) policy_action = policy(start_state) new_actions[0], n...
31,696
async def test_arm_night_success(hass): """Test arm night method success.""" responses = [RESPONSE_DISARMED, RESPONSE_ARM_SUCCESS, RESPONSE_ARMED_NIGHT] with patch( "homeassistant.components.totalconnect.TotalConnectClient.TotalConnectClient.request", side_effect=responses, ): aw...
31,697
def configure(config): """Interactively configure the bot's ``[core]`` config section. :param config: the bot's config object :type config: :class:`~.config.Config` """ config.core.configure_setting('nick', 'Enter the nickname for your bot.') config.core.configure_setting('host', 'Enter the ser...
31,698
def set_gcc(): """Try to use GCC on OSX for OpenMP support.""" # For macports and homebrew if platform.system() == "Darwin": gcc = extract_gcc_binaries() if gcc is not None: os.environ["CC"] = gcc os.environ["CXX"] = gcc else: global use_openmp ...
31,699