code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@login_required <NEW_LINE> def modify_user(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> form = UserModificationForm(request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> data = form.cleaned_data <NEW_LINE> user = User.objects.get(pk=request.user.id) <NEW_LINE> user.first_nam...
Edits core User data :param request: http request object :return: renders User detail form or updates
625941c54428ac0f6e5ba7f7
def my_get_features(state,idt,idp): <NEW_LINE> <INDENT> me = StateFoot(state,idt,idp) <NEW_LINE> dJB = me.distance(me.ball_pos) <NEW_LINE> dJmC = me.distance(me.my_goal) <NEW_LINE> dJoC = me.distance(me.opp_goal) <NEW_LINE> oppNearest = nearest(me.my_pos, me.opponents) <NEW_LINE> dJDef = me.distance(oppNearest) <NEW_LI...
extraction du vecteur de features d'un etat, ici distance a la balle, distance au but, distance balle but
625941c5236d856c2ad447de
@array_function_dispatch(_tensorsolve_dispatcher) <NEW_LINE> def tensorsolve(a, b, axes=None): <NEW_LINE> <INDENT> a, wrap = _makearray(a) <NEW_LINE> b = asarray(b) <NEW_LINE> an = a.ndim <NEW_LINE> if axes is not None: <NEW_LINE> <INDENT> allaxes = list(range(0, an)) <NEW_LINE> for k in axes: <NEW_LINE> <INDENT> allax...
Solve the tensor equation ``a x = b`` for x. It is assumed that all indices of `x` are summed over in the product, together with the rightmost indices of `a`, as is done in, for example, ``tensordot(a, x, axes=b.ndim)``. Parameters ---------- a : array_like Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tup...
625941c52eb69b55b151c8b3
def test_get(self): <NEW_LINE> <INDENT> with translation.override('en'): <NEW_LINE> <INDENT> request = self.request_factory.get('/url/') <NEW_LINE> request.user = self.user <NEW_LINE> response = TestCreateView.as_view()(request) <NEW_LINE> self.assertEqual(response.status_code, 200)
Display an empty form
625941c538b623060ff0adf3
def close(self): <NEW_LINE> <INDENT> pass
stop listening
625941c5d164cc6175782d53
@click.command('lint') <NEW_LINE> @options.optional_tools_arg() <NEW_LINE> @click.option( '--report_level', type=click.Choice(['all', 'warn', 'error']), default="all" ) <NEW_LINE> @click.option( '--fail_level', type=click.Choice(['warn', 'error']), default="warn" ) <NEW_LINE> @pass_context <NEW_LINE> def cli(ctx, path,...
Check specified tool(s) for common errors and adherence to best practices.
625941c55f7d997b87174a9c
def _enter_results(self, **results): <NEW_LINE> <INDENT> self._wait() <NEW_LINE> self.browser.find_option_by_text(results["winner"]).first.click() <NEW_LINE> positions = ["pm", "mg", "lo", "mo"] <NEW_LINE> for position in positions: <NEW_LINE> <INDENT> result_data = results[position] <NEW_LINE> debater_name_index = 2 i...
Enters results for a ballot, where results are a dict in the following format: { "winner": String "pm": { "first": {Bool}, "speaks": {Float}, "ranks": {Int} } "mg": { "first": {Bool}, "speaks": {Float}, "ranks": {Int} } "lo": { "first": {Bool}, "speaks": {Float}, "ranks": {Int} } "mo": { "first": {...
625941c5e5267d203edcdca4
def test_password_too_short(self): <NEW_LINE> <INDENT> payload = { 'email': 'thomas.kim@gmail.com', 'password': 'pw' } <NEW_LINE> res=self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> user_exists = get_user_model().object.filter( email=payloa...
Test that password must be more than 5 characters
625941c5b545ff76a8913e1c
def __init__(__self__, *, from_port: int, protocol: str, to_port: int, cidr_blocks: Optional[Sequence[str]] = None, description: Optional[str] = None, ipv6_cidr_blocks: Optional[Sequence[str]] = None, prefix_list_ids: Optional[Sequence[str]] = None, security_groups: Optional[Sequence[str]] = None, self: Optional[bool] ...
:param int from_port: Start port (or ICMP type number if protocol is `icmp`) :param str protocol: Protocol. If you select a protocol of "-1" (semantically equivalent to `all`, which is not a valid value here), you must specify a `from_port` and `to_port` equal to `0`. If not `icmp`, `tcp`, `udp`, or `-1` use the [proto...
625941c5d58c6744b4257c66
def getLeftMost(self,bTree): <NEW_LINE> <INDENT> if self.child[0] == None: <NEW_LINE> <INDENT> return self.items[0] <NEW_LINE> <DEDENT> return bTree.nodes[self.child[0]].getLeftMost(bTree)
Return the left-most item in the subtree rooted at self.
625941c5fbf16365ca6f61c7
def calc_psi4_energy(molecule, fragment_indicies, model, cp, settings): <NEW_LINE> <INDENT> if not has_psi4: <NEW_LINE> <INDENT> raise LibraryNotAvailableError("psi4") <NEW_LINE> <DEDENT> log_file = settings.get("files", "log_path") + "/calculations/" + model + "/" + str(cp) + "/" + molecule.get_SHA1()[:8] + "frags:" +...
Calculates the energy of a subset of the fragments of a molecule with psi4 Args: molecule - the Molecule object to calculate the energy of fragment_indicies - list of indicies of fragments to include in the calculation model - the model to use for this calculation, should be specified as method/ba...
625941c507f4c71912b11487
def _discover_bridge(): <NEW_LINE> <INDENT> SSDP_ADDR = "239.255.255.250" <NEW_LINE> SSDP_PORT = 1900 <NEW_LINE> SSDP_MX = 1 <NEW_LINE> SSDP_ST = "urn:schemas-upnp-org:device:Basic:1" <NEW_LINE> ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + "HOST: %s:%d\r\n" % (SSDP_ADDR, SSDP_PORT) + "MAN...
Naive method to find a phillips hue bridge on the network, via UPNP. Raises ------ DeviceNotFoundException If the bridge is not found. Returns ------- str An IP address representing the bridge that was found
625941c5b830903b967e9912
def weight_map(self): <NEW_LINE> <INDENT> if isinstance(self.like, gtutils.SummedLikelihood): <NEW_LINE> <INDENT> cmap = self.like.components[0].logLike.countsMap() <NEW_LINE> try: <NEW_LINE> <INDENT> p_method = cmap.projection().method() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> p_method = 0 <NEW_...
Return 3-D weights map for this component as a Map object. Returns ------- map : `~fermipy.skymap.MapBase`
625941c57c178a314d6ef463
def __init__(self, submapping: Mapping[str, Any]) -> None: <NEW_LINE> <INDENT> self._submapping = submapping
@param submapping: Another read-only mapping which will be used to look up items.
625941c5a4f1c619b28b0042
def add_user_is_anonymous(**kwargs): <NEW_LINE> <INDENT> user = kwargs.get('user') <NEW_LINE> if user and getattr(user, 'is_anonymous', False): <NEW_LINE> <INDENT> return dict(user=None, user_is_anonymous=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dict(user_is_anonymous=False)
If user is anonymous, add a boolean flag and set user to None.
625941c5d8ef3951e3243543
def disable_aux(self): <NEW_LINE> <INDENT> self.ade.next = 0 <NEW_LINE> yield self.clock.posedge
Makes the ADE signal 0
625941c57cff6e4e8111798c
def _get_last_clear(self): <NEW_LINE> <INDENT> return self.__last_clear
Getter method for last_clear, mapped from YANG variable /lldp/state/counters/last_clear (yang:date-and-time) YANG Description: Indicates the last time the counters were cleared.
625941c58c3a8732951583bf
def artificial_data(dt1, dt2, minutes=1): <NEW_LINE> <INDENT> def fxweek(x): <NEW_LINE> <INDENT> return 2 - x * (1 - x) <NEW_LINE> <DEDENT> def sat(x): <NEW_LINE> <INDENT> return 2 * x + 2 <NEW_LINE> <DEDENT> data = [] <NEW_LINE> dt = datetime.timedelta(minutes=minutes) <NEW_LINE> while dt1 < dt2: <NEW_LINE> <INDENT> i...
Generates articial data every minutes. @param dt1 first date @param dt2 second date @param minutes interval between two observations @return dataframe .. runpython:: :showcode: import datetime from mlinsights.timeseries.datasets import artificial_data now = datetim...
625941c592d797404e30418f
def resize_image(img): <NEW_LINE> <INDENT> height_orig = img.shape[0] <NEW_LINE> width_orig = img.shape[1] <NEW_LINE> unit_scale = 384. <NEW_LINE> if width_orig > height_orig: <NEW_LINE> <INDENT> scale = width_orig / unit_scale <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> scale = height_orig / unit_scale <NEW_LINE> <D...
Resize image and make it fit for network. Args: img (array): image Returns: tensor: data ready for network
625941c54f6381625f114a42
def execute_numpy_min_max(): <NEW_LINE> <INDENT> n, m = list(map(int, input().split())) <NEW_LINE> arr = np.zeros((n, m), np.int) <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> arr[i] = np.array(input().split(), np.int) <NEW_LINE> <DEDENT> print(np.max(np.min(arr, axis=1)))
Problem 1: numpy challenges 10/15
625941c54e4d5625662d43e0
def get_gifs_from_giphy(search_string): <NEW_LINE> <INDENT> baseurl = "https://api.giphy.com/v1/gifs/search" <NEW_LINE> response = requests.get(baseurl, params={'q':search_string, 'api_key':api_key, 'limit':5}) <NEW_LINE> r = json.loads(response.text) <NEW_LINE> return r['data']
Returns data from Giphy API with up to 5 gifs corresponding to the search input
625941c54f6381625f114a41
def predict(self, x): <NEW_LINE> <INDENT> x2C = list(map(self.dfun, [x]*self.k, self.C)) <NEW_LINE> return np.argmin(x2C)
Predict the cluster name of x should belong to
625941c563b5f9789fde70eb
def _add_to_cache(self, using, ct): <NEW_LINE> <INDENT> key = (ct.app_label, ct.document) <NEW_LINE> self.__class__._cache.setdefault(using, {})[key] = ct <NEW_LINE> self.__class__._cache.setdefault(using, {})[ct.id] = ct
Insert a ContentType into the cache.
625941c592d797404e304190
def __init__(self, zone_identifier, ): <NEW_LINE> <INDENT> self.zone_identifier = zone_identifier <NEW_LINE> self.match = None <NEW_LINE> self.name = None <NEW_LINE> self.order = None <NEW_LINE> self.page = None <NEW_LINE> self.per_page = None <NEW_LINE> self.content = None <NEW_LINE> self.type = None <NEW_LINE> self.p...
:param zone_identifier:
625941c531939e2706e4ce72
def reload_from_json(self, json): <NEW_LINE> <INDENT> for key, value in json.items(): <NEW_LINE> <INDENT> self.__dict__[key] = value
Public method that replaces all attributes of the Student instance
625941c5bf627c535bc131d5
def test_subdomain_reserve_paid_over_limit(self, client, current_user, session): <NEW_LINE> <INDENT> sub1 = subdomain.ReservedSubdomainFactory(user=current_user, name="sub") <NEW_LINE> sub2 = subdomain.ReservedSubdomainFactory(user=current_user, name="subtract") <NEW_LINE> sub3 = subdomain.ReservedSubdomainFactory(user...
User can't reserve more than 5 subdomains if they are paid tier
625941c5851cf427c661a516
def configure(conf): <NEW_LINE> <INDENT> for node in conf.children: <NEW_LINE> <INDENT> key = node.key.lower() <NEW_LINE> val = node.values <NEW_LINE> if key == 'metric_list': <NEW_LINE> <INDENT> global METRICS_CONFIGURED <NEW_LINE> METRICS_CONFIGURED = val <NEW_LINE> collectd.debug('Exporting the following metrics ' +...
Receive configuration block. Sets up the global system metrics list to export. Arguments: Takes the collectd Config object (https://collectd.org/documentation/manpages/collectd-python.5.shtml#config). Returns: None.
625941c53617ad0b5ed67efe
def has_finished(self): <NEW_LINE> <INDENT> return self.status == PropResult.FINISHED
Get a value indicating whether the PropResult is finished. :return: bool True if the execution is finished; otherwise, False.
625941c55fc7496912cc3984
def getNumPoints(self): <NEW_LINE> <INDENT> return self.pLibTSG.tsgGetNumPoints(self.pGrid)
if points have been loaded, returns the same as getNumLoaded() otherwise, returns the same as getNumNeeded()
625941c5379a373c97cfab4a
def unpublished_conditional(self): <NEW_LINE> <INDENT> unknown_start = Q(start__isnull=True) <NEW_LINE> no_country = Q(country__isnull=True) <NEW_LINE> no_venue = Q(venue__exact="") <NEW_LINE> no_address = Q(address__exact="") <NEW_LINE> no_latitude = Q(latitude__isnull=True) <NEW_LINE> no_longitude = Q(longitude__isnu...
Return conditional for events without: start OR country OR venue OR url OR are marked as 'cancelled' (ie. unpublished events). This will be used in `self.published_events`, too.
625941c529b78933be1e56b4
def remove_group(group_name): <NEW_LINE> <INDENT> if config.groups_config().has_section(group_name): <NEW_LINE> <INDENT> config.groups_config().remove_section(group_name) <NEW_LINE> config.groups_config().save() <NEW_LINE> return True <NEW_LINE> <DEDENT> return False
Removes a group from the global groups file if the group exists
625941c557b8e32f524834a0
def test(self, arch, compiler_name, compiler_version, service): <NEW_LINE> <INDENT> logging.info("Testing Docker by service %s." % service) <NEW_LINE> try: <NEW_LINE> <INDENT> image = "%s/%s:%s" % (self.variables.docker_username, service, self.variables.docker_build_tag) <NEW_LINE> libcxx_list = ["libstdc++"] if compil...
Validate Docker image by Conan install :param arch: Name of he architecture :param compiler_name: Compiler to be specified as conan setting e.g. clang :param compiler_version: Compiler version to be specified as conan setting e.g. 3.8 :param service: Docker compose service name
625941c5377c676e912721af
def __init__(self, c_session: CData) -> None: <NEW_LINE> <INDENT> self.c_session = c_session
Create a new EncryptionSession from the C struct
625941c53617ad0b5ed67eff
def format_instruction(isa, inst): <NEW_LINE> <INDENT> atoms = [] <NEW_LINE> args = [] <NEW_LINE> atoms.append(isa.types['INST_OPCODE'].describe(inst.op)) <NEW_LINE> if inst.cond: <NEW_LINE> <INDENT> atoms.append(isa.types['INST_CONDITION'].describe(inst.cond)) <NEW_LINE> <DEDENT> if inst.sat: <NEW_LINE> <INDENT> atoms...
Format instruction as text.
625941c5be7bc26dc91cd609
def _similarity_measure(x, y, constant): <NEW_LINE> <INDENT> numerator = 2 * x * y + constant <NEW_LINE> denominator = x ** 2 + y ** 2 + constant <NEW_LINE> return numerator / denominator
Calculate feature similarity measurement between two images
625941c58da39b475bd64f78
@memoize <NEW_LINE> def Tget_range_restriction_tag(T): <NEW_LINE> <INDENT> from spyne.model.primitive import Decimal <NEW_LINE> from spyne.model.primitive import Integer <NEW_LINE> if issubclass(T, Decimal): <NEW_LINE> <INDENT> def _get_float_restrictions(prot, restriction, cls): <NEW_LINE> <INDENT> if cls.Attributes.f...
The get_range_restriction template function. Takes a primitive, returns a function that generates range restriction tags.
625941c5aad79263cf390a45
def run(self): <NEW_LINE> <INDENT> build.run(self) <NEW_LINE> for rule in CustomBuild._rules: <NEW_LINE> <INDENT> args = shlex.split(rule) <NEW_LINE> cmd = args.pop(0) <NEW_LINE> if cmd == 'copy': <NEW_LINE> <INDENT> args[1] = self.path_from_package(args[1]) <NEW_LINE> self.copy_file(*args) <NEW_LINE> <DEDENT> elif cmd...
run build process
625941c573bcbd0ca4b2c07d
@pytest.fixture(scope="function") <NEW_LINE> def abstract_mailbox(request, discussion, test_session): <NEW_LINE> <INDENT> from assembl.models import AbstractMailbox <NEW_LINE> ps = AbstractMailbox( discussion=discussion, name='a source', type='abstract_mailbox') <NEW_LINE> test_session.add(ps) <NEW_LINE> test_session.f...
An AbstractMailbox fixture with type of abstract_mailbox
625941c5b7558d58953c4f1d
def test_list_users(self): <NEW_LINE> <INDENT> self.driver.update_from_datasource() <NEW_LINE> user_list = self.driver.state[keystone_driver.KeystoneDriver.USERS] <NEW_LINE> self.assertIsNotNone(user_list) <NEW_LINE> self.assertEqual(2, len(user_list)) <NEW_LINE> self.assertTrue(('alice', 'alice foo', 'True', '019b18a1...
Test conversion of complex user objects to tables.
625941c532920d7e50b281d5
def getBill(self, product, amount): <NEW_LINE> <INDENT> self.cur += 1 <NEW_LINE> discount = self.discount if not self.cur%self.n else 1 <NEW_LINE> ans = 0 <NEW_LINE> for i, j in zip(product, amount): <NEW_LINE> <INDENT> ans += self.d[i]*j <NEW_LINE> <DEDENT> return ans * discount
:type product: List[int] :type amount: List[int] :rtype: float
625941c526238365f5f0ee73
def load_api_folder(api_folder_path): <NEW_LINE> <INDENT> api_definition_mapping = {} <NEW_LINE> api_items_mapping = load_folder_content(api_folder_path) <NEW_LINE> for api_file_path, api_items in api_items_mapping.items(): <NEW_LINE> <INDENT> if isinstance(api_items, list): <NEW_LINE> <INDENT> for api_item in api_item...
load api definitions from api folder. Args: api_folder_path (str): api files folder. api file should be in the following format: [ { "api": { "def": "api_login", "request": {}, "validate": [] } ...
625941c5b57a9660fec33889
def unpin(self, key): <NEW_LINE> <INDENT> i = self.keys_to_indices[key] <NEW_LINE> entry = self.data[i] <NEW_LINE> if entry.pins == 0: <NEW_LINE> <INDENT> raise ValueError(f"Key {key!r} has not been pinned") <NEW_LINE> <DEDENT> entry.pins -= 1 <NEW_LINE> if entry.pins == 0: <NEW_LINE> <INDENT> self.__pinned_entry_count...
Undo one previous call to ``pin(key)``. Once all calls are undone this key may be evicted as normal.
625941c55fdd1c0f98dc0239
def _pair_diff(ts_score): <NEW_LINE> <INDENT> mid_score = ts_score.unsqueeze(-1) <NEW_LINE> mid_score = mid_score.expand( mid_score.size()[:-1] + (mid_score.size()[-2],) ) <NEW_LINE> pair_diff = mid_score - mid_score.transpose(-2, -1) <NEW_LINE> return pair_diff
score's i - j in the last dimension :param ts_score: :return:
625941c5d268445f265b4e75
def DataArrayInt_Modulus(*args): <NEW_LINE> <INDENT> return _MEDCoupling.DataArrayInt_Modulus(*args)
DataArrayInt_Modulus(DataArrayInt a1, DataArrayInt a2) -> DataArrayInt 1
625941c556ac1b37e62641d9
def cancel_event(self, urlname, event_id): <NEW_LINE> <INDENT> pdb.set_trace() <NEW_LINE> params = {'key' : self._api_key} <NEW_LINE> post = {'remove_from_calendar': False} <NEW_LINE> query = urllib.parse.urlencode(params) <NEW_LINE> url = '{0}/{1}/{2}'.format(URL_DELETE_EVENT, urlname, event_id) <NEW...
Post PythonKC meetup event. Returns ------- ??? Exceptions ---------- * PythonKCMeetupsBadJson * PythonKCMeetupsBadResponse * PythonKCMeetupsMeetupDown * PythonKCMeetupsNotJson * PythonKCMeetupsRateLimitExceeded
625941c5e1aae11d1e749cbc
def test_fetch_returns_ready_media(self): <NEW_LINE> <INDENT> self.client.credentials(HTTP_AUTHORIZATION=self.auth, format='json') <NEW_LINE> response = self.client.get(self.fetch_uri) <NEW_LINE> self.client.credentials() <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(response.data['...
GET api/v1/curate/fetch returns ready media.
625941c5aad79263cf390a46
def performance_per_gene(population: list, event_list_split: int, finder: BaseFinder): <NEW_LINE> <INDENT> performance = [] <NEW_LINE> for gene in population: <NEW_LINE> <INDENT> print('GENE', gene) <NEW_LINE> performance.append([fitness(gene, event_list_split, finder), gene]) <NEW_LINE> <DEDENT> def get_key(item): <NE...
Finds the mcc performance of the given gens :param population: all the genes that are being considered :param event_list_split: number of events to test in the events list :param finder: finder to be used in the fitness calculation :return: list of list of mcc and genes
625941c5e76e3b2f99f3a814
def __iter__(self): <NEW_LINE> <INDENT> return Capture._Iter(self.duplicate().__video_capture)
-> iter<FrameInfo>
625941c5462c4b4f79d1d6d7
def stn_relaxation(): <NEW_LINE> <INDENT> events = [Event(name='e%d'%(i)) for i in range(4)] <NEW_LINE> tcs = [TemporalConstraint(start=events[0],end=events[1],ctype='controllable',lb=7.0,ub=10.0), TemporalConstraint(start=events[1],end=events[2],ctype='controllable',lb=4.0,ub=10.0), TemporalConstraint(start=events[0],...
Example of performing minimum-cost relaxation to restore STN feasibility.
625941c532920d7e50b281d6
def test_run_command(): <NEW_LINE> <INDENT> data = [ ([u'echo', '-n', 1], '1'), ([u'echo', '-n', u'Köln'], 'Köln'), ] <NEW_LINE> for cmd, x in data: <NEW_LINE> <INDENT> r = run_command(cmd) <NEW_LINE> assert r == x <NEW_LINE> <DEDENT> with pytest.raises(subprocess.CalledProcessError): <NEW_LINE> <INDENT> run_command(['...
Run command.
625941c55f7d997b87174a9d
def generic_ai_start(self, function: callable) -> None: <NEW_LINE> <INDENT> self.graphism = False <NEW_LINE> self.set_first_elements() <NEW_LINE> while self.move(): <NEW_LINE> <INDENT> while self.zero: <NEW_LINE> <INDENT> function() <NEW_LINE> <DEDENT> function()
Allow to play according to the argument `function` without the graphic interface
625941c59c8ee82313fbb77b
def getLastBestSolutionIteration(self): <NEW_LINE> <INDENT> return self.__lastBestSolutionIteration
! Getter of last iteration when algorithm found new solution. @return Integer: Last iteration when algorithm found new solution.
625941c516aa5153ce362480
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(SetAutopilotParamsRequest, self).__init__(*args, **kwds) <NEW_LINE> if self.values is None: <NEW_LINE> <INDENT> self.values = [] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.values = []
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: values :param args: complete set ...
625941c566673b3332b92098
def register_node(self, address): <NEW_LINE> <INDENT> parsed_url = urlparse(address) <NEW_LINE> self.nodes.add(parsed_url.netloc) <NEW_LINE> def valid_chain(self, chain): <NEW_LINE> <INDENT> last_block = chain[0] <NEW_LINE> current_index = 1 <NEW_LINE> while current_index < len(chain): <NEW_LINE> <INDENT> block = chain...
Вносим новый узел в список узлов :param address: <str> адрес узла , другими словами: 'http://192.168.0.5:5000' :return: None
625941c591af0d3eaac9ba1e
def action_on_failure_validator(x): <NEW_LINE> <INDENT> valid_values = ["CONTINUE", "CANCEL_AND_WAIT"] <NEW_LINE> if x not in valid_values: <NEW_LINE> <INDENT> raise ValueError("ActionOnFailure must be one of: %s" % ", ".join(valid_values)) <NEW_LINE> <DEDENT> return x
Property: Step.ActionOnFailure
625941c591f36d47f21ac4f8
def ExecuteOptionID(self, *args, **kwargs): <NEW_LINE> <INDENT> pass
Override this method.
625941c5099cdd3c635f0c62
def parse( env: Environment, templates: List[ThemedTemplateSource], globals: Optional[Mapping[str, object]] = None, ) -> List[ThemedTemplate]: <NEW_LINE> <INDENT> parsed_templates = [] <NEW_LINE> for bundle in templates: <NEW_LINE> <INDENT> parsed_theme = env.from_string( bundle.theme.source, path=bundle.theme.path, gl...
Parse a list of templates using the given environment.
625941c57c178a314d6ef464
def links(self, other_extent_name=None, other_field_name=None): <NEW_LINE> <INDENT> i = self._i <NEW_LINE> return i._db._entity_links(i._extent.name, i._oid, other_extent_name, other_field_name)
Return dictionary of (extent_name, field_name): entity_list pairs, or list of linking entities if `other_extent_name` and `other_field_name` are supplied.
625941c5656771135c3eb874
def startTestClass(self, testcls): <NEW_LINE> <INDENT> pass
Called just before a ``testcls`` runs its tests.
625941c599cbb53fe6792bee
def get_error_content(self): <NEW_LINE> <INDENT> return str(self)
Return the error content
625941c5d8ef3951e3243544
def test_dfs_edge_classification_directed_cyclic_has_tree_edges(self): <NEW_LINE> <INDENT> res = self.classification_undirected_cyclic.has_tree_edges() <NEW_LINE> self.assertTrue(res)
Test method "has_tree_edges" using a directed graph.
625941c5009cb60464c633ba
def get_all_entry_points(): <NEW_LINE> <INDENT> extension_points = get_entry_points(EXTENSION_POINT_GROUP_NAME) <NEW_LINE> entry_points = defaultdict(dict) <NEW_LINE> for dist in importlib_metadata.distributions(): <NEW_LINE> <INDENT> for ep in dist.entry_points: <NEW_LINE> <INDENT> if ep.group not in extension_points:...
Get all entry points related to ``ros2cli`` and any of its extensions. :returns: mapping of entry point names to ``EntryPoint`` instances :rtype: dict
625941c5cc0a2c11143dce97
@mod_auth.route('/setnewpass/<reset_key>', methods=['GET', 'POST']) <NEW_LINE> @mod_auth.route('/setnewpass/<reset_key>/', methods=['GET', 'POST']) <NEW_LINE> def setnewpass(reset_key): <NEW_LINE> <INDENT> user = PasswordReset.get_by_key(reset_key) <NEW_LINE> if not user: <NEW_LINE> <INDENT> flash("That is not a valid ...
Set the user's new password Update the user's password if they entered a new one correctly. Arguments: reset_key - the unique key for resetting the password
625941c599fddb7c1c9de399
def make_all_pairs_with_master(granule_info_list, master_index): <NEW_LINE> <INDENT> master_slave_info_list = [] <NEW_LINE> for i, granule_info_slave in enumerate(granule_info_list): <NEW_LINE> <INDENT> if i == master_index: <NEW_LINE> <INDENT> print('Skip master with master pairing') <NEW_LINE> continue <NEW_LINE> <DE...
Pairs all granules in the list of granule info dictionaries with the granule specified through the master index Args: granule_info_list: list of granule info dictionaries master_index: an integer for the master index Returns: a list of master slave dictionaries
625941c5d7e4931a7ee9df24
def get(self, key: K) -> V: <NEW_LINE> <INDENT> return self._dict[key]
Return the value for the specified key.
625941c5adb09d7d5db6c797
def main(a, b, c): <NEW_LINE> <INDENT> if (a <= -1): <NEW_LINE> <INDENT> return '1' <NEW_LINE> <DEDENT> if (a >= 0 | a <= 5): <NEW_LINE> <INDENT> return '2' <NEW_LINE> <DEDENT> if (a >= 6): <NEW_LINE> <INDENT> return 3/0
a: [3; 3][-10; -3][1; 2] b: [9; 12][-10; -3][4, 8] c: [9; 12][-10; -3][4, 8]
625941c50383005118ecf5eb
def update_position(self,player): <NEW_LINE> <INDENT> x,y = player.car.get_coor() <NEW_LINE> x += player.car.vel * np.cos(player.car.angle) <NEW_LINE> y += player.car.vel * np.sin(player.car.angle) <NEW_LINE> player.count += 1 <NEW_LINE> if self.is_out(x,y,player.car.block): <NEW_LINE> <INDENT> newblock = player.car.bl...
Calculates new car's position if car reaches a wall velocity is set to 0
625941c59b70327d1c4e0ddb
def SetupTooltip(self,canvasPoint,e): <NEW_LINE> <INDENT> pass
SetupTooltip(self: GH_AbstractInteraction,canvasPoint: PointF,e: GH_TooltipDisplayEventArgs)
625941c57d847024c06be2c1
def djmodel(Tx, n_a, n_values): <NEW_LINE> <INDENT> X = Input(shape=(Tx, n_values)) <NEW_LINE> a0 = Input(shape=(n_a,), name='a0') <NEW_LINE> c0 = Input(shape=(n_a,), name='c0') <NEW_LINE> a = a0 <NEW_LINE> c = c0 <NEW_LINE> outputs = list() <NEW_LINE> for t in range(Tx): <NEW_LINE> <INDENT> x = Lambda(lambda x: X[:,t,...
Implement the model Arguments: Tx -- length of the sequence in a corpus n_a -- the number of activations used in our model n_values -- number of unique values in the music data Returns: model -- a keras model with the
625941c557b8e32f524834a1
def find_minimal_subsets(runner, cur_features, min_subsets): <NEW_LINE> <INDENT> test_pref = runner.test_num <NEW_LINE> logger = logging.getLogger('network-testing') <NEW_LINE> cache = {} <NEW_LINE> min_sets = delta_debugging.ddmin_iter( list(get_unique_features(cur_features)), lambda f: cached_test(runner, filter_feat...
Finds all minimal failure-inducing subsets of features from a starting set of features, minimal subsets are saved JSON format on disk :param runner: TestRunner for the test case to be minimized :param cur_features: Initially enabled features :param min_subsets: Previously identified minimal subsets
625941c5de87d2750b85fd98
def as_event_description(self): <NEW_LINE> <INDENT> description = { 'name': self.name, 'timestamp': self.timestamp, } <NEW_LINE> if self.data is not None: <NEW_LINE> <INDENT> description['data'] = self.data <NEW_LINE> <DEDENT> return description
Get the event description. Returns a dictionary describing the event.
625941c52eb69b55b151c8b4
def train_document_da_dbow(model, doc_words, doctag_indexes, alpha, work=None, train_words=False, learn_doctags=True, learn_words=True, learn_hidden=True, word_vectors=None, word_locks=None, doctag_vectors=None, doctag_locks=None, doctag_vectors2=None, doctag_locks2=None): <NEW_LINE> <INDENT> if doctag_vectors is None:...
Update distributed bag of words model ("PV-DBOW") by training on a single document. Called internally from `Doc2Vec.train()` and `Doc2Vec.infer_vector()`. The document is provided as `doc_words`, a list of word tokens which are looked up in the model's vocab dictionary, and `doctag_indexes`, which provide indexes into...
625941c5004d5f362079a33b
def fit(self, X, y=None): <NEW_LINE> <INDENT> X, y = self._check_Xy(X, y) <NEW_LINE> self.classes_ = np.unique(y) <NEW_LINE> self.filters_, self.patterns_, _ = _fit_xdawn( X, y, n_components=self.n_components, reg=self.reg, signal_cov=self.signal_cov) <NEW_LINE> return self
Fit Xdawn spatial filters. Parameters ---------- X : array, shape (n_epochs, n_channels, n_samples) The target data. y : array, shape (n_epochs,) | None The target labels. If None, Xdawn fit on the average evoked. Returns ------- self : Xdawn instance The Xdawn instance.
625941c597e22403b379cfa1
def edit_playlist_information_guide(*args: str, **kwargs) -> str: <NEW_LINE> <INDENT> field = args[0] <NEW_LINE> text = "" <NEW_LINE> if field == "title": <NEW_LINE> <INDENT> text = f"{_fountain_pen} Enter playlist name/description" <NEW_LINE> <DEDENT> elif field == "description": <NEW_LINE> <INDENT> text = f"{_books} ...
Guides the users how to edit their playlists. Two fields are available to edit: 1. title 2. description :param args: Field: the field that is going to be edited :param kwargs: :return: A text containing how to edit playlists
625941c50fa83653e4656fc3
def register_peer(self, pid, paddr): <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> self.peers[pid] = orb.Stub(paddr) <NEW_LINE> print("Peer {} has joined the system.".format(pid)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.lock.release()
Register a new peer joining the network.
625941c5a8370b77170528a7
def on_init(self): <NEW_LINE> <INDENT> self.controller = gameController.Controller()
This method create and assign an object Controller to the app.
625941c52ae34c7f2600d139
def add_topping(self, topping: str) -> None: <NEW_LINE> <INDENT> topping = self.topping.create_ingredient(topping) <NEW_LINE> self.pizza.add_ingredient(topping)
Добавляет топпинг
625941c54527f215b584c460
def plot(self): <NEW_LINE> <INDENT> fig, ax = plt.subplots() <NEW_LINE> for run in self.runs: <NEW_LINE> <INDENT> data = run.get_dataset("stats-performance-raw-*.csv") <NEW_LINE> data = data['rt_s_act'] + data['ndb_s_act'] <NEW_LINE> ecdf = sm.distributions.ECDF(data) <NEW_LINE> ax.plot(ecdf.x, ecdf.y, drawstyle='steps...
Plots the CDF of path stretch.
625941c54428ac0f6e5ba7f9
def test_same_start_date_and_offset(self): <NEW_LINE> <INDENT> directory = os.path.dirname(__file__) <NEW_LINE> with open(os.path.join(directory, 'timezone_same_start_and_offset.ics'), 'rb') as fp: <NEW_LINE> <INDENT> data = fp.read() <NEW_LINE> <DEDENT> cal = icalendar.Calendar.from_ical(data) <NEW_LINE> d = cal.subco...
testing if we can handle VTIMEZONEs whose different components have the same DTSTARTs, TZOFFSETFROM, and TZOFFSETTO.
625941c521bff66bcd68495c
def loss_values(self): <NEW_LINE> <INDENT> return list(zip(*[x.loss for x in self.batches]))
Return a list of concatenated loss values. Every tuple in the list contains NUM_BATCHES values of one loss. e.g. [ (0.2,0.19,0.15,...), # loss index 0 (0.2,0.19,0.15,...), # loss index 1 ... ]
625941c5236d856c2ad447e0
def get_word_score(self, word_list): <NEW_LINE> <INDENT> word2id = {} <NEW_LINE> count = 1 <NEW_LINE> for word in word_list: <NEW_LINE> <INDENT> word2id[word] = count <NEW_LINE> count += 1 <NEW_LINE> <DEDENT> words = {} <NEW_LINE> que = Queue() <NEW_LINE> for w in word_list: <NEW_LINE> <INDENT> if w not in words: <NEW_...
每个单词在经过text rank 后的得分 :param title: 文档标题 :param sentence: 文档内容 都是经过分词处理的 :return:
625941c5fb3f5b602dac3699
def start_session(self, cid): <NEW_LINE> <INDENT> self.cid = cid <NEW_LINE> self.cart = [] <NEW_LINE> clear_screen() <NEW_LINE> print ('Customer session started.') <NEW_LINE> while True: <NEW_LINE> <INDENT> print ('Welcome, what would you like to do today?') <NEW_LINE> print ('1. Search for products') <NEW_LINE> print ...
Main interface, called from login system
625941c560cbc95b062c654a
def _is_extra(self, edition): <NEW_LINE> <INDENT> return re.search("extra", edition, re.IGNORECASE) is not None
Checks if edition is extra or not.
625941c57b25080760e39461
def confd_state_internal_cdb_client_subscription_path(self, **kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") <NEW_LINE> internal = ET.SubElement(confd_state, "internal") <NEW_LINE> cdb = ET.SubElem...
Auto Generated Code
625941c51f037a2d8b946206
def lengthOfLIS(self, nums): <NEW_LINE> <INDENT> arr = [] <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> if not arr or num > arr[-1]: <NEW_LINE> <INDENT> arr.append(num) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pos = self.getFirstLarger(arr, num) <NEW_LINE> arr[pos] = num <NEW_LINE> <DEDENT> <DEDENT> return len(a...
:type nums: List[int] :rtype: int
625941c5ff9c53063f47c1fc
@functools.lru_cache(maxsize=None) <NEW_LINE> def fetch_release(client, bucket, key, version_id=None) -> Release: <NEW_LINE> <INDENT> extras = {} <NEW_LINE> if version_id is not None: <NEW_LINE> <INDENT> extras["VersionId"] = version_id <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> resp = client.get_object(Bucket=bucket...
Fetches a release from a S3 object. Arguments: client (botocore.client.S3): client for AWS S3. bucket (str): bucket's name. key (str): object's key. version_id (str or None): version ID of the S3 object. If the `version_id` is `None`, it will return the latest release. Returns: Release or ...
625941c5eab8aa0e5d26db5f
def _onPress(self,event): <NEW_LINE> <INDENT> if self.helpIndex: <NEW_LINE> <INDENT> ShowHelp(self.helpIndex,self.parent) <NEW_LINE> return <NEW_LINE> <DEDENT> self.dlg = wx.Dialog(self.parent,wx.ID_ANY,'Help information', style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) <NEW_LINE> mainSizer = wx.BoxSizer(wx.VERTICAL) <...
Respond to a button press by displaying the requested text
625941c5d7e4931a7ee9df25
def setRoomType(self, roomType): <NEW_LINE> <INDENT> self.roomType = roomType
:param roomType: (Optional) 房间类型 1-小房间(音频单流订阅) 2-大房间(音频固定订阅)
625941c58e7ae83300e4afd4
def rotate(self, R): <NEW_LINE> <INDENT> self.A[0:3,0:3] = np.dot(R, self.A[0:3,0:3]) <NEW_LINE> self.A[0:3,-1]=np.dot(R, self.A[0:3,-1]) <NEW_LINE> return self
apply a rotation Parameters ---------- R : np.array 3x3 rotation matrix Returns ------- self
625941c5e64d504609d74847
def create_group_configuration_experiment(self, groups, associate_experiment): <NEW_LINE> <INDENT> self.course_fixture._update_xblock(self.course_fixture._course_location, { "metadata": { u"user_partitions": [ self.create_user_partition_json(0, "Name", "Description.", groups), ], }, }) <NEW_LINE> if associate_experimen...
Creates a Group Configuration containing a list of groups. Optionally creates a Content Experiment and associates it with previous Group Configuration. Returns group configuration or (group configuration, experiment xblock)
625941c5a219f33f34628973
def update_metadata(metadata: dict, new_result: bool, msg: str): <NEW_LINE> <INDENT> metadata['prev_syncdatetime'] = metadata['syncdatetime'] <NEW_LINE> metadata['prev_syncresult'] = metadata['syncresult'] <NEW_LINE> metadata['syncdatetime'] = datetime.datetime.now() <NEW_LINE> metadata['syncresult'] = new_result <NEW_...
Update the metadata structure with new values. :param metadata: The dictionary to update. :param new_result: The result to set. :param msg: A message to set. :return:
625941c5a05bb46b383ec82b
def getAccount(self, pub): <NEW_LINE> <INDENT> name = self.getAccountFromPublicKey(pub) <NEW_LINE> if not name: <NEW_LINE> <INDENT> return {"name": None, "type": None, "pubkey": pub} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> account = Account(name, dpay_instance=self.dpay) <NEW_LINE> <DEDEN...
Get the account data for a public key (first account found for this public key) :param str pub: Public key
625941c55f7d997b87174a9e
@util.fixes(issues.AnchorNotFound) <NEW_LINE> def fix_anchor_not_found(issue: issues.AnchorNotFound, tree: Tree, patches: Patches, opt: options.Options) -> None: <NEW_LINE> <INDENT> if opt.mode == '-i': <NEW_LINE> <INDENT> __fix_anchor_not_found_i(issue, tree, patches, opt) <NEW_LINE> <DEDENT> elif opt.mode == '-a': ...
Fix an `AnchorNotFound` issue. The result of this function's successful run is a patch added to `patches`.
625941c58e05c05ec3eea37b
def network_output_before_softmax(self, x): <NEW_LINE> <INDENT> layer = 0 <NEW_LINE> for b, w in zip(self.biases, self.weights): <NEW_LINE> <INDENT> if layer == len(self.sizes) - 1: <NEW_LINE> <INDENT> x = np.dot(w, x) + b <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = sigmoid(np.dot(w, x) + b) <NEW_LINE> <DEDENT> l...
Return the output of the network before softmax if ``x`` is input.
625941c5bf627c535bc131d6
def altaVenta(self): <NEW_LINE> <INDENT> query = QtSql.QSqlQuery() <NEW_LINE> query.prepare( 'insert into ventas (codfacventa, codarticventa, cantidad, precio) VALUES (:codfacventa, :codarticventa,' ' :cantidad, :precio )') <NEW_LINE> query.bindValue(':codfacventa', int(var.venta[0])) <NEW_LINE> query.bindValue(':codar...
Módulo que añade líneas de venta en una factura creada :return: None :rtype: None Inserta en la tabla ventas una línea de venta que se va mostrando cada vez que realizamos la transacción. Tras realizar la venta se crea una nueva factura incluyendo el combobox de selección de artículor
625941c5e5267d203edcdca6
def sha256sum(path, blocksize=65536): <NEW_LINE> <INDENT> sig = hashlib.sha256() <NEW_LINE> with open(path, 'rb') as f: <NEW_LINE> <INDENT> buf = f.read(blocksize) <NEW_LINE> while len(buf) > 0: <NEW_LINE> <INDENT> sig.update(buf) <NEW_LINE> buf = f.read(blocksize) <NEW_LINE> <DEDENT> <DEDENT> return sig.hexdigest()
Computes the SHA256 signature of a file to verify that the file has not been modified in transit and that it is the correct version of the data.
625941c5283ffb24f3c5590a
def test_disable_domain(self): <NEW_LINE> <INDENT> domain2 = unit.new_domain_ref() <NEW_LINE> self.resource_api.create_domain(domain2['id'], domain2) <NEW_LINE> project2 = unit.new_project_ref(domain_id=domain2['id']) <NEW_LINE> self.resource_api.create_project(project2['id'], project2) <NEW_LINE> user2 = unit.create_u...
Call ``PATCH /domains/{domain_id}`` (set enabled=False).
625941c5d58c6744b4257c68
def analise_sintatica(fila): <NEW_LINE> <INDENT> if fila.__len__(): <NEW_LINE> <INDENT> op = '+-*/(){}[]' <NEW_LINE> <DEDENT> _fila = Fila() <NEW_LINE> characteres = '' <NEW_LINE> if fila.vazia(): <NEW_LINE> <INDENT> raise ErroSintatico('') <NEW_LINE> <DEDENT> while not fila.vazia(): <NEW_LINE> <INDENT> current = fila....
Função que realiza analise sintática de tokens produzidos por analise léxica. Executa validações sintáticas e se não houver erro retorn fila_sintatica para avaliacao :param fila: fila proveniente de análise lexica :return: fila_sintatica com elementos tokens de numeros Complexidade: o(n) em tempo de execução e memória
625941c5e5267d203edcdca7
def fromisoformat(date_string, cls=datetime): <NEW_LINE> <INDENT> if not isinstance(date_string, str): <NEW_LINE> <INDENT> raise TypeError('fromisoformat: argument must be str') <NEW_LINE> <DEDENT> dstr = date_string[0:10] <NEW_LINE> tstr = date_string[11:] <NEW_LINE> try: <NEW_LINE> <INDENT> date_components = _parse_i...
Construct a datetime from the output of datetime.isoformat().
625941c530c21e258bdfa4a4
@auth.route('/logout') <NEW_LINE> @login_required <NEW_LINE> def logout(): <NEW_LINE> <INDENT> logout_user() <NEW_LINE> flash("You've been successfully registered!") <NEW_LINE> return redirect(url_for("main.index"))
View Function to logout a user
625941c5283ffb24f3c5590b