content
stringlengths
22
815k
id
int64
0
4.91M
def error(msj = None): """Imprime un mensaje de error Args: msj (str): Mensaje adicional a agregar al error """ if msj == None: print("ERROR") else: print("ERROR:", msj)
5,313,100
def test_no_op(): """Should retrun input df""" assert json_to_table(data, 'name').equals(data)
5,313,101
def before_request(): """ description: before render template javascript for the authentication - :return: """ session.permanent = True app.permanent_session_lifetime = timedelta(minutes=60) try: access_token = request.cookies.get('access_token') check = auth.verify_session_...
5,313,102
def _arg_raw(dvi, delta): """Return *delta* without reading anything more from the dvi file""" return delta
5,313,103
async def write_mapInfoReply(maps: Sequence[BeatmapInfo]) -> bytearray: """ Write `maps` into bytes (osu! map info). """ ret = bytearray(len(maps).to_bytes(4, 'little')) # Write files for m in maps: ret.extend(struct.pack('<hiiiBbbbb', m.id, m.map_id, m.set_id, m.thread_id, m.status...
5,313,104
def getPolarPoints2(x, y, center): """Convert list of cartesian points to polar points The returned points are not rounded to the nearest point. User must do that by hand if desired. Parameters ---------- x : (N,) :class:`numpy.ndarray` List of cartesian x points to convert to polar domain...
5,313,105
def to_bytes(binary_string: str) -> bytes: """Change a string, like "00000011" to a bytestring :param str binary_string: The string :returns: The bytestring :rtype: bytes """ if len(binary_string) % 8 != 0: binary_string += "0" * ( 8 - len(binary_string) % 8 ) # fill...
5,313,106
def choose_best_assembly_name(assembly_names): """ Given a list of reference genome names returns the best according to the following criteria: 1) Prefer Ensembl reference names to UCSC 2) Prefer reference names with higher numbers in them. Parameters ---------- assembly_names :...
5,313,107
def user_follow(request): """ This one is VERY similar to the <image_like> func in app-image/views. There are only two options after all (well, true for some cases) :D """ user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: ...
5,313,108
def module_patch_twin(connectionId, twin): # noqa: E501 """Updates the device twin # noqa: E501 :param connectionId: Id for the connection :type connectionId: str :param twin: :type twin: dict | bytes :rtype: None """ if connexion.request.is_json: twin = Twin.from_dict(...
5,313,109
def test_custom_model_registered(): """Test that a registered subclassed Model can be serialized. """ estimator = KerasRegressor(model=build_fn_custom_model_registered) check_pickle(estimator, fetch_california_housing)
5,313,110
def rgbToHsv(r, g, b): """ Converts an RGB color value to HSV. Conversion formula adapted from http://en.wikipedia.org/wiki/HSV_color_space. Args: r, g, b (int): red, green, and blue values between 0 and 255 inclusive Returns: Array [hue, saturation, value] hue between 0 and 36...
5,313,111
def assign_from_checkpoint(model_path, var_list): """Creates an operation to assign specific variables from a checkpoint. Args: model_path: The full path to the model checkpoint. To get latest checkpoint use `model_path = tf.train.latest_checkpoint(checkpoint_dir)` var_list: A list of (possibly par...
5,313,112
def _read_tmpfd(fil): """Read from a temporary file object Call this method only when nothing more will be written to the temporary file - i.e., all the writing has already been done. """ fil.seek(0) return fil.read()
5,313,113
def eigenvalues_and_eigenvectors(a: Matrix, epsilon=eps, max_iterations=1000) \ -> (TransposedVectorView, Matrix): """Eigenvalues|vectors with QR factorization""" assert is_symmetric(a) a_k = a.copy() v_k = Matrix.identity(a.size()[0]) for i in range(max_iterations): if almost_upper_...
5,313,114
def evens(input): """ Returns a list with only the even elements of data Example: evens([0, 1, 2, 3, 4]) returns [0,2,4] Parameter input: The data to process Precondition: input an iterable, each element an int """ result = [] for x in input: if x % 2 == 0: result.a...
5,313,115
def _setup_output_skip_keys(args): """reduce tensors pulled from data files to save time/space """ if (args.subcommand_name == "dmim") or (args.subcommand_name == "synergy"): skip_keys = [] elif (args.subcommand_name == "mutatemotifs"): skip_keys = [ DataKeys.ORIG_SEQ_PWM_HIT...
5,313,116
def create_example(speakers: List[List[nparr]]) -> nparr: """ :param speakers: a list of speakers where each item is a list of microphones where each contains a sound file padded to a consistent length :return: matrix of size [features(freq),file_len(time),(mic_num-1)*2] which contains the cosine and a ...
5,313,117
def todo_detail(request, pk): """API endpoint to get single todo or update its last exec date GET: Displays single ToDo PUT: Updates last exec date """ todo = get_object_or_404(ToDo, pk=pk) if request.method == 'GET': serializer = ToDoSerializer(todo) return Response(data=seria...
5,313,118
def print_conserved(): """Prints errors in conserved quantities""" print 'mass:', (thdiag[:,1].max()-thdiag[:,1].min())/thdiag[:,1].max() print 'L1 norm:',(thdiag[:,2].max()-thdiag[:,2].min())/thdiag[:,2].max() print 'Total momentum:',(thdiag[:,3].max()-thdiag[:,3].min()) print 'Total energy:',(thdi...
5,313,119
def SaveNumSummary(doc:NexDoc, filename): """Saves the summary of numerical results to a text file with the specified name.""" return NexRun("SaveNumSummary", locals())
5,313,120
def test_list_zone_changes_no_authorization(shared_zone_test_context): """ Test that list zone changes without authorization fails """ client = shared_zone_test_context.ok_vinyldns_client client.list_zone_changes('12345', sign_request=False, status=401)
5,313,121
def get_binary_balanced_purity_ranges(preds, class_labels, bin_size, total_class_counts): """ Get balanced purity for each class, for each range of probabilities, for binary classifier. Return dict. of class names to balanced purity at each prob threshold (10 thresholds) :param preds: List of Numpy row...
5,313,122
def bond_symmetry_numbers(xgr, frm_bnd_key, brk_bnd_key): """ symmetry numbers, by bond the (approximate) symmetry number of the torsional potential for this bond, based on the hydrogen counts for each atom It is reduced to 1 if one of the H atoms in the torsional bond is a neighbor to the special ...
5,313,123
def shutdown_worker_process(signal, sender, **kw): """ Called automatically when `celery worker` is stopped. This is executed inside each forked worker process. Calls :func:`ichnaea.taskapp.config.shutdown_worker`. """ celery_app = app_or_default() shutdown_worker(celery_app)
5,313,124
def pivot_table( data: pandas.core.frame.DataFrame, values: Literal["B"], index: Literal["A"], columns: Literal["C"], aggfunc: Literal["sum"], ): """ usage.dask: 2 """ ...
5,313,125
def test_int(): """Testing passing `None` type.""" assert syllapy.count(2) == 0
5,313,126
def compile_catalog(locale_dir, domain, locale): """ Compile `*.po` files into `*.mo` files and saved them next to the original po files found. Parameters ---------- output_dir: str FIXME: domain: str FIXME: locale: str, optional FIXME: """ # Check if loc...
5,313,127
def get_last_end_time(project_id, bucket_name): """ Get the end_time as a string value from a JSON object in GCS. This file is used to remember the last end_time in case one isn't provided """ last_end_time_str = "" file_name = '{}.{}'.format(project_id, config.LAST_END_TIME_FILENAME) loggi...
5,313,128
def make_header_layout(): """The html layout for the dashboard's header view.""" return html.Div( id="header", className="header", children=[ html.Div(id="title", className="header--project", children="rubicon-ml"), html.Div( id="links", ...
5,313,129
def get_cells(browser): """ get novel cells return [cell, cell, cell] """ browser.select('') pass
5,313,130
def test_rc_load_directory_should_fail(*args): """Check error validation when source is directory.""" with pytest.raises(RCError): utils.rc_load_json(Path())
5,313,131
def AfterReplace(image, allow_resize, write_map): """Handle write out an image after replacing entries in it Args: image: Image to write allow_resize: True to allow entries to change size (this does a re-pack of the entries), False to raise an exception write_map: True to wr...
5,313,132
def delete_buzz_upvdwv_meta(comment_interaction, userid, action): """ """ if action == "UPV": BuzzUpvoteDownvoteMeta.objects.get( Q(comment_interaction=comment_interaction), Q(userid=userid), Q(action=BuzzUpvoteDownvoteMeta.ActionChoices.UPVOTE), ).delete() ...
5,313,133
def quimbify(data, qtype=None, normalized=False, chopped=False, sparse=None, stype=None, dtype=complex): """Converts data to 'quantum' i.e. complex matrices, kets being columns. Parameters ---------- data : dense or sparse array_like Array describing vector or operator. qtype :...
5,313,134
def save_predict(predict_model, predict_path): """ 对预测的模型进行分析,找出牙龈线点,并对原始模型进行分割 @predict_model: 预测的模型 @save_path: 结果保存路径 return: None """ # ------加载模型 获取信息------ # ## 预测模型 predict_vs, predict_faces, predict_edges = parse_obje(predict_model) if len(predict_edges) == 0: pri...
5,313,135
def _check_insert_data(obj, datatype, name): """ Checks validity of an object """ if obj is None: return False if not isinstance(obj, datatype): raise TypeError("{} must be {}; got {}".format( name, datatype.__name__, type(obj).__name__)) return True
5,313,136
def create_importance_sampling( baddr: GBAPOMDPThroughAugmentedState, num_samples: int, minimal_sample_size: float ) -> belief_types.BeliefUpdate: """Creates importance sampling Returns a rejection sampling belief update that tracks ``num_samples`` particles in the ``baddr``. Basically glue between ...
5,313,137
def _unshare_network(tm_env, container_dir, app): """Configures private app network. :param ``appenv.AppEnvironment`` tm_env: Treadmill application environment """ unique_name = appcfg.app_unique_name(app) owner = os.path.join(tm_env.apps_dir, unique_name) # Configure DNAT rules while ...
5,313,138
def maps(): """ VALUES TO EDIT: """ name_to_open_file = "act_comercial.csv" """ END OF VALUES TO EDIT """ full_path_to_open_file = "static/databases/" + name_to_open_file with open(full_path_to_open_file) as csv_file: reader = csv.DictReader(csv_file) all_commercial_list = [] ...
5,313,139
def improved_land_choice(context: Context) -> Optional[int]: """ Play untapped land if needed, then ramp, then draw, then randomly choose a playable card """ hand = context.zones["hand"] mana = context.mana gold = context.gold playable_cards = context.playable_cards() # If there's a rea...
5,313,140
def _ParsePath(path): """Parses a path into a bucket name and an object name.""" if not path: return '', '' parts = path.split(_PATH_DELIMITER, 1) bucket = parts[0] if parts[0] else None object_name = parts[1] if 1 < len(parts) else None return bucket, object_name
5,313,141
def get_num_groups(*args, **kargs): """ OpenCL get_num_groups() """ raise _stub_error
5,313,142
def instance (): """ Get single instance of cache. If not setup already, the cache will be set up by default parameters. """ global _CacheInstance if _CacheInstance != None: return _CacheInstance else: return setup ()
5,313,143
def bboxes_iou(boxes1,boxes2): """ Argument: bboxes:dim = (num_box,4), 4 : [x_min,y_min,x_max,y_max] Retiurn: a np.array,dim = (num_box,1) """ boxes1 = np.array(boxes1) boxes2 = np.array(boxes2) boxes1_area = (boxes1[...,2] - boxes1[...,0]) * (boxes1[...,3] - boxes1[...,1]) ...
5,313,144
def dir_exists(foldername): """ Return True if folder exists, else False """ return os.path.isdir(foldername)
5,313,145
def normalizeListVec(v): """Normalizes a vector list.""" length = v[0] ** 2 + v[1] ** 2 + v[2] ** 2 if length <= 0: length = 1 v = [val / np.sqrt(length) for val in v] return v
5,313,146
def sim_1x5bits(K, kappa, num_sim): """ Compute simulation scalar products and return a list of ranks and intersection values for several simulations. Parameters: K -- string kappa -- string num_sim -- integer Return: rank_wr_list -- list of tuples """ # Length of signal part n = 5 # Message mu ...
5,313,147
def check_if_data_exists_at_geoscale(df_load, geoscale): """ Check if an activity or a sector exists at the specified geoscale :param df_load: df with activity columns :param geoscale: national, state, or county """ # filter by geoscale depends on Location System fips_list = create_geoscale...
5,313,148
def athenaupload_start( request: http.HttpRequest, pk: int, workflow: Optional[models.Workflow] = None, ) -> http.HttpResponse: """Load a data frame using an Athena connection. The parameters are obtained and if valid, an operation is scheduled for execution. :param request: Web request ...
5,313,149
def dasum(x): """ Compute the sum of the absolute values of the entries in {x} """ # compute and return the result return gsl.blas_dasum(x.data)
5,313,150
def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port, ready_check_path, mappath): """ Create a SuperviseAndProxyHandler subclass with given parameters """ # FIXME: Set 'name' properly class _Proxy(SuperviseAndProxyHandler): def __init__(self, *args, **kwargs)...
5,313,151
def get_datasets(filename): """ Get the names of datasets in an HDF5 file. Parameters ---------- filename : str Name of an HDF5 file visible to the arkouda server Returns ------- list of str Names of the datasets in the file See Also -------- ls_hdf ...
5,313,152
def stats_particle(difference): """" Returns the relevant statistics metrics about the distribution of the reative energy difference, as the mean, standard deviation, standard error and an appropriate label. :parameter difference: array containing the difference between true energy and the predicted en...
5,313,153
def oxe_set_flex(host, token, flex_ip_address, flex_port): """Summary Args: host (TYPE): Description token (TYPE): Description flex_ip_address (TYPE): Description flex_port (TYPE): Description Returns: TYPE: Description """ packages.urllib3.disable_w...
5,313,154
def process_advisory(url): """Process an advisory URL.""" global rule_number, RULE_TEMPLATE logger.debug('process_advisory({0})'.format(url)) html = requests.get(url).text soup = BeautifulSoup(html, 'html5lib') rule = copy.deepcopy(RULE_TEMPLATE) found = False rule['description'] = soup.find_all('h2')[0].ge...
5,313,155
def configure_opentelemetry( dsn="", service_name: Optional[str] = "", service_version: Optional[str] = "", resource_attributes: Optional[Attributes] = None, resource: Optional[Resource] = None, ): """ configureOpentelemetry configures OpenTelemetry to export data to Uptrace. By default ...
5,313,156
async def rest_handler(request): """Defines a GET handler for the '/rest' endpoint. Users make requests of this handler with a query string containing the following arguments: cmd: The command c to execute | c E {find, stats} params: A list of key-value parameters corresponding to the commands ...
5,313,157
def if_true(value, replace_with=None): """Replaces the value with the passed if the value is true.""" if not value: return '' if replace_with is None: return value return Template(replace_with).safe_substitute(value=value)
5,313,158
def test_div_grad_const(): """ compare div grad to laplace operator """ grid = CartesianGrid([[-1, 1]], 32) # test constant y = ScalarField(grid, 3) for bc in [{"type": "derivative", "value": 0}, {"type": "value", "value": 3}]: bcs = grid.get_boundary_conditions(bc) lap = y.laplace(...
5,313,159
def scenepath(scene): """Generate path for scene directory""" return os.path.join(basedir, name(scene))
5,313,160
def run_local(parser): """Runs build locally.""" parser.add_argument( '-r', '--run', type=str, required=True, help='name of run') parser.add_argument( '-p', '--project', type=str, required=True, help='name of project') parser.add_argument( '-m', '--model-type', ...
5,313,161
async def quineables(ctx) -> None: """ Displays a list of files printable with the quine command """ table = PrettyTable() table.align = "c" table.field_names = ["File Name", "File Path"] for f, p in _generate_valid_files().items(): table.add_row([f, p]) return await ctx.send...
5,313,162
def submit_job_GCP(xps_path, **kwargs): """GCP/HTCondor launcher""" sc = SubmissionConnection(xps_path, **kwargs) _sync_job(sc) _submit_job(sc) # Prepare download command print("To download results (before completion) use:") xcldd = ["xp.com", "DAPPER", "runlog", "err"] # "out\\.*" xc...
5,313,163
def piece_not(piece: str) -> str: """ helper function to return the other game piece that is not the current game piece Preconditions: - piece in {'x', 'o'} >>> piece_not('x') 'o' >>> piece_not('o') 'x' """ return 'x' if piece == 'o' else 'o'
5,313,164
def util(cpu='all', state='user', mode='avg1', host_os=detect_host_os()): """ Returns average percentage of time spent by cpu in a state over a period of time :raises: WrongArgumentError if unknown cpu is supplied :raises: WrongArgumentError if unknown state is supplied :raises: WrongArgumentEr...
5,313,165
def fitgaussian(data): """Returns (height, x, y, width_x, width_y, angle) the gaussian parameters of a 2D distribution found by a fit""" params = moments(data) errorfunction = lambda p: np.ravel(gaussian(*p)(*np.indices(data.shape)) - data) p, success = scipy.optimize.leastsq(errorfunction, params) ...
5,313,166
def retina_debug(): """ Return a dictionary with parameters for the retina suitable for debugging. """ params = retina_default() params.update({'description' : 'debug retina','N': 8}) return params
5,313,167
def argsum(*args): """sum of all arguments""" return sum(args)
5,313,168
def fit_data_multi_files(dir_path, file_prefix, param, start_i, end_i, interpath="entry/instrument/detector/data"): """ Fitting for multiple files with Multiprocessing. Parameters ---------- dir_path : str file_prefix : str param : dict start_i : int start id of given file e...
5,313,169
def test_outcomes_processing(relay_with_processing, mini_sentry, outcomes_consumer): """ Tests outcomes are sent to the kafka outcome topic Send one event to a processing Relay and verify that the event is placed on the kafka outcomes topic and the event has the proper information. """ relay = ...
5,313,170
def mark_up_series( issues: pd.DataFrame, series: str, area_of_testing: str, patterns: str ) -> pd.DataFrame: """ Appends binarized series to df. Parameters: ---------- issues: Bug reports. series: df series name. area_of_testing: area of testing. patterns: ...
5,313,171
def get_exp_parameters(): """ Defines the default values for the hyper-parameters of the experiment. :return: A dictionnary with values of the hyper-parameters :rtype: dict """ parser = ArgumentParser(add_help=False) parser.add_argument('--use_optuna', type=bool, default=False) parse...
5,313,172
def enum_options(values: List[Dict]) -> Tuple[List[str], int, Callable]: """Enumerate options of a enum parameter for display in a select box. Returns a 3-tuple containing a list of option value, the list index of the default option, and a function that provides a mapping from option values to their nam...
5,313,173
def bits_to_netmask(bits): """ Convert bits to netmask Args: bits ('int'): bits to converts ex.) bits = 32 Raise: None Returns: Net mask """ mask = (0xffffffff >> (32 - bits)) << (32 - bits) return (str( (0xff000000 & mask) >> 24) ...
5,313,174
def random_array_spec( shape: Optional[Tuple[int, ...]] = None, name: Optional[Text] = None, dtype: Optional[Type[np.floating]] = None, minimum: Optional[np.ndarray] = None, maximum: Optional[np.ndarray] = None) -> specs.BoundedArray: """Create BoundedArray spec with unspecified parts randomized."...
5,313,175
def _clamp_angle(angle: Angle) -> Angle: """ Certain angles in the game should be prohibited because they are not funny to play. The Function checks if angle is in the forbidden area and adjusts the angle. """ delta_x = deg2rad(30.0) delta_y = deg2rad(15.0) new_angle = angle if _...
5,313,176
def delete(where, item_id): """Returns True if successful; otherwise, False""" item_uri = uri % (where, str(item_id)) h = httplib2.Http() response, content = h.request(item_uri, method="DELETE", headers=headers) return response["status"] == "204", response, content
5,313,177
def calculate_pair_true_positive(docs, dataset_prefix, target_event_types=None): """We need this because in generating trigger candidates, we heuristically reject some candidates So we cannot calculate the true positive from the candidates. We need to go back to the doc level annotations. :type docs: list[...
5,313,178
def getXYforPlanet(time_et, planet, camera, observer=''): """ compute for all time instances in this class the xy position of a planet within a camera_name field-of-view. If not visible, return (-1,-1). If planet is visible, also return the size of the planet in pixels. Routine is tested for planet_...
5,313,179
def test_scan_archive_reset(): """ Tests the scanning of a archive via a filehandle that contains a tar. Trigges resets from clamd.""" fh = _generate_tarfile() magic_socket = Mock() magic_socket.scan_stream = _scan_stream_reset # Set the restriction to 300 bytes. # This should make the 60,120,18...
5,313,180
def queueEvent(eventName,obj,**kwargs): """Queues an NVDA event to be executed. @param eventName: the name of the event type (e.g. 'gainFocus', 'nameChange') @type eventName: string """ _trackFocusObject(eventName, obj) with _pendingEventCountsLock: _pendingEventCountsByName[eventName]=_pendingEventCount...
5,313,181
def change_format(df): """ This function changes the format of the data """ df['date'] = pd.to_datetime(df['date']) to_be_numeric = ['open', 'high', 'low', 'close', 'volume'] df[to_be_numeric] = df[to_be_numeric].apply(pd.to_numeric) return df
5,313,182
def _get_cell_nodes(G, cell_idx): """Get array of nodes for a cell.""" # To get face nodes in MRST: # (The second column in cells_faces are cell indices) # >> G.faces.nodes(G.faces.nodePos(cell_idx) : G.faces.nodePos(cell_idx+1)-1, 1) cell_faces = G.cells.faces[G.cells.facePos[cell_idx,0]:G.cells.fa...
5,313,183
def b64_receipt_to_full_service_receipt(b64_string: str) -> dict: """Convert a b64-encoded protobuf Receipt into a full-service receipt object""" receipt_bytes = base64.b64decode(b64_string) receipt = external_pb2.Receipt.FromString(receipt_bytes) full_service_receipt = { "object": "receiver_re...
5,313,184
def initialize_reports_overview(database: Database) -> None: """Initialize the reports overview if not present in the database.""" # The coverage measurement of the behave feature tests is unstable. Most of the time it reports the last two lines # as covered, sometimes not. It's unclear why. To prevent need...
5,313,185
def test_open_addressed_dict_del(): """test_open_addressed_dict_del.""" oad = OpenAddressHashDict() test_dict = dict() for key in (randrange(-100, 100) for _ in range(1000)): value = randrange(-100, 100) oad[key] = value test_dict[key] = value num_deleted = 0 deleted = di...
5,313,186
def main(file: str = "", action: str = "") -> int: """This is now we figth!""" if not file: return usage() # Resolve shell variables and ~ rom = Path(expandvars(file)).expanduser() if action == "check": return check(rom) if action == "dump": return dump(rom) retur...
5,313,187
def find_elements(node, xpath, allow_zero=True, allow_multiple=True): """Attempt to find child elements in a node by xpath. Raise exceptions if conditions are violated. Return a (possibly empty) list of elements.""" all_elements = node.findall(xpath) if (len(all_elements) == 0 and not allow_zero) or (le...
5,313,188
def register(): """Register the classes of Material Utilities together with the default shortcut (Shift+Q)""" mu_classes_register() bpy.types.VIEW3D_MT_object_context_menu.append(materialutilities_specials_menu) bpy.types.MATERIAL_MT_context_menu.prepend(materialutilities_menu_move) bpy.types.MATE...
5,313,189
def wi_to_demographics(ward_shapefile, outfile): """Parse demographic data included in the Wisconsin shapefile into a separate CSV consistent with dataverse_to_demographics(). Note that the statewide totals of the per-ward demographic data seems to vary from the statewide totals given by the 2010 U.S. Census. ...
5,313,190
def name(class_name: str, chain_class: Type[ChainAPI]) -> Type[ChainAPI]: """ Assign the given name to the chain class. """ return chain_class.configure(__name__=class_name)
5,313,191
def test_objectcentroids(): """Test: obtaining the object centroids""" #inputs for functions image = Image.open('../data/protein_matrix_image.png') desired_color = 'b' #processing split = preprocessing.color_split_image(image, desired_color) contrast_image = preprocessing.image_contrast(spli...
5,313,192
def inference_graph(tf_server, image, model_name): """Do inference using the tf-serve service. We have loaded the saved model into the tf-serve """ with open(image, "rb") as file: bs64_img = base64.b64encode(file.read()).decode("utf8") card_ = PredictCard(None) with timeit("tf-verving"...
5,313,193
def unlock(vault_path, key): """ Unlock legacy vault and retrieve content """ f = open(vault_path, "rb") try: nonce, tag, ciphertext = [f.read(x) for x in (16, 16, -1)] finally: f.close() # Unlock Vault with key cipher = AES.new(get_hash(key), AES.MODE_EAX, nonce) ...
5,313,194
def test_graph_call(): """Test keras.models.Graph.__call__""" nb_samples, input_dim, output_dim = 3, 10, 5 model = Graph() model.add_input('input', input_shape=(input_dim, )) model.add_node(Dense(output_dim=output_dim, input_dim=input_dim), input='input', name='output', create_out...
5,313,195
def module_build_from_modulemd(yaml): """ Create a ModuleBuild object and return. It is not written into database. Please commit by yourself if necessary. """ mmd = load_mmd(yaml) build = ModuleBuild() build.name = mmd.get_module_name() build.stream = mmd.get_stream_name() build.vers...
5,313,196
def check_end_game(game): """Set winner if game over""" if len(game['players'])-len(game['graveyard']) == 1: game['winner'] = list(set(game['players'].keys())-set(game['graveyard']))[0] elif len(game['players']) == len(game['graveyard']): game['winner'] = 'draw'
5,313,197
def GetUserPublisherData(request, callback, customData = None, extraHeaders = None): """ Retrieves the publisher-specific custom data for the user which is readable and writable by the client https://docs.microsoft.com/rest/api/playfab/client/player-data-management/getuserpublisherdata """ if not Pl...
5,313,198
def largest_rectangle_area(heights): """ return largest rectangle in histogram """ stack = [-1] max_area = 0 for i in range(len(heights)): # we are saving indexes in stack that is why we comparing last element in stack # with current height to check if last element in stack not bigger t...
5,313,199