code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _mailbox_post_processing_checks(self, address): <NEW_LINE> <INDENT> parts = address.split('@') <NEW_LINE> lpart = parts[0] <NEW_LINE> if len(lpart) > 1024: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> domn = parts[1] <NEW_LINE> if len(domn) > 253: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> labels ...
Additional post processing checks to ensure mailbox is valid.
625941c7796e427e537b0611
def data(self, text): <NEW_LINE> <INDENT> self.__data.append(text)
Adds character data to the output stream. Parameters ---------- text : str Character data.
625941c757b8e32f524834e6
def init_logger(): <NEW_LINE> <INDENT> path = split(realpath(__file__))[0] <NEW_LINE> with open(join(path, 'log_config.json')) as json_file: <NEW_LINE> <INDENT> log_config_dict = json.load(json_file) <NEW_LINE> filename = log_config_dict.get('handlers').get('file_handler').get('filename') <NEW_LINE> filename = ''.join(...
Initialize the logger and create a time stamp for the file
625941c716aa5153ce3624c5
@pytest.fixture <NEW_LINE> def quteproc(quteproc_process, server, request): <NEW_LINE> <INDENT> request.node._quteproc_log = quteproc_process.captured_log <NEW_LINE> quteproc_process.before_test() <NEW_LINE> quteproc_process.request = request <NEW_LINE> yield quteproc_process <NEW_LINE> quteproc_process.after_test()
Per-test qutebrowser fixture which uses the per-file process.
625941c7a8ecb033257d311a
def variable_to_np_tf(x): <NEW_LINE> <INDENT> return x.data.cpu().numpy().transpose([0, 2, 3, 1])
功能:将variable转换为numpy
625941c7ac7a0e7691ed411a
def _error_handler(self, error): <NEW_LINE> <INDENT> logger.error('Notification got error :' + repr(error))
Handles errors @param error: an error command object @type error: L{command.Command}
625941c7cad5886f8bd27026
def raw_train_data_generator(self): <NEW_LINE> <INDENT> raise NotImplementedError
Returns a generator that yields the TRAIN data one item at a time in a dictionary where each key is a field and the value is of the raw type from the source. DataSources need to implement this.
625941c7bf627c535bc1321b
def test_page_renders_locales(self): <NEW_LINE> <INDENT> response = self.client.get( reverse("wiki.select_locale", args=[self.d.slug]), HTTP_HOST=settings.WIKI_HOST, ) <NEW_LINE> assert response.status_code == 200 <NEW_LINE> assert_no_cache_header(response) <NEW_LINE> doc = pq(response.content) <NEW_LINE> assert ( len(...
Load the page and verify it contains all the locales for l10n.
625941c799fddb7c1c9de3de
def stern_brocot_tree(): <NEW_LINE> <INDENT> sbt = deque([1, 1]) <NEW_LINE> while True: <NEW_LINE> <INDENT> sbt += [sbt[0] + sbt[1], sbt[1]] <NEW_LINE> sbt += [sbt[1] + sbt[2], sbt[2]] <NEW_LINE> yield (sbt.popleft(), sbt.popleft())
Stern-Brocot Tree, an infinite complete binary tree in which the vertices correspond one-for-one to the positive rational numbers, whose values are ordered from left to right as in a search tree. It related to Farey series closely. details see: https://en.wikipedia.org/wiki/Stern%E2%80%93Brocot_tree
625941c71b99ca400220aafe
def read_testdata(src): <NEW_LINE> <INDENT> data = {} <NEW_LINE> size = 0 <NEW_LINE> src_len = len(src) <NEW_LINE> for root, dirs, files in os.walk(src, topdown=False): <NEW_LINE> <INDENT> for name in files: <NEW_LINE> <INDENT> fn = os.path.join(root, name) <NEW_LINE> relname = fn[src_len + 1:] <NEW_LINE> if relname.en...
read all test data into memory
625941c75fdd1c0f98dc027f
def __init__(self, ai_settings, screen): <NEW_LINE> <INDENT> super(Alien, self).__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.image = pygame.image.load('images/alien.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LI...
初始化外星人并设置其初始位置
625941c756b00c62f0f146a5
def build_args(parser): <NEW_LINE> <INDENT> parser.add_argument( "--in-dir", required=True, type=str, help="Path to directory with dataset", ) <NEW_LINE> parser.add_argument( "--out-labeling", required=True, type=str, help="Path to output JSON" ) <NEW_LINE> parser.add_argument( "--num-workers", default=1, type=int, hel...
Constructs the command-line arguments for ``index2color``.
625941c7091ae35668666fad
def generate_password(self): <NEW_LINE> <INDENT> unshuffled_list = [] <NEW_LINE> digits = string.digits <NEW_LINE> lower = string.ascii_lowercase <NEW_LINE> upper = string.ascii_uppercase <NEW_LINE> punctuation = string.punctuation <NEW_LINE> unshuffled_list += random.sample(digits, k=random.randint(1, 7)) <NEW_LINE> u...
This generates a pseudo random string for a password this is not secure at all...
625941c730bbd722463cbe12
def projected_energy(self): <NEW_LINE> <INDENT> numerator = self.estimates[self.names.enumer] <NEW_LINE> denominator = self.estimates[self.names.edenom] <NEW_LINE> return (numerator / denominator).real
Computes projected energy from estimator array. Returns ------- eproj : float Mixed estimate for projected energy.
625941c7a4f1c619b28b0088
def security_group_rule_to_permission(self, rule): <NEW_LINE> <INDENT> protocol = rule[1] <NEW_LINE> from_port, to_port = get_port_range(rule[2], protocol) <NEW_LINE> sg = self.evpc.get_security_group(rule[0]) <NEW_LINE> permission = {"IpProtocol": protocol, "FromPort": from_port, "ToPort": to_port} <NEW_LINE> if sg is...
Return a permission dictionary from a rule tuple.
625941c73539df3088e2e397
def create_single_campaign(self, name, send_date, mailing_lists, message): <NEW_LINE> <INDENT> body = { 'type': 'single', 'name': name, 'sdate': send_date, 'status': 1, 'public': 1, 'tracklinks': 'all', } <NEW_LINE> body.update(self._format_mailing_lists(mailing_lists, body)) <NEW_LINE> body['m[{}]'.format(message)] = ...
Creates a new "single"-type Campaign Corresponds to the ActiveCampaign API's `campaign_create` action. :param name: Name of the campaign :type name: str :param send_date: Date string (format: YYYY-MM-DD hh:mm:ss) representing the date and time the campaign should be sent :type send_date: str :param mailing_lists:...
625941c7d10714528d5ffd2e
def __init__(self, gstate): <NEW_LINE> <INDENT> self.gstate = gstate <NEW_LINE> self.event_funcs = {}
@gstate should be whatever you want sent to the registered functions.
625941c77d43ff24873a2ced
def gen_token(): <NEW_LINE> <INDENT> return uuid4().__str__()
gen token generates a unique token for a session :return: string
625941c72ae34c7f2600d17e
def create_db(self, cursor, db_name, db_template, tablespace = None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.log("Creating test database") <NEW_LINE> query = 'CREATE DATABASE "%s" WITH TEMPLATE "%s"' % (db_name, db_template) <NEW_LINE> if tablespace: <NEW_LINE> <INDENT> query += " TABLESPACE %s" % (tablespac...
Create a new database from a template.
625941c79f2886367277a8db
def unauthenticated_userid(request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> reg = request.registry <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> reg = get_current_registry() <NEW_LINE> <DEDENT> policy = reg.queryUtility(IAuthenticationPolicy) <NEW_LINE> if policy is None: <NEW_LINE> <INDENT> retu...
Return an object which represents the *claimed* (not verified) user id of the credentials present in the request. ``None`` if there is no :term:`authentication policy` in effect or there is no user data associated with the current request. This differs from :func:`~pyramid.security.authenticated_userid`, because the e...
625941c7a79ad161976cc192
def updateLoadedFileLabel(self): <NEW_LINE> <INDENT> self._label.setText('Showing: ' + self._internalModel.dataFile() + ' ')
Updates the label above the table. Assumes data file loaded.
625941c7287bf620b61d3ab1
def compute_ids(ref, hyp): <NEW_LINE> <INDENT> if(len(ref) == 0): <NEW_LINE> <INDENT> raise ValueError('reference can\'t be empty string') <NEW_LINE> <DEDENT> num_ins, num_del, num_sub = 0, 0, 0 <NEW_LINE> if(len(hyp) == 0): <NEW_LINE> <INDENT> num_del = len(ref) <NEW_LINE> return num_ins, num_del, num_sub <NEW_LINE> <...
Compute insersion, deletion and substitution of two string. Args: ref: string, reference hyp: string, hypothesis Returns: insersion: int deletion: int substitution: int Raises: ValueError: If ref is empty
625941c750485f2cf553cde6
def no_html_finder(url, max_width=None): <NEW_LINE> <INDENT> embed = self.dummy_finder(url, max_width) <NEW_LINE> embed['html'] = None <NEW_LINE> return embed
A finder which returns everything but HTML
625941c74527f215b584c4a5
@utils.arg('server', metavar='<server>', help='Name or ID of server.') <NEW_LINE> def do_show(cs, args): <NEW_LINE> <INDENT> _print_server(cs, args)
Show details about the given server.
625941c7d486a94d0b98e192
def from_dict(self, dct): <NEW_LINE> <INDENT> self.person_id = dct.get('id') or dct.get('attrib').get('id') <NEW_LINE> self.name = dct.get('name') or dct.get('value') <NEW_LINE> self.photo = dct.get('url','photo') <NEW_LINE> self.save()
Информация о персоне из словаря, возвращаемого API.
625941c7c4546d3d9de72a80
def ncbi(kingdom, n_genomes, output): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> Entrez.email = 'hadrien.gourle@slu.se' <NEW_LINE> Entrez.tool = 'InSilicoSeq' <NEW_LINE> Entrez.api_key = 'd784b36672ca73601f4a19c3865775a17207' <NEW_LINE> full_id_list = Entrez.read(Entrez.esearch( 'assembly', ter...
download random genomes sequences from ncbi genomes with entrez eutils and requests. Args: kingdom (string): the kingdom from which the sequences are from n_genomes (int): the number of genomes to download Returns: str: the output file
625941c7ad47b63b2c509fcc
def test_heap_insert_value_low(self): <NEW_LINE> <INDENT> A = HeapCapable([7, 16, 7, 4, 8, 13, 18, 3, 10, 7, 12, 8, 17, 3]) <NEW_LINE> HeapSort(A) <NEW_LINE> increasekey(A,13,1) <NEW_LINE> heap_max = extractMax(A) <NEW_LINE> self.assertEqual(heap_max,1)
heap_insert_value_low: inserts low value
625941c73cc13d1c6d3c73c7
def reinit(self): <NEW_LINE> <INDENT> self.delete() <NEW_LINE> self.init();
Delete and create a new SAT solver.
625941c72eb69b55b151c8fb
def makePartialJac(spec_pair, varnames, select=None): <NEW_LINE> <INDENT> fargs, fspec = spec_pair <NEW_LINE> J = QuantSpec('J', fspec) <NEW_LINE> dim = len(varnames) <NEW_LINE> if J.dim == dim: <NEW_LINE> <INDENT> return (fargs, fspec) <NEW_LINE> <DEDENT> assert J.dim > dim, "Cannot add variable names to system while ...
Use this when parameters have been added to a modified Generator which might clash with aux fn argument names. (E.g., used by find_nullclines). 'select' option (list of varnames) selects those entries from the Jac of the varnames, e.g. for constructing Jacobian w.r.t. 'parameters' using a parameter formerly a va...
625941c799cbb53fe6792c33
def log(self, txt, dt=None): <NEW_LINE> <INDENT> dt = dt or self.datas[0].datetime.date(0) <NEW_LINE> print('%s, %s' % (dt.isoformat(), txt)) <NEW_LINE> self.f.write('%s, %s\n' % (dt.isoformat(), txt))
Logging function fot this strategy
625941c73cc13d1c6d3c73c8
def limit_length(string, desired_length): <NEW_LINE> <INDENT> if desired_length < 2: <NEW_LINE> <INDENT> raise ValueError( "You cannot limit a string to such a short length!") <NEW_LINE> <DEDENT> if len(string)<=desired_length: <NEW_LINE> <INDENT> return string <NEW_LINE> <DEDENT> starter = string[ : desired_length - 2...
Ensure that a string is no longer than a desired length.
625941c767a9b606de4a7f07
def preprocess_data(numbers, size): <NEW_LINE> <INDENT> if size <= 2: <NEW_LINE> <INDENT> return numbers, [], [] <NEW_LINE> <DEDENT> times = {} <NEW_LINE> for value in numbers: <NEW_LINE> <INDENT> if value in times: <NEW_LINE> <INDENT> times[value] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> times[value] = 1 <NE...
Remove unnecessary duplicates. Args: numbers (list): The set of numbers size (int): Size of the subsets Returns: tuple: A subset of the numbers array, a list of the numbers which have duplicates, and a list with groups which should be included
625941c7596a897236089b0f
def assert_preservation_pending_count(query, count): <NEW_LINE> <INDENT> total_count = query.count() <NEW_LINE> assert total_count > 0 <NEW_LINE> assert ( query.with_transformation(MuseumObject.filter_preservation_pending) .count() == count ) <NEW_LINE> assert ( query.with_transformation(MuseumObject.exclude_preservati...
Assert that for a query a given number of preservable objects exist, and that the rest of the objects are non-preservable
625941c776e4537e8c3516bf
def create_autospec(spec, spec_set=False, instance=False, _parent=None, _name=None, **kwargs): <NEW_LINE> <INDENT> if _is_list(spec): <NEW_LINE> <INDENT> spec = type(spec) <NEW_LINE> <DEDENT> is_type = isinstance(spec, type) <NEW_LINE> _kwargs = {'spec': spec} <NEW_LINE> if spec_set: <NEW_LINE> <INDENT> _kwargs = {'spe...
Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the `spec` object as their spec. Functions or methods being mocked will have their arguments checked to check that they are called with the correct signature. If `spec_set` is True then attempting to se...
625941c7099cdd3c635f0ca8
def singleline_diff_format(line1, line2, idx): <NEW_LINE> <INDENT> equal_op = [] <NEW_LINE> small_len = min(len(line1),len(line2)) <NEW_LINE> if (("\n" in line1) | ("\n" in line2) | ("\r" in line1) | ("\r" in line2) | (idx < 0) | (idx > small_len)): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN...
Inputs: line1 - first single line string line2 - second single line string idx - index at which to indicate difference Output: Returns a three line formatted string showing the location of the first difference between line1 and line2. If either input line contains a newline or carriage return, then ret...
625941c799cbb53fe6792c34
def headless(ui='dummy', stdout=None): <NEW_LINE> <INDENT> p = Popen(['kak', '-n', '-ui', ui], stdout=stdout) <NEW_LINE> time.sleep(0.01) <NEW_LINE> return p
Start a headless Kakoune process.
625941c7d4950a0f3b08c39d
def __init__(self, eid=None, fpath=None): <NEW_LINE> <INDENT> self.schedule = nflgame.schedule.games_byid.get(self.eid, None) <NEW_LINE> self.home = self.data['home']['abbr'] <NEW_LINE> self.away = self.data['away']['abbr'] <NEW_LINE> self.stats_home = _json_team_stats(self.data['home']['stats']['team']) <NEW_LINE> sel...
Creates a new Game instance given a game identifier. The game identifier is used by NFL.com's GameCenter live update web pages. It is used to construct a URL to download JSON data for the game. If the game has been completed, the JSON data will be cached to disk so that subsequent accesses will not re-download the da...
625941c7d164cc6175782d9a
def record_set_properties(object_id, input_params={}, always_retry=True, **kwargs): <NEW_LINE> <INDENT> return DXHTTPRequest('/%s/setProperties' % object_id, input_params, always_retry=always_retry, **kwargs)
Invokes the /record-xxxx/setProperties API method. For more info, see: https://documentation.dnanexus.com/developer/api/introduction-to-data-object-metadata/properties#api-method-class-xxxx-setproperties
625941c71d351010ab855b69
def content(self, rule: str) -> str: <NEW_LINE> <INDENT> res = ''.join(self.texts(rule)) <NEW_LINE> return res
return str
625941c7498bea3a759b9afc
def get_data(self): <NEW_LINE> <INDENT> data = super(GetItemFile, self).get_data() <NEW_LINE> if not data.get("title"): <NEW_LINE> <INDENT> data["title"] = data.get("id") <NEW_LINE> <DEDENT> return data
Files from Plone 3 could have title not set. In this case, set it with the id
625941c7956e5f7376d70ebb
def set_work_mesh(self, mesh_name): <NEW_LINE> <INDENT> self.mesh_name = mesh_name <NEW_LINE> smesh = smeshBuilder.New() <NEW_LINE> mesh_path = "/Mesh/" + mesh_name <NEW_LINE> obj = salome.myStudy.FindObjectByPath(mesh_path).GetObject() <NEW_LINE> if obj: <NEW_LINE> <INDENT> self.work_mesh = smesh.Mesh(obj) <NEW_LINE> ...
set which mesh to export
625941c70383005118ecf630
def crossover_simple(select_pop, new_pop_size, crossover_rate): <NEW_LINE> <INDENT> new_pop = [] <NEW_LINE> random.shuffle(select_pop) <NEW_LINE> non_cross = int((1-crossover_rate)*new_pop_size) <NEW_LINE> if non_cross != 0.0: <NEW_LINE> <INDENT> new_pop.extend(select_pop[:non_cross]) <NEW_LINE> <DEDENT> while len(new_...
Simple crossover function. It chooses which branch from the first parent tree that has to be removed for crossing. It then attaches the opposite branch to the tree.
625941c756b00c62f0f146a6
def color_negative_red(val): <NEW_LINE> <INDENT> if val < 0 : <NEW_LINE> <INDENT> color = 'green' <NEW_LINE> <DEDENT> elif val == 0: <NEW_LINE> <INDENT> color = 'black' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> color = 'red' <NEW_LINE> <DEDENT> return 'color: %s' % color
Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise.
625941c76fece00bbac2d78a
def redraw(self): <NEW_LINE> <INDENT> self.set_cursor(self.cursor) <NEW_LINE> if self.cursor is None: <NEW_LINE> <INDENT> self.top = 0 <NEW_LINE> <DEDENT> elif self.cursor < self.top or self.show_cursor == False: <NEW_LINE> <INDENT> self.top = self.cursor <NEW_LINE> <DEDENT> end_of_displaylist = len(self.dl) + 1 if sel...
Draw the scrollable, ensuring the cursor is visible Updates the field, scrolling until the cursor is visible. If we are not showing the cursor, the top line of the field is always the cursor line.
625941c776d4e153a657eb7e
def test_colour_correction_Vandermonde(self): <NEW_LINE> <INDENT> RGB = np.array([0.17224810, 0.09170660, 0.06416938]) <NEW_LINE> np.testing.assert_almost_equal( colour_correction_Vandermonde(RGB, MATRIX_TEST, MATRIX_REFERENCE), np.array([0.15034881, 0.10503956, 0.10512517]), decimal=7, ) <NEW_LINE> np.testing.assert_a...
Test :func:`colour.characterisation.correction.colour_correction_Vandermonde` definition.
625941c763d6d428bbe4453d
def __str__(self): <NEW_LINE> <INDENT> return self.name
Format the enumeration value as a string - just return the name. Returns:
625941c7435de62698dfdc9a
def saveModelJSON(theModel, modelName): <NEW_LINE> <INDENT> modelFilePath = os.path.join(modelsDirectory, modelName + '.json') <NEW_LINE> model_json = theModel.to_json() <NEW_LINE> with open(modelFilePath, 'w') as json_file: <NEW_LINE> <INDENT> json_file.write(model_json)
Saves the Model as JSON Args: model: the Keras NN Model modelName: the Name Returns:
625941c76fb2d068a760f0e9
def t200220_x29(): <NEW_LINE> <INDENT> assert t200220_x21(z16=1002, mode20=0, mode21=0, mode22=0, mode23=0) <NEW_LINE> return 0
State 0,1
625941c7099cdd3c635f0ca9
def _parse_namespace_worksheet(self, worksheet): <NEW_LINE> <INDENT> nsmap = {self.NS_STIX : 'stix', self.NS_SAXON : 'saxon'} <NEW_LINE> for i in xrange(1, worksheet.nrows): <NEW_LINE> <INDENT> if not any(self._get_cell_value(worksheet, i, x) for x in xrange(0, worksheet.ncols)): <NEW_LINE> <INDENT> continue <NEW_LINE>...
Parses the Namespaces worksheet of the profile. Returns a dictionary representation: d = { <namespace> : <namespace alias> } By default, entries for http://stix.mitre.org/stix-1 and http://icl.com/saxon are added.
625941c726068e7796caed2a
def test_get_ports_skip_2(test, monkeypatch): <NEW_LINE> <INDENT> with pytest.raises(pytest.skip.Exception) as excinfo: <NEW_LINE> <INDENT> test.get_ports([['sw1', 'sw2', 100], ]) <NEW_LINE> <DEDENT> assert str(excinfo.value) == "Insufficient links count required for test"
Verify that behavior of method get_ports is correct if input data of links are incorrect between devices.
625941c7656771135c3eb8bb
def GetValue(self,s): <NEW_LINE> <INDENT> knn = self.GetkNNSet(s) <NEW_LINE> return self.CalcmaxQValue(knn)
Return the Q value of state (s) for action (a)
625941c7ff9c53063f47c241
@pagina_privata(permessi=(GESTIONE_SOCI,)) <NEW_LINE> def us(request, me): <NEW_LINE> <INDENT> sedi = me.oggetti_permesso(GESTIONE_SOCI) <NEW_LINE> persone = Persona.objects.filter( Appartenenza.query_attuale(sede__in=sedi).via("appartenenze") ).distinct('cognome', 'nome', 'codice_fiscale') <NEW_LINE> attivi = Persona....
Ritorna la home page per la gestione dei soci.
625941c7fff4ab517eb2f489
def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(RootLayout, self).__init__(**kwargs) <NEW_LINE> self.orientation = 'vertical' <NEW_LINE> self.padding = (50, 50) <NEW_LINE> with self.canvas.before: <NEW_LINE> <INDENT> self.texture = Image(source=os.path.join(IMAGE_DIR, 'background_logo.jpg')).texture <NEW_LINE> ...
Constructor for background layout - this is the main layout. :param kwargs: arguments from kivy constructor
625941c745492302aab5e310
def test(): <NEW_LINE> <INDENT> bkwd_date = lambda x: datetime.datetime.now()-datetime.timedelta(seconds = x) <NEW_LINE> siad = 60*60*24 <NEW_LINE> xs = [456, 365, 232, 23, 12.5, 0.5, 0.3] <NEW_LINE> for x in xs: <NEW_LINE> <INDENT> req_datetime = bkwd_date(siad*x) <NEW_LINE> log.info("\nINPUT: %s\nOutput: %s\n******...
a small set of tests
625941c74428ac0f6e5ba83f
def is_browser_on_page(self): <NEW_LINE> <INDENT> home_page = HomePage(self.browser) <NEW_LINE> try: <NEW_LINE> <INDENT> return ("you have signed out" in self.browser.page_source.lower()) or home_page.is_browser_on_page() <NEW_LINE> <DEDENT> except WebDriverException: <NEW_LINE> <INDENT> return False
Is browser on the page? Returns: True if the sign out message is on the page.
625941c73317a56b86939ca8
def SetTituxRows(self,titulos,ancho): <NEW_LINE> <INDENT> pass
Asigna los títulos por fila al grid
625941c70a50d4780f666edf
def sqrt_poly(f): <NEW_LINE> <INDENT> if not f.is_monic(): <NEW_LINE> <INDENT> raise ValueError("f must be monic") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return prod([g**Integer(e/Integer(2)) for g,e in f.factor()]) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> raise ValueError("f must be a perfect sq...
Return the square root of the polynomial `f`. .. note:: At some point something like this should be a member of the polynomial class. For now this is just used internally by some charpoly functions above. EXAMPLES:: sage: import sage_modabvar sage: R.<x> = QQ[] sage: f = (x-1)*(x+2)*(x^2 + 1/3*...
625941c7187af65679ca516c
def get_active_contracts(self): <NEW_LINE> <INDENT> ProjectContract = apps.get_model('contracts', 'ProjectContract') <NEW_LINE> return self.contracts.exclude(status=ProjectContract.STATUS_COMPLETE)
Returns all associated contracts which are not marked complete.
625941c74e696a04525c9499
def do_sanity_check(): <NEW_LINE> <INDENT> for ts in total_samples: <NEW_LINE> <INDENT> print([[map_snapshot_to_frequency[sn] for sn in bs] for bs in chosen_snapshots[ts]]) <NEW_LINE> <DEDENT> return
Do a sanity check and ...DOES THIS DO ANYTHING RIGHT NOW
625941c715fb5d323cde0b5c
def put_attachment(self, doc, content, filename=None, content_type=None): <NEW_LINE> <INDENT> if filename is None: <NEW_LINE> <INDENT> if hasattr(content, 'name'): <NEW_LINE> <INDENT> filename = os.path.basename(content.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('no filename specified for atta...
Create or replace an attachment. Note that the provided `doc` is required to have a ``_rev`` field. Thus, if the `doc` is based on a view row, the view row would need to include the ``_rev`` field. :param doc: the dictionary or `Document` object representing the document that the attachment should be adde...
625941c7fbf16365ca6f6210
def coefficients_to_quadrature(coeffs): <NEW_LINE> <INDENT> coeffs = numpy.asfarray(coeffs) <NEW_LINE> if len(coeffs.shape) == 2: <NEW_LINE> <INDENT> coeffs = coeffs.reshape(1, 2, -1) <NEW_LINE> <DEDENT> assert len(coeffs.shape) == 3, "shape %s not allowed" % coeffs.shape <NEW_LINE> assert coeffs.shape[-1] >= 1 <NEW_LI...
Construct Gaussian quadrature abscissas and weights from three terms recurrence coefficients. Examples: >>> distribution = chaospy.Normal(0, 1) >>> coeffs, = chaospy.construct_recurrence_coefficients(4, distribution) >>> coeffs array([[0., 0., 0., 0., 0.], [1., 1., 2., 3., 4.]]) >>> (abs...
625941c78a43f66fc4b540b4
def get_future_index(code='', start='', end='', type=0): <NEW_LINE> <INDENT> pass
:param end: datetime.datetime :param start: datetime.datetime :param code: 品种缩写 CU,RB 如果为'',返回全部品种的数据 :param type: 指数类型 加权指数,主力指数,连续指数 :return:
625941c7dd821e528d63b1f7
def filter(self, terms=None, date_ranges=None, icase=True): <NEW_LINE> <INDENT> selected = set(self.entries.keys()) <NEW_LINE> if date_ranges: <NEW_LINE> <INDENT> selected = self._filter_by_date( set(title for title in selected if REFERENCE_REGEX.match(title)), *date_ranges, ) <NEW_LINE> <DEDENT> if terms: <NEW_LINE> <...
Filter the entries. Parameters: terms (Iterable[str]): Search terms for the entries. date_ranges (Sequence[DateRange]): Date ranges for the entries. Optional. icase (bool): Ignore case. Defaults to True. Returns: dict[str, Entry]: The entries.
625941c77d43ff24873a2cee
def _lines_to_claim(self, claim_lines, columns): <NEW_LINE> <INDENT> self._assert_split_claims_have_same_header_level_values(claim_lines, columns) <NEW_LINE> top = claim_lines[0] <NEW_LINE> tmp_claim = { new_col: top[columns[old_col]] for old_col, new_col in self.CLAIM_LEVEL_COLUMNS.items() } <NEW_LINE> tmp_claim['dx_c...
Convert set of lines of a claim into a claim model. TODO: Add null / empty string handling for each of the values in case they don't exist.
625941c74a966d76dd55105c
def get_grade(s1, s2, s3): <NEW_LINE> <INDENT> avg_grade = (s1 + s2 + s3) / 3 <NEW_LINE> if avg_grade >= 90: <NEW_LINE> <INDENT> return 'A' <NEW_LINE> <DEDENT> elif avg_grade >= 80: <NEW_LINE> <INDENT> return 'B' <NEW_LINE> <DEDENT> elif avg_grade >= 70: <NEW_LINE> <INDENT> return 'C' <NEW_LINE> <DEDENT> elif avg_grade...
Return letter grade reflecting average grade in class.
625941c72ae34c7f2600d17f
def test_response_one(testserver): <NEW_LINE> <INDENT> cli = JsonWspClient(testserver.url, ['ClacService']) <NEW_LINE> assert cli.sum(numbers=[1, 2, 3]).result == 6
test response one
625941c7f8510a7c17cf974a
def dispatch(self): <NEW_LINE> <INDENT> request = self.request <NEW_LINE> method_name = request.route.handler_method <NEW_LINE> if not method_name: <NEW_LINE> <INDENT> method_name = _normalize_handler_method(request.method) <NEW_LINE> <DEDENT> method = getattr(self, method_name, None) <NEW_LINE> if method is None: <NEW...
Dispatches the request. This will first check if there's a handler_method defined in the matched route, and if not it'll use the method correspondent to the request method (``get()``, ``post()`` etc).
625941c71f037a2d8b94624c
def test_arm(self): <NEW_LINE> <INDENT> d = build_dict(self._config(dict( OS_TARGET='Linux', TARGET_CPU='arm', MOZ_WIDGET_TOOLKIT='gtk2', ))) <NEW_LINE> self.assertEqual('arm', d['processor']) <NEW_LINE> d = build_dict(self._config(dict( OS_TARGET='Linux', TARGET_CPU='armv7', MOZ_WIDGET_TOOLKIT='gtk2', ))) <NEW_LINE> s...
Test that all arm CPU architectures => arm.
625941c78da39b475bd64fc0
def update(self, k, current_state, next_state): <NEW_LINE> <INDENT> cost = 0.5 * (self._param.get_annual_state_cost(current_state) + self._param.get_annual_state_cost(next_state)) * self._param.get_delta_t() <NEW_LINE> utility = 0.5 * (self._param.get_annual_state_utility(current_state) + self._param.get_annual_state_u...
updates the discounted total cost and health utility :param k: simulation time step :param current_state: current health state :param next_state: next health state
625941c78da39b475bd64fc1
def inline_text_payload(self, sent): <NEW_LINE> <INDENT> return {'text_snippet': {'content': sent, 'mime_type': 'text/plain'} }
Converts the input sentence into GCP's callable format Args: sent (string) - input sentence Return: (dict) - GCP NER input format
625941c7a934411ee37516e1
def observeState(self, gameState): <NEW_LINE> <INDENT> pacmanPosition = gameState.getPacmanPosition() <NEW_LINE> noisyDistances = gameState.getNoisyGhostDistances() <NEW_LINE> if len(noisyDistances) < self.numGhosts: return <NEW_LINE> emissionModels = [busters.getObservationDistribution(dist) for dist in noisyDistances...
Resamples the set of particles using the likelihood of the noisy observations. To loop over the ghosts, use: for i in range(self.numGhosts): ... A correct implementation will handle two special cases: 1) When a ghost is captured by Pacman, all particles should be updated so that the ghost appears in its...
625941c75fcc89381b1e170c
def save_raw_json_map_data(query, filepath): <NEW_LINE> <INDENT> response = fetch_raw_http_response(query) <NEW_LINE> file_utils.save_bytes(response, filepath)
run overpass api http query and save response to file as a raw byte stream of json data
625941c791f36d47f21ac53f
def compile_multiple(sources, options): <NEW_LINE> <INDENT> sources = [os.path.abspath(source) for source in sources] <NEW_LINE> processed = set() <NEW_LINE> results = CompilationResultSet() <NEW_LINE> timestamps = options.timestamps <NEW_LINE> verbose = options.verbose <NEW_LINE> context = None <NEW_LINE> cwd = os.get...
compile_multiple(sources, options) Compiles the given sequence of Pyrex implementation files and returns a CompilationResultSet. Performs timestamp checking and/or recursion if these are specified in the options.
625941c7498bea3a759b9afd
def main(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> context.binary = ELF(BINARY) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> print(f'Failed to load binary ({BINARY})') <NEW_LINE> <DEDENT> libc = None <NEW_LINE> try: <NEW_LINE> <INDENT> libc = ELF(LIB) <NEW_LINE> env = os.environ.copy() <NEW_LINE> env['...
Does general setup and calls exploit.
625941c78e7ae83300e4b01a
def package_installed( cluster_id, host_id, cluster_ready, host_ready, username=None ): <NEW_LINE> <INDENT> with util.lock('serialized_action') as lock: <NEW_LINE> <INDENT> if not lock: <NEW_LINE> <INDENT> raise Exception( 'failed to acquire lock to ' 'do the post action after package installation' ) <NEW_LINE> <DEDENT...
Callback when package is installed. .. note:: The function should be called out of database session.
625941c794891a1f4081baf7
def fset(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(value) > self._maxelems: <NEW_LINE> <INDENT> raise ElemError("Number of elements exceeds maximum.") <NEW_LINE> <DEDENT> for elem in value: <NEW_LINE> <INDENT> if not isinstance(elem, LineElem): <NEW_LINE> <INDENT> raise ElemError( "Cannot connec...
check if number of elems exceeds maximum. Set if it doesn't.
625941c792d797404e3041d8
def __init__(self, obj, parent=None): <NEW_LINE> <INDENT> logger.info('%s initialization' % obj.name) <NEW_LINE> morse.core.sensor.Sensor.__init__(self, obj, parent) <NEW_LINE> logger.info('Component initialized, runs at %.2f Hz', self.frequency)
Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent.
625941c763f4b57ef000116a
def get_shipping_address(self, form): <NEW_LINE> <INDENT> country = form.cleaned_data.get('country', settings.SHUUP_ADDRESS_HOME_COUNTRY) <NEW_LINE> return MutableAddress(postal_code=form.cleaned_data['postal_code'], country=country)
Just return a MutableAddress with a postal code set
625941c750812a4eaa59c371
def lnprior(self, counts): <NEW_LINE> <INDENT> if np.all(counts >= 0): <NEW_LINE> <INDENT> return -np.sum(counts) - 0.5 * np.log(np.prod(counts)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -np.inf
Log Prior Parameters: ----------- counts: array each entry is a count for each source type in the following order: [foreground_counts, gaussian_counts, all_other_glitch_counts] N.B.: technically, the exp^(-Sum(counts)) term is part of the likelihood in FGMC
625941c731939e2706e4ceba
def parse_cookie(value, cookie_duration): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> parts = value.split("|") <NEW_LINE> if len(parts) != 3: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if cookie_signature(parts[0], parts[1]) != parts[2]: <NEW_LINE> <INDENT> logging.war...
Parses and verifies a cookie value from set_cookie
625941c7009cb60464c63400
def to_url(self, upload=False, generator='Python script', new_layer=True, layer_name=''): <NEW_LINE> <INDENT> values = {'data': self.to_xml(output='url', upload=upload, generator=generator)} <NEW_LINE> if new_layer is False: <NEW_LINE> <INDENT> values['new_layer'] = 'false' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>...
:type output: string doc for formatted file output, url for concise output :type generator: string documentation to be added to OSM xml file for tool that generated the XML data :type new_layer: bool set to False to add data to currently open layer in JOSM :type layer_name: string name for the layer to be created if ne...
625941c70383005118ecf631
def predictor_expfaconpath_set(expfac): <NEW_LINE> <INDENT> from phcpy.phcpy2c3 import py2c_set_value_of_continuation_parameter as set <NEW_LINE> return set(15, expfac)
Sets the value of the expansion factor to increase the step size in case of a successful corrector stag, along a path, before the end game, to the value of *expfac*. On return is the failure code, which equals zero if all went well.
625941c730c21e258bdfa4eb
def add_args(self): <NEW_LINE> <INDENT> self.add_argument("-l", "--list-history", dest="list_history", action="store_true", help="Print out the context history and exit.") <NEW_LINE> self.add_argument("-x", "--starting-context", dest="starting_context", help="Use the affected datasets computation starting with this his...
Add diff-specific command line parameters.
625941c74f88993c3716c0b6
def request(self): <NEW_LINE> <INDENT> if self.test == self.LIVE_TEST or not self.test: <NEW_LINE> <INDENT> url = self.API_URI['live'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = self.API_URI['test'] <NEW_LINE> <DEDENT> debug_string = " paython.gateways.authorize_net.request() -- Attempting request to: " <NEW_L...
Makes a request using lib.api.GetGateway.make_request() & move some debugging away from other methods.
625941c791af0d3eaac9ba66
def get_ccy2(self): <NEW_LINE> <INDENT> return self.name[3:7]
Get the 2nd currency (CCY2) in the pair, :returns: ISO 4217 format currency pair name of CCY2 :rtype: str
625941c766673b3332b920df
def __getitem__(self, key): <NEW_LINE> <INDENT> if key in self.defined_attributes: <NEW_LINE> <INDENT> return self.attributes.get(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError("Undefined attribute '%s'" % key)
Adds C{dict} like attribute reading Allows:: person['id'] person['name'] Developer Note: This method of accessing attributes is used internally and should never be overridden by subclasses. @raise KeyError: If C{key} is not a defined attribute. @param key: name of the attribute to get
625941c7cdde0d52a9e53081
def result_from_uid(self, task_uid): <NEW_LINE> <INDENT> task = celery.AsyncResult(task_uid) <NEW_LINE> return ResultProxy(task)
Query a task from the given task UID. :param task_uid: A UID :type:`str` for a task.
625941c757b8e32f524834e8
def clone(self): <NEW_LINE> <INDENT> newenv = Environment(self.space, self.handle) <NEW_LINE> newenv.maxBytesPerCharacter = self.maxBytesPerCharacter <NEW_LINE> newenv.maxStringBytes = self.maxStringBytes <NEW_LINE> return newenv
Clone an existing environment. used when acquiring a connection from a session pool, for example.
625941c7ac7a0e7691ed411c
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, CatalogType): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c799fddb7c1c9de3e0
def __init__(self, default_mode=None, items=None): <NEW_LINE> <INDENT> self._default_mode = None <NEW_LINE> self._items = None <NEW_LINE> self.discriminator = None <NEW_LINE> if default_mode is not None: <NEW_LINE> <INDENT> self.default_mode = default_mode <NEW_LINE> <DEDENT> if items is not None: <NEW_LINE> <INDENT> s...
IoK8sApiCoreV1DownwardAPIVolumeSource - a model defined in Swagger
625941c7baa26c4b54cb116f
def eucl_dist(self, other): <NEW_LINE> <INDENT> if not isinstance(other, TimeSeries): <NEW_LINE> <INDENT> raise TypeError('other should be of type TimeSeries. Got "{}"'.format(type(TimeSeries))) <NEW_LINE> <DEDENT> l = [] <NEW_LINE> for i, j in zip(self.values, other.values): <NEW_LINE> <INDENT> l.append((i - j) ** 2) ...
Calculate the euclidean distance between TimeSeries and other TimeSeries :param other: Another TimeSeries object :return: float
625941c7090684286d50ed33
def prepare_vocab(data_urls, pretrained_url, update=True, min_count=1): <NEW_LINE> <INDENT> binary = pretrained_url and pretrained_url.endswith('.bin') <NEW_LINE> return gen_vocab_from_data(data_urls, pretrained_url, binary=binary, update=update, min_count=min_count)
prepare vocab and embedding Args: data_urls: urls to data file for preparing vocab pretrained_url: url to pretrained embedding file min_count: minimum count of word update: force to update
625941c7236d856c2ad44827
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SelectedSettingResource): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c70c0af96317bb8236
def multi_joints_motion(self, **j_dict): <NEW_LINE> <INDENT> send_data = 'G00 ' <NEW_LINE> all_keys = [] <NEW_LINE> for i in range(1, 7): <NEW_LINE> <INDENT> all_keys.append('J{}'.format(str(i))) <NEW_LINE> <DEDENT> for key in all_keys: <NEW_LINE> <INDENT> if j_dict[key] and (j_dict[key] != ' '): <NEW_LINE> <INDENT> se...
关节运动,点对点 :param j_dict: 字典——六轴目标值,{'J*': **, ...} :return:
625941c78c3a873295158408
def create_form(self): <NEW_LINE> <INDENT> T = current.T <NEW_LINE> db = current.db <NEW_LINE> response = current.response <NEW_LINE> user = current.auth.user.pe_id <NEW_LINE> stable = current.s3db.pr_subscription <NEW_LINE> formstyle = current.deployment_settings.get_ui_formstyle() <NEW_LINE> query = (stable.pe_id == ...
Build form for subscription settings
625941c75fdd1c0f98dc0281
def calc_sent_dist ( self, limit_phrases: int, ) -> typing.List[Sentence]: <NEW_LINE> <INDENT> unit_vector = self.get_unit_vector(limit_phrases) <NEW_LINE> sent_dist: typing.List[Sentence] = [ Sentence( start = s.start, end = s.end, sent_id = sent_id, phrases = set(), distance = 0.0, ) for sent_id, s in enumerate(self....
For each sentence in the document, calculate its distance from a *unit vector* of top-ranked phrases. limit_phrases: maximum number of top-ranked phrases to use in the *unit vector* returns: a list of sentence distance measures
625941c7aad79263cf390a8e
def __str__(self): <NEW_LINE> <INDENT> res = "" <NEW_LINE> for item in self.starts: <NEW_LINE> <INDENT> res += "(" + str(item.start) + "--" + str(item.end) + ")" <NEW_LINE> <DEDENT> return res
:return: string representation of this node.
625941c74e4d5625662d4428
def opposite(self): <NEW_LINE> <INDENT> trend = (self.tr + 180.) % 360. <NEW_LINE> plunge = -self.pl <NEW_LINE> return GVect(trend, plunge)
Return the opposite GVect. Example: >>> GVect(0, 30).opposite() GVect(180.00, -30.00) >>> GVect(315, 10).opposite() GVect(135.00, -10.00)
625941c7507cdc57c6306d27
def inspect_projwfc_serial(self): <NEW_LINE> <INDENT> calculation = self.ctx.calc_projwfc <NEW_LINE> if not calculation.is_finished_ok: <NEW_LINE> <INDENT> self.report(f'ProjwfcCalculation failed with exit status {calculation.exit_status}') <NEW_LINE> return self.exit_codes.ERROR_SUB_PROCESS_FAILED_PROJWFC <NEW_LINE> <...
Verify that the Projwfc calculation finished successfully, then clean its remote directory.
625941c7442bda511e8be468
def files_properties_add(self, path, property_groups): <NEW_LINE> <INDENT> warnings.warn( 'properties/add is deprecated.', DeprecationWarning, ) <NEW_LINE> arg = file_properties.AddPropertiesArg(path, property_groups) <NEW_LINE> r = self.request( files.properties_add, 'files', arg, None, ) <NEW_LINE> return None
:param str path: A unique identifier for the file or folder. :param list property_groups: The property groups which are to be added to a Dropbox file. :rtype: None :raises: :class:`.exceptions.ApiError` If this raises, ApiError will contain: :class:`dropbox.files.AddPropertiesError`
625941c763d6d428bbe4453e