content
stringlengths
22
815k
id
int64
0
4.91M
def validators(*chained_validators): """ Creates a validator chain from several validator functions. :param chained_validators: :type chained_validators: :return: :rtype: """ def validator_chain(match): # pylint:disable=missing-docstring for chained_validator in chained_valida...
35,100
def jacobian(vf): """Compute the jacobian of a vectorfield pointwise.""" vf0_dz, vf0_dy, vf0_dx = image_gradients(vf[..., 0:1]) vf1_dz, vf1_dy, vf1_dx = image_gradients(vf[..., 1:2]) vf2_dz, vf2_dy, vf2_dx = image_gradients(vf[..., 2:3]) r1 = tf.concat([vf0_dz[..., None], vf0_dy[..., None], vf0_dx[...
35,101
def insert_ones(y, segment_end_ms, Ty, steps=50, background_len=10000.0): """Update the label vector y The labels of the output steps strictly after the end of the segment should be set to 1. By strictly we mean that the label of segment_end_y should be 0 while, the 50 followinf labels should be ones. ...
35,102
def stream_name_mapping(stream, exclude_params=['name'], reverse=False): """ Return a complete dictionary mapping between stream parameter names to their applicable renames, excluding parameters listed in exclude_params. If reverse is True, the mapping is from the renamed strings to the origina...
35,103
def newton(f, df, x0, tolx, tolf, nmax): """ Algoritmo di Newton per il calcolo dello zero di una funzione. :param f: la funzione di cui calcolare lo zero :param df: la derivata della funzione di cui calcolare lo zero :param x0: il valore di innesco :param tolx: la tolleranza sull'incremento ...
35,104
def preprocess(x, scale='std', clahe=True): """ Preprocess the input features. Args: x: batch of input images clahe: perform a contrast limited histogram equalization before scaling scale: 'normalize' the data into a range of 0 and 1 or 'stan...
35,105
def process_commands(operators, log_level, log_file, mip, dry_run): """This result callback is invoked with an iterable of all the chained subcommands. As in this example each subcommand returns a function we can chain them together to feed one into the other, similar to how a pipe on unix works. ...
35,106
def endswith(s, tags): """除了模拟str.endswith方法,输入的tag也可以是可迭代对象 >>> endswith('a.dvi', ('.log', '.aux', '.dvi', 'busy')) True """ if isinstance(tags, str): return s.endswith(tags) elif isinstance(tags, (list, tuple)): for t in tags: if s.endswith(t): retu...
35,107
def parse(data): """ Takes the byte string of an x509 certificate and returns a dict containing the info in the cert :param data: The certificate byte string :return: A dict with the following keys: - version """ structure = load(data) if structure[0][0] != Se...
35,108
def to_auto_diff(x): """ Transforms x into a automatically differentiated function (ADF), unless it is already an ADF (or a subclass of it), in which case x is returned unchanged. Raises an exception unless 'x' belongs to some specific classes of objects that are known not to depend on ...
35,109
def voc_eval(class_recs: dict, detect: dict, iou_thresh: float = 0.5, use_07_metric: bool = False): """ recall, precision, ap = voc_eval(class_recs, detection, [iou_thresh], [use_07_metric]) Top level fun...
35,110
def data_upgrades(): """Add any optional data upgrade migrations here!""" query =''' INSERT INTO public."ModuleGrids"( "ID","Module_ID", "TypeObj", "Name", "Label", "GridRender", "GridSize", "CellType", "GridOrder", "QueryName", "Options", "FilterOrder", "FilterSize", "IsSearchable", "FilterDefaultValue", ...
35,111
def birth() -> character.Character: """Gives birth to krydort.""" krydort = character.Character('Krydort Wolverry') krydort.attributes.INT = 8 krydort.attributes.REF = 6 krydort.attributes.DEX = 6 krydort.attributes.BODY = 6 krydort.attributes.SPD = 4 krydort.attributes.EMP = 10 ...
35,112
def imagePath(image): """ Return full path to given image. """ return os.path.join(":/images", image)
35,113
def compress(from_name: str, to_name: Optional[str]=None, remove_original: bool=False) -> None: """ Compress the file `from_name` and store it as `to_name`. `to_name` defaults to `from_name` with `.bz2` appended. If `remove_original` is True, removes `from_name` when the compress finishes. """ i...
35,114
def LinearCombinationOfContVars(doc:NexDoc, resultName, contVar1:NexVar, coeff1, contVar2:NexVar, coeff2): """Calculates a linear combination of two continuous variables.""" return NexRun("LinearCombinationOfContVars", locals())
35,115
def main(): """Main function""" config = get_config() reddit = init_reddit(config) subreddit = config['reddit']['subreddit'] arg = argparse.ArgumentParser() arg.add_argument("--clock", help="set sidebar with the current time (utc)", action="store_true") arg.add_argument(...
35,116
def handler404(request, exception): # pylint: disable=unused-argument """404: NOT FOUND ERROR handler""" response = render_to_string( "404.html", request=request, context=get_base_context(request) ) return HttpResponseNotFound(response)
35,117
def get_notification_user(operations_shift): """ Shift > Site > Project > Reports to """ if operations_shift.supervisor: supervisor = get_employee_user_id(operations_shift.supervisor) if supervisor != doc.owner: return supervisor operations_site = frappe.get_doc("Operations Site", oper...
35,118
def list_groups( namespace: str = "default", account_id: Optional[str] = None, boto3_session: Optional[boto3.Session] = None ) -> List[Dict[str, Any]]: """List all QuickSight Groups. Parameters ---------- namespace : str The namespace. Currently, you should set this to default . account...
35,119
def find_tm5_output(path, expname=None, varname=None, freq=None): """ Finds TM5 outputfiles, which consist of varname + "_" + "AER"[freq] + * + dates + ".nc" inputs: Path (mandatory) experiment name (optional) varname (optional) frequency (optional) output: list of full paths to file...
35,120
def big_diagram(BFIELD=1000,output='S0'): """ Main code to plot 'big' diagram with the following components: - Theoretical absorption spectrum (top panel) - Breit Rabi diagram for 0 to specified B-field (left) - Energy levels for ground and excited states (bottom panel) - Arrows for each transition, undernea...
35,121
def _add_subject(subject_list: List[t_subject], subject: t_subject) -> None: """Add one Subject to the list.""" value = Subject(uuid_ref=subject['uuid-ref'], type=subject['type']) if 'title' in subject: value.title = subject['title'] if 'properties' in subject: props = [] propert...
35,122
def referenced_fmr(X=None, Y=None, Z=None, delta_x_idx:{"type": "int", "min":0, "max": 1, "hint": "Distance of the background signal (in x-index units)"}=0,): """ For each X-index, calculate Z[X]-X([+delta_x_idx], X will be set to X[X] ...
35,123
def categorize_dish(dish_name, dish_ingredients): """ :param dish_name: str :param dish_ingredients: list :return: str "dish name: CATEGORY" This function should return a string with the `dish name: <CATEGORY>` (which meal category the dish belongs to). All dishes will "fit" into one of the ca...
35,124
def read_text_subset( subset: str, source_dir: str = "data/CUB_200_2011_with_text/text" ) -> Tuple[List[str], List[int], List]: """ Read the pretrained embedding caption text for the birds and flowers datasets as encoded using a pretrained char-CNN-RNN network from: https://arxiv.org/abs/1605.05...
35,125
def generate_points_realistic(N=100, distortion_param=0, rng=None): """Generates two poses and the corresponding scene points and image points.""" # Check if a seed is used (for unittests) if not rng: rng = np.random.default_rng() # Relative translation t = 2 * rng.random((3, 1)) - 1 #...
35,126
def truncated_step( x: array, f_x: float, grad: array, step_size: float = 0.1, search_direction: Optional[array] = None, step_lower_bound: float = 0.0, ): """Motivated by https://arxiv.org/abs/1903.08619 , use knowledge of a lower-bound on f_x to prevent from taking a step too large ...
35,127
def test_single_feature_label(): """ >>> allure_report = getfixture('allure_report') >>> assert_that(allure_report, ... has_test_case('test_single_feature_label', ... has_feature('single feature') ... )) """ pass
35,128
def search_covid_results(patient_id: str, covid_df: pd.DataFrame): """ Given a patient ID and a dataframe of COVID-19 PCR results, return whether a patient had a positive result at any point and the date of their first positive. If no positives but negative results exist, return...
35,129
def is_slow_test_hostile(): """Use this to disable some tests in CI enviroment where 15 minute deadline applies.""" return "CI" in os.environ or "SKIP_SLOW_TEST" in os.environ
35,130
def str_is_path(p: str): """Detects if the variable contains absolute paths. If so, we distinguish paths that exist and paths that are images. Args: p: the Path Returns: True is is an absolute path """ try: path = Path(p) if path.is_absolute(): return Tr...
35,131
def run_tests(requested_test_classes, serial, config): """Actually run the test suites, potentially in parallel.""" root_tmpdir = tempfile.mkdtemp(prefix='faucet-tests-') ports_sock = os.path.join(root_tmpdir, 'ports-server') ports_server = threading.Thread( target=faucet_mininet_test_util.serve...
35,132
def PLAY(command: Command) -> Command: """ Moves clip from background to foreground and starts playing it. If a transition (see LOADBG) is prepared, it will be executed. """ return command
35,133
def deserialize(data: str) -> dict: """ Given a string, deserialize it from JSON. """ if data is None: return {} def fix(jd: Any) -> Any: if type(jd) == dict: # Fix each element in the dictionary. for key in jd: jd[key] = fix(jd[key]) ...
35,134
def seq_windows_df( df, target=None, start_index=0, end_index=None, history_size=1, target_size=1, step=1, single_step=False, ): """ create sliding window tuples for training nns on multivar timeseries """ data = [] labels = [] start_index = start_index + history_...
35,135
def get_cachable_provider( cachables: List[Cachable] = [Collection1(), Collection2()] ) -> Callable[[], List[Cachable]]: """ Returns a cachable_provider. """ return lambda: cachables
35,136
def getQuality(component, propertyName): # type: (JComponent, String) -> int """Returns the data quality for the property of the given component as an integer. This function can be used to check the quality of a Tag binding on a component in the middle of the script so that alternative actions ...
35,137
def init(): """Initialize a directory with tasks.""" if os.path.isdir('tasks'): print('Directory "tasks" already exists!') sys.exit(0) os.mkdir('tasks') os.chdir('tasks') templates_dir = os.path.join( os.path.dirname(inspect.getfile(mlpractice)), 'templates', ) ...
35,138
def norm1(x): """Normalize to the unit sphere.""" return x / x.square().sum(axis=-1, keepdims=True).sqrt()
35,139
def set_each_question_path(config: DictConfig): """ qstを読み取るのめんどくさい """ # hedファイルを全体で指定しているか、各モデルで設定しているかを判定する for typ in ('timelag', 'duration', 'acoustic'): if config[typ].question_path is None: config[typ].question_path = config.question_path else: config[t...
35,140
def markup_sentence(s, modifiers, targets, prune_inactive=True): """ Function which executes all markup steps at once """ markup = pyConText.ConTextMarkup() markup.setRawText(s) markup.cleanText() markup.markItems(modifiers, mode="modifier") markup.markItems(targets, mode="target") marku...
35,141
def get_stream_info(stream_id): """ Uses the `/stream/info` endpoint taking the stream_id as a parameter. e.g. stream_id="e83a515e-fe69-4b19-afba-20f30d56b719" """ endpoint = KICKFLIP_API_URL + '/stream/info/' payload = {'stream_id': stream_id} response = kickflip_session.post(endpoint, p...
35,142
def invchisquared_sample(df, scale, size): """Return `size` samples from the inverse-chi-squared distribution.""" # Parametrize inverse-gamma alpha = df/2 beta = df*scale/2. # Parametrize gamma k = alpha theta = 1./beta gamma_samples = np.random.gamma(k, theta, size) return 1./g...
35,143
def get_data_from_matlab(file_url, index, columns, data): """Description:* This function takes a Matlab file .mat and extract some information to a pandas data frame. The structure of the mat file must be known, as the loadmat function used returns a dictionary of arrays and they must be call...
35,144
def get_loop_end(header: bytes) -> int: """Return loop end position.""" assert isinstance(value := _unpack(header, "LOOP_END"), int), type(value) assert 0 < value < 65535, value return value
35,145
def report(filename: str, ignore_result: tuple, hide_empty_groups:bool): """{p}arse a report and do a simple output""" if not os.path.exists(filename): logger.error("Failed to find file {}, bailing", filename) return False if ignore_result: print(f"Ignoring the following result valu...
35,146
def test_no_subfield(add_citation): """ When no institution is linked, return None. """ citation = add_citation() assert citation.subfield == None
35,147
def measuresegment(waveform, Naverage, minstrhandle, read_ch, mV_range=2000, process=True, device_parameters=None): """Wrapper to identify measurement instrument and run appropriate acquisition function. Supported instruments: m4i digitizer, ZI UHF-LI Args: waveform (dict): waveform specification ...
35,148
def user_list(ks_cli): """Print a list of all users, Requires ADMIN Credentials.""" users = ks_cli.users.list() # print_structure(users.data[0],geta=False) for i in users.data: print(i.id, i.name, i.enabled) return
35,149
def grid_definition_proj(): """Custom grid definition using a proj string.""" return { "shape": (1, 1), "bounds": (-4000000.0, -4000000.0, 4000000.0, 4000000.0), "is_global": False, "proj": example_proj, }
35,150
def _compare_lines(line1, line2, tol=1e-14): """ Parameters ---------- line1: list of str line2: list of str Returns ------- bool """ if len(line1) != len(line2): return False for i, a in enumerate(line1): b = line2[i] if type(a) not in {int, float...
35,151
def helping_func(self, driver, value): """Helper function for testing method composition. """ return value + 1
35,152
def ffmpeg_video_write(data, video_path, fps=25): """Video writer based on FFMPEG. Args: data: A `np.array` with the shape of [seq_len, height, width, 3] video_path: A video file. fps: Use specific fps for video writing. (optional) """ assert len(data.shape) == 4, f'input shape is not valid! Got {d...
35,153
def add_languages_modify(schema, fields, locales=None): """Adds localized field keys to the given schema""" if locales is None: locales = get_locales() ignore_missing = toolkit.get_validator('ignore_missing') convert_to_extras = toolkit.get_converter('convert_to_extras') for locale in locale...
35,154
def package_tests(zip_file, robotium_cfg_file, test_apk, skp_dir=None, resource_dir=None): """Package all tests into a zip file.""" sdcard_files = [] with zipfile.ZipFile(zip_file, 'w') as zip_file: zip_file.write(test_apk, os.path.basename(test_apk), zipfile.ZIP_DEFLATED) if skp_dir: ...
35,155
def apply_temporary_fixes(font, is_for_cros=False, is_for_web=False): """Apply some temporary fixes.""" # Fix usWeight: font_name = font_data.font_name(font) weight = noto_fonts.parse_weight(font_name) weight_number = noto_fonts.WEIGHTS[weight] # Chrome OS wants Thin to have usWeightClass=100 ...
35,156
def from_iterable( iterable: tp.Union[tp.Iterable[T], pypeln_utils.Undefined] = pypeln_utils.UNDEFINED, use_thread: bool = True, ) -> tp.Union[Stage[T], pypeln_utils.Partial[Stage[T]]]: """ Creates a stage from an iterable. Arguments: iterable: A source Iterable. use_thread: If set ...
35,157
def get_consumer_secret(): """This is entirely questionable. See settings.py""" consumer_secret = None try: loc = "%s/consumer_secret.txt" % settings.TWITTER_CONSUMER_URL url = urllib2.urlopen(loc) consumer_secret = url.read().rstrip() exc...
35,158
def thread_keep_storing_one_File(syn, project, schedule_for_cleanup): """Makes one file and stores it over and over again.""" # Make a local file to continuously store path = utils.make_bogus_data_file() schedule_for_cleanup(path) myPrecious = File(path, parent=project, description='This bogus file...
35,159
def preprocess(src, cutoff, shape=(240, 240)): """Pre-processes the image""" # Resizing the image, for computational reasons, else the algorithm will take too much time dst = cv2.resize(src, shape) # (automated) Canny Edge Detection dst = aced.detect(dst) # Binary or Adaptive thresholding ds...
35,160
def test_main(): """ call the main :return: """ visitor.main()
35,161
def is_aware(value): """ Determines if a given datetime.datetime is aware. The concept is defined in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. ...
35,162
def check_manifest(of: fsspec.core.OpenFile, manifest: str) -> bool: """ Check to see if a given string exists in a manifest file. Parameters ========== x: str The string to check. manifest: str The path to a manifest file. Returns ======= True if the file is *not...
35,163
def loadExpObjectFast(filename): """loads a CiPdeN object from a JSON file irnores generation data, expect the first and the last Parameters ---------- filename : str includes path and filename Returns ------- dict returns a dict if it worked, else retu...
35,164
def makeLoc(*args): """This function creates locators based on the number specified by the user""" # We query the number of arms given by the user start.armsValue = cmds.intSliderGrp(start.numArms, q=True, v=True) # We iterate over this number for i in range(1, start.armsValue+2): # ...
35,165
def Vij_beam_correct(j, Vij, centre=None): """Corrects Vij for the beam amplitude. This is required when beam correction has not been done during calibration. Assumes identical beam patterns. Assumes calibrator source is at centre of image""" my_shape = Vij[0, 0, :, :].shape if centre is None: ...
35,166
def set_colorize(value: bool) -> None: """Globally turn colored terminal output on/off""" global _COLOR _COLOR = value
35,167
def _calc_sc_1ph(net, bus): """ calculation method for single phase to ground short-circuit currents """ _add_auxiliary_elements(net) # pos. seq bus impedance ppc, ppci = _pd2ppc(net) _calc_ybus(ppci) # zero seq bus impedance ppc_0, ppci_0 = _pd2ppc_zero(net) _calc_yb...
35,168
def get_data(github, selected_repos): """Generate json form custom-cards org.""" org = "custom-cards" data = {} repos = [] if selected_repos: repos.append(selected_repos) else: for repo in list(github.get_user(org).get_repos()): repos.append(repo.name) for repo in...
35,169
def provider_pre_delete(sender, instance, **kwargs): """Forward signal to ChangeBuilder""" from supervisr.core.providers.multiplexer import ProviderMultiplexer from supervisr.core.providers.objects import ProviderAction from supervisr.core.models import ProviderTriggerMixin if issubclass(instance._...
35,170
def test_convert(pending_info, expected): """ Test conversion from the minimum version supported to the last version supported. """ convert(pending_info) diff = DeepDiff(pending_info, expected) assert ( not diff ), "diff found between converted pending_info and expected pending_info"
35,171
def fensemble_boosting_regressor(preds_valid, targs_valid, preds_train, targs_train, alpha=0.9): """ Learn combination of ensemble members from training data using Gradient Boosting Regression Also provides prediction intervals (using quantile regression) alpha = % prediction interval https://sciki...
35,172
def setup_land_units(srank): """ Sets up our land forces for an effective social rank. We go through an populate a dictionary of constants that represent the IDs of unit types and their quantities. That dict is then returned to setup_units for setting the base size of our navy. Args: ...
35,173
def one_hot_encode_test(test, txt_indexes_test): """Return the test dataframe with label-encoded textual features. Keyword arguments: test -- the test dataframe txt_indexes_test -- ndarray of test textual column indexes """ test_dummies = pd.get_dummies(test.iloc[:, txt_indexes_test]) test.drop(test.sele...
35,174
def get_with_label(label, tree): """ Get a tree's node given it's label """ return [n for n in tree.children if n.label == label][0]
35,175
def plot_image_retrieval(query_image, query_image_class, query_dataset, queried_dataset, top_distances, top_indices): """Prints and plots the results of a retrieval query, showing the query image and the top results and distances. Args: query_image: tensor with the original image pixels. query_imag...
35,176
def test_convertcolor_pipeline(plot=False): """ Test ConvertColor of transforms """ logger.info("test_convertcolor_pipeline") convert_color(mode.ConvertMode.COLOR_BGR2GRAY, cv2.COLOR_BGR2GRAY, plot) convert_color(mode.ConvertMode.COLOR_BGR2RGB, cv2.COLOR_BGR2RGB, plot) convert_color(mode.Con...
35,177
def test_text_dataframe_csv(): """ Tests if the songs are written into the dataframe, if omitted clauses still exists or not, if .csv is created """ namelist = ['eric-clapton'] loc = os.getcwd() df_ = text_dataframe_csv(namelist, loc) str_unf = df_[df_['eric-clapton'].str.contains("Unfortun...
35,178
def load_state_dicts(checkpoint_file, map_location=None, **kwargs): """ Load torch items from saved state_dictionaries """ if map_location is None: checkpoint = torch.load(checkpoint_file) else: checkpoint = torch.load(checkpoint_file, map_location=map_location) for key, value in kw...
35,179
def build_transform_gen(cfg, is_train): """ Create a list of :class:`TransformGen` from config. Now it includes resizing and flipping. Returns: list[TransformGen] """ if is_train: min_size = cfg.INPUT.MIN_SIZE_TRAIN max_size = cfg.INPUT.MAX_SIZE_TRAIN sample_styl...
35,180
def initialize_uninitialized_variables(session, var_list=None): """Initializes all uninitialized variables. Parameters ---------- session: tf.Session The TensorFlow session to scan for uninitialized variables var_list: list(tf.Varaible) or None The list of variables to filter for uni...
35,181
def test_atomic_g_year_month_min_inclusive_1_nistxml_sv_iv_atomic_g_year_month_min_inclusive_2_3(mode, save_output, output_format): """ Type atomic/gYearMonth is restricted by facet minInclusive with value 2012-02. """ assert_bindings( schema="nistData/atomic/gYearMonth/Schema+Instance/NISTS...
35,182
def rain_specific_attenuation(R, f, el, tau): """Compute the specific attenuation γ_R (dB/km) given the rainfall rate. A method to compute the specific attenuation γ_R (dB/km) from rain. The value is obtained from the rainfall rate R (mm/h) using a power law relationship. .. math:: \\gamma...
35,183
def filter(dg, start=None, end=None, tasks=(), skip_with=states.SKIPPED.name): """Filters a graph TODO(dshulyak) skip_with should also support NOOP, which will instead of blocking task, and its successors, should mark task as visited :param skip_with: SKIPPED or NOOP """ error_msgs = [] su...
35,184
def parse_input(usr_input): """Main logic of program""" usr_input = usr_input.strip() if usr_input.upper() == QUIT_KEY: #exit logic return False else: usr_input = usr_input.split() if len(usr_input) == 1: #if only one argument supplied default to weekly ...
35,185
def plot_feature_importances(clf, title='Feature Importance', feature_names=None, max_num_features=20, order='descending', x_tick_rotation=0, ax=None, figsize=None, title_fontsize="large", text_fontsize="...
35,186
def license(soup): """ Find the license text """ license = None try: license_section = get_license_section(soup) license = extract_node_text(license_section[0], "license-p") except(IndexError): return None return license
35,187
def filter_nofix(df,NoFrames): """ Filter for immobilized origami with DNA-PAINT based tracking handle (TH) as described in `spt`_. Positives are groups - with a trajectory within the first 5 frames after the start of the measurement - and number localizations within group are greater...
35,188
def read_array(cls, start=None,end=None,weight=None,use_datetime = False, convert_delta = False): """ Read arrays of values for start, end and weight values that represent either the cummulative value of the data steps or the direct step values seperately, indexed by the start and possibly end arrays. ...
35,189
def store_nugget_nodes(gold_nuggets, sys_nuggets, m_mapping): """ Store nuggets as nodes. :param gold_nuggets: :param sys_nuggets: :param m_mapping: :return: """ # Stores time ML nodes that actually exists in gold standard and system. gold_nodes = [] sys_nodes = [] # Store t...
35,190
def return_union_item(item): """union of statements, next statement""" return " __result.update({0})".format(item)
35,191
def normalize_basename(s, force_lowercase=True, maxlen=255): """Replaces some characters from s with a translation table: trans_table = {" ": "_", "/": "_slash_", "\\": "_backslash_", "?": "_question_", "%": "_percent_", ...
35,192
def download_from_url(url, dst): """ kindly used from https://gist.github.com/wy193777/0e2a4932e81afc6aa4c8f7a2984f34e2 @param: url to download file @param: dst place to put the file """ file_size = int(requests.head(url).headers["Content-Length"]) if os.path.exists(dst): first_byte ...
35,193
def _get_toc_string_from_log(file_handle): """ Returns a toc string or None for a given log file (EAC or XLD) Copyright (c) 2018 Konstantin Mochalov Released under the MIT License Original source: https://gist.github.com/kolen/765526 """ def _filter_toc_entries(file_handle): """ ...
35,194
def _matrix_M_entry(row, col): """Returns one entry for the matrix that maps alpha to theta. See Eq. (3) in `Möttönen et al. (2004) <https://arxiv.org/pdf/quant-ph/0407010.pdf>`_. Args: row (int): one-based row number col (int): one-based column number Returns: (float): transf...
35,195
def get_environment_variable_names(): """Helper to return names of environment variables queried. Returns: tuple: name of environment variable to control log level, name of environment variable to control logging to file """ __log_file_environment_variable_name = mwi_env.get_env...
35,196
def examine_vmx(dsname): """ function to download any vmx file passed to it via the datastore browser and find the 'vc.uuid' and 'displayName' """ args = get_args() try: for file_vmx in VMX_PATH: # print(file_vmx) username = args.user password = args....
35,197
def get_device_total_memory(index=0): """ Return total memory of CUDA device with index """ pynvml.nvmlInit() return pynvml.nvmlDeviceGetMemoryInfo( pynvml.nvmlDeviceGetHandleByIndex(index) ).total
35,198
def repeat_elements(x, rep, axis): """Repeats the elements of a tensor along an axis, like `np.repeat`. If `x` has shape `(s1, s2, s3)` and `axis` is `1`, the output will have shape `(s1, s2 * rep, s3)`. # Arguments x: Tensor or variable. rep: Python integer, number of times to repeat....
35,199