content
stringlengths
22
815k
id
int64
0
4.91M
def data_anscombes_quartet(id): """ Generate one case for each of the Anscombe's quartet """ if id == 1: x = [10.0, 8.0, 13.0, 9.0, 11.0, 14.0, 6.0, 4.0, 12.0, 7.0, 5.0] y = [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68] elif id == 2: x = [10.0, 8.0, 13.0, 9.0, 1...
43,500
def rinko_curve_fit_eq(X, a, b, c, d, e, f, g, h): """ Same as rinko_oxy_eq, but in a form that is more suitible for scipy's curve fit routine X contains pressure, temperature, voltage, and OS (the normal arguments for rinko_oxy_eq) """ press, temp, oxyvo, os = X o2_cal = RinkoO2Cal(a, b, c, d,...
43,501
def test_base_rtidy(driver: selenium.webdriver, *args, **kwargs): """ Test the creation of a project with a R Tidyverse base. Args: driver """ b = lambda : \ testutils.elements.AddProjectBaseElements(driver).r_tidyverse_base_button.find() testutils.prep_base(driver, b)
43,502
def join_paths(*paths): """ Looks for a resource (e.g. configuration file). :param workspace: :param name: :param resources_dir: :return: path to requested resource """ return os.path.join(*paths)
43,503
def str_create(args, maxdy): """ create closed string operator automatically from input nx and ny for systems long in y direction Parameters ---------------- args : dictionary should include 'nx', 'ny', 'xperiodic' entries maxsep : int maximum separation of the closed string...
43,504
def InstallFile(filename, old_root, new_root): """Install a single file by moving it into a new location. Args: filename: Relative name of file to install. old_root: The current location of the file. new_root: The new desired root for the file. """ oldname = os.path.join(old_root, filename) util...
43,505
def _create_links(paths, file_list, makedirs=True): """.. Create symlinks from list of files containing linking instructions. Create symbolic links using instructions contained in files of list ``file_list``. Instructions are `string formatted <https://docs.python.org/3....
43,506
def SearchList(items, message="Select an item:", title='FontParts'): """ A dialgo to search a given list. Optionally a `message`, `title` and `allFonts` can be provided. :: from fontParts.ui import SearchList result = SearchList(["a", "b", "c"]) print(result) """ retur...
43,507
def attack(N, e, phi, c): """ Computes possible plaintexts when e is not coprime with Euler's totient. More information: Shumow D., "Incorrectly Generated RSA Keys: How To Recover Lost Plaintexts" :param N: the modulus :param e: the public exponent :param phi: Euler's totient for the modulus ...
43,508
async def bsi_score_trend( business_id: int, time_period: str = Query( ..., enum=DATEFILTER.date_filter), auth: Depends = Depends(get_current_user), ) -> dict[str, int]: """ Shows the media presence of the company on a monthly basis. This is calculated using the ‘Business Sentiment Index’ f...
43,509
def empty_dir(local_path): """ Removes all children and descendants of a directory, leaving the directory itself intact """ for entry in scandir(local_path): if entry.is_dir(): rmtree(entry.path) else: remove(entry.path)
43,510
def create_role(party: Party, role_info: dict) -> PartyRole: """Create a new party role and link to party.""" party_role = PartyRole( role=JSON_ROLE_CONVERTER.get(role_info.get('roleType').lower(), ''), appointment_date=role_info['appointmentDate'], cessation_date=role_info['cessationDat...
43,511
def murmur2_32(byte_data, seed=DEFAULT_SEED): """ Creates a murmur2 32 bit integer hash from the given byte_data and seed. :param bytes byte_data: the bytes to hash :param int seed: seed to initialize this with :return int: 32 bit hash """ length = len(byte_data) # Initialize the hash ...
43,512
def cell_segmenter(im, thresh='otsu', radius=20.0, image_mode='phase', area_bounds=(0,1e7), ecc_bounds=(0, 1)): """ This function segments a given image via thresholding and returns a labeled segmentation mask. Parameters ---------- im : 2d-array Image to be segmented...
43,513
def test_color_yes_collection_on_non_atty(testdir, verbose): """skip collect progress report when working on non-terminals. #1397 """ testdir.makepyfile( """ import pytest @pytest.mark.parametrize('i', range(10)) def test_this(i): assert 1 """ ) ar...
43,514
def convert_id_to_location(df, locations_df): """Converts c3 `id` to covid forecast hub `location_name`. c3 uses `id` as the PK while covid forecast hub uses `location_name` (labeled just `location` there instead of `location_name`) as the PK. locations_df contains `id` and `location_name` mapping. ...
43,515
def extract_scoring_history_field(aModel, fieldOfInterest, takeFirst=False): """ Given a fieldOfInterest that are found in the model scoring history, this function will extract the list of field values for you from the model. :param aModel: H2O model where you want to extract a list of fields from the ...
43,516
def get_num_beats(times, voltages): """ Calculates the number of beats in the sample. :param times: List of time data :param voltages: List of voltage data :return: Int representing the number of detected beats """ return get_beats_times(times, voltages).size
43,517
def find_all_indexes_r(text, pattern, itext=0, ipattern=0, indices=None): """Recursive implementation of find_all_indexes. The time complexity should be equialent to find all indexs not recursive.""" if indices is None: indices = [] if len(text) == itext + ipattern: if len(pattern) == ip...
43,518
def image_scale(pts, scale): """scale to original image size""" def __loop(x, y): return [x[0] * y, x[1] * y] return list(map(functools.partial(__loop, y=1/scale), pts))
43,519
def fit_tophat(x, y, verify=False): """ Fit the x and y data to a tophat function, returning: base_level - the y-value inside the tophat hat_level - the y-value outside the tophat hat_start - start of the tophat hat_end - end of the tophat :param x: iterable of x values :param y: corres...
43,520
def test_atomic_id_max_length_1_nistxml_sv_iv_atomic_id_max_length_2_3(mode, save_output, output_format): """ Type atomic/ID is restricted by facet maxLength with value 62. """ assert_bindings( schema="nistData/atomic/ID/Schema+Instance/NISTSchema-SV-IV-atomic-ID-maxLength-2.xsd", instan...
43,521
def check_existance(fpath): """ It must be a file. If it is a directory, it will not work. """ relv_servers = [] for server_ip in SERVER_LIST: cmd = ['ssh', server_ip, 'test', '-f', fpath] p = subprocess.Popen(cmd) _ = p.communicate() if p.returncode == 0: ...
43,522
def current_session_view(request): """ Current SEssion and Term """ if request.method == 'POST': form = CurrentSessionForm(request.POST) if form.is_valid(): session = form.cleaned_data['current_session'] term = form.cleaned_data['current_term'] AcademicSession.objects.filter(name=session)....
43,523
def post_css_transform(doc, url): """ User-customizable CSS transform. Given a CSS document (with URLs already rewritten), returns modified CSS document. """ global config if config.hack_skin and not config.special_mode: if config.skin == MONOBOOK_SKIN: doc = monobook_h...
43,524
async def get_user_ads(context, account, community=None): """List all ad posts created by account. If `community` is provided, it lists all ads submitted to that community and their state.""" db = context['db'] account_id = await get_account_id(db, account) params = {'account_id': account_id} ...
43,525
def _new_paper_email(sender, **kw): """ Send an email to the organizers with details on the paper presented. """ recipients = settings.TALK_SUBMISSION_NOTIFICATION_EMAIL if not recipients: # Nothing to do return tlk = kw['talk'] subject = '[new paper] "%s %s" - %s' % (sender....
43,526
def test_subclass_nt_to_disease(rosetta,eg): """named_thing -> Disease""" node = KNode('MONDO:0005737', type=node_types.NAMED_THING) rosetta.synonymizer.synonymize(node) assert eg.get_leaf_type(node,node_types.NAMED_THING)[0] == node_types.DISEASE
43,527
def sql_e2e_test( name, data = [], args = [], known_error_files = [], **extra_args): """Invoke a SQL end-to-end test suite against a SQL engine. Similar to cc_test, with an extra argument "known_error_files". load("//zetasql/compliance:builddefs.bzl", "sql_e2e_t...
43,528
def MDP2Trans(MDPs, J, action_in_states = False, combined = True): """ Input: a list (len-N) of trajectory [state matrix [T * 3], actions, rewards] - I need to modify evaluate.ipynb Output: a list of (s,a,s',u) (combined together) """ def MDP2Trans_one_traj(i): obs, actions, utilities = MDPs...
43,529
def get_pullrequests(creds, repository_owner, repository_name, pullrequest_state_strings, limit): """ Return list of pull request information as follows. The list is empty when no pull requests are found. Or, return None on any errors. state State of the Pull Request. number ...
43,530
def second_rmpoint_command(jenni, input): """<nick>-- - Removes 1 point to the score system for <nick>.""" nick = input.group(1) if nick: nick = nick.strip() num_of_neg = list(nick).count('-') if len(nick) == num_of_neg or nick[0] in ['-']: return nick = nick[:-2] for each i...
43,531
def main(): """ driver function """ test_cases = int(input()) while test_cases > 0: size = int(input()) numbers = list(map(int, input().strip().split(" "))) print(maximum_sum_increasing_subsequence(numbers, size)) test_cases -= 1
43,532
def remove_nuisance_word_hits(result_str): """ >>> a = '#@@@the@@@# cat #@@@in@@@# #@@@the@@@# hat #@@@is@@@# #@@@so@@@# smart' >>> remove_nuisance_word_hits(a) 'the cat in the hat is so smart' """ ret_val = rcx_remove_nuisance_words.sub("\g<word>", result_str) return ret_val
43,533
def processImages(files: List[Path]): """ Batch operates on a set of images in a multiprocess pool """ echo( style("[INFO] ", fg="green") + f"Processing (number of processes: {conf['NUM_OF_PROCESSES']})" ) echo(style("[INFO] ", fg="green") + "compiling...") with Pool(conf["N...
43,534
def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = ...
43,535
def test_inverse_add_sub_rles(df): """Testing with small integers, since small value floating points might lead to mul then div not being equal to identity function because of float equality.""" cv = Rle(df.Runs.values, df.Values.values) cv2 = Rle(np.random.permutation(df.Runs.values), df.Values2.values)...
43,536
def regression( method, x_train_cols: List[Union[str, int]], y_train_col: List[Union[str, int]], x_pred_cols: Optional[List[Union[str, int]]] = None, input_ts="-", columns=None, start_date=None, end_date=None, dropna="no", clean=False, round_index=None, skiprows=None, ...
43,537
def cache(route: str): """ Retrieves the contents of the file specified by the cache route if it exists. """ path = environ.paths.user('reader', 'cache', route) if not os.path.exists(path): return '', 204 return flask.send_file( path, mimetype=mimetypes.guess_type(pa...
43,538
def download_from_gdrive(id, destination): """ Download file from Google Drive :param str id: g-drive id :param str destination: output path :return: """ url = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(url, params={'id': id}, st...
43,539
def get_password(length: int, exclude_punctuation: bool = False) -> str: """ Return password. :param int length: password length :param bool exclude_punctuation: generate password without special chars :return: password :rtype: str """ validate_length(length) alphabet = ALPHABET_WO...
43,540
def _read_image(filepath, image_size=None): """Read an image and optionally resize it (size must be: height, width).""" cv2 = tfds.core.lazy_imports.cv2 with tf.io.gfile.GFile(filepath, 'rb') as f: image = cv2.imdecode( np.fromstring(f.read(), dtype=np.uint8), flags=cv2.IMREAD_GRAYSCALE) if image_...
43,541
def localise_overlay(over: 'Entity', origin: Vec, angles: Union[Angle, Matrix]=None) -> None: """Rotate an overlay like what is done in instances.""" if angles is not None: for key in ('basisNormal', 'basisU', 'basisV'): ang = Vec.from_str(over[key]) @ angles over[key] = ang.join...
43,542
def get_txt_version(): """Get version string from version.txt.""" try: with open("version.txt", "r") as fp: return fp.read().strip() except IOError: return None
43,543
def Main(): """Main routine. """ (opts, args) = ParseOptions() utils.SetupToolLogging(opts.debug, opts.verbose) if args: logging.error("No arguments are expected") return constants.EXIT_FAILURE if opts.full_run: logging.info("Running in full mode") getent = runtime.GetEnts() try: f...
43,544
def get_args(): """Get arguments from the command line.""" parser = argparse.ArgumentParser(description='Train ResNet-50. Fast.') parser.add_argument('--output-dir', type=str, required=True, help='Output directory') parser.add_argument('--job-id', type=str, default=None, ...
43,545
def main(): """ Parses command line arguments """ parser = optparse.OptionParser() parser.add_option("-w", "--write", action="store_true", help="Write back modified files") parser.add_option("-n", "--no-backup", action="store_false", dest="backup", help="Do not write any ba...
43,546
def clear_outliers(points: np.ndarray, confidence:np.ndarray, iterations=1, to_dump=0.05): """ clears outliers based on horizontal distance between point and regression line :param points: array of points in (x,y) form :param confidence: confidence of points corresponding to points array :param iter...
43,547
def parse(content_type): """parse the Content-Type header. """ return ( Ok(content_type) .then(lex) .then(label) .then(parse_lexeme) )
43,548
def plot_umap(file_index, lead_num): """ Plots a 2-D UMAP representation for a particular lead, patient combination :param file_index: [int] index of the file (1-indexed) :param lead_num: [int] lead number (1-indexed) :return None: """ if lead_num < 1 or lead_num > 4: sys.stderr.writ...
43,549
def test_fix_aux_factories_real_cube(real_hybrid_pressure_cube): """Test fixing of hybrid pressure coordinate on real cube.""" check_if_fix_aux_factories_is_necessary() assert not real_hybrid_pressure_cube.coords('air_pressure') _io._fix_aux_factories(real_hybrid_pressure_cube) air_pressure_coord = ...
43,550
def add_to_deployment(): """Add things to a deployment."""
43,551
def main_with_omxplayer(): """ Launch yt, using omxplayer. """ parser = argparse.ArgumentParser(prog='pi-yt') # Albert - November 23rd # Fixing broken pi-yt: Invoking the Ui passing parameters in the same way as it done from main() # parser.add_argument('--player', default=OMXPLAYER_MO...
43,552
def check_commands(no_fastqc=False, bowtie2=False): """Confirm all command line tools are installed and in PATH""" print("INFO: Verifying all tools are installed. Please wait...", file=sys.stderr) # default tools and arguments to check for cmds = [["trim_galore", "--version"], ["samtools", "--version"],...
43,553
def _getter(path): """Loads configparser config""" config = _configparser() # ok if config file does not exist config.read(path, encoding=OPEN['encoding']) # return dict(config.items()) # behaves like dict return config
43,554
def unexpected_exception_handler(request: Request, exc: Exception) -> JSONResponse: """Обработчик любых непредвиденных и необработанных ошибок""" service_code = request.app.service_code classify_exception_and_send_to_sentry(exc) error_message = "Возникла непредвиденная ошибка. Пожалуйста, обратитесь к а...
43,555
def save_expert_games(buffer, saved_games_zlib, game_ids): """ Stores a series of expert games in compressed saved game proto format :param buffer: An instance of the memory buffer. :param saved_games_zlib: List of compressed saved game proto :param game_ids: List of game ids (same length as...
43,556
def chebyshev_polynomial(X, k): # 返回一个稀疏矩阵列表 """Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices.""" print("Calculating Chebyshev polynomials up to order {}...".format(k)) T_k = list() T_k.append(sp.eye(X.shape[0]).tocsr()) # T0(X) = I T_k.append(X) # T1(X) = L~...
43,557
def printY(prt): """ Print in yellow """ print("\033[93m {}\033[00m".format(prt))
43,558
def PIsCompatable (in1, in2): """ Tells if two CArrays have compatable geometry returns True or False * in1 = first input Python CArray * in2 = second input Python CArray """ ################################################################ # Checks if not PIsA(in1): pr...
43,559
def connect_sqs( aws_access_key_id: str | None = None, aws_secret_access_key: str | None = None, **kwargs: Any ) -> AsyncSQSConnection: """Return async connection to Amazon SQS.""" from .sqs.connection import AsyncSQSConnection return AsyncSQSConnection( aws_access_key_id, aws_secret_acc...
43,560
def load_json_from_string(string): """Load schema from JSON string""" try: json_data = json.loads(string) except ValueError as e: raise ValueError('Given string is not valid JSON: {}'.format(e)) else: return json_data
43,561
def TestNodeListDrbd(node, is_drbd): """gnt-node list-drbd""" master = qa_config.GetMasterNode() result_output = GetCommandOutput(master.primary, "gnt-node list-drbd --no-header %s" % node.primary) # Meaningful to note: there is but one insta...
43,562
def advance_searches(string, pos=0, has_strikethrough=False, has_math=False): """ These tokens are special cases, because they start and end with the same character therefore, we need to re-search as we progress, to reset the opening character """ code_match = code_pattern.search(string, pos) ...
43,563
def two_sample_ttest(arr1, arr2): """Performs independent two-sample t-test between two arrays""" from scipy import stats import numpy as np # Remove nan if any arr1 = arr1[~np.isnan(arr1)] arr2 = arr2[~np.isnan(arr2)] tval, pval = stats.ttest_ind(arr1, arr2, nan_policy='omit') sig = g...
43,564
def test_enum_1h_auto(): """ Check behaviour of an auto-valued one-hot enumeration """ @packtype.enum(mode="ONEHOT") class DummyEnum: """ Test description 12345 """ KEY_A : Constant(desc="Description A") # 1 KEY_B : Constant(desc="Description B") # 2 KEY_C : Constant(desc="De...
43,565
def parse(instructions: typing.List[str]) -> Wire: """Calculate the points upon a wire and create a class from them.""" points = [Point(0, 0)] for instruction in instructions: dir = instruction[:1] dist = int(instruction[1:]) for _ in range(dist): if dir == "R": ...
43,566
def add_shortcut(storage, shortcut_serializer, query_directory, alias, filename): """ Adds a shortcut to the Report_Info File. If a shortcut already exists for an alias, it replaces that shortcut. :type storage: Storage Object. :param storage: Type of Storage System. :type shortcut_serializer: Shor...
43,567
def one_shot_gamma_alpha_matrix(k, t, U): """Assume U is a sparse matrix and only tested on one-shot experiment""" Kc = np.clip(k, 0, 1 - 1e-3) gamma = -(np.log(1 - Kc) / t) alpha = U.multiply((gamma / k)[:, None]) return gamma, alpha
43,568
def generate_device_watchdog_answer(diameter_request, origin_host, origin_realm): """ Method used with the purpose of handling DWR requests and sending DWA responses.(Device Watchdog) Builds the DWA message, the header and AVPs lis...
43,569
def apply(tree: ProcessTree, parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> EventLog: """ Generate a log by a playout operation Parameters --------------- tree Process tree parameters Parameters of the algorithm, including: - Parameters.NO_TRACES: num...
43,570
def setupPedFilter(relfilter='oo',dfile=None): """ figure out who to drop to satisfy relative filtering note single offspring only from each family id ordering of pdict keys makes this 'random' as the first one only is kept if there are multiple sibs from same familyid. """ dropId = {} keepo...
43,571
async def parse(url: str, session: ClientSession, **kwargs) -> set: """Find HREFs in the HTML of `url`.""" found = set() try: html = await fetch_html(url=url, session=session, **kwargs) except ( aiohttp.ClientError, aiohttp.http_exceptions.HttpProcessingError, ) as e: ...
43,572
def auth(options) -> bool: """Set up auth and nothing else.""" objectStore = FB_ObjectStore(options) if options.get("test", False): # If we only care if it's valid, just check and leave auth_token = objectStore.get_cached_auth_token() # Validate and return cached auth token. ...
43,573
def _parse_detector(detector): """ Check and fix detector name strings. Parameters ---------- detector : `str` The detector name to check. """ oklist = ['n0', 'n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9', 'n10', 'n11'] altlist = [str(i) for i in range(12)] ...
43,574
def mobius_area_correction_spherical(tria, mapping): """ Find an optimal Mobius transformation for reducing the area distortion of a spherical conformal parameterization using the method in [1]. Input: tria : TriaMesh (vertices, triangle) of genus-0 closed triangle mesh mapping: nv x 3 vertex c...
43,575
def publish_left_target_pose(): """ This function publishes left desired pose which the controller will subscribe to. :return: None """ left_marker_pose.header.frame_id = "base" left_marker_pose.header.stamp = rospy.Time(0) left_pose_pub.publish(left_marker_pose)
43,576
def display_logout_message(sender, **kwargs): """Inform user they've successfully logged out""" request = kwargs.get("request") success( request, "Successfully logged out", fail_silently=True, )
43,577
def test_create_driver_payload(accelerator: NpuAccelerator): """Tests npu_create_driver_payload""" # Generate a random command stream with defined beginning and end random.seed(0) num_commands = 793 register_command_stream = random.choices(range(1 << 32), k=num_commands) register_command_stream[...
43,578
def rel_ordered(x1,x2,x3,x4): """ given 4 collinear points, return true if the direction from x1->x2 is the same as x3=>x4 requires x1!=x2, and x3!=x4 """ if x1[0]!=x2[0]: i=0 # choose a coordinate which is varying else: i=1 assert x1[i]!=x2[i] assert x3[i]!=x4[i] ...
43,579
def video_agent(env, video_env, policy, video_filename, frames=500): """Saves a video of the agent in the environment. Args: env: TF Environement. video_env: Py Environement. """ time_step = env.reset() with imageio.get_writer(video_filename, fps=60) as video: video.append_d...
43,580
def _getsemaphore(semaphoreid): """ Acquire a semphore; if the ID does not exist, it is created. @param semaphoreid: Uniquely identifies the particular semaphore to acquire @return: 204 NO CONTENT if the semaphore is acquired successfully 403 FORBIDDEN if the semaphore is not available ...
43,581
def test_lidar_packet(meta: client.SensorInfo) -> None: """Test reading and writing values from empty packets.""" pf = _client.PacketFormat.from_info(meta) p = client.LidarPacket(bytes(pf.lidar_packet_size), meta) w = pf.columns_per_packet h = pf.pixels_per_column assert len( client.Cha...
43,582
def profile_sim(seed,sim_conf,fit_conf,ntrials,output_file): """ run the simulation using a profiler """ import cProfile import pstats cProfile.runctx('go(seed,sim_conf,fit_conf,ntrials,output_file)', globals(),locals(), 'profile_stats') p = psta...
43,583
def min_rl(din): """ A MIN function should "go high" when any of its inputs arrives. Thus, OR gates are all that is needed for its implementation. Input: a list of 1-bit WireVectors Output: a 1-bit WireVector """ if len(din) == 1: dout = din[0] ...
43,584
def test_empty_codeblock(mocker): """Test that empty code blocks render correctly""" mocker.patch.object(lookatme.config, "LOG") fake_config = mocker.patch.object(lookatme.render.pygments, "config") fake_config.STYLE = { "style": "monokai", } rendered = render_markdown( """ ```p...
43,585
def fetch(u, data, indices, indptr, lmbda): """ """ is_skip = 1 if lmbda > 0: u0, u1 = indptr[u], indptr[u + 1] val, ind = data[u0:u1], indices[u0:u1] if u1 > u0: is_skip = 0 else: val = np.empty(0, dtype=data.dtype) ind = np.empty(0, dtype=np.int3...
43,586
def _gcc_parse_params(gcc: Gcc) -> List[Option]: """Parse the param help string from the GCC binary to find options.""" # Pretty much identical to _gcc_parse_optimize logger.debug("Parsing GCC param space") result = gcc("--help=param", "-Q", timeout=60) out = result.split("\n")[1:] param_enum...
43,587
def test_compare_flash_no_board(mock_isfile, check_no_board_connected): """Test the compare-flash command when no board is connected.""" file_name = "random_file_name.hex" file_content = "Intel Hex lines here" mock_isfile.return_value = True runner = CliRunner() with mock.patch( "ubitto...
43,588
def _vmexclude_not_found(): """Throw exception indicating order not found.""" pecan.abort(404, u._('Not Found. Sorry but your exclude is in ' 'another castle.'))
43,589
def pgrrec(CONST_STRING, lon, lat, alt, re, f): """pgrrec(ConstSpiceChar * CONST_STRING, SpiceDouble lon, SpiceDouble lat, SpiceDouble alt, SpiceDouble re, SpiceDouble f)""" return _cspyce0.pgrrec(CONST_STRING, lon, lat, alt, re, f)
43,590
def set(isamAppliance, name, properties, attributes=None, description=None, type="JavaScript", new_name=None, check_mode=False, force=False): """ Creating or Modifying a JavaScript PIP """ ret_obj = search(isamAppliance, name=name) id = ret_obj['data'] if id == {}: # If no id wa...
43,591
def init_model(model, opt, argv): """select the network initialization method""" if hasattr(opt, 'weight_init') and opt.weight_init == 'xavier': network_weight_xavier_init(model) elif hasattr(opt, 'weight_init') and opt.weight_init == 'MSRAPrelu': network_weight_MSRAPrelu_init(model) eli...
43,592
def get_bash_commands(root_parser, root_prefix, choice_functions=None): """ Recursive subcommand parser traversal, returning lists of information on commands (formatted for output to the completions script). printing bash helper syntax. Returns: subparsers : list of subparsers for each parse...
43,593
def shoulders_up(x, y, max_angle=10): """ 1:"Neck", 2:"RShoulder", 5:"LShoulder". looks at line from left shoulder to neck, and line from right shoulder to neck if either are not straight returns 1 if both are flat (slope of 0 or close to 0) returns 1 """ left_degrees = math.degr...
43,594
def test_get_payload_data_parameter(search_api): """Tests get payload dict method for SearchAPI with parameter data""" payload = search_api.get_payload(scene_id='TEST') assert payload assert type(payload) == dict assert payload.get('scenename') == 'TEST'
43,595
def init_logging(log_config_file, log_path): """ Logging initialization. :param log_config_file: Log file name. :param log_path: Json log files path. :return: None """ if os.path.exists(log_config_file): f = open(log_config_file, 'rt') conf = json.loads(f.read()) f.c...
43,596
def str(x: i32) -> str: """ Return the string representation of an integer `x`. """ if x == 0: return '0' result: str result = '' if x < 0: result += '-' x = -x rev_result: str rev_result = '' rev_result_len: i32 rev_result_len = 0 pos_to_str: list...
43,597
def pagination_logic(returned): """Function with logic to paginate through search results Arguments required: dictionary of database query search results """ pagination_menu(returned) len_returned = len(returned) counter = 0 while counter < len_returned: pagination = input("Enter l...
43,598
def grad_spsp_mult_entries_x_reverse(b_out, entries_a, indices_a, entries_x, indices_x, N): """ Now we wish to do the gradient with respect to the X matrix in AX=B Instead of doing it all out again, we just use the previous grad function on the transpose equation X^T A^T = B^T """ # get the transp...
43,599