content
stringlengths
22
815k
id
int64
0
4.91M
def test_api_team_get_me_awards_logged_in(): """Can a user get /api/v1/teams/me/awards if logged in""" app = create_ctfd(user_mode="teams") with app.app_context(): user = gen_user(app.db) team = gen_team(app.db) team.members.append(user) user.team_id = team.id app.db....
43,200
def l2_normalization( inputs, scaling=False, scale_initializer=init_ops.ones_initializer(), reuse=None, variables_collections=None, outputs_collections=None, data_format='NHWC', trainable=True, scope=None): """Implement L2 normalization on ever...
43,201
def generate_com_filter(size_u, size_v): """ generate com base conv filter """ center_u = size_u // 2 center_v = size_v // 2 _filter = np.zeros((size_v, size_u, 2)) # 0 channel is for u, 1 channel is for v for i in range(size_v): for j in range(size_u): _filter[i, j, 0] =...
43,202
def test_all_tag_subclasses_accounted_for(): """Checks that every subclass of TagInTimeseries has exactly one TagType enum value.""" subclass_tag_types = _get_subclass_tag_types(taglib.TagInTimeseries) assert set(taglib.TagType) == set(subclass_tag_types) assert len(list(taglib.TagType)) == len(subclass...
43,203
def worker_transmit(conn, func) -> None: """ Generic communication protocol: worker side Blocks until routine is terminated by dispatcher :param conn: dispatcher-worker connection, worker side :type conn: multiprocessing.connection.Connection :param func: functor with supporting evaluation by ...
43,204
def retrieve_scores_grouped_ordered_pair_by_slug(panelist_slug: str, database_connection: mysql.connector.connect ) -> List[tuple]: """Returns an list of tuples containing a score and the corresponding number of ins...
43,205
def convert_numeric_values(location): """ Convert Numeric fields to numeric data types """ if os.path.isfile(location): df = pd.read_csv(location) df['DIV'].replace('U', '0', inplace=True) df[['MAT', 'SCI', 'SST', 'ENG', 'AGG', 'DIV']] = df[ ['MAT', 'SCI', 'SST', 'ENG...
43,206
def set_rgb_color(r, g, b, a=1.0): """Define el color de dibujado RGB""" glColor4fv(get_rgb_normalized(r, g, b, a))
43,207
def set_job_id(): """Define job id for output paths. Returns: job_id: Identifier for output paths. """ job_id = FLAGS.job_id if not job_id: job_id = datetime.datetime.now().strftime('%Y%m%d-%H%M%S') return job_id
43,208
def is_owner(obj, user): """ Check if user is owner of the slice """ return obj and user in obj.owners
43,209
def boxplot_errors_wrt_RUL( results_dict: Dict[str, List[PredictionResult]], nbins: int, y_axis_label: Optional[str] = None, x_axis_label: Optional[str] = None, ax=None, **kwargs, ): """Boxplots of difference between true and predicted RUL over Cross-validated results Parameters --...
43,210
def create_client(admin_user: str, key_file: str) -> CloudChannelServiceClient: """Creates the Channel Service API client Returns: The created Channel Service API client """ # [START channel_create_client] # Set up credentials with user impersonation credentials = service_account.Credent...
43,211
def init_item(account_id, mgt_account_id, ou_id): """ Init the account and write the account to dynamodb table. """ item_exp = { 'AccountId': account_id, 'MgtId': mgt_account_id, 'OuId': ou_id } try: dynamodb_table.put_item(Item=item_exp) except Exception as e...
43,212
def fourier_map(sinogram: np.ndarray, angles: np.ndarray, intp_method: str = "cubic", count=None, max_count=None) -> np.ndarray: """2D Fourier mapping with the Fourier slice theorem Computes the inverse of the Radon transform using Fourier interpolation. Warning: This is...
43,213
def password_generator(length=12, chars=None): """ Simple, naive password generator """ if not chars: chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for _ in range(length))
43,214
def get_node_hint(node): """Return the 'capabilities:node' hint associated with the node """ capabilities = node.get('properties').get('capabilities') capabilities_dict = capabilities_to_dict(capabilities) if 'node' in capabilities_dict: return capabilities_dict['node'] return None
43,215
def execPregionsExactCP(y, w, p=2,rho='none', inst='none', conseq='none'): #EXPLICAR QUÉ ES EL P-REGIONS """P-regions model The p-regions model, devised by [Duque_Church_Middleton2009]_, clusters a set of geographic areas into p spatially contiguous regions while minimizing within cluster heterogeneit...
43,216
def generate_scale(name, octave, major=True): """ Generates a sequence of MIDI note numbers for a scale (do re mi fa sol la si do). `name` specifies the base note, `octave` specifies in which octave the scale should be, and `major` designates whether the produced scale should be major or minor. ...
43,217
def tensor_product(a, b, reshape=True): """ compute the tensor protuct of two matrices a and b if a is (n, m_a), b is (n, m_b), then the result is (n, m_a * m_b) if reshape = True. or (n, m_a, m_b) otherwise Parameters --------- a : array-like of shape (n, m_a) b :...
43,218
def test_transform_data(): """Test applying linear (time) transform to data.""" # make up some data n_sensors, n_vertices, n_times = 10, 20, 4 kernel = rng.randn(n_vertices, n_sensors) sens_data = rng.randn(n_sensors, n_times) vertices = [np.arange(n_vertices)] data = np.dot(kernel, sens_da...
43,219
def simple_object_init(self, *args, **kwargs): """ Want a simple class that has a number of attributes writable via assignment or keywords in initialization? class MySimpleClass(object): __slots__ = ['foo', 'bar'] from core.utils import simple_object_init as __init__ my_simple_obje...
43,220
def disable_user( request, username ): """ Enable/disable an user account. If the account is disabled, the user won't be able to login. """ userModel = get_user_model() try: user = userModel.objects.get( username= username ) except userModel.DoesNotExist: raise Http...
43,221
def get_next_event(user: User) -> Event | None: """ Get event that provided user has next. """ current_time = datetime.datetime.now().hour*60 + datetime.datetime.now().minute return Event.query \ .join(Event.subject, aliased=True) \ .filter(Subject.user == user, Event...
43,222
def affineToText(matrix): """ Converts a libcv matrix into human readable text """ tiltv = matrix[0,0] * matrix[1,1] rotv = (matrix[0,1] - matrix[1,0]) / 2.0 if abs(tiltv) > 1: tilt = degrees(math.acos(1.0/tiltv)) else: tilt = degrees(math.acos(tiltv)) if tilt > 90.0: tilt = tilt - 180.0 if abs(rotv) < 1...
43,223
def fill_block_config(ret, block_config, tid, group, desc_inputs, desc_bprop, expect, desc_const, const_first, add_fake_input, fake_input_type): """ Fill in block config. Args: ret (dict): The filled config. block_config (tuple): Block config. tid (str): Testin...
43,224
def main(): """ Script to scan entire archive (by managing multiple calls to ``scan_dataset.py``. """ start = datetime.datetime.now() print( "===============================") print( "Script started at: %s." %(str(start))) #Gets command line arguments. com_args = util.sanitise_args(do...
43,225
def createBridgeSets(blocksize,operating,MPSS): """Use this function to create the iidx sets for bridges.""" sets = tuple() xul = blocksize[0]-operating xdl = operating yul = int(blocksize[0]/2+operating) ydl = int(blocksize[0]/2-operating) xts = xul xbs = xdl for i in range(MPSS): ...
43,226
def get_uniq_id_with_dur(meta, deci=3): """ Return basename with offset and end time labels """ bare_uniq_id = get_uniqname_from_filepath(meta['audio_filepath']) if meta['offset'] is None and meta['duration'] is None: return bare_uniq_id if meta['offset']: offset = str(int(round(...
43,227
def delete(table, whereclause = None, **kwargs): """Return a ``DELETE`` clause element. This can also be called from a table directly via the table's ``delete()`` method. table The table to be updated. whereclause A ``ClauseElement`` describing the ``WHERE`` condition of the ``U...
43,228
def oversized_junk(): """ Return a string of random lowercase letters that is over 4096 bytes long. """ return "".join(random.choice(string.ascii_lowercase) for _ in range(4097))
43,229
def dcm_to_unrescaled(dcm_dict, save_path=None, show=True, return_resolution=False): """ just stack dcm files together :param return_resolution: :param show: :param dcm_dict: :param save_path: the save path for stacked array :return: the stacked array in float32 """ array_stacked, re...
43,230
def sai_testbed( duthost, request, ptfhost, start_sai_test_container, prepare_ptf_server): """ Pytest fixture to handle setup and cleanup for the SAI tests. """ try: __setup_dut(ptfhost, request) yield finally: __store_test_result(ptfhost) ...
43,231
def plot_posterior_pair( hddm_model=None, axes_limits="samples", # 'samples' or dict({'parameter_name': [lower bound, upper bound]}) font_scale=1.5, height=2, aspect_ratio=1, n_subsample=1000, kde_levels=50, model_ground_truth=None, save=False, save_path=None, show=True, ): ...
43,232
def change_unit_of_metrics(metrics): """Change order of metrics from bpd to nats for binarized mnist only""" if hparams.data.dataset_source == 'binarized_mnist': # Convert from bpd to nats for comparison metrics['kl_div'] = metrics['kl_div'] * jnp.log(2.) * get_effective_n_pixels() metri...
43,233
def get_ff(filename): """Get path to a file in ffxml directory """ file_path = resource_filename('mosdef_slitpore', os.path.join('ffxml', filename)) return file_path
43,234
def step(ram: dict, regs: dict, inputs: list[int]) -> tuple: """Advance robot by a single step :param ram: memory contents :param regs: register map :param inputs: input queue :return: updated pc; new color and turn direction """ pc = regs['pc'] relative_base = regs['rb'] output_val...
43,235
def replace_start(text, pattern, repl, ignore_case=False, escape=True): """Like :func:`replace` except it only replaces `text` with `repl` if `pattern` mathces the start of `text`. Args: text (str): String to replace. p...
43,236
def setup(params): """Sets up the environment that BenchmarkCNN should run in. Args: params: Params tuple, typically created by make_params or make_params_from_flags. Returns: A potentially modified params. Raises: ValueError: invalid parames combinations. """ # Set up environment variab...
43,237
def copy_excel_cell_range( src_ws: openpyxl.worksheet.worksheet.Worksheet, min_row: int = None, max_row: int = None, min_col: int = None, max_col: int = None, tgt_ws: openpyxl.worksheet.worksheet.Worksheet = None, tgt_min_row: int = 1, tgt_min_col: int = 1...
43,238
def test_function_panel_button_on(): """test the panel button function (enabling) by comparing output""" instance = printer.Dummy() instance.panel_buttons() assert instance.output == b"\x1B\x63\x35\x00"
43,239
def index(request): """Home page""" return render(request, 'index.html')
43,240
def task_progress(msg: str, *args, progress: float): """Indicate progress of some task. If this function is called after :func:`task_begin`, the task message will be updated with a progress bar. If there were other log messages between :meth:`task_begin` and call to this function, nothing will happen. ...
43,241
def get_teams_selected(request, lottery_info): """ get_teams_selected updates the teams selected by the user @param request (flask.request object): Object containing args attributes @param lottery_info (dict): Dictionary keyed by reverse standings order, with dictionary values c...
43,242
def test_process_input_multiline(capsys): """Input processing with multiple lines of data.""" pipe_r, pipe_w = os.pipe() config = chromaterm.__main__.Config() rule = chromaterm.Rule('hello world', color=chromaterm.Color('bold')) config.add_rule(rule) os.write(pipe_w, b'\nt hello world t\n' * 2...
43,243
def test_compute_cone_envelope(): """ Use cbar vectors computed manually for demand models that allow negative workload. """ # @TODO pass
43,244
def assert_fails_with(d, *exc_types, **kwargs): """Assert that ``d`` will fail with one of ``exc_types``. The normal way to use this is to return the result of ``assert_fails_with`` from your unit test. Equivalent to Twisted's ``assertFailure``. :param Deferred d: A ``Deferred`` that is expected ...
43,245
def assert_dim_coords(a, b): """check dim and coord entries and order.""" # check dim and coord size and entries for d in a.dims: assert a[d].size == b[d].size, print(a[d], "!=", b[d]) for c in a.coords: assert (a[c] == b[c]).all(), print(a[c], "!=", b[c]) # check dim and coords entr...
43,246
def temporal_affine_backward(dout, cache): """ Backward pass for temporal affine layer. Input: - dout: Upstream gradients of shape (N, T, M) - cache: Values from forward pass Returns a tuple of: - dx: Gradient of input, of shape (N, T, D) - dw: Gradient of weights, of shape (D, M) ...
43,247
def test_create_volume_image_form(volume_image_form): # NOTE: if the volume is successfully create that means the test is good """ Volume test with image Covers: vol-03-Create volume root disk VM Image Form """ pass
43,248
def _make_cmake(config_info): """This function initializes a CMake builder for building the project.""" configure_args = ["-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"] cmake_args = {} options, option_fns = _make_all_options() def _add_value(value, key): args_key, args_value = _EX_ARG_FNS[key](valu...
43,249
def box_to_delta(box, anchor): """((x1,y1) = upper left corner, (x2, y2) = lower right corner): * box center point, width, height = (x, y, w, h) * anchor center point, width, height = (x_a, y_a, w_a, h_a) * anchor = (x1=x_a-w_a/2, y1=y_a-h_a/2, x2=x_a+w_a/2, y2=y_a+h_a/2) ...
43,250
def mutual_information(prob1, prob2, prob_joint): """ Calculates mutual information between two random variables Arguments ------------------ prob1 (numpy array): The probability distribution of the first variable prob1.sum() should be 1 prob2 (numpy array): The probability distrubi...
43,251
def hog(img, num_bins, edge_num_cells=2): """ Histogram of oriented gradients :param img: image to process :param edge_num_cells: cut img into cells: 2 = 2x2, 3 = 3x3 etc. :return: """ if edge_num_cells != 2: raise NotImplementedError w, h = img.shape[:2] cut_x = w /...
43,252
def get_graph(adj) -> nx.classes.graph.Graph: """ Returns a nx graph from zero-padded adjacency matrix. @param adj: adjustency matrix [[0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [1. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [1. 0. 0. 0. 1. 1. 0. 0. 0. 0. ...
43,253
def cert_config(pth_config, config_str, pth_prepend="cert="): """ Update config file located at pth_config with a string(config_str). """ # Determine path of cert from config_str list of strings (first str containing pth_prepend) path_cert = [x.split(pth_prepend) for x in config_str if pth_prepend in x][0]...
43,254
def analysis_directed(net, label, outpath): """ Analyze directed network. """ result_dict = dict() # Check whether graph is directed is_directed = net.isDirected() if not is_directed: logging.error('Input graph should be directed.') else: logging.info('Directed graph') ...
43,255
def build_response_message(object_spec, response_message, namespace): """Function to build the response message used to inform users of policy decisions""" try: opa_response = requests.post( opa_url, json=object_spec, headers={"Content-Type": "application/json"}, ...
43,256
def findSamplesInRage(pointIds, minVal, maxVal): """根据样本编号的范围[1, 10]处理ID Args: pointIds (ndarray): 样本的ID minVal (Number): 样本范围的起始位置 maxVal (Number): 样本范围的结束位置 Returns: result (ndarray): 样本的ID """ digits = pointIds % 100 result = (digits >= minVal) & (digits <= m...
43,257
def test_results_form_average(fill_market_trade_databases): """Tests averages are calculated correctly by ResultsForm, compared to a direct calculation """ Mediator.get_volatile_cache().clear_cache() market_df, trade_df, order_df = get_sample_data() trade_df, _ = MetricSlippage().calculate_metric(...
43,258
def _prot_builder_from_seq(sequence): """ Build a protein from a template. Adapted from fragbuilder """ names = [] bonds_mol = [] pept_coords, pept_at, bonds, _, _, offset = templates_aa[sequence[0]] names.extend(pept_at) bonds_mol.extend(bonds) offsets = [0, offset] for idx,...
43,259
def test_ct_g008_ct_g008_v(mode, save_output, output_format): """ TEST :Syntax Checking for top level complexType Declaration : complexContent, content of restriction and content with group then two attributes TSTF concluded these schemas are OK in 1.0, despite violating subsumption """ asse...
43,260
def connect_thread(): """ Starts a SlaveService on a thread and connects to it. Useful for testing purposes. See :func:`rpyc.utils.factory.connect_thread` :returns: an RPyC connection exposing ``SlaveService`` """ return factory.connect_thread(SlaveService, remote_service = SlaveService)
43,261
def cleanup(): """ Delete keys in old format from the compiledir. Old clean up include key in old format: 1) keys that have an ndarray in them. Now we use a hash in the keys of the constant data. 2) key that don't have the numpy ABI version in them 3) They do not have a compile version s...
43,262
def emit_enum_info(agi): """Emit major enumerations based on stuff we collected from the graph.""" msge('emit_enum_info') # make everything uppercase nonterminals = [ s.upper() for s in agi.nonterminal_dict.keys()] operand_types = [ s.upper() for s in agi.operand_types.keys()] operand_widths = [ s...
43,263
def test_read_env_failed_set_attribute(monkeypatch, environment): """Test read env, trying to set attribute.""" spec = {"HOST": Str()} monkeypatch.setenv("HOST", "google") env = read_env(environment, spec) with pytest.raises(TypeError): env.HOST = "yahoo"
43,264
def test_11_run_migration_bad_command(): """Verify that run_migration detects a bad command""" try: os.unlink(TEST_DB_FILE) except: pass rc = pydbvolve.run_migration(TEST_CONFIG_FILE, 'BAD_COMMAND_STRING', 'r1.0.0', True, False) assert(rc != 0) # test second path (which...
43,265
def yxyx_to_albu(yxyx: np.ndarray, img_size: Tuple[PosInt, PosInt]) -> np.ndarray: """Unnormalized [ymin, xmin, ymax, xmax] to Albumentations format i.e. normalized [ymin, xmin, ymax, xmax]. """ h, w = img_size ymin, xmin, ymax, xmax = yxyx.T ymin, ymax = ymin / h, ymax / h ...
43,266
def parse_tags(source): """ extract any substring enclosed in parenthesis source should be a string normally would use something like json for this but I would like to make it easy to specify these tags and their groups manually (via text box or command line argument) http://stackoverf...
43,267
def NonZeroMin(data): """Returns the smallest non-zero value in an array. Parameters ---------- data : array-like A list, tuple or array of numbers. Returns ------- An integer or real value, depending on data's dtype. """ # 1) Convert lists and tuples into arrays if ty...
43,268
def get_99_pct_params_ln(x1: float, x2: float): """Wrapper assuming you want the 0.5%-99.5% inter-quantile range. :param x1: the lower value such that pr(X > x1) = 0.005 :param x2: the higher value such that pr(X < x2) = 0.995 """ return get_lognormal_params_from_qs(x1, x2, 0.005, 0.995)
43,269
def cli(ctx, aws_profile, verbose, config_file): """Infrastructure as Code deployment CLI""" ctx.obj = Cli(aws_profile, verbose, config_file)
43,270
def summarize_data(data): """ """ #subset desired columns data = data[['scenario', 'strategy', 'confidence', 'decile', 'cost_user']] #get the median value data = data.groupby(['scenario', 'strategy', 'confidence', 'decile'])['cost_user'].median().reset_index() data.columns = ['Scenario', ...
43,271
def test_token_pattern001_1412_token_pattern001_1412_v(mode, save_output, output_format): """ TEST :Facet Schemas for string : facet=pattern and value=[a-z]{3} and document value=abc """ assert_bindings( schema="msData/datatypes/Facets/token/token_pattern001.xsd", instance="msData/da...
43,272
def gen_cam(image, mask): """ 生成CAM图 :param image: [H,W,C],原始图像 :param mask: [H,W],范围0~1 :return: tuple(cam,heatmap) """ # mask转为heatmap heatmap = cv2.applyColorMap(np.uint8(255 * mask), cv2.COLORMAP_JET) # heatmap = np.float32(heatmap) / 255 heatmap = heatmap[..., ::-1...
43,273
def SetInputFilePath(path): """ Set input file name This function updates the file name that is stored in the database It is used by the debugger and other parts of IDA Use it when the database is moved to another location or when you use remote debugging. @param path: new input file path ...
43,274
def read_zones() -> List[str]: """Read the list of zone_names from the sys.stdin.""" zones: List[str] = [] for line in sys.stdin: line = line.strip() if not line: continue if line.startswith('#'): continue zones.append(line) return zones
43,275
def get_username(strategy, details, backend, user=None, *args, **kwargs): """Resolve valid username for use in new account""" if user: return None settings = strategy.request.settings username = perpare_username(details.get("username", "")) full_name = perpare_username(details.get("full_na...
43,276
def not_at_max_message_length(): """ Indicates if we have room left in message """ global message return message.count(SPACE) < WORD_LIMIT
43,277
def _create_jwt( user, scopes=None, expires_in=None, is_restricted=False, filters=None, aud=None, additional_claims=None, use_asymmetric_key=None, secret=None, ): """ Returns an encoded JWT (string). Arguments: user (User): User for which to generate the JWT. ...
43,278
def results(event, production, file, hash=None): """ Fetch or list the results of a production. """ if config.get("ledger", "engine") == "gitlab": _, repository = connect_gitlab() gitlab_event = gitlab.find_events(repository, subset=event) event = gitlab_event[0].event_object ...
43,279
def save_logits(path: str, logits: np.ndarray): """Save an array of logits to a file""" with open(path, "w") as fh: for example_logits in logits: fh.write(" ".join(str(logit) for logit in example_logits) + "\n") pass
43,280
def make_log_dir( _run, log_dir: str, log_level: Union[int, str], ) -> str: """Creates log directory and sets up symlink to Sacred logs. Args: log_dir: The directory to log to. log_level: The threshold of the logger. Either an integer level (10, 20, ...), a string of dig...
43,281
def ls( ctx: typer.Context, perf_type: Optional[PerfType] = typer.Option( None, help="Filter games to the selected `perf-type`" ), ): """List your games""" chessli_paths, cli_config = extract_context_info(ctx) games_reader = GamesReader(chessli_paths, cli_config) games_reader.ls()
43,282
async def handle_invalid_end_of_quoted_string_error(ctx, exc): """ Exception handler for :exc:`~discord.ext.commands.InvalidEndOfQuotedStringError`. Informs the user that closing quotation marks must be followed by nothing or a space, but not a character. """ _ = ctx.locale # NOTE: Title o...
43,283
def check_files_exist(file_list: Iterable[str]) -> list[str]: """Check if all files exist. Return False if not.""" file_errors: list[str] = [] cwd = Path(os.getcwd()) for file_ in file_list: if cwd.joinpath(file_).is_file() is False: file_errors.append(file_) return sorted(file_e...
43,284
def _fill_arc_trigonometry_array(): """ Utility function to fill the trigonometry array used by some arc* functions (arcsin, arccos, ...) Returns ------- The array filled with useful angle measures """ arc_trig_array = [ -1, math.pi / 4, # -45° math.pi / 6, # -30° ...
43,285
def get_default_tag_to_block_ctor( tag_name: str ) -> Optional[CurvatureBlockCtor]: """Returns the default curvature block constructor for the give tag name.""" global _DEFAULT_TAG_TO_BLOCK_CTOR return _DEFAULT_TAG_TO_BLOCK_CTOR.get(tag_name)
43,286
def panel_list_tarefas(context, tarefas, comp=True, aluno=True): """Renderiza uma lista de tarefas apartir de um Lista de tarefas""" tarefas_c = [] for tarefa in tarefas: tarefas_c.append((tarefa, None)) context.update({'tarefas': tarefas_c, 'comp': comp}) return context
43,287
def get_bdy_times(init_time, fcst_hours, bdy_interval): """ Returns a list of datetime objects representing the times of boundary conditions. Read the init_time, fcst_hours and bdy_interval from config and returns a list of datetime objects representing the boundary condition times. ...
43,288
def remove_stopwords(label): """ Remove stopwords from a single label. """ tokenized = label.split() # Keep removing stopwords until a word doesn't match. for i,word in enumerate(tokenized): if word not in STOPWORDS:# and len(word) > 1: return ' '.join(tokenized[i:]) # Fo...
43,289
def run_queries2(): """- What are the ten most expensive items (per unit price) in the database *and* their suppliers? 1. Côte de Blaye - Aux joyeux ecclésiastiques 2. Thüringer Rostbratwurst - Plutzer Lebensmittelgroßmärkte AG 3. Mishi Kobe Niku - Tokyo Traders ...
43,290
def single_device_training_net(data_tensors, train_net_func): """ generate training nets for multiple devices :param data_tensors: [ [batch_size, ...], [batch_size, ...], ... ] :param train_net_func: loss, display_outputs, first_device_output = train_net_func(data_tensors, default_reuse) ...
43,291
def test_WidefieldImage_DatasetID_Attributes(): """Dataset IDs are written as attributes of the widefieldImage dataset. """ # Remake the datastore dbName = testDataRoot / Path('database_test_files/myDB_WF_Metadata.h5') if dbName.exists(): remove(str(dbName)) # Load the widefi...
43,292
def get_grafana_session(config): """ Connect to grafana and get a session. We try for 60 seconds. """ session = requests.Session() tries = 30 url = get_grafana_url(config) user = config['grafana']['user'] password = config['grafana']['password'] # Wait for grafana to be ready for 60...
43,293
def ALMACopyTable(inObj, outObj, inTab, err, inVer=1, outVer=0, logfile='', check=False, debug = False): """ Copy AIPS Table Returns task error code, 0=OK, else failed * inObj = Input Object (UV or Image) * outObj = Output object * inTab = Table type, e.g. "AIPS A...
43,294
def get_commit_date(component_path, repo_name, bug_id, version): """ Get date of triggerring commit """ bug_info_path = join(component_path, DependencyAnalyzerConstants.PROJECTS_DIR, repo_name, DependencyAnalyzerConstants.BUGS_DIR, str(bug_id), DependencyAnalyzerConstants.BUG_INFO_FILEN...
43,295
def clopper_pearson(k,n,alpha): """Confidence intervals for a binomial distribution of k expected successes on n trials: http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval Parameters ---------- k : array_like number of successes n : array_like number of trials ...
43,296
def add_link(news_list:list) -> list: """ Description: Function to remove the readmore and the add the url as a marked up link for the 'content' key in the 'articles' dictionary. Arguments: news_list {list} : list containing the news articles dictionaries Returns: news_list ...
43,297
def taitnumber(c): """ Return Tait number from signed edge list of Tait graph. """ c = array(c) # If type(c) != ndarray tau = sum(sign(c[:, 0])) return tau
43,298
def _difference_map(image, color_axis): """Difference map of the image. Approximate derivatives of the function image[c, :, :] (e.g. PyTorch) or image[:, :, c] (e.g. Keras). dfdx, dfdy = difference_map(image) In: image: numpy.ndarray of shape C x h x w or h x w x C, with C = 1 or C = 3 ...
43,299