content
stringlengths
22
815k
id
int64
0
4.91M
def export_grid(gdf, file): """This function produces a shapefile with the shapes contained in the specified GeoDataFrame :param gdf: A GeoDataFrame with the polygons of the grid :param file: The filename or path where the shapefile should be saved (including the `.shp` extension) """ print...
54,400
def parse_args(): """ Parse the command line arguments and return an object representing the command line (as returned by argparse's parse_args()). Returns ------- The commandline argparse namespace. """ parser = argparse.ArgumentParser(description='Utility for listing or ' ...
54,401
def test_flag_robots(app, mock_user_ctx, request_headers, objects): """Test flag_robots preprocessor.""" def build_event(headers): with app.test_request_context(headers=headers): event = file_download_event_builder({}, app, objects[0]) return flag_robots(event) assert build_even...
54,402
def scan(graph, connectionInfo, logger, thread): """ Get all VMs that exist on a xen server. Necessary values in the configuration file of this collector module: - timeout Timeout this collector module shall use (Integer) - xenuri The URI opf the Xen server - xenuser The user...
54,403
def health_indicators_warehouse(): """ Grab everything from the health indicator warehouse tagged Obesity. """ print '~~~~ Fetching master dataset list from Indicator "Warehouse" ~~~~' content = urllib.urlopen(HEALTHINDICATORS_URL).read() base_dom = fromstring(content) base_dom.make_links_ab...
54,404
def plot_mean_and_CI(axes, mean, lb, ub, label, freqs, linestyle='-'): """ Plot mean and confidence boundaries. Args: axes: plt.axes mean: np.ndarray lb: np.ndarray ub: np.ndarray label: string freqs: list linestyle: string Returns: plt.axes ...
54,405
def messages(request): """ Display some messages """ adjax.success(request, "This is your first success") adjax.info(request, "This is your first info") adjax.warning(request, "This is your first warning") adjax.error(request, "This is your first error") adjax.debug(request, "This is your first ...
54,406
def test_provider(horse, provider): """All Horse objects should contain a reference to the provider instance from which they were sourced""" assert horse.provider == provider
54,407
def locked(acquire, release): """Decorator taking two methods to acquire/release a lock as argument, returning a decorator function which will call the inner method after having called acquire(self) et will call release(self) afterwards. """ def decorator(f): def wrapper(self, *args, **kwarg...
54,408
def test_update_local(mock_cache): """ Tests the ``update``-function on the minion's local cache. Updates mine functions from pillar+config only. """ kernel_ret = "Linux!" foo_ret = "baz" ip_ret = "2001:db8::1:3" config_mine_functions = { "ip_addr": {"mine_function": "network.ip_...
54,409
def app_checkout_entry_info(source, sn): """app支付info接口 deprecated之前只有lvye_skiing接入 """ from api_x.zyt.evas.payment.config import PaymentScene return redirect(config.HOST_URL + url_for('biz_entry.pay_info', sn=sn, payment_scene=PaymentScene.lvye_skiing))
54,410
def linreg(X, Y): """ Summary Linear regression of y = ax + b Usage real, real, real = linreg(list, list) Returns coefficients to the regression line "y=ax+b" from x[] and y[], and R^2 Value """ if len(X) != len(Y): raise ValueError("unequal length") N = len(...
54,411
def _handle_row_wise_sharding_sharded_tensor( input, world_size, weight, local_shard_t, bias, pg ): """ Entry-point function to handle the logic of row-wise sharding of weight for Linear when the input is a sharded tensor. (Detailed explanations of the logic can be found in the comment for sharded_l...
54,412
def put_tags(new_tag_list, cgx_dict): """ This function looks at a CloudGenix config object, and puts tags. :param new_tag_list: List of tags to add if not already present. :param cgx_dict: CloudGenix config dict, expects "tags" keys supported in root. :return: CloudGenix config dict with added tags...
54,413
def perturb_actions(states, actions, perturbations, limits=None): """Create state-action pairs by perturbing the actions. Parameters ---------- states : ndarray An (N x n) array of states at which we want to generate state-action pairs. actions : ndarray An (N x m) array of ...
54,414
def create_histogram(data, figure_path, range_min=-70, range_max=20, step=10, xlabel='Power [dB]'): """Create histogram Parameters ---------- data : list, List of several data sequences figure_path : str, Filepath to be output figure range_min : int, optional...
54,415
def median(image_set, size=None): """ Applies a median filter to the image set. This function is a wrapper around scipy.ndimage.filters.median_filter """ if size is None: print('Please set a filter size. Defaulting to size = 3.') size = 3 print('Applying median filte...
54,416
def conditional_demographic_parity_ratio(labels, pred, attr, groups): """ Calculate conditional demographic parity by calculating the average demographic parity ratio across bins defined by `groups`. """ ratios = [] for group in set(groups): mask = groups == group ratios.append...
54,417
def get_all_files(path: Path, recursion=True): """ 获取指定目录下的所有文件 path: 路径 recursion: 是否递归遍历子文件夹 """ for f in path.iterdir(): if f.is_file(): yield f else: # f.is_dir() == True yield from get_all_files(f, recursion=recursion)
54,418
def calculate_ddx_G2(neighborindices, neighborpositions, eta, Rc, Rs, i, m, l): """ Calculates coordinate derivative of G2 symmetry function for atom at index i and position Ri with respect to coordinate x_{l} of atom index m. Parameters --------- neighborindices : list of int List ...
54,419
def _correct_module_lettercase(module: str): """ 修正模块的大小写. 示例: 'qtquick-window' -> 'QtQuick.Window' 'qtgraphicaleffects' -> 'QtGraphicalEffects 注意: 存在一些特殊情况: 'qt-labs-animation' -> 'Qt.labs.animation' 思路: 1. 我们需要把模块的名字按照词来拆分: 'qtgraphicaleff...
54,420
def normalize(x, axis=None, degree = 2, avoid_nans = False): """ Normalize array x. :param x: An array :param axis: Which axis to normalize along :param degree: Degree of normalization (1 for L1-norm, 2 for L2-norm, etc) :param avoid_nans: If, along an axis, there is a norm of zero, then normali...
54,421
def get_default_curriculum_env_config(method, env_config=None): """Get default curriculum env config. Args: method: The method used in curriculum learning. env_config: Optional. The env config. If None, use the default env config file. Default, None. Returns: A curriculum env config. """ i...
54,422
def _get_libc(): """Load the lib-C for unix systems.""" libc = _system_libraries.get("libc") if libc is None: libc_name = find_library("c") if libc_name is None: # pragma: no cover return None libc = ctypes.CDLL(libc_name, mode=_RTLD_NOLOAD) _system_libraries["li...
54,423
def test_update(cursor): """verify update""" test = MockTable(the_key=10, name='a', yeah='a') test.name = 'test' test.yeah = 'lala' run_async(test.save, cursor) assert cursor.query == \ "UPDATE 'tester' SET 'name'=%s,'yeah'=%s WHERE 'the_key'=%s" assert cursor.query_after == \ ...
54,424
async def read(ctx): """取 k 线数据 Args: ctx: channel: okex 频道名, 如 'swap/candle60s' {'instrument_id': 'BTC-USD-SWAP','n':100} n 可选参数,取最新的 n 条 k 线数据 返回:最新的 n 条 k 线数据列表。 subscribe 'okex/name/swap/candle60s' 可以在有新 k 线时得到通知,通知内容为最新 k 线的 timestamp,表示这个 timestamp 之前的 k 线已经确定,可...
54,425
def try_multiple_dec_s3(func): """An S3 specific adapter to @try_multiple_dec To decorate func to try multiple times after some sleep upon encountering some intermittent error from S3 """ return try_multiple_dec( ntrials=4, duration=2., increment_type...
54,426
def tolerance(*args, **kwargs): """ This command sets tolerances used by modelling operations that require a tolerance, such as surface fillet. Linear tolerance is also known as positionaltolerance. Angular tolerance is also known as tangentialtolerance. In query mode, return type is based on queried fl...
54,427
def standardize_education_level(education_column): """This function aims at standardizing the education level. The column has mixed types (ints and categories, with overlapping categories). Args: education_column (pd.Series): column in which we will replace the identified matching values. ...
54,428
def test_ass_event_list_append_reindex() -> None: """Test that event insertion populates the event.index property.""" event1 = AssEvent() event2 = AssEvent() events = AssEventList() events.append(event2) events.insert(0, event1) assert event1.index == 0 assert event2.index == 1 asser...
54,429
def main(argv): """Creates an operator group for the operator CSV if the CSV does not support AllNamespaces.""" op_group_file = None op_name = None csv_file = None namespace = None namespace2 = None installmode = None try: opts, args = getopt.getopt(argv, "g:o:v:n:a:i:", ["opgr...
54,430
def neutral_key_state(game: Game): """ Logic to execute when no relevant key is pressed. Returns updated neutral_count """ player = game.player previous_orientation = player.orientation if player.is_moving_up(): player.reset_speed() player.orientation = DIRECTIONS.get(0) game.sc...
54,431
def _to_bel_lines_footer(graph): """Iterate the lines of a BEL graph's corresponding BEL script's footer. :param pybel.BELGraph graph: A BEL graph :rtype: iter[str] """ unqualified_edges_to_serialize = [ (u, v, d) for u, v, d in graph.edges(data=True) if d[RELATION] in UNQUA...
54,432
def reshape_from_matrix(output_tensor, orig_shape_list): """Reshapes a rank 2 tensor back to its original rank >= 2 tensor.""" if len(orig_shape_list) == 2: return output_tensor output_shape = get_shape_list(output_tensor) # output_shape = tf.shape(output_tensor) orig_dims = orig_shape_list[0:-1] widt...
54,433
def git_change_audit(event: KubernetesAnyChangeEvent, action_params: GitAuditParams): """ Audit Kubernetes resources from the cluster to Git as yaml files (cluster/namespace/resources hierarchy). Monitor resource changes and save it to a dedicated Git repository. Using this audit repository, you can ea...
54,434
def compute_unconstrained_optimization_weights(cov, mean, market_return, rfr, market_var, l=None): """ """ # risk aversion if l is None: l = (market_return - rfr) / market_var return np.dot(np.linalg.inv(l*cov), mean)
54,435
def get_coordinates_partition_path(coordinates_dir: str, partition_type: utils.PartitionType) -> str: """Gets the path to the coordinates for the provided partition file. Args: coordinates_dir: A directory containing coordinates files. partition_type: A p...
54,436
def setup_animation(tracks, step_interval): """ Set up data structures and a matplotlib FuncAnimation instance for animating a list of track DataFrames. :param tracks: list of track DataFrames :param step_interval: step interval for animation (e.g., '15S') :return: FuncAnimation instance """...
54,437
def eval_standard(ner_model, examples, label=None): """ Evaluates the model using the standard evaluation metrics If label parameter is not defined, the scores will be calculated for the whole document, otherwise it will calculate the scores for the selected label only Parametres ----------...
54,438
def test_controller_given_init_positions(model_img, model, net_input): """ :param model_img: directory for the output image of the model :param model: index of the model :param net_input: input of the network (between: prox_values, prox_comm and all_sensors) """ from generate_simulation_data im...
54,439
def calc_E_G_C_hs_d_t(): """冷房設備機器のガス消費量(MJ/h)(23b)を計算する Args: Returns: ndarray: 冷房設備機器のガス消費量(MJ/h) """ return calc_E_G_C_hs_MR_d_t() + calc_E_G_C_hs_OR_d_t()
54,440
def Keplerian1D_neg(x, mass=1., v0=0., r0=0.): """Computes the keplerian velocity at requested distances. Args: x (array_like): Distances to the central object. mass (float, optional): Mass of the central object. v0 (float, optional): Velocity offset ...
54,441
def process_modules_csv(drcty): """ Separate out MFG from model and append these columns to base data frame """ dp = os.path.join(os.getcwd(), drcty) fp = os.path.join(dp, 'CEC Modules.csv') df = pd.read_csv(fp, index_col=0, skiprows=[1,2]) names = list(df.index.values) mfgs = list() ...
54,442
def create_sample_table(word_count): """ Create negative sample table for vocabulary, words with higher frequency will have higher occurrences in table. """ table = [] frequency = np.power(np.array(word_count), 0.75) sum_frequency = sum(frequency) ratio = frequency / sum_frequency co...
54,443
def stringify_body(request_params): """Json dump the data to string if not already in string """ data = request_params.get('data') if data and not isinstance(data, (str, unicode)): # datetime is not json serializable, use str() if isinstance(data, (datetime,)): request_params...
54,444
def create_supervised_evaluator( model: nn.Module, metrics: Dict, device, dtype, output_transform=lambda x, y, y_pred: (y_pred, y,)): """ Factory function for creating an evaluator for supervised models. Args: model (`torch.nn.Module`): the model to train. metrics (dict of str - :cl...
54,445
def post(activity: dict, collection_id=None, **kwargs): """Celery task to deal with data post processing.""" execution = execution_from_collection(activity, collection_id=collection_id, activity_type=post.__name__) collection = execution.activity.collection scene_id = activity['sceneid'] logging....
54,446
def test_md030_bad_configuration_ol_single(): """ Test to verify that a configuration error is thrown when supplying the ol_single value with a string that is not an integer. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md030.ol_single=n...
54,447
def feed_forward_cnn_small_categorical_fun(action_space, config, observations): """Small cnn network with categorical output.""" obs_shape = common_layers.shape_list(observations) x = tf.reshape(observations, [-1] + obs_shape[2:]) with tf.variable_scope("network_parameters"): dropout = getattr(config, "drop...
54,448
def check_next_in_request(request): """ Проверяет наличие слова 'next' в объекте запроса request методе POST :param request: :return: """ return True if 'next' in request.POST else False
54,449
def save_range_map_meta(): """ Download the meta data (CSV table) for the range maps. This file lets us know the URLs of the raster map images. More info: https://cornelllabofornithology.github.io/ebirdst/index.html Click "Introduction - Data Access and Structure" for info on the data. """ ...
54,450
def test_dijkstra_with_empty_graph_raises_error(empty_weight_graph): """Test that ValueError raised if dijkstra used on empty graph.""" with pytest.raises(ValueError): empty_weight_graph.dijkstra_min(4, 19)
54,451
def build_data_pipeline( chain: List[Callable], kwargs: DataFuncKwargs, args_mut: DataFuncArgsMut ): """ Higher order function :param chain: array of callable :param **kwargs: any kwargs you like """ for call in chain: # note: returned kwargs are not utilized to guarantee immutabilit...
54,452
def tokenize_by_word(text, deacc): """Tokenize input text. Before tokenizing transforms text to lower case and removes accentuation and acronyms set :const:`~gensim.summarization.textcleaner.AB_ACRONYM_LETTERS`. Parameters ---------- text : str Given text. Returns ------- gener...
54,453
def stub_replace(mod_name): """Replace a module from the SDK/Rutime. Replaces it with a stub provided in ``stubs/``. Used for * ``subprocess``: Needed by concurrency primitives. We don't actually use these primitives in most of our libraries, but we do use the interface. * ``_multip...
54,454
def _iterate_property_value( text: str, include: Optional[Sequence[str]] = None, exclude: Optional[Sequence[str]] = () ) -> Iterator[Tuple[str, str]]: """Returns a series of (key, value) tuples from a k = v string.""" # Normalize spaces around equal sign so that the negative lookahead works text...
54,455
def overlap_slices(large_array_shape, small_array_shape, position): """ Modified version of `~astropy.nddata.utils.overlap_slices`. Get slices for the overlapping part of a small and a large array. Given a certain position of the center of the small array, with respect to the large array, tuples o...
54,456
def mrr(scores: torch.Tensor) -> np.float: """ Tested | Accepts one (n,) tensor """ ranks = (torch.argsort(scores, dim=0) == 0).nonzero()[0] recirank = 1.0 / (ranks + 1).float() return recirank.detach().cpu().numpy().item()
54,457
def write_to_raveler(sps, sp_to_segment, segment_to_body, directory, gray=None, raveler_dir='/usr/local/raveler-hdf', nproc_contours=16, body_annot=None): """Output a segmentation to Raveler format. Arguments: - sps: the superpixel map (nplanes * nx * ny numpy n...
54,458
def rotmat(x, origin=(0, 0, 0), upvector=(0, 0, 1)): """ Given a position vector x, find the rotation matrix to r,h,v coordinates. """ x = numpy.asarray(x) - numpy.asarray(origin) nr = x / numpy.sqrt((x * x).sum()) nh = numpy.cross(upvector, nr) if all(nh == 0.0): nh = numpy.cross((1...
54,459
def curry(func): """Curry a function, but keep the docstring Args: func: a function to curry Returns: a curried function >>> def add(a, b): ... '''Add stuff''' ... return a + b >>> curry(add)(1)(2) 3 >>> print(curry(add).__doc__) Add stuff """ retur...
54,460
def score_func(house_data, venue_data): """Function for calculating location-based score of a house. Function gets a house and venues within 1 km radius of that house, calculates each venue's influential score on that house with dividing venue's check-in count with the distance. With that division,...
54,461
def bold(s): """Return the string bold. Source: http://stackoverflow.com/a/16264094/2570866 :param s: :type s: str :return: :rtype: str """ return r'\textbf{' + s + '}'
54,462
def train( n_layer, init_scale=1, scale_upper_bound=128, accum_upper_bound=4096, method="approx_range", update_per_n_iteration=1, warmup_attr_ratio=None, warmup_n_epoch=None, n_class=10, manual_seed=0, train_batch=128, device=-1, learnrate=0.1, ): """ Train functi...
54,463
def print_item(group): """Print an Azure object instance.""" print("\tName: {}".format(group.name)) print("\tId: {}".format(group.id)) print("\tLocation: {}".format(group.location)) print("\tTags: {}".format(group.tags)) if hasattr(group, 'properties'): print_properties(group.properties)
54,464
def verify_access_key(key): """ Confirm that the access key is valid. :param str key: Access key string. """ try: access_key = models.AccessKey.objects.get(key=key) except models.AccessKey.DoesNotExist: return None return access_key
54,465
def send_sns_message(sns_client, payload, sns_topic_arn): """Publishes the message to sns. Arguments: sns_client (client): The boto3 client for SQS payload (dict): the payload to post to SNS sns_topic_arn (string): the arn for the SNS topic """ dumped_payload = get_escaped_json...
54,466
def plot_zone_income_histogram(calculate = True, save_path = 'Figures/Zoning/income_housing_typology.svg', cache_path = 'shared_data/calculations/zoning_income_data.csv'): """ Plots the distribution of incomes conditional on broad zones in Austin and D...
54,467
def filter_first_altloc(atoms, altloc_ids): """ Filter all atoms, that have the first *altloc* ID appearing in a residue. Structure files (PDB, PDBx, MMTF) allow for duplicate atom records, in case a residue is found in multiple alternate locations (*altloc*). This function is used to r...
54,468
def test_config(mocker, plugin_no_server, qtbot): """Test that config page can be created and shown.""" dlg = ConfigDialog() page = NotebookConfigPage(plugin_no_server, parent=plugin_no_server) page.initialize() dlg.add_page(page) dlg.show() qtbot.addWidget(dlg) # no assert, just check t...
54,469
def dlqr(A, B, Q, R, optimal_cost_function=False): """Solves for the optimal lqr controller. x(n+1) = A * x(n) + B * u(n) J = sum(0, inf, x.T * Q * x + u.T * R * u) """ # P = (A.T * P * A) - (A.T * P * B * numpy.linalg.inv(R + B.T * P *B) * (A.T * P.T * B).T + Q # 0.5 * X.T * P * X -> optimal co...
54,470
def test_get_integration_instance_local_error(get_integration): """ .get_by_internal_integration() should fail for local integrations """ local_integration = get_integration(is_local=True) assert models.Application.objects.count() == 0 with pytest.raises(ValueError): models.Application.o...
54,471
def add_single_scale_rpn_losses(model): """Add losses for a single scale RPN model (i.e., no FPN).""" # Spatially narrow the full-sized RPN label arrays to match the feature map # shape model.net.SpatialNarrowAs( ['rpn_labels_int32_wide', 'rpn_cls_logits'], 'rpn_labels_int32' ) if cfg.T...
54,472
def htons(*args,**kw): """htons(integer) -> integer Convert a 16-bit integer from host to network byte order.""" pass
54,473
def product(data): """ Generate the product for the entries specified by the data. """ return "tRNA-{aa} ({anticodon})".format( aa=data["metadata"]["isotype"], anticodon=data["metadata"]["anticodon"], )
54,474
def _pad_image(image, factor=2): """Enlarges the image canvas, filling new pixels with colors at the edge. :param image: An RGB image :param factor: A scalar representing the factor in which the canvas is to be enlarged. A factor of 2 will double the canvas, a factor of 1 will keep it ...
54,475
def change_multi_asset_mode(self, multiAssetsMargin: str, **kwargs): """ | | **Change Multi-Assets Mode (TRADE)** | *Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on Every symbol* :API endpoint: ``POST /fapi/v1/multiAssetsMargin`` :API doc: https://binance-docs.github...
54,476
def get_image_data(docx_file_path, image_name): """ Return base 64 encoded data for the image_name that is stored in the docx_file_path. """ with ZipFile(docx_file_path) as f: images = [ e for e in f.infolist() if e.filename == 'word/media/%s' % image_name ] ...
54,477
def export_menu(self, context): """ This function creates the export menu item. This will be referenced in other functions as a means of appending and removing it's contents from the top bar editor class definition. :param object self: This refers the the Menu class definition that this function wi...
54,478
async def get_a_user(user_id): """ Get a single user --- /api/users/{user_id}: get: summary: Buscar um usuário pelo ID security: - APIKeyHeader: [] tags: - User parameters: - in: path name: user_id required: true schema: ...
54,479
def extract_string_from_tensor(input_ids: Tensor, mode="single",config = None, tokenizer = None): """ Args: input_ids(Tensor): input tensor of sequence index. Shape: (self.batchsize,self.seq_length) mode(str): "pair","single"and "CBT", "pair" for tasks with paired inputs, such ...
54,480
async def create_deliverer_keyboard( customer_tg_id, button_text: str, callback_action: str, ) -> InlineKeyboardMarkup: """Creates a keyboard for delivery man.""" keyboard = [ [ InlineKeyboardButton( text=button_text, callback_data=f'{callback_acti...
54,481
def add_docker(): """ Create volume mappings for `docker`, `nvidia-docker` if present and the various components like the unitx socket for docker in the container to communicate back to the host. """ pass # can i query docker for the location of the docker for the location of the # socke...
54,482
def add_weeks(self): """Check the addWeeks function with DateTime64 extended range.""" add_subtract_functions( clh_func="addWeeks", py_key="days", test_range=range(6), years_padding=(0, 1), modifier=7, )
54,483
def run_homecontrol(config: dict, config_file: str, start_args: dict): """ Runs HomeControl config: dict The loaded config file config_file: str Path to the config file start_args: dict The commandline arguments by ArgumentParser """ loop = asyncio.get_event_loop() ...
54,484
def get_trial_id(): """Trial id for the corresponding trial of this Trainable. For function API use only. Do not call this method in the Class API. Use `self.trial_id` instead. """ _session = get_session() return _session.trial_id
54,485
def import_maxquant_data( file: str, sample: Union[str, list, None] = None ) -> pd.DataFrame: """Import peptide level data from MaxQuant. Args: file (str): The name of a file. sample (Union[str, list, None]): The unique raw file name(s) to filter the original file. Defaults to None. In ...
54,486
def cuda_step_euler(last, dt, drift, volatility, noise, res): """ Approximate SDE in one time step with Euler scheme with cuda u-funcs""" for i in range(last.shape[0]): res[i] = last[i] res[i] += drift[i] * dt for j in range(volatility.shape[1]): res[i] += volatility[i, j] ...
54,487
def glTexCoord3fv( v): """ v - seq( GLfloat, 3) """ if 3 != len( v): raise TypeError( len( v), "3-array expected") _gllib.glTexCoord3fv( v)
54,488
def get_z_from_freq(obs_freq): """ Convert observed frequency to (measured) redshift Parameters ========== obs_freq: float Observation (central) frequency in units of Hz ! Return ====== z: float Measured redshift """ z = ( _HI_RESTFREQ / obs_freq ) - 1. return ...
54,489
def R_to_orientstring(R): #************************ """ Purpose: Convert transformation matrix to 3-character string defining orientation (e.g., RAI, LPI etc) Arguments: R: 4x4 transformation matrix Returns: orientation: A 3-character string. """ #LPI orient_decode =...
54,490
def get_executor(): """ Gets executor from the current event thread if applicable. If not, starts a new one. Returns ------- executor : ``ExecutorThread`` or ``ClaimedExecutor`` """ loop = current_thread() if isinstance(loop, EventThread): executor = loop.claim_executor() ...
54,491
def shape4(tik_instance, input_x, res, dtype): """input shape (32, 8, 28, 28, 16)""" zero = tik_instance.Scalar(dtype="float16", init_value=0) with tik_instance.for_range(0, 32, block_num=32) as block_idx, tik_instance.for_range(0, 2) as cc1_db, \ tik_instance.for_range(0, 2, thread_num=2) as db...
54,492
def parse_person(elt): """Parse a person type response element into nested dictionaries http://developer.healthvault.com/sdk/docs/urn.com.microsoft.wc.thing.types.person.1.html """ return dict( name = elt.find('name').text, organization = text_or_none(elt, 'organization'), profe...
54,493
def main(): """ >>> get_context() {'name': 'demo', 'app_id': 2} >>> get_context2() {'name': 'demo', 'app_id': 6s} """ pass
54,494
def main(): """Main body for script.""" parser = ArgumentParser(description="Update FCOE device udev persisted " "ordering.") parser.add_argument("--prefix", "-p", default="/target", help="System files will be accessed under this " ...
54,495
def to_absolute_coordinates(keypoints, height, width, check_range=True, scope=None): """Converts normalized keypoint coordinates to absolute pixel coordinates. This function raises an assertion failed error when the maximum keypoint coordinate value is larger than 1.01 (in which case ...
54,496
def get_zygosity(call): """Check if a variant position qualifies as a variant 0,1,2,3==HOM_REF, HET, UNKNOWN, HOM_ALT""" zygdict = dict([(0, "nocall"), (1, "het"), (2, "nocall"), (3, "hom")]) return zygdict[call]
54,497
def discrete_mutual_info(mus, ys): """Compute discrete mutual information.""" num_codes = mus.shape[0] num_factors = ys.shape[0] print(mus.shape,ys.shape) m = np.zeros([num_codes, num_factors]) for i in range(num_codes): for j in range(num_factors): m[i, j] = sklearn.metrics.mutual_info_score(ys[j...
54,498
def get_stderr(self, uid, iwd, out, err, job_id, job_name=None, instance_id=-1): """ Return the stdout from the specified job """ if instance_id > -1: if os.path.isfile('%s/job.%d.err' % (iwd, instance_id)): with open('%s/job.%d.err' % (iwd, instance_id), 'rb') as fd: ...
54,499