content
stringlengths
22
815k
id
int64
0
4.91M
def track_progress( iterable: Iterable, name: Optional[str] = None, total: Optional[int] = None, update_label: bool = False, label_func: Optional[Callable] = lambda x: x, clear: Optional[bool] = True, ): """ simple tracking loop using rich progress """ if name is None: na...
7,900
def trainAndEvaluateKNN(): """ auxiliary function to call train_KNearestNeighbour() on full dataset takes no parameters and evaluates the currently loaded test set """ print('***Begin training KNN***') knn = train_KNearestNeighbour(x_train, y_train) print('***Begin evaluating KNN***'...
7,901
def attach_common_event_handlers( parser, result, errors, is_response ): """Attach common event handlers to a HTTPParser. The ``result`` parameter must be ``dict`` that contains the results of parsing. The ``errors`` parameter must be a ``list`` of exceptions that happened. """ d...
7,902
def _get_parse_pauli_sums(): """Helper function to obtain the generator of the sampled list of the pauli sum coefficients after parsing pauli sums.""" # TODO(jaeyoo) : this will be c++ op def _parse_pauli_sums(pauli_sums, n_programs, n_ops): """Helper function to parse given pauli sums to colle...
7,903
def is_fully_defined(x): """Returns True iff `x` is fully defined in every dimension. For more details, see `help(tf.TensorShape.is_fully_defined)`. Args: x: object representing a shape; convertible to `tf.TensorShape`. Returns: is_fully_defined: `bool` indicating that the shape is fully known. """...
7,904
def make_shell_context(): """ Creates a python REPL with several default imports in the context of the current_app :return: """ return dict(current_app=current_app)
7,905
def recommend_hybrid_user( df, model, interactions, user_id, user_dict, item_dict, topn, new_only=True, threshold=3, show=True): """Function to produce user recommendations. Hybrid version of recommend_known_user Args: mo...
7,906
def addTopic(self, id, title='', REQUEST=None): """ Create an empty topic. """ topic = Topic(id) topic.id = id topic.title = title self._setObject(id, topic, suppress_events=True) if REQUEST is not None: REQUEST['RESPONSE'].redirect('manage_main')
7,907
def test_est_params_default_method(): """Assert that custom parameters overwrite the default ones.""" trainer = DirectClassifier("RF", est_params={"n_jobs": 3}, random_state=1) trainer.run(bin_train, bin_test) assert trainer.rf.estimator.get_params()["n_jobs"] == 3 assert trainer.rf.estimator.get_pa...
7,908
def i(mu_i, mu_ij, N) : """Calcule le tableau I[i, j]""" return [[I_ij(i, j, mu_i, mu_ij, N) for j in range(0, N)] for i in range(0, N)]
7,909
def format_datetime(this, date, date_format=None): """Convert datetime to a required format.""" date = dateutil.parser.isoparse(date) if date_format is None: date_format = "%d-%m-%Y" return date.strftime(date_format)
7,910
def _estimate_melting_levels(latitudes_deg, valid_time_unix_sec): """Estimates melting level at each point. This estimate is based on linear regression with respect to latitude. There is one set of regression coefficients for each month. :param latitudes_deg: numpy array of latitudes (deg N). :pa...
7,911
def train_word2vec(infile, outfile, skipgram, loss, size, epochs): """ train_word2vec(args**) -> Takes the input file, the output file and the model hyperparameters as arguments and trains the model accordingly. The model is saved at the output location. Arguments --------- infile : Input pre-processed wiki dump ...
7,912
def test_child_events(): """Test that evented lists bubble child events.""" # create a random object that emits events class E: test = Signal(str) e_obj = E() root: EventedList[E] = EventedList(child_events=True) mock = Mock() root.events.connect(mock) root.append(e_obj) ass...
7,913
def do_sharedstoragepool_list(cs, args): """Output a list of sharedstoragepool.""" # sharedstoragepools = cs.sharedstoragepool.list(args.cluster) sharedstoragepools = cs.sharedstoragepool.list() _print_sharedstoragepool_list(sharedstoragepools)
7,914
def edit_municipality(self, request, form): """ Edit a municipality. """ layout = EditMunicipalityLayout(self, request) if form.submitted(request): form.update_model(self) request.message(_("Municipality modified."), 'success') return redirect(layout.success_url) if not form.e...
7,915
def plot_period_transactions( model, max_frequency=7, title="Frequency of Repeat Transactions", xlabel="Number of Calibration Period Transactions", ylabel="Customers", **kwargs ): """ Plot a figure with period actual and predicted transactions. Parameters ---------- model: l...
7,916
def operate_monitor(params): """ different apps has different required params""" ret_obj = copy.deepcopy(RET_OBJ) group_id = params.get("group_id", type=int, default=None) app_name = params.get("app_name") operate = "update" if key_exist(group_id, app_name) else "insert" valid_key = "_".join([...
7,917
def run_task(*_): """ Wrap DDPG training task in the run_task function. :param _: :return: """ env = TfEnv(gym.make('FetchReach-v1')) action_noise = OUStrategy(env.spec, sigma=0.2) policy = ContinuousMLPPolicy( env_spec=env.spec, name="Policy", hidden_sizes=[25...
7,918
def construct_rgba_vector(img, n_alpha=0): """ Construct RGBA vector to be used to color faces of pcolormesh This funciton was taken from Flamingo. ---------- Args: img [Mandatory (np.ndarray)]: NxMx3 RGB image matrix n_alpha [Mandatory (float)]: Number of border pixels ...
7,919
def nice(val): """Make sure this value is nice""" if pd.isna(val): return None return val
7,920
def retrieve_tree(issue_id): """Retrieve a tree of issues from Redmine, starting at `issue_id`.""" logging.info(f" Retrieving issue #{issue_id} ...") params = { 'issue_id': issue_id } response = requests.get(ISSUES_ENDPOINT, params=params, headers=HEADERS) data = json.loads(response.tex...
7,921
def cmdline_args(argv: Sequence[str], options: Sequence[Option], *, process: callable = None, error: callable = None, results: dict = None) -> (Dict, Sequence[str]): """ Take an array of command line args, process them :param argv: argument array :param options: sequence of options to p...
7,922
def trailing_zeroes(value): # type: (int) -> int """Count the number of trailing zeros in a given 8-bit integer""" return CTZ_TABLE[value]
7,923
def test_text_tweet(): """Ensure that text tweets are properly parsed.""" results = { 'tweets': 0, 'retweets': 0, 'media': [] } parse_tweet(TEXT_TWEET, True, 'large', results) assert results['tweets'] == 1 assert results['retweets'] == 0 assert len(results['media']) =...
7,924
def _calc_WaterCirculation(heat_load, CT_design, WBT, DBT, fixedCWT_ctrl, pump_ctrl, ignore_CT_eff, max_CT_eff=0.85): """Calculates the water circulation loop. Used by simulate_CT(). Parameters: Returns: All (time x CT) arrays as HWT Hot water temp [pint, C] C...
7,925
def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=None, mode='w' ): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_dir' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if instal...
7,926
def read_dataset_from_csv(data_type, path): """Read dataset from csv Args: data_type (str): train/valid/test Returns: pd: data """ data = pd.read_csv(tf.io.gfile.glob(path + data_type + "*")[0]) return data
7,927
def _ReportMissing(missing): """Report missing utilities, then exit. Args: missing: List of missing utilities, as returned by osutils.FindMissingBinaries. If non-empty, will not return. """ if missing: raise SystemExit( 'The tool(s) %s were not found.\n' 'Please install t...
7,928
def search_ignore_case(s, *keywords): """Convenience function to search a string for keywords. Case insensitive version. """ acora = AcoraBuilder(keywords, ignore_case=True).build() return acora.findall(s)
7,929
def print_caves(): """ Print out the current cave structure """ for number in cave_numbers: print(number, ":", caves[number]) print('----------')
7,930
def _logger_setup(logger: logging.Logger, header_label: str, formatter: Formatter = None, level: int = logging.INFO, level_normalized: int = logging.INFO, handler_delegate=Union[logging.StreamHandler,Iterable[logging.StreamHandler...
7,931
def _prepare_directory(data_dir: Union[str, PathLike], ignore_bad: bool = True, confirm_uids: bool = True) -> List[str]: """ Reorganizes PPMI `data_dir` to a structure compatible with ``heudiconv`` PPMI data starts off with a sub-directory structure that is not...
7,932
def find_log_for(tool_code, form_id, log_f): """Returns an array of lines from log for given tool code (P1,N3,...) and form_id. The form_id is taken from runner - thus we search for formula number ``form_id+1`` """ log = open(log_f,'r') current_f = -1 formula = re.compile('.*ltl:(\d+): (...
7,933
def test_decode_goto(): """Create program with GOTO from program number""" program_number = GOTO # expected program expected_program = read_program("test_goto.s") # decode program assert expected_program == decode_number_as_code(program_number)
7,934
def get_images(repository_name): """Call ecr to get available images""" eprint("obtaining available images") try: out = json.loads( run_command([ "aws", "ecr", "describe-images", "--repository-name", repository_name, "--no-paginate" ]).stdout) except s...
7,935
def lint_repo(*, fail_on_missing_sub_src, exclude_lint, warn_lint): """Lint all sites using checks defined in :mod:`pegleg.engine.errorcodes`. """ warns = pegleg_main.run_lint( exclude_lint, fail_on_missing_sub_src, warn_lint) if warns: click.echo("Linting passed, but produced some warni...
7,936
def exe_cmd_and_poll_output(cmd, encoding='UTF-8', is_capture_output=False): """ 将命令输出实时打印到标准输出 :param is_capture_output: :param cmd: 命令行 :param encoding: 字符编码 :return: 标准输出字符串列表 """ import shlex func_name = inspect.stack()[0][3] hlog.enter_func(func_name) hlog.trace("cmd=%...
7,937
def throw(exception, *args, **kwargs): # pragma: no cover """ Raises an exception (as an expression) """ raise exception(*args, **kwargs)
7,938
def create_patric_boolean_dict(genome_dict,all_ECs): """ Create new dict of dicts to store genome names :param genome_dict: dict of key=genome_id, value=dict of genome's name, id, ec_numbers :param all_ECs: set of all ECs found across all genomes """ ## new format: key=genome, value={EC:0 or 1}...
7,939
def append_ast_if_req(field): """ Adds a new filter to template tags that for use in templates. Used by writing {{ field | append_ast_if_req }} @register registers the filter into the django template library so it can be used in template. :param Form.field field: a field of a form that you...
7,940
def getPileupMixingModules(process): """ Method returns two lists: 1) list of mixing modules ("MixingModule") 2) list of data mixing modules ("DataMixingModules") The first gets added only pileup files of type "mc", the second pileup files of type "data". """ mixModules, dataMixModules = [], [] ...
7,941
def GetFirstTypeArgImpl_(type_: Hashable, parentClass: Type[Any]) -> Type[Any]: """ Returns the actual type, even if type_ is a string. """ if isinstance(type_, type): return type_ if not isinstance(type_, str): # It's not a type and it's not a str. # We don't know what to do with ...
7,942
def tree_map_zipped(fn: Callable[..., Any], nests: Sequence[Any]): """Map a function over a list of identical nested structures. Args: fn: the function to map; must have arity equal to `len(list_of_nests)`. nests: a list of identical nested structures. Returns: a nested structure whose leaves are ou...
7,943
def square_area(side): """Returns the area of a square""" # You have to code here # REMEMBER: Tests first!!! return pow(side,2)
7,944
def match_collision_name_to_mesh_name(properties): """ This function matches the selected collison to the selected mesh. :param object properties: The property group that contains variables that maintain the addon's correct state. :return str: The changed collision name. """ collisions = get_fr...
7,945
def prepare_ms_tree_certificates(ms_tree): """ filter and process the uploaded device pem certificates """ pem_certificates = ms_tree.pop("pem_certificates", []) certificates = [] for pem_certificate in pem_certificates: certificate = x509.load_pem_x509_certificate(pem_certificate.encode...
7,946
def main(args=None): """Perform the validation.""" # Read the CLI args if args: schema = args.schema data = args.data # Validate validator = Validator(schema, data) validator.validate()
7,947
def _handle_event_colors(color_dict, unique_events, event_id): """Create event-integer-to-color mapping, assigning defaults as needed.""" default_colors = dict(zip(sorted(unique_events), cycle(_get_color_list()))) # warn if not enough colors if color_dict is None: if len(unique_events) > len(_ge...
7,948
def redirect_logs_and_warnings_to_lists( used_logs: list[logging.LogRecord], used_warnings: list ) -> RedirectedLogsAndWarnings: """For example if using many processes with multiprocessing, it may be beneficial to log from one place. It's possible to log to variables (logs as well as warnings), pass it to t...
7,949
def get_file_picker_settings(): """Return all the data FileUploader needs to start the Google Drive Picker.""" google_settings = frappe.get_single("Google Settings") if not (google_settings.enable and google_settings.google_drive_picker_enabled): return {} return { "enabled": True, "appId": google_settings.a...
7,950
def find_version(*file_paths): """ Args: *file_paths: Returns: """ here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """ Args: *parts: Returns: """ with codecs.open(os.path.join(here, *parts), "r") as fp: ...
7,951
def match_subset(pattern: oechem.OEMol, target:oechem.OEMol): """Check if target is a subset of pattern.""" # Atoms are equal if they have same atomic number (so explicit Hydrogens are needed as well for a match) atomexpr = oechem.OEExprOpts_AtomicNumber # single or double bonds are considered identica...
7,952
def get_quad_strike_vector(q): """ Compute the unit vector pointing in the direction of strike for a quadrilateral in ECEF coordinates. Top edge assumed to be horizontal. Args: q (list): A quadrilateral; list of four points. Returns: Vector: The unit vector pointing in strike direc...
7,953
def CP_to_TT( cp_cores, max_rank, eps=1e-8, final_round=None, rsvd_kwargs=None, verbose=False, ): """ Approximate a CP tensor by a TT tensor. All cores of the TT are rounded to have a TT-rank of most `max_rank`, and singular values of at most `eps` times the largest singular val...
7,954
def _create_key_list(entries): """ Checks if entries are from FieldInfo objects and extracts keys :param entries: to create key list from :return: the list of keys """ if len(entries) == 0: return [] if all(isinstance(entry, FieldInfo) for entry in entries): return [entry.ke...
7,955
def compose_rule_hierarchies(rule_hierarchy1, lhs_instances1, rhs_instances1, rule_hierarchy2, lhs_instances2, rhs_instances2): """Compose two rule hierarchies.""" if len(rule_hierarchy1["rules"]) == 0: return rule_hierarchy2, lhs_instances2, rhs_instances2 if len(rule_h...
7,956
def write_drc_script(cell_name, gds_name, extract, final_verification, output_path, sp_name=None): """ Write a klayout script to perform DRC and optionally extraction. """ global OPTS # DRC: # klayout -b -r drc_FreePDK45.lydrc -rd input=sram_8_256_freepdk45.gds -rd topcell=sram_8_256_freepdk45 ...
7,957
def expand_tile(value, size): """Add a new axis of given size.""" value = tf.convert_to_tensor(value=value, name='value') ndims = value.shape.ndims return tf.tile(tf.expand_dims(value, axis=0), [size] + [1]*ndims)
7,958
def before_request(): """Set parameters in g before each request.""" g.user = None if 'user_id' in session: g.user = User.query.get(session['user_id']) g.referer = get_referer(request) or url_for('index') g.request_headers = request.headers
7,959
def fetch_exchange(zone_key1='DK-DK1', zone_key2='DK-DK2', session=None, target_datetime=None, logger=logging.getLogger(__name__)): """ Fetches 5-minute frequency exchange data for Danish bidding zones from api.energidataservice.dk """ r = session or requests.session() sorted_...
7,960
def snitch(func): """ This method is used to add test function to TestCase classes. snitch method gets test function and returns a copy of this function with 'test_' prefix at the beginning (to identify this function as an executable test). It provides a way to implement a st...
7,961
async def test_sensor_entity_meter_model( hass, mock_config_entry_data, mock_config_entry ): """Test entity loads meter model.""" api = get_mock_device() api.data.available_datapoints = [ "meter_model", ] api.data.meter_model = "Model X" with patch( "aiohwenergy.HomeWizardE...
7,962
def average_h5(path, path_dc): """Return averaged data from HDF5 DC measurements. Subtracts dark current from the signal measurements. Args: - path, path_dc: paths to signal and dark measurement files. Returns: - 2D array containing averaged and DC-subtracted measurement. """ with h5....
7,963
def test_profile_to_osco_execute_bogus_config(tmp_path): """Test execute call bogus config.""" section = None tgt = profile_to_osco.ProfileToOsco(section) retval = tgt.execute() assert retval == TaskOutcome.FAILURE
7,964
def init(templates_path: str = None, modules: dict = None, log: logging = None) -> None: """Set templates_path, and modules to import in Jinja2. :param templates_path: Path to templates :param modules: List of modules to import in Jinja2 :param log: logging :return: None""" import sys glob...
7,965
def edit_distance(hypothesis, truth, normalize=True, name="edit_distance"): """Computes the Levenshtein distance between sequences. This operation takes variable-length sequences (`hypothesis` and `truth`), each provided as a `SparseTensor`, and computes the Levenshtein distance. You can normalize the edit dis...
7,966
def file_timestamp(path): """ Returns a datetime.datetime() object representing the given path's "latest" timestamp, which is calculated via the maximum (newest/youngest) value between ctime and mtime. This accounts for platform variations in said values. If the path doesn't exist, the earliest ti...
7,967
def kl_bernoulli(p: np.ndarray, q: np.ndarray) -> np.ndarray: """ Compute KL-divergence between 2 probabilities `p` and `q`. `len(p)` divergences are calculated simultaneously. Parameters ---------- p Probability. q Probability. Returns ------- Array with the KL...
7,968
def _incremental_mean_and_var(X, last_mean, last_variance, last_sample_count): """Calculate mean update and a Youngs and Cramer variance update. last_mean and last_variance are statistics computed at the last step by the function. Both must be initialized to 0.0. In case no scaling is required last_var...
7,969
def avg_pds_from_events( times, gti, segment_size, dt, norm="frac", use_common_mean=True, silent=False, fluxes=None, errors=None, ): """Calculate the average periodogram from a list of event times or a light curve. If the input is a light curve, the time array needs to be un...
7,970
def check_random_state(seed): """ Turn seed into a random.Random instance If seed is None, return the Random singleton used by random. If seed is an int, return a new Random instance seeded with seed. If seed is already a Random instance, return it. Otherwise raise ValueError. """ # Code...
7,971
def chunk(seq, size, groupByList=True): """Returns list of lists/tuples broken up by size input""" func = tuple if groupByList: func = list return [func(seq[i:i + size]) for i in range(0, len(seq), size)]
7,972
def registerNamespace(namespace, prefix): """ Register a namespace in libxmp.exempi @namespace : the namespace to register @prefix : the prefix to use with this namespace """ try: registered_prefix = libxmp.exempi.namespace_prefix(namespace) # The namespace already exists, return actual prefix. return r...
7,973
def definition(): """ Lists the parent-child relationships through the curriculum structure. """ sql = """ --Course to session SELECT c.course_id as parent_id, CASE WHEN cc.course_id IS NULL THEN 0 ELSE 1 END as linked, cs.course_session_id as child_id, 'course' as parent, cs.description + ' ' + ...
7,974
def create_user(strategy, details, backend, user=None, *args, **kwargs): """Aggressively attempt to register and sign in new user""" if user: return None request = strategy.request settings = request.settings email = details.get("email") username = kwargs.get("clean_username") if ...
7,975
def enumerate_benchmark_replay(folder, runtime='python', time_kwargs=None, skip_long_test=True, time_kwargs_fact=None, time_limit=4, verbose=1, fLOG=None): """ Replays a benchmark stored with function :func:`enumerate_validated_operator_opsets ...
7,976
def add_regex_def(name: str, regex: str, priority: str, entity: str): """ Add additional regexes to the JSON file. Parameters ---------- name : str Regex name. regex : str Regex definition. priority : str Regex priority. entity : str Entity corresponding ...
7,977
def wiggles(data, wiggleInterval=10, overlap=5, posFill='black', negFill=None, lineColor='black', rescale=True, extent=None, ax=None): """ 2-D Wiggle Trace Variable Amplitude Plot Parameters ---------- x: input data (2D numpy array) wiggleInterval: (default, 10) Plot 'wiggles' every...
7,978
def save_dumps(module_name, dumps, dump_root="."): """ Serialize dump files to the disk. Parameters ---------- module_name : str File name, referring to the module that generated the dump contents dumps : dict The output contents to be saved into the files dump_root ...
7,979
def prendreTresorPlateau(plateau,lig,col,numTresor): """ prend le tresor numTresor qui se trouve sur la carte en lin,col du plateau retourne True si l'opération s'est bien passée (le trésor était vraiment sur la carte paramètres: plateau: le plateau considéré lig: la ligne où se trou...
7,980
def load_styles(style_yaml) -> dict: """ Load point style dictionary """ default_style = {"icon_image": DEFAULT_ICON_IMAGE, "icon_color": DEFAULT_ICON_COLOR, "icon_scale": DEFAULT_ICON_SCALE, "text_scale": DEFAULT_TEXT_SCALE, } ...
7,981
def everything_deployed(project, chain, web3, accounts, deploy_address) -> dict: """Deploy our token plan.""" yaml_filename = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..","crowdsales", "allocated-token-sale-acceptance-test.yml")) deployment_name = "testrpc" chain_data = load_...
7,982
def task_get_all(context, filters=None, marker=None, limit=None, sort_key='created_at', sort_dir='desc', admin_as_user=False): """ Get all tasks that match zero or more filters. :param filters: dict of filter keys and values. :param marker: task id after which to start page :param ...
7,983
def updateAppMonConf(AppID, requestModel): """Update an Application Monitoring Configuration for a given application Args: AppID (str): This is the application ID of the Web App you are interested in. requestModel: This is the data you wish to update and you need to put it in this f...
7,984
def plot_morphology(morphology, order=MORPHOLOGY_ORDER, colors=MORPHOLOGY_COLORS, metastases=None, metastasis_color=METASTASIS_COLOR, ax=None, bg_color='#f6f6f6', **kwargs): ""...
7,985
def get_btc(path, date1, date2, period="5-min", delay=3): """ period = '5-min', 'Hourly' """ url2_1 = ( r"https://bitcoincharts.com/charts/chart.json?m=krakenUSD&SubmitButton=Draw&r=5&i=" + period + "&c=1&s=" ) url2_2 = r"&Prev=&Next=&t=S&b=&a1=&m1=10&a2=&m2=25&x=0&i1...
7,986
def test_section_trsp(get_test_ds,myfunc,tfld,xflds,yflds,factor,args,mask,error): """compute a volume transport, within the lat/lon portion of the domain""" ds = get_test_ds grid = ecco_v4_py.get_llc_grid(ds) ds['U'],ds['V'] = get_fake_vectors(ds['U'],ds['V']) for fx,fy in zip(xflds,yflds): ...
7,987
def scores_summary(CurDataDir, steps = 300, population_size = 40, regenerate=False): """Obsolete for the one above! better and more automatic""" ScoreEvolveTable = np.full((steps, population_size,), np.NAN) ImagefnTable = [[""] * population_size for i in range(steps)] fncatalog = os.listdir(CurDataDir) ...
7,988
def post(name,url,message,params=None): """Wrap a post in some basic error reporting""" start = dt.now() s = requests.session() if params is None: response = s.post(url,json=message) else: response = s.post(url,json=message,params=params) end = dt.now() if not response.status...
7,989
def get_lin_reg_results(est, true, zero_tol=0): """ Parameters ---------- est: an Estimator A covariance estimator. true: array-like, shape (n_features, n_features) zero_tol: float Output ------ out: dict with keys 'utri' and 'graph' """ est_coef = get_coef(est)[...
7,990
def download_file(requested_url: str) -> str: """Download a file from github repository""" url = f"https://github.com/{requested_url.replace('blob', 'raw')}" resp = requests.get(url) logging.info(F"Requested URL: {requested_url}") if resp.status_code != 200: logging.info(f"Can not download...
7,991
def readBody(response): """ Get the body of an L{IResponse} and return it as a byte string. This is a helper function for clients that don't want to incrementally receive the body of an HTTP response. @param response: The HTTP response for which the body will be read. @type response: L{IRespon...
7,992
def is_valid_mac(address): """Verify the format of a MAC address.""" class mac_dialect(netaddr.mac_eui48): word_fmt = '%.02x' word_sep = ':' try: na = netaddr.EUI(address, dialect=mac_dialect) except Exception: return False return str(na) == address.lower()
7,993
def build_state_abstraction(similar_states, mdp, tol=0.1): """ """ bools = similar_states + np.eye(similar_states.shape[0]) < tol # approximate abstraction if bools.sum() == 0: raise ValueError('No abstraction') mapping, parts = partitions(bools) idx = list(set(np.array([p[0] for p i...
7,994
def diagram(source, rstrip=True): """High level API to generate ASCII diagram. This function is equivalent to: .. code-block:: python Diagram(source).renders() :param source: The ADia source code. :type source: str or file-like :param rstrip: If ``True``, the trailing wihtespaces at t...
7,995
def eng_to_kong(eng_word: str)-> list[str]: """ Translate given English word into Korean into matching pronounciation, matching the English Loanword Orthography. For example, "hello" will be translated into 헐로. # Panics When given a english word that it cannot translate, `eng_to_kong` will rai...
7,996
def test_ME109(applicability_code, amount): """ If the flag 'amount' on duty expression is 'mandatory' then an amount must be specified. If the flag is set to 'not permitted' then no amount may be entered. """ measure = factories.MeasureFactory.create() condition = factories.MeasureConditi...
7,997
def write_csv(path, data): """TODO""" with open(path, 'w', newline='', encoding='utf-8') as csv_file: writer = csv.writer(csv_file) writer.writerows(data)
7,998
def targets_to_moves( initial: Coordinates[AxisKey, CoordinateValue], targets: List[MoveTarget[AxisKey]] ) -> Iterator[Move[AxisKey]]: """Transform a list of MoveTargets into a list of Moves.""" all_axes: Set[AxisKey] = set() for target in targets: all_axes.update(set(target.position.keys())) ...
7,999