content
stringlengths
22
815k
id
int64
0
4.91M
def make_rst_sample_table(data): """Format sample table""" if data is None: return "" else: tab_tt = tt.Texttable() tab_tt.set_precision(2) tab_tt.add_rows(data) return tab_tt.draw()
37,700
def execute_unarchive(ext, temp_download_file, temp_download_repo): """ un-archives file using unzip or tar to the temp_download_repo :param str ext: extension used to determine type of compression :param str temp_download_file: the file path to be unarchived :param str temp_download_repo: where th...
37,701
def is_thunk(space, w_obj): """Check if an object is a thunk that has not been computed yet.""" while 1: w_alias = w_obj.w_thunkalias if w_alias is None: return space.w_False if w_alias is w_NOT_COMPUTED_THUNK: return space.w_True w_obj = w_alias
37,702
def plot_roc_curve( fpr, tpr, roc_auc=None, ax=None, figsize=None, style="seaborn-ticks", **kwargs, ): """Plots a receiver operating characteristic (ROC) curve. Args: fpr: an array of false postive rates tpr: an array of true postive rates roc_auc (None): the...
37,703
def test_linked_list_iter(): """Tests linked list iteration.""" list = LinkedList() # Fill list with subsequent numbers for i in range(0, 100): list.append(i) # Iterate through list i = 0 for item in list: # Assert i is equivalent to the item assert i == item.data ...
37,704
def Canny(image, threshold1, threshold2, edges=None, apertureSize=None, L2gradient=None): """ Canny(image, threshold1, threshold2[, edges[, apertureSize[, L2gradient]]]) -> edges or Canny(dx, dy, threshold1, threshold2[, edges[, L2gradient]]) -> edges """ pass
37,705
def my_place_or_yours(our_address: Address, partner_address: Address) -> Address: """Convention to compare two addresses. Compares lexicographical order and returns the preceding address """ if our_address == partner_address: raise ValueError("Addresses to compare must differ") sorted_addresses...
37,706
def get_dataset_json(met, version): """Generated HySDS dataset JSON from met JSON.""" return { "version": version, "label": met['data_product_name'], "starttime": met['sensingStart'], }
37,707
def hlmoft_SEOB_dict(P,Lmax=2): """ Generate the TD h_lm -2-spin-weighted spherical harmonic modes of a GW with parameters P. Returns a dictionary of modes. Just for SEOBNRv2 SEOBNRv1, and EOBNRv2. Uses aligned-spin trick to get (2,2) and (2,-2) modes. A hack. Works for any aligned-spin time-do...
37,708
def test_multiple_sorted(): """Test multiple items with the output sorted.""" arg = '"red bull" pizza doughnuts cigarettes' out = getoutput(f'{file} {arg} --sorted') expected = 'You are going to buy cigarettes, doughnuts, pizza, and red bull.' assert out.strip() == expected
37,709
def encode(value): """ pyg_mongo.encoder is similar to pyg_base.encoder with the only exception being that bson.objectid.ObjectId used by mongodb to generate the document _id, are not encoded Parameters ---------- value : value/document to be encoded Returns ------- encoded value/docum...
37,710
def _generate_trace(seconds, throughput): """Generate a <throughput>Mbps trace that lasts for the specified seconds.""" debug_print("Creating " + str(seconds) + " sec trace @: " + str(throughput) + "Mbps") bits_per_packet = 12000 low_avg = int((throughput) / (bits_per_packet / 1000)) ...
37,711
def locate_line_segments(isolated_edges): """ Extracts line segments from observed lane edges using Hough Line Transformations :param isolated_edges: Lane edges returned from isolated_lane_edges() :return: Line segments extracted by HoughLinesP() """ rho = 1 theta = np.pi / 180 t...
37,712
def up_cmd(clean: bool, force_recreate: bool, initialize_buckets: bool, other_service_sets: List[str]): """Start up common services""" if clean: down(clean=clean) up(force_recreate=force_recreate, other_service_sets=other_service_sets) if initialize_buckets: run_sup_compose_commands(['cm...
37,713
def proj(A, B): """Returns the projection of A onto the hyper-plane defined by B""" return A - (A * B).sum() * B / (B ** 2).sum()
37,714
def v6_multimax(iterable): """Return a list of all maximum values. Bonus 2: Make the function works with lazy iterables. Our current solutions fail this requirement because they loop through our iterable twice and generators can only be looped over one time only. We could keep track of the maximu...
37,715
def test_rolling_forecast_with_refitting(caplog): """Also rolling forecasting, but with re-fitting the model in between. We'll test if the expected number of re-fittings happened. Also, the model we end up with should not be the one we started with.""" caplog.set_level(logging.DEBUG, logger="timetomodel...
37,716
def format_traceback_string(exception): """Format exception traceback as a single string. Args: exception: Exception object. Returns: Full exception traceback as a string. """ return '\n'.join( traceback.TracebackException.from_exception(exception).format() )
37,717
def get_stored_file(file_id): """Get the "stored file" or the summary about the file.""" return JsonResponse(StoredFile.objects(id=ObjectId(file_id)).first())
37,718
def _compute_array_job_index(): # type () -> int """ Computes the absolute index of the current array job. This is determined by summing the compute-environment-specific environment variable and the offset (if one's set). The offset will be set and used when the user request that the job runs in a n...
37,719
def make_transpose(transpose_name, input_name, input_type, perm): """Makes a transpose node. Args: transpose_name: name of the transpose op. input_name: name of the op to be the tranpose op's input. input_type: type of the input node. perm: permutation array, e.g. [0, 2, 3, 1] for NCHW ...
37,720
def is_batch_norm(layer): """ Return True if `layer` is a batch normalisation layer """ classname = layer.__class__.__name__ return classname.find('BatchNorm') != -1
37,721
def main(): """ Uploads albums from 'd:picsHres' and takes following parameters -a <array of album names> -p <array of album paths> -t <a tree folder with all the album paths """ if len(sys.argv) < 3: logging.critical(f"Too few arguments. Please see help") retur...
37,722
def predictive_entropy(y_input, y_target): """ Computes the entropy of predictions by the model :param y_input: Tensor [N, samples, class] :param y_target: Tensor [N] Not used here. :return: mean entropy over all examples """ y_input = torch.exp(y_input) # model output is log_softmax so we ...
37,723
def exec_cmd(cmd_args, *args, **kw): """ Execute a shell call using Subprocess. All additional `*args` and `**kwargs` are passed directly to subprocess.Popen. See `Subprocess <http://docs.python.org/library/subprocess.html>`_ for more information on the features of `Popen()`. :param cmd_args:...
37,724
def roundTime(dt=None, roundTo=1): """Round a datetime object to any time period (in seconds) dt : datetime.datetime object, default now. roundTo : Closest number of seconds to round to, default 1 second. Author: Thierry Husson 2012 - Use it as you want but don't blame me. http://stackoverflow.com/q...
37,725
def compute_interval_scores(valid_time_scores_dict, test_time_scores_dict, save_time_results=None, method='greedy-coalescing'): """ Takes input time scores stored in test_pickle and valid_pickle (for test and valid KBs respectively) Using these time scores, depending on method it...
37,726
def get_imagery_layers(url): """ Get the list of available image layers that can be used as background or foreground based on the URL to a WTML (WorldWide Telescope image collection file). Parameters ---------- url : `str` The URL of the image collection. """ available_laye...
37,727
def _typecheck(op1, op2): """Check the type of parameters used and return correct enum type.""" if isinstance(op1, CipherText) and isinstance(op2, CipherText): return ParamTypes.CTCT elif isinstance(op1, PlainText) and isinstance(op2, PlainText): return ParamTypes.PTPT elif isinstance(op...
37,728
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None): """ inqueue: 用于分发存储内部结构化的任务 inqueue = Pool._inqueue = SimpleQueue() outqueue: 用于分发存储任务的执行结果 outqueue = Pool._outqueue = SimpleQueue() initializer: 启动每个 worker 进程后执行的函数 initializer = Pool._initializer = initializer initargs:...
37,729
def vm_update_cb(result, task_id, vm_uuid=None, new_node_uuid=None): """ A callback function for api.vm.base.views.vm_manage. """ vm = Vm.objects.select_related('dc').get(uuid=vm_uuid) _vm_update_cb_done(result, task_id, vm) msg = result.get('message', '') force = result['meta']['apiview']['...
37,730
def _class_effective_mesh_size( geo_graph: geograph.GeoGraph, class_value: Union[int, str] ) -> Metric: """ Return effective mesh size of given class. Definition taken from: https://pylandstats.readthedocs.io/en/latest/landscape.html """ class_areas = geo_graph.df["geometry"][ g...
37,731
def noam_schedule(step, warmup_step=4000): """ original Transformer schedule""" if step <= warmup_step: return step / warmup_step return (warmup_step ** 0.5) * (step ** -0.5)
37,732
def setup_app_logging(config: Config) -> None: """Prepare custom logging for our application.""" _disable_irrelevant_loggers() root = logging.getLogger() root.setLevel(config.LOGGING_LEVEL) root.addHandler(get_console_handler()) root.propagate = False
37,733
def _write_metadata(results: SingleLanePerSampleSingleEndFastqDirFmt): """Writes the metadata for the output qza as phred-offset33 Args: results (SingleLanePerSampleSingleEndFastqDirFmt): The SingleLanePerSampleSingleEndFastqDirFmt type of the output. """ metadata = YamlFormat() m...
37,734
def getoldiddfile(versionid): """find the IDD file of the E+ installation E+ version 7 and earlier have the idd in /EnergyPlus-7-2-0/bin/Energy+.idd """ vlist = versionid.split('.') if len(vlist) == 1: vlist = vlist + ['0', '0'] elif len(vlist) == 2: vlist = vlist + ['0'] ver...
37,735
def word_list_to_long(val_list, big_endian=True): """Word list (16 bits int) to long list (32 bits int) By default word_list_to_long() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 16 bits int value :type val_list: list :...
37,736
def _show_problems_info(id_tournament: int) -> List: """ Функция возвращает информацию о задачах турнира по его id(id_tournament) """ return loop.run_until_complete(get_request(f'https://codeforces.com/api/contest.standings?contestId=1477&from=1&count=5&showUnofficial=true'))['problems']
37,737
def make_shell_context() -> Dict[str, Any]: """Make objects available during shell""" return { "db": db, "api": api, "Playlist": Playlist, "User": User, "BlacklistToken": BlacklistToken, }
37,738
async def find_user_by_cards(app, cards, fields=["username"]): """Find a user by a list of cards assigned to them. Parameters ---------- app : aiohttp.web.Application The aiohttp application instance cards : list The list of cards to search for fields : list, default=["username"...
37,739
def print_help(): """ Print the help of the tool :return: """ ctx = click.get_current_context() click.echo(ctx.get_help()) ctx.exit()
37,740
def _calc_y_from_dataframe(trafo_df, baseR): """ Calculate the subsceptance y from the transformer dataframe. INPUT: **trafo** (Dataframe) - The dataframe in net.trafo which contains transformer calculation values. RETURN: **subsceptance** (1d array, np.complex128) - The subs...
37,741
def test_creation(): """Test that a TorchBox is automatically created from a torch tensor""" x = torch.tensor([0.1, 0.2, 0.3]) res = qml.proc.TensorBox(x) assert isinstance(res, TorchBox) assert res.interface == "torch" assert isinstance(res.unbox(), torch.Tensor) assert torch.allcl...
37,742
def mutual_coherence(A, B): """"Mutual coherence between two dictionaries A and B """ max_val, index = mutual_coherence_with_index(A, B) return max_val
37,743
def pdf_page_enumeration(pdf): """Generate a list of pages, using /PageLabels (if it exists). Returns a list of labels.""" try: pagelabels = pdf.trailer["/Root"]["/PageLabels"] except: # ("No /Root/PageLabels object"), so infer the list. return range(1, pdf.getNumPages() + 1) ...
37,744
def add_linear_obj(community, exchanges): """Add a linear version of a minimal medium to the community. Changes the optimization objective to finding the growth medium requiring the smallest total import flux:: minimize sum |r_i| for r_i in import_reactions Arguments --------- communi...
37,745
def transform_points_torch(points, homography): """Transforms input points according to homography. Args: points: [..., H, W, 3]; pixel (u,v,1) coordinates. homography: [..., 3, 3]; desired matrix transformation Returns: output_points: [..., H, W, 3]; transformed (u,v,w) coordinates...
37,746
def _sane_fekete_points(directions, n_dim): """ get fekete points for DirectionalSimulator object. use get_directions function for other use cases. """ if directions is None: n_dir = n_dim * 80 elif isinstance(directions, int): n_dir = directions else: try: ...
37,747
def write_results(results): """Print the test results to the console output Returns: None """ for r in results: write_result(r)
37,748
def backoffPolicy(initialDelay=1.0, maxDelay=60.0, factor=1.5, jitter=_goodEnoughRandom): """ A timeout policy for L{ClientService} which computes an exponential backoff interval with configurable parameters. @since: 16.1.0 @param initialDelay: Delay for the first reconnection at...
37,749
def block_group(inputs, filters, strides, block_fn, block_repeats, conv2d_op=None, activation=tf.nn.swish, batch_norm_activation=nn_ops.BatchNormActivation(), dropblock=nn_ops.Dropblock(), ...
37,750
def test_scenario10(kiali_client, openshift_client, browser): """ Permissive mode allow mTLS connections to services """ tests = ValidationsTest( kiali_client=kiali_client, openshift_client=openshift_client, browser=browser, objects_path=istio_objects_mtls_path.strpath) tests.test_istio...
37,751
def GeneratePublicKeyDataFromFile(path): """Generate public key data from a path. Args: path: (bytes) the public key file path given by the command. Raises: InvalidArgumentException: if the public key file path provided does not exist or is too large. Returns: A publi...
37,752
def test_format_pep8(): """ Test if pep8 is respected. """ pep8_checker = StyleGuide() files_to_check = [] for path in list_files(".py"): rel_path = os.path.relpath(path, pylearn2.__path__[0]) if rel_path in whitelist_pep8: continue else: files_to_...
37,753
def parse_overrides(overrides, pre): """Find override parameters in the cli args. Note: If you use the same cli flag multiple time the values will be aggregated into a list. For example `--x:a 1 --x:a 2 --x:a 3` will give back `{'a': [1, 2, 3]}` :param overrides: The cli flags and ...
37,754
def get_server_backup_price() -> None: """ Printing server backups price as Table in console """ server_backup_price = Table(title="Server backup") server_backup_price.add_column("Percentage, %", justify="center", style="bold") server_backup_price.add_column("About") global _data global...
37,755
def make_keyword_html(keywords): """This function makes a section of HTML code for a list of keywords. Args: keywords: A list of strings where each string is a keyword. Returns: A string containing HTML code for displaying keywords, for example: '<strong>Ausgangsw&ouml;rter:</stro...
37,756
def is_match(set, i): """Checks if the three cards all have the same characteristic Args: set (2D-list): a set of three cards i (int): characterstic Returns: boolean: boolean """ if (set[0][i] == set[1][i] and set[1][i] == set[2][i]): return True ret...
37,757
def write_sentence(f, sentence): """ Writes the given sentence surrounded from top by SENTENCE_SEPARATOR :param f: open file handle :param sentence: sentence to write """ f.write(SENTENCE_SEPARATOR + "\n" + sentence + "\n")
37,758
def notGroup (states, *stateIndexPairs): """Like group, but will add a DEFAULT transition to a new end state, causing anything in the group to not match by going to a dead state. XXX I think this is right... """ start, dead = group(states, *stateIndexPairs) finish = len(states) states.append...
37,759
def test_get_job_by_id(auth_client): """API endpoint api/jobs/{jobID}""" auth_client = auth_client[0] response = auth_client.get("api/jobs/3") sub_time = datetime.fromisoformat("2016-08-29T09:12:00.000000+00:00").astimezone() sub_time = sub_time.strftime(format="%Y-%m-%d %H:%M") expected_respo...
37,760
def copy_file_to(local_file_path_or_handle, cloud_storage_file_path, metadata=None): """Copy local file to a cloud storage path.""" if (isinstance(local_file_path_or_handle, basestring) and not os.path.exists(local_file_path_or_handle)): logs.log_error('Local file %s not ...
37,761
def test_format_team_row(): """ Check that a team retrieved from Github's API is correctly formatted """ formatted = format_team_row( {'edges': [{'node': {'login': 'bla'}}, {'node': {'login': 'ba'}}]}, 'faketeam' ) assert len(formatted) == 2 assert formatted['bla'] == 'faketeam'
37,762
def get_image_array(conn, image_id): """ This function retrieves an image from an OMERO server as a numpy array TODO """ import numpy as np image = conn.getObject("Image", image_id) #construct numpy array (t, c, x, y, z) size_x = image.getSizeX() size_y = image.getSizeY() siz...
37,763
def test_softsign(): """Test using a reference softsign implementation. """ def softsign(x): return np.divide(x, np.ones_like(x) + np.absolute(x)) x = K.placeholder(ndim=2) f = K.function([x], [activations.softsign(x)]) test_values = get_standard_values() result = f([test_values])[...
37,764
def run( package_out_dir, package_tests_dir, work_dir, packages): """Deployes build *.cipd package locally and runs tests against them. Used to verify the packaged code works when installed as CIPD package, it is important for infra_python package that has non-trivial structure. Args: pack...
37,765
def get_published_questions(quiz): """ Returns the QuerySet of the published questions for the given quiz """ questions = get_questions_by_quiz(quiz) #Questions are ordered by serial number return questions.filter(published = True)
37,766
def test_compute_high_altitude_not_inplace() -> None: """Returns a Dataset.""" z = np.linspace(86, 1000) * ureg.km ds1 = init_data_set(z=z) ds2 = compute_high_altitude(data_set=ds1, mask=None, inplace=False) assert ds1 != ds2 assert isinstance(ds2, xr.Dataset)
37,767
def moving_average(x, window): """ :param int window: odd windows preserve phase From http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/DataFiltering.ipynb """ return np.convolve(x, np.ones(window) / window, "same")
37,768
def plot_activations(image_dir): """ Plot the activations for a given image :param checkpoint_file: Where the model is saved :param image_dir: """ read_image = cv2.imread(image_dir, 0) read_image = cv2.resize(read_image, (24, 24), interpolation=cv2.INTER_AREA) run_model_image(checkpoint...
37,769
def validate_interval_avg_data(in_data): # test """Validates input to get_avg_since for correct fields Args: in_data: dictionary received from POST request Returns: boolean: if in_data contains the correct fields """ expected_keys = {"patient_id", "heart_rate_average_since"} f...
37,770
def test_graph_construction(): """ Test that we can construct a popart._internal.ir.Graph object. """ ir = _ir.Ir() g1Id = _ir.GraphId("g1") g1 = _ir.Graph(ir, g1Id)
37,771
def _get_cm_control_command(action='--daemon', cm_venv_name='CM', ex_cmd=None): """ Compose a system level command used to control (i.e., start/stop) CloudMan. Accepted values to the ``action`` argument are: ``--daemon``, ``--stop-daemon`` or ``--reload``. Note that this method will check if a virtualen...
37,772
def get_all_db_data() -> list: """Возвращает все строки из базы""" cursor.execute('''SELECT * FROM news''') res = cursor.fetchall() return res
37,773
def test_doc_storage_name(session, desc, reg_num, doc_name): """Assert that building a storage document name works as expected.""" registration: Registration = Registration.find_by_registration_number(reg_num, 'PS12345', True) test_name = registration.registration_ts.isoformat()[:10] test_name = test_na...
37,774
def astra_projector(vol_interp, astra_vol_geom, astra_proj_geom, ndim, impl): """Create an ASTRA projector configuration dictionary. Parameters ---------- vol_interp : {'nearest', 'linear'} Interpolation type of the volume discretization. This determines the projection model that is cho...
37,775
def __hit(secret_number, choice): """Check if the choice is equal to secret number""" return secret_number == choice
37,776
def generate_faces(src_path, dst_path): """ Generate faces from source directory and store cropped faces in destination directory """ for root, dirs, files in os.walk(src_path): for name in dirs: dir_name = os.path.join(root, name) images = os.listdir(dir_name) ...
37,777
def showField(fichier,field,name,mesh="dom",dim=2,rotx=-45,roty=45,rotz=0,plotmesh=True,time=-1,win=False): """ Methods to plot a field from a .lata file. Parameters --------- fichier : str The .lata file we want to plot its mesh with visit. field : str The field we want to pl...
37,778
def minimal_product_data(setup_data): """Valid product data (only required fields)""" return { 'name': 'Bar', 'rating': .5, 'brand_id': 1, 'categories_ids': [1], 'items_in_stock': 111, }
37,779
def flatten_column_array(df, columns, separator="|"): """Fonction qui transforme une colonne de strings séparés par un séparateur en une liste : String column -> List column""" df[columns] = ( df[columns].applymap(lambda x: separator.join( [str(json_nested["name"]) for json_nested in x])...
37,780
def delete_folder(*folder_path: str): """ Delete a list of folders if folder exists. :param folder_path: the list of paths of the folder to look up. """ for folder in folder_path: if folder_exists(folder): shutil.rmtree(folder)
37,781
def part2(lines: List[List[int]]): """ """ grid = Grid.from_text(lines) lim_x = grid.width() lim_y = grid.height() for by in range(5): for bx in range(5): if bx == by == 0: continue for dy in range(lim_y): for dx in range(lim_x): ...
37,782
def translate_point(point, y_offset=0, x_offset=0): """Translate points. This method is mainly used together with image transforms, such as padding and cropping, which translates the top left point of the image to the coordinate :math:`(y, x) = (y_{offset}, x_{offset})`. Args: point (~nump...
37,783
def _get_tau_var(tau, tau_curriculum_steps): """Variable which increases linearly from 0 to tau over so many steps.""" if tau_curriculum_steps > 0: tau_var = tf.get_variable('tau', [], initializer=tf.constant_initializer(0.0), trainable=False) tau_...
37,784
def des_descrypt(s): """ DES 解密 :param s: 加密后的字符串,16进制 :return: 解密后的字符串 """ iv = constants.gk k = des(iv, CBC, iv, pad=None, padmode=PAD_PKCS5) #print binascii.b2a_hex(s) de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5) print de return de
37,785
def ghg_call(url, response, args): """ Callback function for the US GHG Emissions download. Open the downloaded zip file and read the contained CSV(s) into pandas dataframe(s). :param url: :param response: :param args: :return: """ df = None year = args['year'] with zipfile.Z...
37,786
def get_compound_coeff_func(phi=1.0, max_cost=2.0): """ Cost function from the EfficientNets paper to compute candidate values for alpha, beta and gamma parameters respectively. These values are then used to train models, and the validation accuracy is used to select the best base parameter...
37,787
def setup_logging(): """The function to setup logger""" logger.setLevel(logging.DEBUG) formatter = logging.Formatter( fmt="%(levelname)s: %(message)s", ) app_handler = logging.FileHandler( filename=DEFAULT_APP_HANDLER_FPATH, ) app_handler.setLevel(logging.DEBUG) app_hand...
37,788
def get_kver_bin(path, split=False, proc=None): """ Get version of a kernel binary at 'path'. The 'split' and 'proc' arguments are the same as in 'get_kver()'. """ if not proc: proc = Procs.Proc() cmd = f"file -- {path}" stdout = proc.run_verify(cmd)[0].strip() msg = f"ran thi...
37,789
def post_apply_become_provider_apply_id_accept(request: HttpRequest, apply_id, **kwargs) -> JsonResponse: """ 允许成为设备拥有者 :param request: 视图请求 :type request: HttpRequest :param kwargs: 额外参数 :type kwargs: Dict :return: JsonResponse :rtype: JsonResponse """ handle_reason: str = requ...
37,790
def get_var_info(line, frame): """Given a line of code and a frame object, it obtains the value (repr) of the names found in either the local or global scope. """ tokens = utils.tokenize_source(line) loc = frame.f_locals glob = frame.f_globals names_info = [] names = [] for tok in...
37,791
def filter_events_for_client(store, user_id, events, is_peeking=False, always_include_ids=frozenset()): """ Check which events a user is allowed to see Args: store (synapse.storage.DataStore): our datastore (can also be a worker store) user_id(str): ...
37,792
def MPS_SimAddRule(event_mask: Union[IsoSimulatorEvent, FeliCaSimulatorEvent, VicinitySimulatorEvent, NfcSimulatorEvent, Type2TagSimulatorEvent], delay: ...
37,793
def groupconv_to_conv(op: Node): """ Function makes GroupConv op back to Conv op with weights reshaping :param op: :return: """ assert op.soft_get('type') == 'GroupConvolution', \ 'Wrong operation type, {} instead of GroupConvolution!'.format(op.soft_get('type')) weights_shape = op....
37,794
def wr1996(size=200): """Generate '6d robot arm' dataset (Williams and Rasmussen 1996) Was originally created in order to test the correctness of the implementation of kernel ARD. For full details see: http://www.gaussianprocess.org/gpml/code/matlab/doc/regression.html#ard x_1 picked randomly in ...
37,795
def to_pretty_json(obj): """Encode to pretty-looking JSON string""" return json.dumps(obj, sort_keys=False, indent=4, separators=(',', ': '))
37,796
def parse_access_token(request): """Get request object and parse access token""" try: auth_header = request.headers.get('Authorization') return auth_header.split(" ")[1] except Exception as e: return
37,797
def postscriptWeightNameFallback(info): """ Fallback to the closest match of the *openTypeOS2WeightClass* in this table: === =========== 100 Thin 200 Extra-light 300 Light 400 Normal 500 Medium 600 Semi-bold 700 Bold 800 Extra-bold 900 Black === ======...
37,798
def down_spatial(in_planes, out_planes): """downsampling 21*21 to 5*5 (21-5)//4+1=5""" return nn.Sequential(nn.Conv2d(in_planes, out_planes, kernel_size=5, stride=4), nn.BatchNorm2d(out_planes))
37,799