content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def S_inverse_values(_data_list, _infinity_value='inf'): """ Returns data samples where values are inversely proporsional. """ i_data = [] ds = len(_data_list) for i in range(ds): if _data_list[i] == 0: i_data.append(_infinity_value) if _data_list[i] == _infinity...
97a140b1cb3649c7036758eaaeb7c21bcc8da06d
81,571
def forward_propagate(x, w1, b1, w2, b2): """ 构建三层神经网络 -- 前向传播 """ """ x.shape = (m,n1) y.shape = (m, n3) w1.shape = (n, n2) b1.shape = (1, n2) w2.shape = (n2, n3) b2.shape = (1, n3) """ z_1 = np.dot(x, w1) + b1 a_1 = sigmoid(z_1) z_2 = np.dot(a_1, w2) + b...
bc5ce85fa622021a2026c5426c6a27735133125b
81,572
def dsp(typenames=None,name1=None,name2=None,templates=None): """Delete special points. Type FUNC(x,list) to delete the special points in list from the Python object x, which must be a solution list or a bifurcation diagram. Type FUNC(list,'xxx') to delete from the data-files b.xxx, and s.xxx. Type...
e48196952f257b297d6914bfb12d5f3ac917242f
81,573
def map_flat_chunked(f, values, *, limit=1<<29): """ Apply the function f to chunked, flattened, concatenated values, then split and reshape back to original shapes. """ values = tuple(values) for v in values: assert not isinstance(v, tf.IndexedSlices) values = [tf.convert_to_tensor(v) f...
cfb27fa8a337966fc384ec45bf49ef0c730c973e
81,574
def execute_steps(data_type, runtype, data_repository, step_list, tc_junit_object, iter_ts_sys): """executes steps based on given data_type and runtype""" tc_status = True if data_type.upper() == 'CUSTOM' and \ runtype.upper() == 'SEQUENTIAL_KEYWORDS': tc_status = execute_custom(data_typ...
dc5cd2493584bc5c96467f24699ffec4d43afc93
81,575
def findPayload(message, type): """ Find a payload/part that matches a type as closely as possible and decode it properly. Parameters ---------- message : email.message.Message The message to search. type : str A MIME type. Returns ------- str The payload as a string. """ charset =...
265159546f1b0d2a6cc065e2c467528ea74048ef
81,576
def get_from_convergence(J, domain, nof_coefficients, disc_type='sp_quad', interval_type='log', mapping_type='sp_hes', permute=None, residual=True, low_memory=True, stable=False, min_ncap=10, max_ncap=2000, step_ncap=1, stop_rel=1e-10, stop_abs=...
1c72eac980700b0c263ba631b4dbf4ac03c332ca
81,578
import csv def calculate_number_of_synthetic_data_to_mix(original_data_file, target_ratio): """Calculate the number of negative samples that need to be added to achieve the target ratio of negative samples. Args: original_data_file: path to the origi...
eb83cdbb9af39715f16e412f8ae799222a2a232f
81,580
def label_genres(row): """For each segment in `genres_mean`, labels the apps that cost less than its segment's mean with `1` and the others with `0`.""" aff = row["affordability"] gc = row["genre_count"] price = row["Price"] if price < genres_mean.loc[(aff, gc)][0]: return 1 el...
afedf4c591370ab4cb105a0b7bbdaef57e27b930
81,581
import html def card(target, responses, score): """Summary card component""" kpi_color = get_color_from_score(score) return dbc.Card( [ dbc.CardBody( [ html.Img(src=f"assets/img/{target.image}", className="card-img"), html.H4(targ...
8d77115ab396d48afe34183bf601d57ab56596c3
81,582
import tqdm from typing import Iterable def eval_bootstrap_rdm(model, data, theta=None, method='cosine', N=1000, rdm_descriptor='index', boot_noise_ceil=True): """evaluates a model on data performs bootstrapping to get a sampling distribution Args: model(pyrsa.model.Model):...
b46c71188dea0416fec5a376188c438eb6432230
81,583
def is_empty(self) -> ObservableBase: """Determines whether an observable sequence is empty. Returns an observable {Observable} sequence containing a single element determining whether the source sequence is empty. """ return self.some().map(lambda b: not b)
20c18aec3a4020a17e759aa733fe5e1b6aba9a10
81,584
def crawler_dou_ban(): """ 豆瓣讨论精选 :return: """ url = 'https://www.douban.com/group/explore' headers = { 'Host': 'www.douban.com', 'Referer': 'https://www.douban.com/group/explore' } response_html = get_text(url, options=headers) content_list = [] if response_html:...
e49c5190b12a8b7beaa6b0979b9a2ec12c9e88b5
81,585
def _spark_col_apply(col_or_df, sfun): """ Performs a function to all cells on a dataframe, the function being a known sql function. """ if isinstance(col_or_df, Column): return sfun(col_or_df) assert isinstance(col_or_df, DataFrame) df = col_or_df df = df._spark_select([sfun(df[col]...
317587fff888af117b4426fea656a886294fed0b
81,586
from typing import Any from typing import List from typing import Dict import requests def get_data(url: str, /, **kwargs: Any) -> List[Dict[str, Any]]: """ Extract data from URL. Parameters ---------- url : str URL where to send the request to. **kwargs : Any ...
3200e020c05df822183011c116e8f25a7643e9f3
81,587
def _get_valid_number(section, option, provided): """Validates an int type configuration option. Returns None by default if the option is unset. """ if provided is None: return None try: return int(provided) except ValueError: error = "Value provided for '{0}: {1}' is...
533934aa48693ec53b30c4069804431095c4d717
81,588
from re import T def is_line_comment(token): """ ラインコメント判定 """ if is_comment(token): comment = token.token_next_by_type(0, T.Comment) return comment.value not in ["/*", "*/"] return False
8786ec5cd1f881509ed8a065f164c683c6dfdc04
81,589
def get_view_name(stack): """Determine view name from leftover stack of path segments :param stack: a list of path segments left over after consuming the path. :return: view name string or ``None`` if no view name can be determined. """ unconsumed_amount = len(stack) if unconsumed_amount ...
65e0878689a08a07d14db1976c460f5b598f2919
81,590
def granulation(time, sigma, tau): """ Create granulation time series Usage: time - array: time stamps sigma - float: rms amplitude (ppm) tau - float: characteristic timescale (s) Author: grd349 Edited by jsk389 """ # Compute cadence from time series - assuming regular sampl...
8f9a12679e70bb5c1c340eb6a7f8f8a303a880b1
81,591
import time def get_public_ip(instance_id:str=None) -> str: """ A function to get public IP for an instance :param instance_id: instance id """ ec2_client = boto3.client("ec2", region_name="ap-south-1") reservations = ec2_client.describe_instances(InstanceIds=[instance_id]).get("Reservations")...
a58d4a8291c403baab8566ecb3dcdec6de129b5b
81,592
def e_x_lda_unpolarized(rho): """Evaluates LDA exchange energy density for spin unpolarized case. Parr & Yang Density-functional theory of atoms and molecules Eq. 6.1.20. Args: rho: Float numpy array with shape (num_grids,), the electron density. Returns: Float numpy array with shape (num_grids,), th...
f95f0f711dc334f66400c7b676b0c77f9e2bdb9a
81,594
def get_policy_document(override_json=None, policy_id=None, source_json=None, statements=None): """ Generates an IAM policy document in JSON format. This is a data source which can be used to construct a JSON representation of an IAM policy document, for use with resources which expect policy docum...
e6001db84deeabbb7868a7a0b627f454e84962fc
81,595
import torch from typing import Union def allclose(mat1: torch.Tensor, mat2: Union[torch.Tensor, float], tol=_EPS): """Check if all elements of two tensors are close within some tolerance. Either tensor can be replaced by a scalar. Note: This is similar to torch.allclose(), but considers just th...
208367c6f38d1c4a923bfa4d324e7de0eff4a786
81,596
def my_lcs(string, sub): """ Calculates longest common subsequence for a pair of tokenized strings :param string : list of str : tokens from a string split using whitespace :param sub : list of str : shorter string, also split using whitespace :returns: length (list of int): length of the longest co...
f81ad39b7eb5e80847d22f1f6643021c1bcd3dd2
81,597
def gausslin_logL(xi, A=0.5, sigma=1.0, mu=5.0, L=10.0): """Equation 5.80: gaussian likelihood with uniform background""" xi = np.asarray(xi) shape = np.broadcast(sigma, A, mu, L).shape xi = xi.reshape(xi.shape + tuple([1 for s in shape])) return np.sum(np.log(A * np.exp(-0.5 * ((xi - mu) / sigma...
269b31c2a664f22e6a68eaec4b1c85db4d1190f4
81,598
def get_batch_account( batch_mgmt_client, config, account_name=None, resource_group=None, raw_override=False, get_keys=False): # type: (azure.mgmt.batch.BatchManagementClient, dict, str, str, bool) -> # Tuple[azure.mgmt.batch.models.BatchAccount, # azure.mgmt.batch.models...
d7abcd1bd162a44a050f01689dd6922e204d8934
81,599
def GenerateId_base10(hash_sha512, input_file): """ Implement asset id of input file for base10 format @param hash_sha512: string to encode @param input_file: input file to encode """ string_id = int(hash_sha512.encode("hex_codec"), 16) return string_id
82512598623ca4cefe1abf535b556d175fe1549e
81,600
def calc_M_arc_line(arc: ArcAbstract, line: Line): """Comupute the mutual between an arc and a line.""" VEC_0 = np.array([0., 0., 0.]) Rp = arc.radius x_u = arc.vec_x y_u = arc.vec_y θ1 = arc.theta s_u = line.vec_n Ls = line.ell s0 = np.sqrt((line.vec_r0 - arc.vec_r0) @ (line.vec_...
4a67336f315792a52e4736cc3f26f3a99c71b82a
81,601
def static_fallback_open(static_path, mode="r"): """ attempts to open static_path first within collected staticfiles storage. if that doesn't work then next does a file system search for the file and if located then attempts opening using standard file i/o. """ writing = "w" in mode or ...
3d0764b44155cb148c0d06fc53c0f6b301d2bc44
81,602
def get_metadata(dataset_id, fname=None, force=False): """ Downloads a CSV of document metadata for all documents in the dataset. """ return _download_file(dataset_id, "sampled-metadata", file_name=fname, force=force)
7597bc31363f14a100cf5463080fd67de8ab815b
81,603
def awaiting_submission_app(): """Fixture for testing application submission types""" application = BootcampApplicationFactory.create( state=AppStates.AWAITING_USER_SUBMISSIONS.value ) installment = InstallmentFactory.create(bootcamp_run=application.bootcamp_run) app_steps = [ Applic...
889ced1e238b635402326afa625fce3ab0e581b5
81,604
def get_profile_info(): """ Gets the profile information of the last executed query :param db: db connection :return: time in milli seconds """ cursor = db.system.profile.find({"op": 'query'}, {"millis": 1}).sort("ts", pymongo.DESCENDING).limit(1) return cursor.next()['millis']
b62fb52eec3e767435e223901642d1238e01f8e3
81,605
import logging def _do_call_do_repository(repository, command): """Run the command's _do_repository on the given repository.""" # pylint: disable=protected-access def determine_outcome_labels(): """Helper function to inject rpeository name into command labels.""" result = command._do_determine_outcome_m...
484dc5a46b8495992b099fc08988fd48f105e206
81,606
def get_user_input(prompt_message): """ Get input from the user This function uses the console to get user input for the main menu. This also checks that the user entered 1, 2, or X. There is no unittest coverage for this function. Args: prompt_message The default message when asking fo...
30ec084dd2e877e07ee91a54292fc68ed67d521b
81,607
from typing import Tuple def pluralize(forms: Tuple[str, str, str], amount: int) -> str: """ Возвращает правильную форму слова в зависимости от количества. Формы слова: #. Единственное число, именительный падеж (штука). #. Единственное число, родительный падеж (штуки). #. Множественное число...
3e356b8c7f4c34a5aed5bd95fa0d88f5a918c0b0
81,608
def update_products(product_id): """Updates a specific product's details""" email = get_jwt_identity() user = users_obj.get_user_by_email(email) role = user["role"] if role != "admin": return jsonify({"Message": "You must be an admin to perform this action"}), 401 ...
d62c48587d00ffa23a492c79a2840c113f1a52c7
81,609
import json def global_weight(criterion, report): """ Formula: Global Weight = Criterion W value / Criterion Count For example: W Value = 1 Criterion Count = 5 Global Weight = 1 / 5 = 0.2 """ criterion_count = criterion['parent']['count'] data = report.criterion_compare[str(cr...
02ce4873fa93556e5d7f86037819c0962b0ad207
81,610
def modelToShape(model, dynamic=False): """ :type model: panda3d.core.NodePath :type dynamic: bool :return: tuple(panda3d.bullet.BulletTriangleMeshShape, transform) """ geomnodes = model.findAllMatches('**/+GeomNode') transform = model.getTransform() gn = geomnodes.getPath(0).node() ...
81fd00464e5d189c55f923b467f03ef818a938f2
81,613
import warnings def kruskal(dataset: pd.DataFrame, test_col: str, target_col: str, nan_policy: str = 'propagate') -> np.float: """Applies Kruskal-Wallis H-test to a single column Applies Kruskal-Wallis H-test to (test col, target_col) in order to test whether the medians in each of the classes in test_c...
c8be3e55c51310cadef6b2aac6d88c5431b5bb87
81,614
def add_nancodes(df): """Add nancodes to a signal dataframe.""" # Default missingness codes df["missing_val"] = Nans.NOT_MISSING df["missing_se"] = Nans.NOT_APPLICABLE df["missing_sample_size"] = Nans.NOT_APPLICABLE # Mark any remaining nans with unknown remaining_nans_mask = df["val"].isnu...
8e451656a7025e0363c4616e403853c4051543f2
81,615
def dictfetchall(cursor): """ Returns all rows from a cursor as a dict """ columns = [column[0] for column in cursor.description] return [dict(zip(columns, row)) for row in cursor.fetchall()]
710d0f31fe931bb953a536070a1b50f23203e5a8
81,616
def list_usages(client, resource_group_name, account_name): """ List usages for Azure Cognitive Services account. """ return client.list_usages(resource_group_name, account_name).value
83c03cef1e887f31eb15da85f63b095a15460693
81,617
def pickChromosomes(selection='A'): """ Selects the chromosomes you want to overlap. :param selection: A(autosomes), AS (Auto+Sex), or ASM (Auto+Sex+M) :return: chrList """ chrList = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', ...
40b1922a6995ad0d5ead8c282b945c152ecbf0be
81,618
def getTestStream(size: int): """ Produces a stream of repeating prime sequences to avoid accidental repetition """ arr = bytearray() while True: for prime in [4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937]: ...
0a0d8d8a8eead10ed15b12ff74aaa85145947a5f
81,619
def get_contact_info_keys(status_update): """Returns the contact info method keys (email, sms) used to send a notification for a status update if the notification exists. Returns [] if there is no notification """ if hasattr(status_update, 'notification'): return list(status_update.notificat...
020a9742df99cd65be1433165823c4f364009d85
81,620
def _jobs_cleanup_hard_timed_out(): """Find all jobs with hard_timeout values which have passed and delete them, logging the timeout / failure as appropriate""" now = timeutils.utcnow() session = get_session() num_del = session.query(models.Job)\ .filter(models.Job.hard_timeout <= now)\ ...
eff12a79b259eba1ce3f5ef0165ab0d065130089
81,622
from typing import Iterable def count_if(iterable: Iterable, unary_predicate: UnaryPredicate) -> int: """Count for how many elements in a iterable an unary predicate returns True. Args: iterable: An iterable for which to count for how many elements unary_predicate returns True unary_predicate...
3fd773ca3d6f7f611a5695cd4ce77edd8fda0a9f
81,623
import requests def insert(g, named_graph_uri=None): """ Securely insert a named graph into the DB""" if named_graph_uri: data = {'update': 'INSERT DATA { GRAPH <' + named_graph_uri + '> { ' + g.serialize(format='nt').decode("utf-8") + ' } }'} else: # insert into default graph data = {'up...
5c635b1c2e3dbd17dfd8dcc4ab1a99264961d316
81,624
async def _wtforms_base_form_validate(self, extra_validators=None): """ Validates the form by calling `validate` on each field. :param extra_validators: If provided, is a dict mapping field names to a sequence of callables which will be passed as extra validators to the field's `val...
378366444278c4409bc5164b143ee8971af53bf1
81,625
def remove_empty_elements(d): """ Remove empty elements from dict or list """ if isinstance(d, dict): return dict((k, remove_empty_elements(v)) for k, v in d.items() if v and remove_empty_elements(v)) elif isinstance(d, list): return [remove_empty_elements(v) for v in d if v and remo...
e440c6d6e478ed02bbd99071edf4de05146392c2
81,626
def plot_optimization_history(study: Study) -> "go.Figure": """Plot optimization history of all trials in a study. Example: The following code snippet shows how to plot optimization history. .. testcode:: import optuna def objective(trial): x = trial....
7487a17ad312d6b07c1dfb98cd4c3e0c5a9b9f18
81,627
from typing import Optional def test_selection_in_resolver(query: str, runtime_type: Optional[str], expected_result: dict): """ Test selected_field_names() when used in a resolver function """ # GraphQL resolver def resolve_object(obj, info: graphql.GraphQLResolveInfo): names = selected_field_name...
d33f305613e37d9f60dcc3efc4d27f906726a7be
81,628
def get_vpc_running_config(device): """Gets vpc running config Args: device (Device): This is the device object of an NX-API enabled device using the Device class within device.py Returns: str: 'show run section vpc' """ command = 'show running section vpc' try: ...
9b71d62cc07ae5a4f314956f0e0adf7d6db2d196
81,629
def rel_ent_key_list(topic_model, n_top_keywords, relevant_topics): """Returns a list of the top n keywords based on relative entropy score Arguments: topic_model (TopicModel): a topic by vocabulary word matrix where each entry is the total word count for that word in that topic n_top_word...
c650875e3f3287b9f1ccf4b6d6637c4014cf0e06
81,630
def isgooddeltainfo(revlog, deltainfo, revinfo): """Returns True if the given delta is good. Good means that it is within the disk span, disk size, and chain length bounds that we know to be performant.""" if deltainfo is None: return False # - 'deltainfo.distance' is the distance from the ...
15b4a094a9ae11123cbccc544508835e7d6ecba7
81,631
def count_running_ns(): """Find the number of the instantiated NSs in OSM r4 """ running_ns = 0 token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username')) ns = Ns(token) request = ns.get_list() ns_list = request.json() fo...
c78088dd6e4b5ae78f4b1763a350f51217b21dd7
81,632
def pack_to_uint64(locale): """Pack a full locale into a 64-bit unsigned integer.""" _, script, _ = get_locale_parts(locale) return ((pack_to_uint32(locale) << 32) | (ord(script[0]) << 24) | (ord(script[1]) << 16) | (ord(script[2]) << 8) | ord(script[3]))
73a73e46ee47087d832205f4918b97bb19d62949
81,633
def _convert_generator_to_delayed_seq_block(generator, chunksize=5000): """ Converts from a generator to a block of sequences """ seq_block = [dask.delayed(_to_seq_array)(seqs) for seqs in _chunks(generator, chunksize)] return seq_block
e626509eabe801b7a2aa66fe8b1dd8523b91c484
81,634
def hardnet68(**kwargs): """ HarDNet-68 model from 'HarDNet: A Low Memory Traffic Network,' https://arxiv.org/abs/1909.00948. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location ...
28d4e98e43a7dfad3a4658ccf7211e8ad5a0a3aa
81,635
from io import StringIO def _array_schema_html(schema: tiledb.ArraySchema) -> str: """Returns a HTML representation of a TileDB array.""" output = StringIO() output.write("<ul>\n") output.write("<li>\n") output.write("Domain\n") output.write("<table>\n") for i in range(schema.domain.ndim):...
bb06bceb0382f680464067b8833a1104eb2ab252
81,636
def binary_search(input_list, number, min_idx, max_idx): """ Find the index for a given value (number) by searching in a sorted array Time complexity: O(log2(n)) Space Complexity: O(1) Args: - input_list(array): sorted array of numbers to be searched in - number(int)...
20358c096c529937d57503285150a90a37f62dd1
81,637
def get_goal_status(goal): """ 1 = Success 2 = Rejected 3 = Locked """ print(goal.is_closed) if goal.is_closed: if goal.was_accomplished: return 1 else: return 2 return 3
64e742899a3a6484855f0543a7184db24c0c396f
81,638
def omega_s(distance_source, mass, xi_var, x_ratios, x_lin_dist): """Returns the evaluated kernel OMEGA""" gamma0_const = gamma0_ds(distance_source, x_lin_dist) return gamma0_const*xi_var*np.sqrt(x_ratios*(1.-x_ratios))*(mass)**(-1./2.)
427ce345b159356b2c0f9ad5d04d4e8049f6b29d
81,639
def _IntersectTwoHandlers(first_handler, second_handler): """Returns intersections of first_handler and second_handler patterns.""" shared_prefix = _SharedPrefix(first_handler.pattern, second_handler.pattern) if shared_prefix: return _HandleCommonPrefix(first_handler, second_handler, shared_prefix) share...
af143ec8940a076ab961aeb19237d5ed845739c8
81,640
def string_to_root(string_in): """Arguments: string_in [string]: input in XML format in a string Return: [element]: root element of parsed etree """ return etree.fromstring(string_in)
b768c03e434e3fc8d9d6cf187ff9887930c7ad6c
81,641
def get_ranking17(): """ Return the ranking with ID 17. """ return [ ("a3", 0.500000), ("a2", 0.433013), ("a4", 0.433013), ("a1", 0.000000), ("a5", 0.000000), ]
5b3e3083a86d3a484f6932d6cb6430bef6a3383e
81,642
import scipy def spectral_layout(data, graph, dim, random_state, metric="euclidean", metric_kwds={}): """Given a graph compute the spectral embedding of the graph. This is simply the eigenvectors of the laplacian of the graph. Here we use the normalized laplacian. Parameters ---------- data: ...
593709a3a8ce6333b441a03b91e033c689dff9c9
81,643
def uefa_dims(): """ Create 'uefa dimensions.""" return FixedDims(left=0., right=105., top=68., bottom=0., aspect=1., width=68., length=105., pitch_width=68., pitch_length=105., goal_width=7.32, goal_length=2., goal_bottom=30.34, goal_top=37.66, six...
de14239cf10443b1c5683e477d287813325f31a5
81,644
def compute_date_level_metrics(df_detail, bin_labels, date_col_name, return_col_name, feature, corr_method): """ Description: This function computes the back...
87faef203a21dbeba1bc3980cbd2bba9116f76ef
81,645
def row_basis(matrix): """ Outputs a basis for the rows of the matrix. Parameters ---------- matrix: numpy.ndarray The input matrix Returns ------- numpy.ndarray A numpy.ndarray matrix where each row is a basis element. Examples -------- >>> H=np.arra...
ede9e83cdeddae71df61316590ea274213e702bf
81,646
def show_zoning_enabled_configuration_rpc(self, zone_name_pattern=None, last_rcvd_zone_name=None, api_timeout=''): """ This is an auto-generated method for the PySwitchLib. **Supported Versions**: * NOS: 6.0.2f, 7.2.0 * SLXOS: 17r.1.01a, 17s.1.02 **Instance Argument(s)**: :ty...
58e98846a9fb25508bd61037d0d0ddcf4d064dc3
81,647
import torch def _calculate_ece(logits, labels, n_bins=10): """ Calculates the Expected Calibration Error of a model. (This isn't necessary for temperature scaling, just a cool metric). The input to this loss is the logits of a model, NOT the softmax scores. This divides the confidence outputs int...
af311a47b7558b07838a38d736386147804ea109
81,648
def buildMod(Adj, thresh): """Builds the modularity matrix from the Adjacency matrix. Given an adj matrix, it constructs the modularity matrix and its graph. """ Dim = Adj.shape[1] #print ("\n Dim = ", Dim) #print ("\n Computing modularity matrix ...") Deg = ...
d8528e1acf5f8a410612928689d147e57c1f420d
81,649
import random def add_ships_to_board(board, ships): """ Function goes through a list of ships and add them randomly into a board. board -> list of board tiles ships -> list of ships to place on board returns list of board tiles with ships placed on certain tiles """ new_board = board[...
13fd365c2249f41ce4147729a97286b7cb58a828
81,650
def closure(kb, closing_relation_id, cat_id): """Return set of ids for logical closure of a category/region. Args: kb: a sling kb closing_relation_id: SUBCLASS_OF_ID or REGION_OF_ID cat_id: id of the category to find ancestors of Returns: the set of all things in the KB of which the category ...
f116064131db68b1288c276614c6271c5656f0c6
81,651
def GetReader(thisalgorithm, dimension, pixelType): """ Get Reader Object to read the input file """ # Check dimension # Check if input stack or single image # If input stack if dimension == "3" and thisalgorithm.GetInputImageStack(): READER = "itk.ImageSeriesReader" READER_PIXELTYPE = "F" # Im...
74f0c361172e0da835fbd41404fadae3cc13f666
81,652
from typing import Tuple def _perform_dmd(video_matrix: np.ndarray, frame_rate: float, filename: str) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Performs DMD computations. Returns the DMD eigenvalues, eigenvectors and initial coefficients. """ print('Performing DMD computations...') ...
425fb10cb202b447c004088b0fb0a03a0e4ad7af
81,654
def build_kwargs(docs: dict, text: str = "Inherited keyword arguments\n", **kwargs) -> str: """ Builds a full keyword-arguments string, ready for use in a class docstring. Args: docs: Documentation dictionary text: A short heading for the keyword arguments ...
7087bb91bae8292db83b718d25f8f2a2528f6a37
81,655
def load_data_wrapper(): """Return a tuple containing ``(training_data, validation_data, test_data)``. Based on ``load_data``, but the format is more convenient for use in our implementation of neural networks. In particular, ``training_data`` is a list containing 50,000 2-tuples ``(x, y)``. ``x`` ...
ac78df90e4d1673c4685e48f6a9c9e55823b5efe
81,656
import itertools def findValidWyckoffCombos(stoich, spacegroup, wy_data=loadWyckoffData()): """ Given a composition's stoichiometry (such as [4,4,12] for Mg4Si4O12) and a single spacegroup (1-230), this function will find all valid wyckoff combinations that can produce that stoichiometry. stoich...
7a86584450f87e3b329d51631495c37410045b21
81,657
from typing import Optional from typing import List def plot_cvrp_solution( solution: CVRPSolution, route_indices_to_plot: Optional[List[int]] = None ) -> None: """Plot solution deliveries in a map This is a simplified version showing only the edges between each delivery. It does not require an OSRM s...
6d00d5fda19d02539ba5602e4dfea13e36d0e59f
81,658
from typing import Union from typing import Optional def getVodPlayInfo( video_seq: Union[str, int], vod_id: str = None, session: UserSession = None, silent: bool = False ) -> Optional[dict]: """Get detailed play info of VOD. Arguments: video_seq (:class:`str`) : Uniqu...
0ebb86a3067311f86a45049f950a98c18a3a8699
81,659
def _thin_iter_2_lut(): """ Thinning morphological operation; lookup table for iteration 2 :return: lookup table """ lut = identity_lut() cond = _thin_cond_g1() & _thin_cond_g2() & _thin_cond_g3_prime() lut[cond] = False return lut
2be73a9d8bd3861cd5b05d47267116306c4a4eb1
81,660
import sympy def expe_minus_1(lhs, ctx): """Element ∆E (num) -> (e ** a) - 1 (str) -> expand expression a """ ts = vy_type(lhs) return { NUMBER_TYPE: lambda: sympy.exp(lhs) - 1, str: lambda: str(sympy.expand(make_expression(lhs))), }.get(ts, lambda: vectorise(expe_minus_1, ...
1567c0141aef6305d12cea38d193aeafd4492f48
81,661
from datetime import datetime def get_last_cdr(phone_number, date_time, cdr_type): """ Gets the last CDR of a phone number """ cdr_type = str.casefold(cdr_type) today = date.today() billing_cycle = today.strftime("%Y%m") new_date = datetime.strptime(date_time, '%Y-%m-%d %H:%M:%S') re...
0673b6a52de23357fa3f975195ec52160b37c8d4
81,662
def floor_div_mul(value, factor): """Fuction to get floor number.""" return (((value) // (factor))) * (factor)
05c9b01c297f4ec68d3c5755db550482c520dac8
81,663
def get_docstring(filename, fragment_loader, verbose=False, ignore_errors=False): """ DOCUMENTATION can be extended using documentation fragments loaded by the PluginLoader from the module_docs_fragments directory. """ data = read_docstring(filename, verbose=verbose, ignore_errors=ignore_errors) #...
ff64279918d2af78b1182cd7083bc5b90882658b
81,664
def get_adjacency_list(nodes, exit_index, include_back_edges=False): """Computes the adjacency list for the control flow graph. Args: nodes: A list of control_flow.ControlFlowNodes. exit_index: The index of the exit node. include_back_edges: Whether to include back edges in the list. Returns: A P...
e48e5b47de7a9832581778692bada7b6626eaeaa
81,665
def ExpandIntData(compint): """ return expanded integer list i.e., 1,3 -5, 10 -12, 18,... -> 1, 3,4,5, 10,11,12, 18,... :param lst compint: commrest integer list :return: expnint(lst) - expanded integers list :seealso: CompressIntData() """ expnint=[] if len(compint) < 0: return exp...
9006bbd3476798f2113b74a74b29a247e18a932f
81,666
def get_activation_layer(activation: str) -> Layer: """Return a activation layer by input activation function. Parameters ---------- activation : str Activation function name. Returns ------- Layer An activation layer. """ if activation == "dice": return Dic...
984ae992e663a1fa8459e6493214088e1770f0f2
81,667
from typing import Callable from typing import Any import functools def with_select(function_object: Callable[["TaborChannelTuple", Any], Any]) -> Callable[["TaborChannelTuple"], Any]: """Asserts the channel pair is selcted when the wrapped function is called""" @functools.wraps(function_object) def sele...
b500dafbde7293b058de2cb4807a1c760b583be4
81,669
def history_parser(arg): """ @param: arg is a string that contains the words seperated by spaces @return: Returns two strings. The first word removed from arg and everything after the space """ v = -1 try: v = arg.index(' ') except ValueError: return None, None first_word...
267f0cd8ddfc0bfa9106d18341421d5d4d48ed1f
81,670
import json import base64 def temp_assignmentToggleShow(): """ POST Request This API can be used in bulk and single manner. In bulk mode, pass multiple ids of assignements to be marked opposite This API reverse the show property of all the assignments whose Id will be provided. I'm relying on Mood...
308e3521d7bfa231dcf1e46b6a1e828094dc83bb
81,671
def _to_scanner(varr): """Transform data to scanner coordinate space by properly swapping axes Standard vnmrj orientation - meaning rotations are 0,0,0 - is axial, with x,y,z axes (as global gradient axes) corresponding to phase, readout, slice. vnmrjpy defaults to handling numpy arrays of: ...
f8a8506e49722e7f5f66199ca15f0a441fb5e180
81,672
def select_clause(table_name, *fields, distinct=False): """ Create a select from clause string for SQL. Args: table_name: The table to select from as string. *fields: The fields to select. Returns: A string with the crafted clause. """ select = ...
3e373d6b493f60d94afe5d0372e2b1e752f98284
81,673
import torch def attr_grad(tensor, h, w, window=8, reduce='sum'): """ :param tensor: B, C, H, W tensor :param h: h position :param w: w position :param window: size of window :param reduce: reduce method, ['mean', 'sum', 'max', 'min'] :return: """ h_x = tensor.size()[2] w_x = t...
727d348dcb360c8d73956d89211a958c7fae354b
81,674
import psutil def get_machine_info(): """ Gets information on the memory, cpu and processes in the server :returns: tuple of strings containing cpu percentage, used memory, free memory and number of active processes """ if not SUPPORTED_OS: return (None, None, None, None) used_cpu = st...
e4352a9e794585a172661ea893a65aea387c17d2
81,676
import pandas as pd import math def removeMissing(filename): """Takes a file that contains missing scans and removes those rows, while providing the subject name and reason for removal.""" loaded_file = pd.read_csv(filename) cleaned_list = [] missing_counter = 0 for row in loaded_file.index: ...
497af6cc2b15da59d0bbad5785368ad8e1cbb5d9
81,677
import msgpack def dumps(msg): """ Transform Python message to bytestream suitable for communication """ try: data = {} # Only lists and dicts can contain serialized values if isinstance(msg, (list, dict)): msg, data, bytestrings = extract_serialize(msg) small_heade...
c74fc086213531eeff1339b1df8bd3b0adb69dcc
81,678
from typing import Dict from typing import Type def get_serialisers(method) -> Dict[Type, Type[RegressionSerialiser]]: """ Gets the serialisers for the given test method. :param method: The test method. :return: The mapping from result type to serialiser. """ return getattr(method, _c...
cb1c524eeccc3abe69545be68e17ac81c00eaa97
81,679