content
stringlengths
22
815k
id
int64
0
4.91M
def optimal_kernel_bandwidth(spiketimes, times=None, bandwidth=None, bootstrap=False): """ Calculates optimal fixed kernel bandwidth, given as the standard deviation sigma. Parameters ---------- spiketimes : np.ndarray Sequence of spike times (sorted to be a...
35,400
def run_visualization(): """Main visualization method""" s = Settings() img = np.zeros((s.window_height, s.window_width, 3), np.uint8) shape_start_x = s.window_width / 2 shape_start_y = s.window_height / 2 bg_start_x = 0 bg_start_y = 0 for chunk_index in range(s.chunks_count): ...
35,401
def run_lsh_omp_coder(data, dictionary, sparsity, num_buckets=1): """Solve the orthogonal matching pursuit problem with LSH bucketing. Use sklearn.linear_model.orthogonal_mp to solve the following optimization program: argmin ||y - X*gamma||^2, subject to ||gamma||_0 <= n_{nonzero coefs}, w...
35,402
def hamming_options(seq1, seq2): """Calculate Hamming distance between two sequences. Interpret ambiguity as options. """ sequence1 = convert_to_nosegment(seq1) sequence2 = convert_to_nosegment(seq2) distance = 0 for i, segment1 in enumerate(sequence1.segments): segment2 = sequenc...
35,403
def __getgyro_decoder__(port: serial.Serial, *args, **kwargs) -> Tuple[int, int, int]: """ Reads the gyro state from the serial port and decodes it as a (x, y, z) tuple. """ val = port.read(8) if(val[7] != 0xAA): raise Exception("Updating configuration data failed.") x = struct.unpack("...
35,404
def spatial_knn(coords, expression, n_neighbors=14, n_sp_neighbors=7, radius=None, which_exprs_dims=None, sample_id=None): """ A variant on the standard knn neighbor graph inference procedure that also includes the spatial neighbors of each spot. With help from Krzysztof Polanski. :para...
35,405
def parse_q(s): """Parse the value of query string q (?q=) into a search sub-term.""" if '=' not in s: names = s.split() term = '/'.join(map(lambda x: 'n.name=' + x, names)) return term else: subterms = s.split() res = [] for subterm in subterms: i...
35,406
def getCompleteData(client , response ,comp): """ This function is useful to receive missing data in tcp packet Input : Client = Tcp Object which interact with host end and client response = received response from the host end comp = comparitive struct defined by...
35,407
def two_squares(n): """ Write the integer `n` as a sum of two integer squares if possible; otherwise raise a ``ValueError``. INPUT: - ``n`` -- an integer OUTPUT: a tuple `(a,b)` of non-negative integers such that `n = a^2 + b^2` with `a <= b`. EXAMPLES:: sage: two_squares(38...
35,408
def getattr_by_path(obj, attr, *default): """Like getattr(), but can go down a hierarchy like 'attr.subattr'""" value = obj for part in attr.split('.'): if not hasattr(value, part) and len(default): return default[0] value = getattr(value, part) if callable(value): ...
35,409
def make_shirt(size, message): """Display information regarding the size and message of a shirt.""" print("The shirt size is " + size + " and the message will read: " + message + ".")
35,410
def assert_array_almost_equal( x: numpy.ndarray, y: numpy.ndarray, decimal: int, err_msg: Literal["Size 15 failed"] ): """ usage.scipy: 8 """ ...
35,411
def entries_to_files(entry_ids): """ Format file details (retrieved using the files' entry IDs) to API expectations to include files in API call. parameter: (list) entry_ids List of entry ID strings for files uploaded to the warroom returns: List of attachment field, value tuples forma...
35,412
def g_mult(a, b, p): """Multiply two polynomials given the irreducible polynomial of a GF""" c = [i % 2 for i in mult(a, b)] c, p = lenshift(c, p) return div(c, p)
35,413
def compute_common_alphanumeric_tokens(column, feature, k): """ compute top k frequent alphanumerical tokens and their counts. tokens only contain alphabets and/or numbers, decimals with points not included """ col = column.str.split(expand=True).unstack().dropna().values token = np.array(list(f...
35,414
def data_augmentation_fn(input_image: tf.Tensor, label_image: tf.Tensor, flip_lr: bool=True, flip_ud: bool=True, color: bool=True) -> (tf.Tensor, tf.Tensor): """Applies data augmentation to both images and label images. Includes left-right flip, up-down flip and color change. :para...
35,415
def get_stack_value(stack, key): """Get metadata value from a cloudformation stack.""" for output in stack.outputs: if output['OutputKey'] == key: return output['OutputValue']
35,416
def add_command_line_sys_path(): """Function that adds sys.path of the command line to Blender's sys.path""" additional_system_paths = get_additional_command_line_sys_path() for additional_sys_path in additional_system_paths: sys.path.append(additional_sys_path) if len(additional_system_paths) ...
35,417
def test_dnn_tag(): """ We test that if cudnn isn't avail we crash and that if it is avail, we use it. """ x = T.ftensor4() old = theano.config.on_opt_error theano.config.on_opt_error = "raise" sio = StringIO() handler = logging.StreamHandler(sio) logging.getLogger('theano.compile.t...
35,418
def cmd_example_cmd_as_module(mixcli: MixCli, **kwargs): """ This function would be called by the processing of ArgumentParser. The contract is the positional argument would be a MixCli instance and the rest are passed as keyword arguments. We recommend to name this function as cmd_<name_of_group>_<name...
35,419
def tee(iterable, n=2): # real signature unknown; restored from __doc__ """ tee(iterable, n=2) --> tuple of n independent iterators. """ pass
35,420
def display_credentials(user_name): """ Function to display saved account credentials """ return Credentials.display_credentials(user_name)
35,421
def add_args(parser): """ parser : argparse.ArgumentParser return a parser added with args required by fit """ # Training settings parser.add_argument('--model', type=str, default='dadgan', metavar='N', help='neural network used in training') parser.add_argument('--b...
35,422
def sk_learn_bootstrap(x, y, z, design_matrix, kf_reg, N_bs=100, test_percent=0.4, print_results=True): """Sci-kit learn bootstrap method.""" x_train, x_test, y_train, y_test = sk_modsel.train_test_split( np.c_[x.ravel(), y.ravel()], z.ravel(), test_size=test_percent, shu...
35,423
def vAdd(v, w): """ Return a new Vector, which is the result of v + w """ return Vector(v[0] + w[0], v[1] + w[1], v[2] + w[2])
35,424
def dynamic_vm_values(trace, code_start=BADADDR, code_end=BADADDR, silent=False): """ Find the virtual machine context necessary for an automated static analysis. code_start = the bytecode start -> often the param for vm_func and usually starts right after vm_func code_end = the bytecode end -> bytecode...
35,425
def getAddresses(pkt): """ 0: ('dst', 'src', 'bssid', None), from sta to sta 1: ('dst', 'bssid', 'src', None), out of ds 2: ('bssid', 'src', 'dst', None), in ds 3: ('recv', 'transl', 'dst', 'src') between dss """ f = pkt.FCfield & 3 # to-DS and from-DS if f == 0:...
35,426
def test_keep_alive_client_timeout(): """If the server keep-alive timeout is longer than the client keep-alive timeout, client will try to create a new connection here.""" try: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) client = ReuseableSanicTestClient(keep_alive_a...
35,427
def _ldmodule_soversion(target, source, env, for_signature): """Function to determine what to use for SOVERSION""" if 'SOVERSION' in env: return '.$SOVERSION' elif 'LDMODULEVERSION' in env: ldmod_version = env.subst('$LDMODULEVERSION') # We use only the most significant digit of LDM...
35,428
def jitter( grid: Grid, min_variance: int = None, max_variance: int = None, size: int = None, clamp: bool = False, variance_list: list[int] = None, ) -> Grid: """Randomly jitter all points in a grid Jitter will apply to both the x and y axises of the grid If a variance list is given...
35,429
def survey_post_save(sender, instance, created, **kwargs): """ Ensure that a table exists for this logger. """ # Force our response model to regenerate Response = instance.get_survey_response_model(regenerate=True, notify_changes=False) # Create a new table if it's missing utils.create_db_table(Re...
35,430
def testAgentInstanceSettingsTo_whenProtoHasNumberField_returnsBytes(): """Test supported serializing int number.""" instance_settings = definitions.AgentSettings( key='agent/ostorlab/BigFuzzer', bus_url='mq', bus_exchange_topic='topic', bus_management_url='mq_managment', ...
35,431
def loadFasta(fa, sep=None, term=None, nfilter=None): """Returns a kapow.Array() with the contents of the file interpreted as a FASTA file, using sep if given.""" def _boundary2int(num, n, start=False): if num == '': return 0 if start else n mult = 1 if num[-1] == 'K': mult = 1000 elif num[-1] == 'M': mult = ...
35,432
def reverse_bits(counter) -> int: """ Reverses the order of the bits in the given counter :param counter: a 7bit value :return: """ # From Elephant reference code (elephant160v2 > spongent.c > retnuoCl) return ((counter & 0x01) << 7) | ((counter & 0x02) << 5) | ((counter & 0x04) << 3) \ ...
35,433
def check_quota(): """ Check quota for the RANDOM.ORG API :return: True if the request is successful AND there is remaining quota available """ resp = requests.request('GET', 'https://www.random.org/quota/?format=plain') if resp.status_code != 200 or int(resp.text) <= 0: return False ...
35,434
def test_unauthorized_source( clirunner, caplog: LogCaptureFixture, docker_registry_secure: DockerRegistrySecure, gpgsigner: GPGSigner, known_good_image: TypingKnownGoodImage, ): """Test docker-sign can handle incorrect credentials.""" caplog.clear() caplog.set_level(logging.DEBUG) ...
35,435
def safe_exit(navigator, err): """Safe exit of the Scan The Code mission.""" yield navigator.mission_params["scan_the_code_color1"].set("RED") yield navigator.mission_params["scan_the_code_color2"].set("GREEN") yield navigator.mission_params["scan_the_code_color3"].set("BLUE")
35,436
def idwt2d(input_node, wavelet, levels=1): """ Constructs a TF graph that computes the 2D inverse DWT for a given wavelet. Args: input_node (tf.placeholder): Input signal. A 3D tensor with dimensions as [rows, cols, channels] wave...
35,437
def readin_rho(filename, rhofile=True, aniso=False): """Read in the values of the resistivity in Ohmm. The format is variable: rho-file or mag-file. """ if aniso: a = [[0, 1, 2], [2, 3, 4]] else: a = [0, 2] if rhofile: if filename is None: filename = 'rho/rho....
35,438
def cofense_report_image_download_command(client: Client, args: Dict[str, str]) -> dict: """ Downloads the image for a specific report. :type client: ``Client`` :param client: Client object to be used. :type args: ``Dict[str, str]`` :param args: The command arguments provided by the user. ...
35,439
def import_data_line(line_num, tokens, samples, organism): """ Function that imports numerical values in input tokens into the database. An exception will be raised if any of the following errors are detected: * The number of columns on this line is not equal to the number of samples plus 1. ...
35,440
def random_indices(batch_size, num_samples): """\ Generate a random sequence of indices for a batch. :param batch_size: length of the random sequence to generate :param num_samples: number of samples available, i.e., maximum value to include in the random sequence + 1 :return: list of integer...
35,441
def diff_first_last(L, *opArg): """ (list) -> boolean Precondition: len(L) >= 2 Returns True if the first item of the list is different from the last; else returns False. >>> diff_first_last([3, 4, 2, 8, 3]) False >>> diff_first_last(['apple', 'banana', 'pear']) True >>> diff_first...
35,442
def update_on_table(df: pd.DataFrame, keys: update_key_type, values: update_key_type, table_name: str, engine: sa.engine.base.Engine, schema: str) -> int: """ :param df: a dataframe with data tha needs to be updated. Must have columns to be used as key and some for values :param keys: t...
35,443
def administrar_investigaciones(request,tipo): """Administrar investigaciones seleccionadas, para ser eliminadas o finalizadas""" if request.method == 'POST': ids = request.POST.getlist('checks[]') if tipo == "incorrecto": #Se han seleccionado investigaciones para ser finalizadas inc...
35,444
def container_images_prepare_defaults(): """Return default dict for prepare substitutions This can be used as the mapping_args argument to the container_images_prepare function to get the same result as not specifying any mapping_args. """ return KollaImageBuilder.container_images_template_inpu...
35,445
def logjsonfiles(cloudvolume: cv.CloudVolume, filenames: list[str], filecontents: list[str] ) -> None: """Stores extra JSON files alongside a provenance file. Args: cloudvolume: A CloudVolume. filenames: A list of filenames to log. file...
35,446
def discriminantcontrast(x, y, con, w): """return discriminant contrast (LDC, crossnobis, CV-Mahalanobis, whatever).""" betas = lsbetas(x, y) conest = con @ betas return np.sum(conest * w, axis=1)
35,447
def calculateCosine(point, origin): """ calculate the polar angle of the given point to the origin point """ x1, y1 = point x0, y0 = origin if y1 == y0: return 1.0 return round((x1 - x0) / calculateDistance(point, origin), ROUND)
35,448
def dirty(grid, times=1, all_pattern=all_pattern): """add random patterns n times at random position in a matrix object""" while times: times-=1 at( grid, randint(0, grid.size_x) , randint(0,grid.size_y), choice(all_pattern) )
35,449
def ValidClassWmi(class_name): """ Tells if this class for our ontology is in a given WMI server, whatever the namespace is. This is used to display or not, the WMI url associated to a Survol object. This is not an absolute rule. """ return class_name.startswith(("CIM_", "Win32_", "WMI_"))
35,450
def autolabel(rects, ax): """Attach some text labels. """ for rect in rects: ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * rect.get_height(), '', ha='center', va='bottom')
35,451
def results(): """Calculate results and route to results page""" # get user input user_input = dict(request.args) user_titles = [] for x in user_input.keys(): if x == "algo": algo_choice = user_input[x] else: user_titles.append(user_input[x]) # construct a...
35,452
def schema(): """ Print the JSON Schema used by FIXtodict. """ print(JSON_SCHEMA_V1)
35,453
def populate_transformation_details(workflow_stats , workflow_info): """ populates the transformation details of the workflow @param workflow_stats the StampedeStatistics object reference @param workflow_info the WorkflowInfo object reference """ transformation_stats_dict ={} wf_transformation_color_map ={} gl...
35,454
def steamspy_tag_data_rename_cols(): """ Update the steamspy_tag_data.csv file to have column names from mapping.json """ df = pd.read_csv("sets/steamspy_tag_data.csv") with open("mapping.json", "r") as f: mapping = json.load(f) df = df.rename(mapping, axis="columns") df.to_c...
35,455
def flatten(d, separator='_', parent_key=None): """ Converts a nested hierarchy of key/value object (e.g. a dict of dicts) into a flat (i.e. non-nested) dict. :param d: the dict (or any other instance of collections.MutableMapping) to be flattened. :param separator: the separator to use when concatenat...
35,456
def _rendered_size(text, point_size, font_file): """ Return a (width, height) pair representing the size of *text* in English Metric Units (EMU) when rendered at *point_size* in the font defined in *font_file*. """ emu_per_inch = 914400 px_per_inch = 72.0 font = _Fonts.font(font_file, p...
35,457
def parse_args(args: str) -> Tuple[UFDLType]: """ Parses the string representation of a list of type arguments. :param args: The type arguments to parse. :return: The parsed types. """ if args == "": return tuple() return tuple(parse_type(arg) for ar...
35,458
def pca_biplot( predictor: Iterable, response: Iterable, labels: Iterable[str] = None ) -> pyplot.Figure: """ produces a pca projection and plot the 2 most significant component score and the component coefficients. :param predictor: :param response: :param labels: :return:""" scaler =...
35,459
def betweenness_centrality(G, k=None, normalized=True, weight=None, endpoints=False, seed=None, result_dtype=np.float64): """ Compute the betweenness centrality for all nodes of the graph G from a sample of 'k' sources. CuGraph does not currently sup...
35,460
def kb_spmat_interp_adjoint( data: Tensor, interp_mats: Tuple[Tensor, Tensor], grid_size: Tensor ) -> Tensor: """Kaiser-Bessel sparse matrix interpolation adjoint. See :py:class:`~torchkbnufft.KbInterpAdjoint` for an overall description of adjoint interpolation. To calculate the sparse matrix tupl...
35,461
def help_send(command: str, help_string_call: Callable[[], str]): """发送帮助信息""" class _HELP(ArgAction): def __init__(self): super().__init__(HelpActionManager.send_action) def handle(self, option_dict, varargs, kwargs, is_raise_exception): action = require_help_send_acti...
35,462
def divide_list(array, number): """Create sub-lists of the list defined by number. """ if len(array) % number != 0: raise Exception("len(alist) % number != 0") else: return [array[x:x+number] for x in range(0, len(array), number)]
35,463
def _sympify(a): """Short version of sympify for internal usage for __add__ and __eq__ methods where it is ok to allow some things (like Python integers and floats) in the expression. This excludes things (like strings) that are unwise to allow into such an expression. >>> from sympy im...
35,464
def remove_category(directory: str, img_dir: str, annotation_file_path: str, category: int = 1): """ category 1 == humans """ annotation_file_path = os.path.join(directory, "annotations", annotation_file_path) assert os.path.isfile(annotation_file_path) with open(annotation_file_path, 'r') as a...
35,465
def process_value(setting_info, color): """Called by the :class:`rivalcfg.mouse.Mouse` class when processing a "reactive_rgbcolor" type setting. :param dict setting_info: The information dict of the setting from the device profile. :param str,tuple,list,None color: The rea...
35,466
def generate_ones(num_bits): """Returns a numpy array with N ones.""" return np.ones(num_bits, dtype=np.int)
35,467
def get_exception_message(exception: Exception) -> str: """Returns the message part of an exception as string""" return str(exception).strip()
35,468
def handle_remove_readonly( func: Callable, path: str, exc: Tuple[BaseException, OSError, TracebackType] ) -> None: """Handle errors when trying to remove read-only files through `shutil.rmtree`. This handler makes sure the given file is writable, then re-execute the given removal function. Arguments:...
35,469
def GetAvailableKernelProfiles(): """Get available profiles on specified gsurl. Returns: a dictionary that maps kernel version, e.g. "4_4" to a list of [milestone, major, minor, timestamp]. E.g, [62, 9901, 21, 1506581147] """ gs_context = gs.GSContext() gs_ls_url = os.path.join(KERNEL_PROFILE_UR...
35,470
def scatterplot(data, x, label=None): """Scatterplot matrix for array data data have all the data (inlcuding missing data) x is a list of arrays without the missing data (for histogram and fitting) """ fig, ax = plt.subplots(data.shape[1], data.shape[1], figsize=(8, 8)) fig.suptitle('Scatterplo...
35,471
def closeForm(f): """Closes the form for the GUI. @param f: File to write to """ f.write("</form>")
35,472
def main() -> None: """Main function""" arguments = [ Argument("-c", "--cluster", "API server IP:port details")] args = parse_args( "Demonstrates Volume Operations using REST API Python Client Library.", arguments, ) setup_logging() headers = setup_connection(args.api_us...
35,473
def _get_dbnd_run_relative_cmd(): """returns command without 'dbnd run' prefix""" argv = list(sys.argv) while argv: current = argv.pop(0) if current == "run": return argv raise DatabandRunError( "Can't calculate run command from '%s'", help_msg="Check that it ...
35,474
def should_commit(kwargs: Kwargs) -> Tuple[bool, Kwargs]: """Function for if a schema class should create a document on instance.""" return kwargs.pop('create') if 'create' in kwargs else True, kwargs
35,475
def create_view_files_widget(ws_names2id: Dict[str, str], ws_paths: Dict[str, WorkspacePaths], output): """Create an ipywidget UI to view HTML snapshots and their associated comment files.""" workspace_chooser = widgets.Dropdown( options=ws_names2id, value=None, description='<b>Choose the workspac...
35,476
def test_hypotest_default(tmpdir, hypotest_args): """ Check that the default return structure of pyhf.utils.hypotest is as expected """ tb = pyhf.tensorlib kwargs = {} result = pyhf.utils.hypotest(*hypotest_args, **kwargs) # CLs_obs assert len(list(result)) == 1 assert isinstance(re...
35,477
def _get_frame_time(time_steps): """ Compute average frame time. :param time_steps: 1D array with cumulative frame times. :type time_steps: numpy.ndarray :return: The average length of each frame in seconds. :rtype: float """ if len(time_steps.shape) != 1: raise ValueError("ERRO...
35,478
def next_symbol_to_learn(ls): """Returns the next symbol to learn. This always returns characters from the training set, within those, gives higher probability to symbols the user doesn't know very well yet. `ls` is the learn state. Returns a tuple like ("V", "...-") """ total = 0.0 candidat...
35,479
def query_table3(song): """ This function returns the SQL neccessary to get all users who listened to the song name passed as an argument to this function. """ return "select user_name from WHERE_SONG where song_name = '{}';".format(song)
35,480
def get_available_user_FIELD_transitions(instance, user, field): """ List of transitions available in current model state with all conditions met and user have rights on it """ for transition in get_available_FIELD_transitions(instance, field): if transition.has_perm(instance, user): ...
35,481
def test_check_input_dtw(params, err_msg): """Test parameter validation.""" with pytest.raises(ValueError, match=re.escape(err_msg)): _check_input_dtw(**params)
35,482
def create_background( bg_type, fafile, outfile, genome="hg18", size=200, nr_times=10, custom_background=None, ): """Create background of a specific type. Parameters ---------- bg_type : str Name of background type. fafile : str Name of input FASTA file....
35,483
def train_test_data(x_,y_,z_,i): """ Takes in x,y and z arrays, and a array with random indesies iself. returns learning arrays for x, y and z with (N-len(i)) dimetions and test data with length (len(i)) """ x_learn=np.delete(x_,i) y_learn=np.delete(y_,i) z_learn=np.delete(z_,i) x_test=np.take(x_,i) y_test=np...
35,484
def construct_Tba(leads, tleads, Tba_=None): """ Constructs many-body tunneling amplitude matrix Tba from single particle tunneling amplitudes. Parameters ---------- leads : LeadsTunneling LeadsTunneling object. tleads : dict Dictionary containing single particle tunneling a...
35,485
def inplace_update_i(tensor_BxL, updates_B, i): """Inplace update a tensor. B: batch_size, L: tensor length.""" batch_size = tensor_BxL.shape[0] indices_Bx2 = tf.stack([ tf.range(batch_size, dtype=tf.int64), tf.fill([batch_size], tf.cast(i, tf.int64)) ], axis=-1) return tf...
35,486
def bert(model = 'base', validate = True): """ Load bert model. Parameters ---------- model : str, optional (default='base') Model architecture supported. Allowed values: * ``'multilanguage'`` - bert multilanguage released by Google. * ``'base'`` - base bert-bahasa released...
35,487
def surface( x_grid, y_grid, z_grid, cmap="Blues", angle=(25, 300), alpha=1., fontsize=14, labelpad=10, title="", x_label="", y_label="", z_label="log-likelihood"): """ Creates 3d contour plot given a grid for each axis. Arguments: ``x_grid`` An NxN grid of values...
35,488
async def record_trade_volume() -> RecordTradeVolumeResponse: """ This api exists for demonstration purposes so you don't have to wait until the job runs again to pick up new data """ await deps.currency_trade_service.update_trade_volumes() return RecordTradeVolumeResponse(success=True)
35,489
def dataload_preprocessing(data_path, dataset, long_sent=800): """ :param data_path: base directory :param dataset: select dataset {'20news', 'mr', 'trec', 'mpqa'} :param long_sent: if dataset has long sentences, set to be constant length value :return: seq_length, num_classes, vocab_size, x_train,...
35,490
def logged_in(): """ Method called by Strava (redirect) that includes parameters. - state - code - error """ error = request.args.get('error') state = request.args.get('state') if error: return render_template('login_error.html', error=error, ...
35,491
def test_time_dependent_to_qutip(): """Test conversion of a time-dependent Hamiltonian""" Hil = LocalSpace(hs_name(), dimension=5) ad = Create(hs=Hil) a = Create(hs=Hil).adjoint() w, g, t = symbols('w, g, t', real=True) H = ad*a + (a + ad) assert _time_dependent_to_qutip(H) == convert_to_q...
35,492
def unit_string_to_cgs(string: str) -> float: """ Convert a unit string to cgs. Parameters ---------- string The string to convert. Returns ------- float The value in cgs. """ # distance if string.lower() == 'au': return constants.au # mass ...
35,493
def _make_passphrase(length=None, save=False, file=None): """Create a passphrase and write it to a file that only the user can read. This is not very secure, and should not be relied upon for actual key passphrases. :param int length: The length in bytes of the string to generate. :param file fil...
35,494
def Mul(x, x_shape, y, y_shape, data_format=None): """mul""" if data_format: x_new = broadcast_by_format(x, x_shape, data_format[0], y_shape) y_new = broadcast_by_format(y, y_shape, data_format[1], x_shape) else: x_new = x y_new = y return mul.mul(x_new, y_new)
35,495
def new_authentication_challenge(usr: User) -> str: """ Initiates an authentication challenge. The challenge proceeds as follows: 1. A user (:class:`sni.user`) asks to start a challenge by calling this method. 2. This methods returns a UUID, and the user has 60 seconds to change its team...
35,496
def _clear_cache(context: CallbackContext, keep_save_pref: Optional[bool] = True) -> None: """Helper function to clear the user data. :param context: The context containing the user data to clear. :param keep_save_pref: Flag to indicate whether to keep user preference for global answer save. """ #...
35,497
def update_data(val): """ """ print('\n\nupdate_data()\nstr_data_key = '+str(str_data_key)+'\n') str_data_key = rad_data.value_selected ser_data = dic_data[str_data_key] print('str_data_key = '+str(str_data_key)+'\n') update(1)
35,498
def create_channel(application_key): """Create a channel. Args: application_key: A key to identify this channel on the server side. Returns: A string id that the client can use to connect to the channel. Raises: InvalidChannelTimeoutError: if the specified timeout is invalid. Other errors ret...
35,499