content
stringlengths
22
815k
id
int64
0
4.91M
def is_valid_hostname(hostname): """Convert domain label into IDN ACE form (handles internationalized domains and regular (ascii) domains""" hostname = from_unicode(hostname).to_text() # stackoverflow.com/a/2532344/1707152 if len(hostname) > 255: return False if hostname[-1] == ".": ...
76,400
def delBlank(strs): """ Delete all blanks in the str. """ ans = "" for e in strs: if e != " ": ans += e return ans
76,401
def jdcnv(year, month, day, hour): """Convert Gregorian time (UTC) to Julian Date Input: year = year (scalar int) month = month 1-12 (scalar int) day = day 1-31 (scalar int) hour = fractional hour (scalar double) Output: julian = Julian Date (scalar double) Origina...
76,402
def get_all_people(): """ You can hit the resource name without an ID to get a listing of all of that resource """ resp = session.get(GHIBLI_URL + "people") people = [Person(**json_person) for json_person in resp.json()] return people
76,403
def flatten(l): """ Flattens a deeply nested iterable, but does not explode str, bytes. From http://stackoverflow.com/a/2158532/ :param l: the list :return: a generator of flattened items """ for el in l: if isinstance(el, Iterable) and not isinstance(el, (str, bytes)): ...
76,404
def generate_preset_test_translations(dimensions=3): """Generates a set of translations.""" permutations = itertools.product([0.1, -0.2, 0.5, 0.7, 0.4, -0.1], repeat=dimensions) return np.array(list(permutations))
76,405
def save_data_txt(code, zz, hubble_array, om_b_array, om_cdm_array, paths, names, lmax,APSunits=None, MPSunits='(Mpc/h)^3', As=2.3e-9, ns=0.96,r=0, z_pk_max=4,tau=0.09, k_max=3, lens_accuracy=0): """Save cosmological quantities for all combinations of hubble constant, omeg...
76,406
def describe_assessment_templates(assessmentTemplateArns=None): """ Describes the assessment templates that are specified by the ARNs of the assessment templates. See also: AWS API Documentation Examples Describes the assessment templates that are specified by the ARNs of the assessment templat...
76,407
def test_validate_paddle_cabling_no_architecture(): """Test that the `canu validate paddle-cabling` command errors on bad architecture.""" bad_ccj_file = "bad.json" with runner.isolated_filesystem(): with open(bad_ccj_file, "w") as f: json.dump(bad_ccj, f) result = runner.invoke...
76,408
def import_tree_debris(input_file: str) -> None: """ Import the requests for tree debris to the database. :param input_file: The file from which to load the requests for tree debris. """ print("Getting requests for tree debris") db = next(get_db()) input_df = pd.read_csv(input_file, sep=',').r...
76,409
def closest_precise_locator_for(element: WebElement, root: WebElement = None): """Builds the most precise locator which matches `element`. If `element` does not have a role, return a semantic locator which matches the closest ancestor with a role. "Precise" means that it matches the fewest other elements, whil...
76,410
def splitn(s, n): """split string s into chunks no more than n characters long""" parts = re.split("(.{%d,%d})" % (n, n), s) map(parts.remove, [""] * parts.count("")) return parts
76,411
def load_output(data_path, provinces, notrade=True): """Read output from disaggregation process and translate to usable pandas DataFrame Parameters - data_path - String name of data path - provinces - pandas DataFrame with provincial/regional data - notrade - Boolean to specify whether ...
76,412
def skinHasImage(image): """ Returns ``True`` if the image file exists in the skin. :param image: string - image filename .. note:: If the media resides in a subfolder include it. (eg. home-myfiles\home-myfiles2.png). You can use the above as keywords for arguments. example:: exi...
76,413
def main() -> None: """ Make a jazz noise here """ args = get_args() print(fib(args.generations, args.litter))
76,414
def check_torchaudio_backend(): """Checks the torchaudio backend and sets it to soundfile if windows is detected. """ current_system = platform.system() if current_system == "Windows": logger.warn( "The torchaudio backend is switched to 'soundfile'. Note that 'sox_io' is not supp...
76,415
def is_date(string, fuzzy=False): """ return whether the string can be interpreted as a date """ try: parse(string, fuzzy=fuzzy) return True except ValueError: return False
76,416
def test_bytes(): """ Dumping and loading a string. PYTHON3 ONLY """ if six.PY3: filename, mode = 'test.h5', 'w' string_obj = b"The quick brown fox jumps over the lazy dog" dump(string_obj, filename, mode) string_hkl = load(filename) #print "Initial list: %s"%list_obj ...
76,417
def known_good_image_archive(request, tmp_path: Path) -> TypingKnownGoodImageArchive: """Provides 'known good' metadata for a local image that can be modified.""" path_destination = tmp_path.joinpath(request.param["resource"]) path_source = get_test_data_path(request, request.param["resource"]) copy(str...
76,418
def LoadMOS(mos_csv): """Load a csv file withMOS scores. Args: mos_csv: Path to a csv file that has degraded and MOS. Returns: Dictionary with filename keys and MOS values """ mos_dict = {} with open(mos_csv, 'r') as csvfile: mos_reader = csv.reader(csvfile) for row in mos_reader: # ...
76,419
def import_gff(name, fn): """ Creates a new genome using the specified GFF file. name: Name of genome fn: path to GFF file """ from edge.models import Genome if Genome.objects.filter(name=name).count() > 0: raise Exception('There is already a genome named "%s"' % (name,)) g = ...
76,420
def main(config_path=None): """ The main entry point for the unix version of dogstatsd. """ COMMANDS_START_DOGSTATSD = [ 'start', ] parser = optparse.OptionParser("%prog [{commands}]".format(commands='|'.join(Dogstatsd.COMMANDS))) parser.add_option('-u', '--use-local-forwarder', action='sto...
76,421
def run(opt, device_id, error_queue): """ run process """ try: gpu_rank = onmt.utils.distributed.multi_init(opt, device_id) if gpu_rank != opt.gpu_ranks[device_id]: raise AssertionError("An error occurred in \ Distributed initialization") single_main(opt, de...
76,422
def url_is_invalid_unicode(url_string): """ Check for unicode control characters in URL """ for x in str(url_string): if unicodedata.category(x)[0] == "C": return True return False
76,423
def fn_with_custom_grad(grad_fn, use_global_vars=False, use_entire_scope=False): """Decorator to create a subgraph with a custom gradient function. The subgraph created by the decorated function is NOT put in a Defun and so does not suffer from the limitations of the Defun (all subgraph ops on the same ...
76,424
def _monkey_patch_dataset_method(strategy): """Monkey-patch `strategy`'s `make_dataset_iterator` method.""" def make_dataset(self, dataset): logging.info('Using pure synthetic data.') with self.scope(): if self.extended._global_batch_size: # pylint: disable=protected-access return SyntheticDa...
76,425
def set_hist_data(start = None,end = None,ktype = None,retry_count = 3,pause=0): """ 获取近三年交易信息存入数据库中,不同的ktype存入不同的表,参数与tushare相同 None 即为取近三年 若ktype = None ,则设定为全部 Parameters ------ return """ engine = create_engine(ct._ENGINE_) dat =pd.read_sql_table...
76,426
def test_program_current_price(): """ current_price should return the price of the latest product version if it exists """ program = ProgramFactory.create() assert program.current_price is None price = 10 ProductVersionFactory.create( product=ProductFactory(content_object=program), p...
76,427
def _xvert(cls, result_item, generate_links=True): """ converts the response object into Json :param generate_links: if True, it will add the HATEOAS links to the response :param result_item: the actual item which will get converted :return: """ if isinstance(result_item, Model): mo...
76,428
def Gamma_correction(low_frequency, alpha=0.5): """ Adjust the coefficient of low frequency component using Gamma correction. :param low_frequency: the low frequency component of the image calculated with Shearlet transformation. :param alpha: adjustment factor with a range from 0 to 1, in addition, it ...
76,429
def write_2_0(root_path, menus): """ Write the menus for version 2.0 of the API. :param root_path: The output path for version 2.0. This is the root path. The subfolder menu will be created. :param menus: The menus to write. :return: """ for resto, resto_menu in menus.items(): overv...
76,430
def test_estimate_moments(): """Test moments estimated from samples and sampling from GMM.""" global X global random_state gmm = GMM(n_components=2, random_state=random_state) gmm.from_samples(X) assert_less(np.linalg.norm(gmm.means[0] - means[0]), 0.005) assert_less(np.linalg.norm(gmm.cova...
76,431
def assign_first_visit(df: DataFrame, column_name_to_assign: str, id_column: str, visit_date_column: str) -> DataFrame: """ Assign column to represent number of participants in household Parameters ---------- df column_name_to_assign id_column visit_date_column """ window = Windo...
76,432
def print_header(fitsfile, ext=0, ofileh=sys.stdout): """Print header from fits file to either stdout or to a file. """ hdr = fitsio.read_header(fitsfile, ext=ext) ofileh.write("%s" % hdr) ofileh.write("\n") outfh.close() return
76,433
def render_map(arguments: argparse.Namespace) -> None: """ Map rendering entry point. :param arguments: command-line arguments """ configuration: MapConfiguration = MapConfiguration.from_options( arguments, float(arguments.zoom) ) cache_path: Path = Path(arguments.cache) cache_p...
76,434
def _msgpack_ext_pack(x): """Msgpack encoders for custom types.""" if isinstance(x, complex): return msgpack.ExtType(_MsgpackExtType.native_complex, msgpack.packb((x.real, x.imag))) if isinstance(x, jax.ShapedArray): return msgpack.ExtType(_MsgpackExtType.shaped_array, ...
76,435
def convert_s3_label_to_bytes(s3_size: str) -> int: """convert 12MiB to 12 * 1024**2""" match = re.match(r"([0-9.]+)(\w+)", s3_size) if match: return int(float(match.groups()[0]) * 1024 ** LABELS_POWER[match.groups()[1]]) return -1
76,436
def ld_prune(df, ld_beds, snvs=None): """ Prune set of GWAS based on LD and significance. A graph of all SNVs is constructed with edges for LD >= 0.8 and the most significant SNV per connected component is kept. Parameters ---------- df : pandas.DataFrame Pandas dataframe with ...
76,437
def perm_to_string(p): """ Convert p to string, slightly more compact than list printing. """ s = "(" for x in p: s = s + "%2d "%x s += ")" return s
76,438
def pg_capital(s : str) -> str: """ If string contains a capital letter, wrap it in double quotes returns: string """ if '"' in s: return s needs_quotes = False for c in str(s): if ord(c) < ord('a') or ord(c) > ord('z'): if not c.isdigit(): needs_...
76,439
def get_client(host, port=None, username=None, password=None, tenant=None, auth_url=None, auth_strategy=None, auth_token=None, region=None, is_silent_upload=False, insecure=False): """ Returns a new client heat client object based on common kwargs. ...
76,440
def divy(curvelist, value): """ Divide y values of the curve(s) by a constant value. >>> curves = pydvif.read('testData.txt') >>> pydvif.divy(curves, 4) :param curvelist: The curve or curvelist :type curvelist: Curve or list :param value: The divisor :type value: float """ cur...
76,441
def ht_syn_one(): """Hash table of words and their synonyms.""" ht = HashTable(10) # import pdb; pdb.set_trace() ht.set('fond', 'enamored') ht.set('wrath', 'anger') ht.set('diligent', 'employed') ht.set('outfit', 'garb') ht.set('guide', 'usher') return ht
76,442
def all_inactive_converter( intersection, DEBUG= False, emergency= False): """ changes all the traffic lights to active if all are inactive\n else remains the same\n if the emergency condition is there then it is also reset\n """ all_inactive = True for index, tl in enumerate( intersection)...
76,443
def escape_bytes(bytes_): """ Convert a bytes object to an escaped string. Convert bytes to an ASCII string. Non-printable characters and a single quote (') are escaped. This allows to format bytes in messages as f"b'{utils.escape_bytes(bytes)}'". """ res = "" for byte in bytes_: ...
76,444
def _minimize_towers(tower_specs, optimizer): """Aggregate and apply gradients for computed losses.""" grad_lists = {} for tower_spec in tower_specs: with ops_lib.device(tower_spec.loss.device): for grad, var in optimizer.compute_gradients(tower_spec.loss): if grad is not None: grad_li...
76,445
async def command(client, param, ctx): """ Syntax: ~current Description: Get it? Current? Haaa Explicitly tells users how Swashbot is working to swash in the channel """ cid = ctx.channel.id e = discord.Embed( title="Current settings for this channel", description=statu...
76,446
def shrink_dimensions(width, height, max_dimension): """ Resize dimensions so max dimension is max_dimension. If dimensions are too small no resizing is done Args: width (int): The width height (int): The height max_dimension (int): The maximum size of a dimension Returns: ...
76,447
def relu_backward(dA, cache): """ This function implements the backward propagation for a single Relu unit @params dA = post-activation gradient, of any shape cache = Retrieve cached Z for computing backward propagation efficiently Returns: dZ = Gradient of the cost with respe...
76,448
def keccak256(value): """Thin wrapper around keccak function.""" return HexBytes(keccak(value))
76,449
def set_id(df, index, possible_matches, col_set, col_check): """Sets the ID in column "col_set" of "df" at "index" to the value in "col_check" in possible_matches. Expects a unique col_check value in possible_matches. """ df[col_set].at[index] = int(possible_matches[col_check].iloc[0])
76,450
def slerp(pt1, pt2, intervals): """Spherical linear interpolation. Args: pt1: Array of points. When interval is 0, the result is pt1. pt2: Array of points. When interval is 1, the result is pt2. intervals: Array of intervals at which to evaluate the linear interpolation ...
76,451
def make_cumvalues(xvalues): """ Takes a Pandas dataframe with one column as input value. Tries to create a cumulative series. """ newvalues = 0.0 * xvalues dx = xvalues.diff() dxpos = dx mask = -xvalues.diff() > 0.9 * xvalues nrsteps = len(dx.loc[mask]) lapidx = np.cumsum((-dx + a...
76,452
def payment_success(request): """ Renders status page after donation passed successfully." """ return render(request, 'payment_success.html')
76,453
def should_workfile_tool_start( project_name, host_name, task_name, task_type, default_output=False ): """Define if host should start workfile tool at host launch. Default output is `False`. Can be overridden with environment variable `OPENPYPE_WORKFILE_TOOL_ON_START`, valid values without case sensiti...
76,454
def create(): """ $ curl -i -X POST -H "Content-Type: application/json" -d '{"username":"user","password":"python"}' http://localhost:5000/api/user """ username = request.json.get("username") password = request.json.get("password") if username is None or password is None: abort(400) #...
76,455
def display_hour_range_dash(value): """ Function that just calls the display_hour_range function. This function is decorated by the Dash Application decorator. Such an arrangement is used as unit testing decorated functions is complex. """ display = display_hour_range(value) return displa...
76,456
def test_invalid_permission(loan_created, params): """Test transition without permission.""" transition = CreatedToPending( 'CREATED', 'PENDING', trigger='next', permission_factory=deny_all ) with pytest.raises(InvalidPermissionError): transition.execute(loan_created, **params) asser...
76,457
def temporary_logger_config( level: Union[int, str] = None, stream_fmt: str = None, stream_datefmt: str = None, ) -> Generator[logging.Logger, None, None]: """ Set a temporary config for the `prefect` logger. The formatting can be updated for `StreamHandlers` but will not update the CloudHandler...
76,458
def flatten_image_directory(): """ I used this once to combine images from all of the files loaded by the imagenet into a single superdirectory """ from shutil import copyfile train_directory = "/media/worklab/data_HDD/cv_data/images/data_imagenet_loader/train" test_directory = "/media/work...
76,459
def test_add_single_stub(shared_datadir, tmp_path): """should add a single stub""" stub_path = shared_datadir / 'esp8266_test_stub' manager = stubs.StubManager() manager.add(stub_path, dest=tmp_path) assert len(manager) == 1 assert stub_path.name in [d.name for d in tmp_path.iterdir()]
76,460
def sample_ingredient(user, name='Cinnamon'): """membuat dan mengembalikan sampel ingredient""" return Ingredient.objects.create(user=user, name=name)
76,461
def test_serialize_rrs_state(): """Verifies that RRS states serialize to YAML correctly.""" rrs = samplespace.RepeatableRandomSequence(seed=12345) [rrs.getnextblock() for _ in range(100)] state = rrs.getstate() expected = rrs.getnextblock() state_as_dict = state.as_dict() [rrs.getnextblock...
76,462
def _get_np_complex_dtype(float_dtype): """ Get equivalent complex type given current float dtype """ if float_dtype == np.float32: return np.complex64 elif float_dtype == np.float64: return np.complex128 else: return np.complex256
76,463
def ResizePad(mask, image_shape): """ Resize and Pad mask back to original shape -- reverse action of CropResize for masks """ if mask.shape == image_shape: return mask h, w = image_shape side = min(h, w) mask = cv2.resize(mask, (side, side), interpolation=cv2.INTER_NEAREST) ...
76,464
def read(filename, *args, **kwds): """Loads a graph from the given filename. This is just a convenience function, calls L{Graph.Read} directly. All arguments are passed unchanged to L{Graph.Read} @param filename: the name of the file to be loaded """ return Graph.Read(filename, *args, **kwds)
76,465
def create_instance_from_template_with_overrides( project_id: str, zone: str, instance_name: str, instance_template_name: str, machine_type: str, new_disk_source_image: str, ) -> compute_v1.Instance: """ Creates a Compute Engine VM instance from an instance template, changing the machine...
76,466
def arg_parse_params(): """ parse the input parameters :return dict: {str: any} """ # SEE: https://docs.python.org/3/library/argparse.html parser = argparse.ArgumentParser() parser.add_argument('-i', '--path_images', type=str, required=True, help='path (pattern) to the in...
76,467
def getPossibleWordInner(str, triedWords, maxAllowTry, i = 0): """ get a possible word that we haven't tried before @BUG if this recursion run over 1000 (997 in fact) times, it will throw RecursionError because it reaches the system maximum """ # if this interaction has reach the max allow n...
76,468
def evaluate(model: Module, dataloader: DataLoader, metrics: List[Union[str, Callable]], prepare_batch: Callable = lambda x: x, loss_fn: Callable = None, prefix: str = 'val_', suffix: str = ''): """Evaluate a model on one or more metrics ...
76,469
def ensureGrayscale(np_image, info=False): """Ensures that given image is in grayscale Keyword argument: np_image -- image as NumPy array Return: np_image as grayscale image """ isConverted = False if len(np_image.shape) == 3: if np_image.shape[2] == 3: np_image = ge...
76,470
def load_unlabelled(filename: str) -> List: """Helper function to load unlabelled dataset for unsupervised training. Args: filename (str): filename of dataset Returns: List: list of dataset by line. """ data = [] with open(filename, "r") as F: for line in F: ...
76,471
def is_key_attribute(df, attr, verbose=False): """ Check if an attribute is a key attribute Args: df (pandas dataframe): Input dataframe attr (str): Attribute in the pandas dataframe verbose (bool): Flag to indicate whether warnings should be printed out Returns: result...
76,472
def client(ctx): """ Canotic API operations """ api_key = '' try: api_key = load_api_key() except Exception as e: pass if len(api_key) == 0: print('User needs to login or set api key') exit() ctx.obj = {} ctx.obj['client'] = Client(api_key=api_key)
76,473
def break_rest(time, flux, flux_err, cadences): """ Breaks up the non-signal cases into bite-sized cadence-length chunks. Parameters ---------- time : np.ndarray Array of time. flux : np.ndarray Array of fluxes. flux_err : np.ndarray Array of flux errors. cade...
76,474
def login_required(fn): """ login required as decorator """ @wraps(fn) def decorated_view(*args, **kwargs): if not 'user' in session or session['user'] == None: return redirect(url_for("login")) return fn(*args, **kwargs) return decorated_view
76,475
def test_get_commits_from_event(event, commits): """ Test the get_commits_from_event method pulls commits from event objects correctly. """ result = action.get_commits_from_event(event) assert result == commits
76,476
def addAge(data, ages): """ The new format in CMD v3.2 does not include the commented line with the 'Age' value, and the logAge column is rounded to 3 decimal places so this value it can not be taken from there. Add this line back to each age for each metallicity file. """ data = data.spli...
76,477
def group_spans(article_id, span_intervals): """ Groups together spans from the same article """ dictionary = dict.fromkeys(article_id, span_intervals) spans = {} for key, value in dictionary.items(): spans.setdefault(key, []) spans[key].append(value) return spans
76,478
def conjugate_gradient_solve(a_mat, b_mat, tol=1e-10): """Returns `X` such that `A * X = B`. Uses Conjugate Gradient to solve many linear systems of equations with the same matrix `a_mat` and multiple right hand sides provided as columns in the matrix `b_mat`. Args: a_mat: a Symmetric Positive Definite ...
76,479
def list_lateral_movement_template_command(client: Client) -> CommandResults: """Retrieve a list of all lateral movement templates. Args: client (Client): Cymulate client. Returns: CommandResults: A CommandResults object that is then passed to 'return_results', cont...
76,480
async def run_test( driver: AbstractCanDriver, load_percentage: float, bitrate: float, mode: StimulusMode, duration: Optional[float] = None, ) -> AsyncGenerator[StatisticElement, Optional[bool]]: """Run the test and yield results. Params ------ driver: A pre-constructed canbus drive...
76,481
def test_atomic_string_white_space_nistxml_sv_iv_atomic_string_white_space_1_5(mode, save_output, output_format): """ Type atomic/string is restricted by facet whiteSpace with value preserve. """ assert_bindings( schema="nistData/atomic/string/Schema+Instance/NISTSchema-SV-IV-atomic-string-w...
76,482
def run_install_checks(): """ We need non-sudo write access into `{CORIANDER_DIR}/include/coriander_plugins`, and `{CORIANDER_DIR}/lib/coriander_plugins` """ INCLUDES_DIR = join(COCL_INCLUDE, 'coriander_plugins') check_folder_exists(INCLUDES_DIR) check_folder_writable(INCLUDES_DIR) LIB...
76,483
def set_vyper_version( version: Union[str, Version], silent: bool = False, vvm_binary_path: Union[Path, str] = None ) -> None: """ Set the currently active `vyper` binary. Arguments --------- version : str | Version, optional Installed `vyper` version to get the path of. If not given, r...
76,484
def test_advanced_activations(): """ Tests that various ways of specifying activations in keras models are handled when replaced with Relu """ inp = Input(shape=(2, )) x = Dense(5, activation='elu')(inp) x = advanced_activations.LeakyReLU()(x) x = Activation('elu')(x) model = Model(inp, x) ...
76,485
def test_ext_nh_cap_admin_dist_tag_ibgp_peer_p1(request): """ Test extended capability nexthop with admin distance and route tag. Verify IPv4 routes are advertised to peer when static routes are configured with ADMIN distance and tag option """ tc_name = request.node.name write_test_header...
76,486
def create_download_response_zip(file_format: str, experiment: Experiment) -> \ FileResponse: """Creates a FileResponse containing a ZIP with all data of the provided experiment, in the desired format. """ # Create the zip using the desired methods if file_format == 'raw': zip_file = _c...
76,487
def ids_to_names(ven_id, ven_name, dev_id, dev_name): """Uses an internal lookup table to return canonical names when known. Returns: tuple(vendor name, device name). """ m = _VENDOR_MAPPING.get(ven_id) if not m: return ven_name, dev_name return m[0], m[1].get(dev_id, dev_name)
76,488
def ns_domain(domain, rtype = "A", dns = ""): """list rtype NS records from domain using provided or default dns, returns dict with hostnames as keys""" hosts = subprocess.Popen(nsls_cmd % {'d': domain, 't': rtype, 's': dns}, stdin = subprocess.PIPE, stdout = subprocess.PIPE, ...
76,489
def assert_cert_belong_to(cert_data: any, user: User): """ Raises a CertificateException if the certificate doesn't belong to the user. """ # Parse the users name form the email [first_name, last_name] = user.email.split("@")[0].split(".") first_name = canonicalize_name(first_name) last...
76,490
def pixel_matrix_from_hash(hash_value): """Sets pixels of the image to on or off based on hash value. Args: hash_value (int): The hash value of the username of user Returns: np.array: A symmetric black and white pixel map matrix """ pixel_matrix = np.zeros((5,5)) # first 25 cha...
76,491
def portfolio_vol(weights, covmat): """ Weights to vol Turns lists,arrays into float volatility figure Last updated 24/12/2020 """ if isinstance(weights, list): weights = np.array(weights) return (weights.T @ covmat @ weights) ** 0.5
76,492
def find_pulsars_in_fov(obsid, psrbeg, psrend, fwhm=None, search_radius=0.02, meta_data=None, full_meta=None, no_known_pulsars=False, no_search_cands=False, offset=0, angle_offset=0): """ Find all pulsars in the fiel...
76,493
def get_zone(zone_uuid): """Get the Redfish Zone. Return Resource Zone redfish JSON. Logs exception of any error and return Internal Server Error or Not Found. Returns: JSON: Redfish json with Resource Zone. """ template_id, enclosure_id = ZoneService.\ ...
76,494
def _get_fargs(func, no_self=False, no_varargs=False): # pragma: no cover """ Same as putil.pinspect.get_function_args """ is_parg = lambda x: (len(x) > 1) and (x[0] == '*') and (x[1] != '*') is_kwarg = lambda x: (len(x) > 2) and (x[:2] == '**') par_dict = signature(func).parameters # Mark position...
76,495
def new_game_nd(dimensions, bombs): """ Start a new game. Return a game state dictionary, with the 'dimensions', 'state', 'board' and 'mask' fields adequately initialized. Args: dimensions (tuple): Dimensions of the board bombs (list): Bomb locations as a list of lists, each an ...
76,496
def deprecation_versions(): """Create a list of valid version for deprecation entries, current+4""" major, minor = [int(version) for version in __version__.split('.')[0:2]] return Any(*['{0}.{1}'.format(major, minor + increment) for increment in range(0, 5)])
76,497
def fitness_score(individual: list) -> int: """ Calculate the fitness score of an individual @param individual: @return: score: int """ score = 0 for row in range(Constants.NUMBER_OF_QUEENS.value): col = individual[row] for other_row in range(Constants.NUMBER_OF_QUEENS.value)...
76,498
def get_main_dir_path(): """ returns the path to the main speech directory for mac and linux depending on the OS """ # checks if I am on my local (mac) or a VM (linux) system = platform.system() if system == 'Linux': path_prefix = '/home/dzubke/awni_speech/speech/' elif system == 'Da...
76,499