code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@blueprint.route("/cohorts", methods=["GET"]) <NEW_LINE> def get_cohorts(): <NEW_LINE> <INDENT> err, code = _authenticate_user() <NEW_LINE> if err is not None: <NEW_LINE> <INDENT> return err, code <NEW_LINE> <DEDENT> folder_name = _get_folder_name_from_token(current_token) <NEW_LINE> result, ok = _list_files_in_bucket(... | Returns a list of filenames -- which are GUIDs -- corresponding to the user's exported
PFBs. We find the appropriate folder ("prefix") in the bucket by asking Fence for
info about the user's access token.
---
responses:
200:
description: Success
403:
description: Unauthorized | 625941d921a7993f00bc7f8a |
def getPlayerFriMailCnd(characterId): <NEW_LINE> <INDENT> sql = "SELECT COUNT(id) FROM tb_mail WHERE receiverId = %d AND `type`=1 and isSaved = 0"%characterId <NEW_LINE> result = dbpool.fetchOne(sql) <NEW_LINE> return result[0] | 获取角色玩家邮件的数量 | 625941d9e76e3b2f99f3aa9f |
def __repr__(self): <NEW_LINE> <INDENT> c = "<Cover cover_id=%s game_id=%s url=%s>" <NEW_LINE> return c % (self.cover_id, self.game_id, self.url) | Provide helpful output when printed | 625941d944b2445a3393232c |
def buildMeanCurvatureFlowOperator(mesh, index, h): <NEW_LINE> <INDENT> return None | Construct the (sparse) mean curvature operator matrix for the mesh.
It might be helpful to use your buildLaplaceMatrix_sparse() and
buildMassMatrix_sparse() methods from before.
Returns the resulting matrix. | 625941d91d351010ab855db3 |
def __init__(self, server_ip='192.168.150.130', server_port=9000, admin="root", password="123456"): <NEW_LINE> <INDENT> self.Gconn = GstoreConnector(server_ip, server_port) <NEW_LINE> ret = self.Gconn.build("weibo", "data/weibo/weibo.nt", admin, password) <NEW_LINE> self.admin = admin <NEW_LINE> self.password = passwor... | initialize a data base operator.
:param server_ip: ip of server, defualt as "127.0.0.1"
:param server_port: port of server, default as 9000
:param admin: administer of the server, default as "root"
:param password: password of the server, default as "123456" | 625941d950485f2cf553d032 |
def apply_changes(self, changes): <NEW_LINE> <INDENT> lines = self.get_wikitext().split("\n") <NEW_LINE> changes.sort(key=lambda x: -x[1]) <NEW_LINE> for change in changes: <NEW_LINE> <INDENT> c = change[0] <NEW_LINE> if c=="I": <NEW_LINE> <INDENT> _, pos, ls = change <NEW_LINE> lines[pos:pos] = ls <NEW_LINE> <DEDENT> ... | Apply changes to this wikitext | 625941d9bf627c535bc13466 |
def fit(self, X, y): <NEW_LINE> <INDENT> X, y = check_X_y(X, y, y_numeric=True, ensure_min_features=2, estimator=self) <NEW_LINE> X = as_float_array(X, copy=False, force_all_finite=False) <NEW_LINE> cv = check_cv(self.cv, X, y, classifier=False) <NEW_LINE> max_iter = (min(max(int(0.1 * X.shape[1]), 5), X.shape[1]) if n... | Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape [n_samples, n_features]
Training data.
y : array-like, shape [n_samples]
Target values.
Returns
-------
self : object
returns an instance of self. | 625941d9e8904600ed9f21c7 |
@relations.command() <NEW_LINE> @click.option( "--skip-indexing", is_flag=True, ) <NEW_LINE> @click.option( "--fail-on-exceptions", is_flag=True, ) <NEW_LINE> @with_appcontext <NEW_LINE> def series(skip_indexing, fail_on_exceptions): <NEW_LINE> <INDENT> migrate_series_relations(raise_exceptions=fail_on_exceptions) <NEW... | Create relations for migrated series. | 625941d985dfad0860c3b0f3 |
def findindexsmallest(a, low, high): <NEW_LINE> <INDENT> index = low <NEW_LINE> for i in range(low+1, high): <NEW_LINE> <INDENT> if a[i] < a[index]: <NEW_LINE> <INDENT> index = i <NEW_LINE> <DEDENT> <DEDENT> return index | Function that returns the index of the smallest element in a list from index "low" to index "high"
Parameters
----------
a: list
List of elements
low: int
Index to start search from.
high: int
Index to end search on.
Return
----------
index: int
The index of the smallest element in the list | 625941d9bde94217f3683086 |
def _index(*args, **kwargs): <NEW_LINE> <INDENT> start = kwargs.pop('start', 0) <NEW_LINE> step = kwargs.pop('step', 1) <NEW_LINE> if len(args) == 2: <NEW_LINE> <INDENT> elem, list_ = args <NEW_LINE> ensure_sequence(list_) <NEW_LINE> predicate = lambda item: item == elem <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> en... | Implementation of list searching.
:param of: Element to search for
:param where: Predicate to search for
:param in_: List to search in
:param start: Start index for the lookup
:param step: Counter step (i.e. in/decrement) for each iteration
:return: Pair of ``(list, index)``,
where ``list`` is the list we se... | 625941d9090684286d50ef7f |
def build_icnr_ip_group(self, client_data, inventory): <NEW_LINE> <INDENT> tunnel_source_network = None <NEW_LINE> if self.skytap_env_vars["network_connection_id"]: <NEW_LINE> <INDENT> matching_tunnels = [ tunnel for tunnel in client_data["tunnels"] if tunnel["id"] == self.skytap_env_vars["network_connection_id"] ] <NE... | update the inventory file to include a group for the ICNR IP addresses | 625941d9ad47b63b2c50a215 |
def test_access(root: Path) -> None: <NEW_LINE> <INDENT> path = root / "etc" / "passwd" <NEW_LINE> assert not path.access(Access.EXECUTE) | It returns False if the path cannot be accessed as specified. | 625941d93317a56b86939eea |
def stop(self): <NEW_LINE> <INDENT> self.__lifecycle.stop() <NEW_LINE> self._is_stopped_evt.set() <NEW_LINE> self.resume() <NEW_LINE> self.join() | Stop the thread. | 625941d9aad79263cf390cdc |
def get_wiki_namespaces(namespaces: str) -> str: <NEW_LINE> <INDENT> ids = [] <NEW_LINE> for namespace in namespaces.lower().split(','): <NEW_LINE> <INDENT> n = namespace.strip() <NEW_LINE> if n in WIKI_NAMESPACES: <NEW_LINE> <INDENT> ids.append(WIKI_NAMESPACES[n]) <NEW_LINE> <DEDENT> <DEDENT> return '|'.join(ids) | Returns a pipe-delimited string of wiki namespace IDs, or an empty string if no matching
namespace was found.
Args:
namespaces: Comma-delimited list of namespaces to include in the return value. | 625941d931939e2706e4d0fe |
def bind(self, array, update_device=True): <NEW_LINE> <INDENT> if not isinstance(array, numpy.ndarray): <NEW_LINE> <INDENT> raise ValueError("only numpy.ndarray can be associated with offload_array") <NEW_LINE> <DEDENT> if array.flags.c_contiguous: <NEW_LINE> <INDENT> order = "C" <NEW_LINE> <DEDENT> elif array.flags.f_... | Create a new offload_array that is bound to an existing
numpy.ndarray. If update_device is False, then one needs to call
update_device() to issue a data transfer to the target device.
Otherwise, the offload_array will be in unspecified state on
the target device. Data transfers to the host overwrite the
data in ... | 625941d916aa5153ce36270f |
def gateway(self, reference=None): <NEW_LINE> <INDENT> return Gateway(self._client, reference) | Access the gateway resource
:param reference:
:return: the gateway resource
:rtype: agilepay.resources.Gateway | 625941d9a8370b7717052b36 |
def get_default_shell(environ=None): <NEW_LINE> <INDENT> if environ is None: <NEW_LINE> <INDENT> environ = os.environ <NEW_LINE> <DEDENT> if "PIAS_OPT_SHELL" in environ: <NEW_LINE> <INDENT> return environ["PIAS_OPT_SHELL"] <NEW_LINE> <DEDENT> shells = [] <NEW_LINE> for filename in (environ.get("SHELL"), "bash", "sh"): ... | Get the user's default shell program. | 625941d9a79ad161976cc3dd |
def to_representation(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, OrderedDict): <NEW_LINE> <INDENT> return obj <NEW_LINE> <DEDENT> return obj.to_dict() | Always return the dict representation. | 625941d97b25080760e396f0 |
def compute_model_for_text(text, model_type=MODEL_3_GRAMS, clean_method=norm.CLEAN_TWEET): <NEW_LINE> <INDENT> if model_type not in model_generator_mapper: <NEW_LINE> <INDENT> raise Exception('Unknown model type received.') <NEW_LINE> <DEDENT> if clean_method not in norm.clean_text_method_mapper: <NEW_LINE> <INDENT> ra... | Builds a model for a given text
:rtype : dict
:param text: The provided text
:param model_type: The model type
:param clean_method: The type of text cleaning method
:return: The computed model | 625941d924f1403a92600dfc |
def max_scatt_meep(r, material, paper, wlen_range, wlen_delta=0.5, surrounding_index=1, asEfficiency=False): <NEW_LINE> <INDENT> wavelength = np.arange(*wlen_range, wlen_delta) <NEW_LINE> scattering = sigma_scatt_meep(r, material, paper, wavelength, surrounding_index=surrounding_index, asEfficiency=asEfficiency) <NEW_L... | Returns maximum scattering cross section using Mie theory for a nanosphere.
Parameters
----------
r : float
Spherical NP radius. Measured in nm.
material: str
Name of the desired material.
paper="R": str
Name of desired source for experimental input data of medium.
wlen_range : tuple
Wavelength range t... | 625941d999fddb7c1c9de628 |
def test_main_page_context(self): <NEW_LINE> <INDENT> response = self.guest_client.get(reverse('index')) <NEW_LINE> post_text_0 = response.context.get('page')[0].text <NEW_LINE> post_author_0 = response.context.get('page')[0].author <NEW_LINE> self.assertEqual(post_text_0, self.post.text) <NEW_LINE> self.assertEqual(po... | Шаблон index сформирован с правильным контекстом | 625941d94f6381625f114cd3 |
def post(self, data, check, mutator): <NEW_LINE> <INDENT> form = GSoCDocumentForm(data=data.POST or None, instance=data.document) <NEW_LINE> validated_document = document.validateForm(data, form) <NEW_LINE> if validated_document: <NEW_LINE> <INDENT> data.redirect.document(validated_document) <NEW_LINE> return data.redi... | Handler for HTTP POST request. | 625941d9851cf427c661a7a4 |
def test_2(sess_scope, mod_scope, func_scope): <NEW_LINE> <INDENT> pass | 使用多个测试演示更有趣。 | 625941d930dc7b7665901bfc |
def maybe_launch_copies(self): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> if now - self.last_check < MIN_STANDING_ORDER_INTERVAL: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> mode = app.config.get('standing_order_mode', 'normal') <NEW_LINE> if mode == 'disabled': <NEW_LINE> <INDENT> stord_logger.debug('no... | Returns True unless nothing happened because we've run a search recently.
| 625941d98e05c05ec3eea60e |
def __init__(self): <NEW_LINE> <INDENT> self.pin = 24 <NEW_LINE> self.state = 0 <NEW_LINE> GPIO.setwarnings(False) <NEW_LINE> GPIO.setmode(GPIO.BCM) <NEW_LINE> GPIO.setup(self.pin, GPIO.OUT) | Initialize GPIO to control the electrical control pin | 625941d96e29344779a628a8 |
def diff_map(self, infuncs): <NEW_LINE> <INDENT> stmts = [] <NEW_LINE> created = False <NEW_LINE> for (sch, fnc, arg) in infuncs.keys(): <NEW_LINE> <INDENT> infunc = infuncs[(sch, fnc, arg)] <NEW_LINE> if isinstance(infunc, Aggregate): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if (sch, fnc, arg) not in self: <NE... | Generate SQL to transform existing functions
:param infuncs: a YAML map defining the new functions
:return: list of SQL statements
Compares the existing function definitions, as fetched from
the catalogs, to the input map and generates SQL statements to
transform the functions accordingly. | 625941d973bcbd0ca4b2c30e |
def _balance_group_by_period(self, from_date, to_date, period, account_types=None, drop_null=False, accounts=None, is_guid=False): <NEW_LINE> <INDENT> sel_df = pandas.DataFrame(self.df_splits, columns=[cols.ACCOUNT_GUID, cols.POST_DATE, cols.FULLNAME, cols.COMMODITY_GUID, cols.ACCOUNT_TYPE, cols.CUM_SUM, cols.SHORTNAME... | Группирует балансы по периоду у заданных типов счетов
Возвращает DataFrame со всеми счетами сгруппированными по периоду (суммирует за период)
:param from_date:
:param to_date:
:param period:
:param account_types:
:param drop_null:
:return: | 625941d957b8e32f52483734 |
def do_setpypi(self, serial): <NEW_LINE> <INDENT> self.db.set_pypi_serial(serial) | Handler for "SETPYPI" message, sent by :class:`DbClient` to update the
last seen serial number from the PyPI changelog. | 625941d9236d856c2ad44a75 |
def predict_proba(self, init_dm=True, dataset='dev'): <NEW_LINE> <INDENT> if not self.sess: <NEW_LINE> <INDENT> logger.error("model unitnialized, not running batch.") <NEW_LINE> return <NEW_LINE> <DEDENT> if init_dm: <NEW_LINE> <INDENT> self.sess.run(self.data_manager.initializer, feed_dict=self.data_manager.get_init_f... | Return probabilistic predictions.
Parameters
----------
X : np.array
Returns
-------
np.array of predictions, dimension m x n, where m is the length
of X and n is the number of classes | 625941d96fb2d068a760f338 |
def trouverFinPath(self, unit): <NEW_LINE> <INDENT> unit.cibleX = unit.cheminTrace[0].x <NEW_LINE> unit.cibleY = unit.cheminTrace[0].y <NEW_LINE> xSave = unit.x <NEW_LINE> ySave = unit.y <NEW_LINE> try: <NEW_LINE> <INDENT> unit.x = unit.cheminTrace[1].x <NEW_LINE> unit.y = unit.cheminTrace[1].y <NEW_LINE> <DEDENT> exce... | Trouver un path entre la fin d'un path et un autre path | 625941d966673b3332b92329 |
def test_encapsulate_bot(self): <NEW_LINE> <INDENT> ds = dcmread(JP2K_10FRAME_NOBOT) <NEW_LINE> frames = decode_data_sequence(ds.PixelData) <NEW_LINE> assert len(frames) == 10 <NEW_LINE> data = encapsulate(frames, fragments_per_frame=1, has_bot=True) <NEW_LINE> assert data[:56] == ( b'\xfe\xff\x00\xe0' b'\x28\x00\x00\x... | Test the Basic Offset Table is correct. | 625941d907f4c71912b1171c |
def scale_by_level(self, level=None): <NEW_LINE> <INDENT> if level is None: <NEW_LINE> <INDENT> level = self.level <NEW_LINE> <DEDENT> return round(0.0 * level, self.num_of_decimals) | Update FrostDamage's attributes and tooltip variable.
| 625941d93539df3088e2e5e2 |
def generator(self, random, args): <NEW_LINE> <INDENT> if self.duplicates: <NEW_LINE> <INDENT> max_count = [self.capacity // item[0] for item in self.items] <NEW_LINE> return [random.randint(0, m) for m in max_count] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [random.choice([0, 1]) for _ in range(len(self.ite... | Return a candidate solution for an evolutionary computation. | 625941d94527f215b584c6ec |
def addGlyphs( self, glyphs ): <NEW_LINE> <INDENT> self.__glyphs.extend( glyphs ) | Adds the given glyphs to the block. | 625941d97cff6e4e81117c1d |
def _validate_query(query): <NEW_LINE> <INDENT> query = deepcopy(query) <NEW_LINE> if query["q"] == BLANK_QUERY["q"]: <NEW_LINE> <INDENT> raise ValueError("No query specified.") <NEW_LINE> <DEDENT> query["q"] = _clean_query_string(query["q"]) <NEW_LINE> if query["limit"] is None: <NEW_LINE> <INDENT> query["limit"] = SE... | Validate and clean up a query to be sent to Search.
Cleans the query string, removes unneeded parameters, and validates for correctness.
Does not modify the original argument.
Raises an Exception on invalid input.
Arguments:
query (dict): The query to validate.
Returns:
dict: The validated query. | 625941d999cbb53fe6792e7e |
def convert_jas_to_alias(self, jas_data): <NEW_LINE> <INDENT> jas_file = open("pfm_plants.txt") <NEW_LINE> jas_data = jas_file.read() <NEW_LINE> new_dict = {} <NEW_LINE> for jas_key in self.interaction_dictionary_jas.keys(): <NEW_LINE> <INDENT> regex = re.compile(">MA" + jas_key[2:6] + "\.\d (\\b\S+)") <NEW_LINE> resul... | (JasToAliasConverter, Dictionary) -> Dictionary
Return a new dictionary constructed from a interaction dictionary of
jaspar names and AGI targets by replacing the jaspar names with
aliases.
Args:
jas_data (Dict): A dictionary of jaspar names with their
corresponsing agi targets as a list
Return:
A di... | 625941d98a349b6b435e840b |
def call(self, y_true, y_pred): <NEW_LINE> <INDENT> error = tf.subtract(y_true[..., :], y_pred[..., :]) <NEW_LINE> same_type_q = tf.cast(tf.constant(self._q_multipliers, dtype=tf.float64), error.dtype) <NEW_LINE> return tf.reduce_mean(tf.maximum(same_type_q * error, (same_type_q - 1.0) * error)) | Computes the quantile loss from targets and sources in the tf graph.
Assumes the same format as is introduced in `IndexedFeed.repeat_targets_for_quantiles`.
Example:
(two targets, three quantiles:)
t-p = error * self._q_multipliers
1 1 q1
1 1 q2
1 1 q3
2 2 ... | 625941d9dd821e528d63b440 |
def usermacro_get( macro=None, hostids=None, templateids=None, hostmacroids=None, globalmacroids=None, globalmacro=False, **connection_args ): <NEW_LINE> <INDENT> conn_args = _login(**connection_args) <NEW_LINE> ret = False <NEW_LINE> try: <NEW_LINE> <INDENT> if conn_args: <NEW_LINE> <INDENT> method = "usermacro.get" <... | Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros wit... | 625941d901c39578d7e750d4 |
def status_api_call(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = api.call(self.base_url, 'GET', 'v2/nsg/cluster/net/{0}/status'.format(self.netid), token=self.token) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> return 503, ex <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return resp... | makes API call v2/nsg/cluster/net/{0}/status and returns the response. Note that
the server does not 'json-stream' response for this API call | 625941d9fff4ab517eb2f6d5 |
def _init_tree(self,s,parent,left,start,end): <NEW_LINE> <INDENT> half = (end+start)//2 <NEW_LINE> node = Node((half,s[half]),None,None,None,None) <NEW_LINE> self.root = node <NEW_LINE> if start <= half-1: <NEW_LINE> <INDENT> self._build_tree(s,node,1,start,half-1) <NEW_LINE> <DEDENT> if end >= half+1: <NEW_LINE> <INDE... | Builds a balanced binary search tree | 625941d915baa723493c420f |
def get_error_element(self): <NEW_LINE> <INDENT> return self.explicit_wait_visibility(LoginPageLocator.locator_error) | 获取登录失败的提示 WebElement 对象
:return: WebElement 对象 | 625941d9a05bb46b383ecab8 |
def write_png(filename, image): <NEW_LINE> <INDENT> import cv2 <NEW_LINE> ret = cv2.imwrite(filename, image) <NEW_LINE> if not ret: <NEW_LINE> <INDENT> logging.error(f"Writing PNG file {filename} failed") | image must be numpy array H X W X channels
| 625941d991af0d3eaac9bcb3 |
def compute_real_coords_y(ticks, resolution, offset, raster_rows): <NEW_LINE> <INDENT> labels = [] <NEW_LINE> for tick in ticks: <NEW_LINE> <INDENT> face_val = (raster_rows - tick) * resolution + offset <NEW_LINE> labels.append("{:.2f}".format(face_val)) <NEW_LINE> <DEDENT> return labels | convert a pixel coord to the real coord in y
:param ticks:
:param resolution:
:param offset:
:return: | 625941d9a8ecb033257d3364 |
def _norm(p, dim): <NEW_LINE> <INDENT> if dim is None: <NEW_LINE> <INDENT> return p.norm() <NEW_LINE> <DEDENT> elif dim == 0: <NEW_LINE> <INDENT> output_size = (p.size(0),) + (1,) * (p.dim() - 1) <NEW_LINE> return p.contiguous().view(p.size(0), -1).norm(dim=1).view(*output_size) <NEW_LINE> <DEDENT> elif dim == p.dim() ... | Computes the norm over all dimensions except dim | 625941d926068e7796caef7a |
def index(self, value, i=0, j=None): <NEW_LINE> <INDENT> if j == None: <NEW_LINE> <INDENT> j=len(self.data) <NEW_LINE> <DEDENT> start = self._normalize_idx(i) <NEW_LINE> end = self._normalize_idx(j) <NEW_LINE> for x in range(start, end): <NEW_LINE> <INDENT> if self.data[x]==value: <NEW_LINE> <INDENT> return x <NEW_LINE... | Returns the index of the first instance of value encountered in
this list between index i (inclusive) and j (exclusive). If j is not
specified, search through the end of the list for value. If value
is not in the list, raise a ValueError. | 625941d9b5575c28eb68e29a |
@tf_export("math.reduce_all", "reduce_all", v1=[]) <NEW_LINE> @dispatch.add_dispatch_support <NEW_LINE> def reduce_all(input_tensor, axis=None, keepdims=False, name=None): <NEW_LINE> <INDENT> keepdims = False if keepdims is None else keepdims <NEW_LINE> return _may_reduce_to_scalar( keepdims, axis, gen_math_ops._all( i... | Computes the "logical and" of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
of the entries in `axis`, which must be unique. If `keepdims` is true, the
reduced dimensions are retained with l... | 625941d931939e2706e4d0ff |
def edge_detection(inid, df, non_disaggregation_columns): <NEW_LINE> <INDENT> check_headers(inid, df) <NEW_LINE> edges = detect_all_edges(inid, df, non_disaggregation_columns) <NEW_LINE> edges = prune_grand_parents(edges) <NEW_LINE> return edges | Check dependencies between columns and write out the edges
If there are any problems return False as this is part of the build.
Args:
inid (str): The indicator id for printing
df (pandas DataFrame): The indicator data read from raw csv
non_disaggregation_columns: List of columns that are not disaggregatio... | 625941d91f037a2d8b946496 |
def test_images_preserved(self): <NEW_LINE> <INDENT> images = [ 'bharath-kumar-a-co-founder-at-pugmarksme-suggests-working-on-a-sunday-late-night.jpg', 'bryan-guido-hassin-a-university-professor-and-startup-junkie-uses-airplane-days.jpg', ] <NEW_LINE> for image in images: <NEW_LINE> <INDENT> self.assertIn(image, self.d... | The div with the comments should be removed. | 625941d992d797404e304423 |
def _lists(thing, encoding): <NEW_LINE> <INDENT> root = ET.Element("Py_Object") <NEW_LINE> real_root = ET.SubElement(root, thing.__class__.__name__, attrib={"length": str(len(thing))}) <NEW_LINE> for item in thing: <NEW_LINE> <INDENT> build_subelement(real_root, item, encoding) <NEW_LINE> <DEDENT> return ET.tostring(ro... | Internal Method for turning lists into an XML document.
:param list thing: the list
:param str encoding: the encoding for strings
:return: string containing xml
:rtype: str | 625941d9f9cc0f698b140892 |
def oddEvenList(self, head): <NEW_LINE> <INDENT> if (not head) or (not head.next): <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> pre_head = ListNode(0) <NEW_LINE> pre_head.next = head <NEW_LINE> odd_head, even_head = head, head.next <NEW_LINE> ptr_odd, ptr_even =odd_head, even_head <NEW_LINE> head = head.next.nex... | :type head: ListNode
:rtype: ListNode | 625941d99c8ee82313fbba0e |
@user.route("/user") <NEW_LINE> @login_required <NEW_LINE> def user_page(): <NEW_LINE> <INDENT> return render_template("user.html") | Display user info page.
Provide way to log out. | 625941d956b00c62f0f148f3 |
def parse_resto(self, response): <NEW_LINE> <INDENT> logger.warn(' > PARSING NEW RESTO PAGE ({})'.format(self.resto_nb)) <NEW_LINE> self.resto_nb += 1 <NEW_LINE> urls_review = get_info.get_urls_review(response) <NEW_LINE> for url_review in urls_review: <NEW_LINE> <INDENT> yield response.follow(url=url_review, callback=... | SECOND PARSING : Given a restaurant, get each review url and get to parse it
- Usually there are 10 comments per page | 625941d9004d5f362079a5cb |
def test_user_model(self): <NEW_LINE> <INDENT> self.user_pair() <NEW_LINE> self.assertEqual(len(self.u.messages), 0) <NEW_LINE> self.assertEqual(len(self.u.followers), 0) | Does basic model work? | 625941d9287bf620b61d3cfb |
def delete_workout(request, id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(id=request.session["user_id"]) <NEW_LINE> Workout.objects.get(id=id).delete() <NEW_LINE> return redirect('/dashboard') <NEW_LINE> <DEDENT> except (KeyError, User.DoesNotExist) as err: <NEW_LINE> <INDENT> messages.info(... | Delete a workout. | 625941d9d486a94d0b98e3df |
def findKthLargest(self, nums, k): <NEW_LINE> <INDENT> return self.compute(nums, len(nums)-k, 0, len(nums)-1) | :type nums: List[int]
:type k: int
:rtype: int | 625941d98e71fb1e9831da41 |
def _check_gifti_params(params): <NEW_LINE> <INDENT> params = handle_base_args(params) <NEW_LINE> for hem in ['lh', 'rh']: <NEW_LINE> <INDENT> if params[f'{hem}_files']: <NEW_LINE> <INDENT> params[f'{hem}_files'] = check_glob(params[f'{hem}_files']) <NEW_LINE> if len(params[f'{hem}_files']) == 0: <NEW_LINE> <INDENT> ra... | Ensure that required fields are included and correctly formatted | 625941d930bbd722463cc061 |
def __init__(self,**kwargs): <NEW_LINE> <INDENT> super(Splitter, self).__init__(**kwargs) <NEW_LINE> self.type = 3 <NEW_LINE> self.stream_count = [1, 3] <NEW_LINE> self.input_streams = {1: None} <NEW_LINE> self.output_streams = {1: None, 2: None, 3: None} <NEW_LINE> self.input_lines = {1: None} <NEW_LINE> self.output_l... | Initializes all the variables. | 625941d9d4950a0f3b08c5e5 |
def _check_sparse_format(spmatrix, accept_sparse=True, dtype=None, force_all_finite=True, context=""): <NEW_LINE> <INDENT> if accept_sparse in [None, False]: <NEW_LINE> <INDENT> raise TypeError('%sA sparse matrix was passed, but dense ' 'data is required. Use X.toarray() to ' 'convert to a dense numpy array.' % context... | Check if a sparse array needs format changes.
Checks the sparse format of spmatrix and alerts if changes are
recommended. Like Scikit-learn's ``_assert_sparse_format`` but without
forced conversion.
Parameters
----------
spmatrix : scipy sparse matrix
Input to validate and convert.
accept_sparse : string, list o... | 625941d994891a1f4081bd43 |
def average_n_steps(self,n): <NEW_LINE> <INDENT> if len(self.times) < 2: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> timedif = self.times[1] - self.times[0] <NEW_LINE> new_data = [] <NEW_LINE> for line in self.data: <NEW_LINE> <INDENT> start_i = 0 <NEW_LINE> sum_time = 0 <NEW_LINE> data_row = [] <NEW_LINE> new_times... | width = self.data.shape[0]
leng = self.data.shape[1]
num_after = leng % n
if num_after != 0:
num_avgs = 1 + leng // n
start = np.reshape(self.data[:,:-num_after],(width,leng,num_avgs-1))
avg_calc = np.average(start,2)
all_avg = np.hstack(avg_calc,np.average(self.data[:,-num_after:]))
else:
num_avgs... | 625941d9596a897236089d57 |
def test_get_word(self): <NEW_LINE> <INDENT> create_word('saluto') <NEW_LINE> response = self.client.get(reverse('api_view_word', args=['saluto'])) <NEW_LINE> self.assertHttpOK(response) <NEW_LINE> self.assertEqual(response['Content-Type'], 'application/json') | Ensure that we can call our JSON API and get a response. | 625941d98e7ae83300e4b266 |
def apply(self, imin, imax, di, evaluation): <NEW_LINE> <INDENT> imin = imin.to_sympy() <NEW_LINE> imax = imax.to_sympy() <NEW_LINE> di = di.to_sympy() <NEW_LINE> index = imin <NEW_LINE> result = [] <NEW_LINE> while index <= imax: <NEW_LINE> <INDENT> evaluation.check_stopped() <NEW_LINE> result.append(from_sympy(index)... | Range[imin_?RealNumberQ, imax_?RealNumberQ, di_?RealNumberQ] | 625941d9925a0f43d254a111 |
def search(index_instance, query_string, **query_options): <NEW_LINE> <INDENT> using = query_options.pop('using', 'default') <NEW_LINE> return get_backend(index_instance, using=using).search(query_string, limit_indexes=[index_instance], **query_options) | search a SearchIndex instance for query_string with query_options, returns
a dict with results, facets, and hits
A particular connection can be specified by passing using in query_options. | 625941d9be383301e01b571b |
def test_00_neighbour_track_one_then_nothing(): <NEW_LINE> <INDENT> labels = numpy.zeros((10, 10), int) <NEW_LINE> labels[3:6, 2:7] = 1 <NEW_LINE> def fn(module, workspace, index): <NEW_LINE> <INDENT> if workspace is not None and index == 0: <NEW_LINE> <INDENT> module.tracking_method.value = "Follow Neighbors" <NEW_LIN... | Run track objects on an object that disappears
Regression test of IMG-1090 | 625941d9a8ecb033257d3365 |
def validate(self, data): <NEW_LINE> <INDENT> honeypot = data.get('url', False) <NEW_LINE> if honeypot: <NEW_LINE> <INDENT> raise serializers.ValidationError( 'Suspected spam in honeypot: {}'.format(honeypot), code='suspected spam', params={'value': honeypot} ) <NEW_LINE> <DEDENT> return data | Override the clean method to check for spam in honeypot. | 625941d9fb3f5b602dac392e |
def check_blank(self): <NEW_LINE> <INDENT> sel = self.selenium <NEW_LINE> self.assertEqual("", sel.get_value("cr_shelter_location_id")) <NEW_LINE> self.assertEqual("", sel.get_value("gis_location_L0")) <NEW_LINE> self.failUnless(sel.is_visible("gis_location_L0")) <NEW_LINE> self.failUnless(sel.is_visible("gis_location_... | Check that a form is free of location (create or update empty) | 625941d976e4537e8c35190d |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(object_grabber3Goal, self).__init__(*args, **kwds) <NEW_LINE> if self.action_code is None: <NEW_LINE> <INDENT> self.action_code = 0 <NEW_LINE> <DEDENT> if self.object_id is None: <NEW_LINE> <INDENT> self.object_id = 0 <NEW... | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
action_code,object_id,grasp_option... | 625941d9187af65679ca53b8 |
def igetattr(self, name, context=None): <NEW_LINE> <INDENT> context = contextmod.copy_context(context) <NEW_LINE> context.lookupname = name <NEW_LINE> try: <NEW_LINE> <INDENT> return bases._infer_stmts(self.getattr(name, context), context, frame=self) <NEW_LINE> <DEDENT> except AttributeInferenceError as error: <NEW_LI... | Infer the possible values of the given variable.
:param name: The name of the variable to infer.
:type name: str
:returns: The inferred possible values.
:rtype: iterable(NodeNG) or None | 625941d9aad79263cf390cdd |
def trim_long_text(text, max_lines): <NEW_LINE> <INDENT> max_lines = max(max_lines, 3) <NEW_LINE> lines = text.splitlines() <NEW_LINE> if len(lines) <= max_lines: <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> lines_to_keep_at_each_end = int((max_lines - 1) / 2) <NEW_LINE> num_lines_skipped = len(lines) - lines_to... | Trim a potentially long multi-line message at the given number of lines.
:param text: the input text
:param max_lines: maximum number of lines
:return: the trimmed message | 625941d923e79379d52ee7fa |
def introspect_class(cls, class_doc, module_name=None): <NEW_LINE> <INDENT> class_doc.specialize_to(ClassDoc) <NEW_LINE> class_doc.docstring = get_docstring(cls) <NEW_LINE> public_names = None <NEW_LINE> if hasattr(cls, '__all__'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> public_names = set([str(name) for name in c... | Add API documentation information about the class C{cls}
to C{class_doc}. | 625941d932920d7e50b2846b |
@rule(methodSignature + shouldBeSemicolonAndNewline + codeBlock) <NEW_LINE> def method(value): <NEW_LINE> <INDENT> return stringsAndErrors(value) | A method. | 625941d9d164cc6175782fe7 |
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) <NEW_LINE> _x = self.header.frame_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE... | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | 625941d9d18da76e23532771 |
def __init__(self, line, *args, **kwargs): <NEW_LINE> <INDENT> super(transaction, self).__init__(*args, **kwargs) <NEW_LINE> for attr in self.attrnames: <NEW_LINE> <INDENT> setattr(self, attr, getattr(line, attr)) <NEW_LINE> <DEDENT> self.transfer_type = 'UNKN' <NEW_LINE> self.remote_account = '' <NEW_LINE> self.remote... | Initialize own dict with read values. | 625941d9283ffb24f3c55b98 |
def finish(self): <NEW_LINE> <INDENT> if self.skip_delete: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> delete_list = [] <NEW_LINE> for obj_id, obj in self.obj_dict.items(): <NEW_LINE> <INDENT> if not obj._found: <NEW_LINE> <INDENT> delete_list.append(obj) <NEW_LINE> <DEDENT> <DEDENT> if self.delete_limit is not None... | Run synchronization, applying delete_func to items not mark():ed | 625941d95fcc89381b1e195a |
def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse("restaurant_tracker:detail", kwargs={"pk": self.pk}) | Returns an absolute URL for editing an instance of a Restaurant | 625941d93346ee7daa2b3006 |
def eval_file_in_history(self, filee): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shas = self.files[filee]["sha"].unique() <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> LOGGER.error(r"No sha for this file {0} ".format(filee)) <NEW_LINE> return <NEW_LINE> <DEDENT> if shas != []: <NEW_LINE> <INDENT> self.eva... | This method take file and eval this file by history of commits
thanks to method evaluate. | 625941d90fa83653e4657253 |
def matrixconstructor(self, args): <NEW_LINE> <INDENT> value = matrix(args[1], args[2], converter=args[3], fake=args[4]) <NEW_LINE> for y in xrange(0, len(args[0])): <NEW_LINE> <INDENT> for x in xrange(0, len(args[0][y])): <NEW_LINE> <INDENT> value.store(y,x, self.deitem(args[0][y][x])) <NEW_LINE> <DEDENT> <DEDENT> ret... | Reconstructs A Matrix. | 625941d9167d2b6e31218e2e |
def handle_opponent_move_result(self, captured_piece, captured_square): <NEW_LINE> <INDENT> pass | This function is called at the start of your turn and gives you the chance to update your board.
:param captured_piece: bool - true if your opponents captured your piece with their last move
:param captured_square: chess.Square - position where your piece was captured | 625941d9f548e778e58cd818 |
def test_get_index_fields(self): <NEW_LINE> <INDENT> index_field_service = IndexFieldService(self.vault) <NEW_LINE> resp = index_field_service.get_index_fields() <NEW_LINE> self.assertEqual(resp['meta']['status'], 200) <NEW_LINE> self.assertGreater(len(resp['data']), 0) | tests IndexFieldService.get_index_fields | 625941d9507cdc57c6306f79 |
def create_config_file(config_file_path): <NEW_LINE> <INDENT> buf = StringIO.StringIO(_DEFAULT_CONFIG) <NEW_LINE> cfg = RawConfigParser() <NEW_LINE> cfg.readfp(buf) <NEW_LINE> with open(config_file_path, "w") as config_file: <NEW_LINE> <INDENT> cfg.write(config_file) | Creates a config file with default values. | 625941d915fb5d323cde0dac |
def get_basic(self): <NEW_LINE> <INDENT> rows = self.table.select(order_by=self.table.c.id).execute().fetchall() <NEW_LINE> recs = [] <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> cur_row = list(row) <NEW_LINE> id = cur_row[0] <NEW_LINE> name = cur_row[1] <NEW_LINE> description = cur_row[2] <NEW_LINE> local_time = ut... | Returns list with basic information about analysis runs that have been performed
| 625941d97c178a314d6ef6fc |
def fit(self, X, y): <NEW_LINE> <INDENT> N = len(X) <NEW_LINE> n = X.shape[1] <NEW_LINE> I = np.identity(n) <NEW_LINE> I[0, 0] = 0 <NEW_LINE> X, y = check_X_y(X, y) <NEW_LINE> left = np.linalg.inv((1 / N) * X.transpose() @ X + self.reg_lambda * I) <NEW_LINE> right = (1/N)*X.transpose()@y <NEW_LINE> self.weights_ = lef... | Fit optimal weights to data using closed form solution.
:param X: A tensor of shape (N, n_features_) where N is the batch size.
:param y: A tensor of shape (N,) where N is the batch size. | 625941d938b623060ff0b086 |
def is_verb(word): <NEW_LINE> <INDENT> if not word: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> pos_info = pos_tag([word]) <NEW_LINE> return pos_info[0][1] in ['VB', 'VBN'] | Check if our word is Verb or no | 625941d95e10d32532c5f1c0 |
def trigger(self): <NEW_LINE> <INDENT> self.regset.evn.ctl_sts = self._CTL_TRG_MASK | Activate SW trigger. | 625941d9be8e80087fb20ed9 |
def host_formatter(task, exception=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import getpass <NEW_LINE> import platform <NEW_LINE> return getpass.getuser()+"@"+platform.node() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return "n/a" | Formater
Example
-------
foo@bar | 625941d956b00c62f0f148f4 |
def add(self, item, priority: float) -> None: <NEW_LINE> <INDENT> if self.contains(item): <NEW_LINE> <INDENT> raise ValueError('item already present') <NEW_LINE> <DEDENT> if self._max: <NEW_LINE> <INDENT> priority *= -1 <NEW_LINE> <DEDENT> self._nodes.append((item, priority)) <NEW_LINE> self._locations[item] = len(self... | Adds an item to the priority queue.
Parameters
----------
item
An item to be inserted into the queue. Does not need to be
hashable.
priority : float
The extrinsic priority of the object.
Returns
-------
None
Nothing. | 625941d950485f2cf553d034 |
def neighbors(x): <NEW_LINE> <INDENT> return move(_OFFSETS, x) | Returns cells that are neighbors of x = (i,j). | 625941d94f88993c3716c2ff |
def service_update(context, service_id, values): <NEW_LINE> <INDENT> return _service_update(context, values, service_id) | Set the given properties on an image and update it.
:raises NotFound if service does not exist. | 625941d960cbc95b062c67dd |
def validate_user(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return User.objects.get(pk=user_id) <NEW_LINE> <DEDENT> except User.DoesNotExist as exc: <NEW_LINE> <INDENT> with translation_language(language): <NEW_LINE> <INDENT> self.status.fail(_('User permission denied.')) <NEW_LINE> <DEDENT> LOGGER.error(f'{log_p... | Validate if the user exists otherwise log error. | 625941d955399d3f0558894e |
def enable_print(): <NEW_LINE> <INDENT> sys.stdout = sys.__stdout__ | Enables displays
| 625941d9379a373c97cfaddf |
def testScanEvents(self): <NEW_LINE> <INDENT> pass | Test ScanEvents | 625941d966656f66f7cbc446 |
def get_ends(self): <NEW_LINE> <INDENT> return (self.head, self.tail) | Return the tuple (head_id, tail_id). | 625941d9a934411ee375192d |
def get_secrets(): <NEW_LINE> <INDENT> with open(local_path / "secrets.json") as f: <NEW_LINE> <INDENT> return json.load(f) | returns the json data in the secrets file | 625941d96aa9bd52df03703e |
def optimal_trade(self, ps_recipe:list, max_iterations:int=2000, include_zero_gft_ps:bool=True)->tuple: <NEW_LINE> <INDENT> num_categories = self.num_categories <NEW_LINE> if len(ps_recipe) != num_categories: <NEW_LINE> <INDENT> raise ValueError( "There are {} categories but {} elements in the PS recipe". format(num_ca... | :param ps_recipe: a list that indicates the number of agents from each category that should be in each PS.
For example: [1,2] means 1 agent from first category (e.g. one buyer) and 2 agents from second category (e.g. two sellers).
:param include_zero_gft_ps: whether or not to include in the optimal trade procurement-se... | 625941d93eb6a72ae02ec77c |
def get_word(words): <NEW_LINE> <INDENT> rand_idx = random.randrange(0, len(words) - 1) <NEW_LINE> return words[rand_idx] | Selects a single word randomly from words list and returns it.
:param words: list of strings
:return word: string from words list | 625941d99b70327d1c4e106f |
def delRoomOwner(self, name): <NEW_LINE> <INDENT> if name in self.config["muc#roomconfig_roomowners"]: <NEW_LINE> <INDENT> self.config["muc#roomconfig_roomowners"].remove(name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> barejid = JID(name).getStripped() <NEW_LINE> for k, v in list(self.par... | Remove an owner from the room. Will not work if there is only one owner and tries to step down | 625941d996565a6dacc8f964 |
def __optimize(self, destinationList): <NEW_LINE> <INDENT> aircraft = self.__aircraft.getAircraft(destinationList[-1]) <NEW_LINE> if aircraft is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> homeDestination = destinationList[0] <NEW_LINE> destinationListPermutations = self.__permute(destinationList) <NEW_LINE... | __optimize(destinationList : list) -> (cheapestPermutation : list)
Returns a cheapest permutation with it's cost. | 625941d9d6c5a102081442e6 |
def checkTorrentFinished(): <NEW_LINE> <INDENT> logger.info("Checking if any torrents have finished seeding and can be removed") <NEW_LINE> myDB = db.DBConnection() <NEW_LINE> results = myDB.select('SELECT * from snatched WHERE Status="Seed_Processed"') <NEW_LINE> for album in results: <NEW_LINE> <INDENT> hash = album[... | Remove Torrent + data if Post Processed and finished Seeding | 625941d9462c4b4f79d1d969 |
def test_get_item_sh_fields_identity_no_uuid(self): <NEW_LINE> <INDENT> identity = { "name": "pepe", "username": "pepepotamo" } <NEW_LINE> empty_item_by_rol = {'author': self.empty_item} <NEW_LINE> def rol_side_effect(rol): <NEW_LINE> <INDENT> return empty_item_by_rol[rol] <NEW_LINE> <DEDENT> self._enrich.__get_item_sh... | uuid is None (not found in sortinghat) or does not exist | 625941d926238365f5f0f10b |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(OBDLoadingPanel, self).__init__(*args, **kwargs) <NEW_LINE> image = wx.Image(LOAD_BACKGROUND_FILENAME) <NEW_LINE> width, height = wx.GetDisplaySize() <NEW_LINE> image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH) <NEW_LINE> self.bitmap = wx.BitmapFrom... | Constructor. | 625941d91b99ca400220ad4b |
def _get_11paths_serialized_headers(x_headers): <NEW_LINE> <INDENT> if x_headers: <NEW_LINE> <INDENT> headers = to_key_val_list(x_headers, sort=True, insensitive=True) <NEW_LINE> serialized_headers = "" <NEW_LINE> for key, value in headers: <NEW_LINE> <INDENT> if key.lower().startswith(X_11PATHS_HEADER_PREFIX.lower()) ... | Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received.
:param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered.
:return: string The serialized headers, an empty string if no headers are passed, or None if there's a problem... | 625941d907f4c71912b1171d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.