code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
def buckets(context=None): <NEW_LINE> <INDENT> api = _create_api(context) <NEW_LINE> return _BucketList(api) | Retrieves a list of Storage buckets.
Args:
context: an optional Context object providing project_id and credentials.
Returns:
An iteratable list of buckets. | 625941ba5fc7496912cc3815 |
@register.simple_tag <NEW_LINE> def build(app_name): <NEW_LINE> <INDENT> url_link = f"http://localhost:3000/{app_name}" <NEW_LINE> file_name = f"dist/{app_name}" <NEW_LINE> try: <NEW_LINE> <INDENT> if requests.get(url_link).status_code == 200: <NEW_LINE> <INDENT> return url_link <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> return static(file_name) | Connecting with the WebPackDev or Django Static
* First, checking the dev server & using it
* if status code is not 200, then using bundle file | 625941ba85dfad0860c3ace8 |
@pytest.mark.slow <NEW_LINE> def test_linemin(H2_ccecp_uhf): <NEW_LINE> <INDENT> mol, mf = H2_ccecp_uhf <NEW_LINE> wf, to_opt = generate_wf(mol, mf) <NEW_LINE> nconf = 100 <NEW_LINE> wf, dfgrad = line_minimization( wf, initial_guess(mol, nconf), gradient_generator(mol, wf, to_opt) ) <NEW_LINE> dfgrad = pd.DataFrame(dfgrad) <NEW_LINE> mfen = mf.energy_tot() <NEW_LINE> enfinal = dfgrad["energy"].values[-1] <NEW_LINE> enfinal_err = dfgrad["energy_error"].values[-1] <NEW_LINE> assert mfen > enfinal | Optimize a Slater-Jastrow wave function and check that it's better than Hartree-Fock | 625941ba3eb6a72ae02ec364 |
def render(self): <NEW_LINE> <INDENT> return [ '%s%s' % (self.name()[0].upper(), self.name()[1:],), ['outputs=', self.outputs], ['inputs=', self.inputs], ['distargs=', self.get_distargs()], ['params=', self.get_params()], ['hypers=', self.get_hypers()], ['suffstats=', self.get_suffstats()], ] | Return an AST-like representation of the CGPM. | 625941ba63d6d428bbe4437f |
@register.simple_tag(takes_context=True) <NEW_LINE> def render_app_icon(context): <NEW_LINE> <INDENT> return AdminMenu.get_app_icon(context['app']['name']) | Render app icon | 625941ba66673b3332b91f26 |
def ReadMetrics( fileName ): <NEW_LINE> <INDENT> DataDF = pd.read_csv(fileName,header = 0, delimiter= ',', parse_dates=['Date']) <NEW_LINE> DataDF = DataDF.set_index('Date') <NEW_LINE> return( DataDF ) | This function takes a filename as input, and returns a dataframe with
the metrics from the assignment on descriptive statistics and
environmental metrics. Works for both annual and monthly metrics.
Date column should be used as the index for the new dataframe. Function
returns the completed DataFrame. | 625941baf548e778e58cd40c |
def check_fleet_edges(ai_settings, monsters): <NEW_LINE> <INDENT> for monster in monsters.sprites(): <NEW_LINE> <INDENT> if monster.check_edges(): <NEW_LINE> <INDENT> change_fleet_direction(ai_settings, monsters) <NEW_LINE> break | Respond appropriately if any aliens have reached an edge. | 625941bae5267d203edcdb30 |
def dns_mx_add(self, client_id, params=None): <NEW_LINE> <INDENT> default = {"server_id": 1, "zone": 1, "name": "www", "data": "127.0.0.1", "aux": 10, "ttl": "3600", "type": "MX", "active": "y"} <NEW_LINE> if params['zone']: <NEW_LINE> <INDENT> server_id = self.dns_zone_get(params['zone']) <NEW_LINE> if server_id: <NEW_LINE> <INDENT> params['server_id'] = server_id['server_id'] <NEW_LINE> <DEDENT> <DEDENT> default = self.update_default_dict(default, params) <NEW_LINE> default = self.dict_to_tuple(default) <NEW_LINE> response = self._call("dns_mx_add", (client_id, default)) <NEW_LINE> return self.check_response(response, int, "Error during 'dns_mx_add' method") | Adds a new DNS MX record.
Param:
id -- Client's id
param -- Dictionary containing record's informations.
Output:
Returns the ID of the newly added record. | 625941bacc40096d615957e2 |
def plot_not_before(self, all_years, nice_years, width=0.35): <NEW_LINE> <INDENT> xaxis_ticks = [] <NEW_LINE> idx = 0 <NEW_LINE> for y in range(2012, 2018): <NEW_LINE> <INDENT> for m in range(1, 13): <NEW_LINE> <INDENT> xaxis_ticks.append('%4d-%02d' % (y, m)) <NEW_LINE> idx += 1 <NEW_LINE> <DEDENT> <DEDENT> xaxis = np.arange(len(xaxis_ticks)) <NEW_LINE> all_y = [all_years[i] for i in xaxis_ticks] <NEW_LINE> nice_y = [nice_years[i] for i in xaxis_ticks] <NEW_LINE> nice_y = [x for x in nice_y] <NEW_LINE> fig, ax = plt.subplots() <NEW_LINE> rects1 = ax.bar(xaxis, nice_y, width, color='b') <NEW_LINE> rects2 = ax.bar(xaxis + width, all_y, width, color='y') <NEW_LINE> plt.xticks(xaxis, xaxis_ticks, rotation='vertical') <NEW_LINE> ax.legend((rects1[0], rects2[0]), ('Nice', 'All')) <NEW_LINE> ax.set_ylabel('Count') <NEW_LINE> ax.set_title('Not before vs. count') <NEW_LINE> plt.show() | Plot not before
:param all_years:
:param nice_years:
:param width:
:return: | 625941ba97e22403b379ce29 |
def bytes_string(text, encode="utf-8"): <NEW_LINE> <INDENT> if not PY3: <NEW_LINE> <INDENT> if isinstance(text, unicode): <NEW_LINE> <INDENT> result = text.encode(encode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = text <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(text, bytes): <NEW_LINE> <INDENT> result = text <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = bytes(text, encode) <NEW_LINE> <DEDENT> <DEDENT> return result | Return a bytes object on Python 3 and a str object on Python 2 | 625941ba8a43f66fc4b53ef9 |
def render(self, data, accepted_media_type=None, renderer_context=None): <NEW_LINE> <INDENT> renderer_context = renderer_context or {} <NEW_LINE> view = renderer_context['view'] <NEW_LINE> request = renderer_context['request'] <NEW_LINE> response = renderer_context['response'] <NEW_LINE> if response.exception: <NEW_LINE> <INDENT> template = self.get_exception_template(response) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> template_names = self.get_template_names(response, view) <NEW_LINE> template = self.resolve_template(template_names) <NEW_LINE> <DEDENT> context = self.resolve_context(data, request, response) <NEW_LINE> return template_render(template, context, request=request) | Renders data to HTML, using Django's standard template rendering.
The template name is determined by (in order of preference):
1. An explicit .template_name set on the response.
2. An explicit .template_name set on this class.
3. The return result of calling view.get_template_names(). | 625941ba4e4d5625662d426c |
def plot_task(task): <NEW_LINE> <INDENT> cmap = colors.ListedColormap( [ '#000000', '#0074D9', '#FF4136', '#2ECC40', '#FFDC00', '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25' ] ) <NEW_LINE> norm = colors.Normalize(vmin=0, vmax=9) <NEW_LINE> fig, axs = plt.subplots(1, 4, figsize=(15, 15)) <NEW_LINE> axs[0].imshow(task['train'][0]['input'], cmap=cmap, norm=norm) <NEW_LINE> axs[0].axis('off') <NEW_LINE> axs[0].set_title('Train Input') <NEW_LINE> axs[1].imshow(task['train'][0]['output'], cmap=cmap, norm=norm) <NEW_LINE> axs[1].axis('off') <NEW_LINE> axs[1].set_title('Train Output') <NEW_LINE> axs[2].imshow(task['test'][0]['input'], cmap=cmap, norm=norm) <NEW_LINE> axs[2].axis('off') <NEW_LINE> axs[2].set_title('Test Input') <NEW_LINE> axs[3].imshow(task['test'][0]['output'], cmap=cmap, norm=norm) <NEW_LINE> axs[3].axis('off') <NEW_LINE> axs[3].set_title('Test Output') <NEW_LINE> plt.tight_layout() <NEW_LINE> plt.show() | Plots the first train and test pairs of a specified task,
using same color scheme as the ARC app | 625941bab545ff76a8913cae |
def __init__(self): <NEW_LINE> <INDENT> from gamestate import GameState <NEW_LINE> self.data_in_q = Queue(MAX_Q_SIZE) <NEW_LINE> self.commands_out_q = Queue(MAX_Q_SIZE) <NEW_LINE> self.gs = GameState() <NEW_LINE> self.logger = None <NEW_LINE> self.last_run_time = None <NEW_LINE> self.delta_time = 0 <NEW_LINE> self._owned_fields = [] | Sets up queues for reading data in and out of this provider | 625941ba9b70327d1c4e0c64 |
def read_all(self): <NEW_LINE> <INDENT> print("\nCRUD: Read (all) test case") <NEW_LINE> docs = self.organizers.read() <NEW_LINE> self.show_docs(docs, 5) | Run Read(all) test case | 625941ba01c39578d7e74cd3 |
def refresh(self, cycles_passed): <NEW_LINE> <INDENT> if not self.busy: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.time_left -= cycles_passed <NEW_LINE> if self.time_left <= 0: <NEW_LINE> <INDENT> self.busy = False <NEW_LINE> self.time_left = 0 <NEW_LINE> return (self.locked_mode, self.locked_range) <NEW_LINE> <DEDENT> return None | Called every VM step, if device is busy, refresh how many cycles it'll busy more | 625941ba498bea3a759b9940 |
def countPrimes(self, n): <NEW_LINE> <INDENT> if n < 3: return 0 <NEW_LINE> primes = [True] * (n+1) <NEW_LINE> res = 0 <NEW_LINE> for i in range(2,n): <NEW_LINE> <INDENT> if primes[i]: <NEW_LINE> <INDENT> res += 1 <NEW_LINE> for j in range(i,n,i): <NEW_LINE> <INDENT> primes[j] = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return res | :type n: int
:rtype: int | 625941ba26238365f5f0ecfa |
def to_file(self, filename=None): <NEW_LINE> <INDENT> t = localtime() <NEW_LINE> size = len(self.a) <NEW_LINE> assumptions = ['Independent Observations'] <NEW_LINE> if self.alt_hyp == 'unequal': <NEW_LINE> <INDENT> alternative = "Mean 1 != " + str(self.popmean) <NEW_LINE> sided = "two-sided" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sided = "one-sided" <NEW_LINE> if self.alt_hyp == "less": <NEW_LINE> <INDENT> alternative = "Mean 1 < " + str(self.popmean) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> alternative = "Mean 1 > " + str(self.popmean) <NEW_LINE> <DEDENT> <DEDENT> data = {} <NEW_LINE> data['sig_test'] = "T-Test (" + sided + ")" <NEW_LINE> data['date'] = strftime("%a, %d %b %Y", t) <NEW_LINE> data['time'] = strftime("%H:%M:%S", t) <NEW_LINE> data['assumptions'] = assumptions <NEW_LINE> data['data_size'] = size <NEW_LINE> data['pop_mean'] = self.popmean <NEW_LINE> data['null_hyp'] = "Mean 1 ==", self.popmean <NEW_LINE> data['alt_hyp'] = alternative <NEW_LINE> data['t_stat'] = self.t_stat <NEW_LINE> data['p_val'] = self.p_val <NEW_LINE> if (self.alpha and self.p_val >= self.alpha) or self.p_val == 0 or not self.alpha: <NEW_LINE> <INDENT> data['reject_null'] = False <NEW_LINE> data['accept_alt'] = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data['reject_null'] = True <NEW_LINE> if self.alt_hyp == 'unequal' or (self.alt_hyp == 'less' and self.t_stat < 0) or (self.alt_hyp == 'greater' and self.t_stat > 0): <NEW_LINE> <INDENT> data['accept_alt'] = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data['accept_alt'] = False <NEW_LINE> <DEDENT> <DEDENT> filename = filename or strftime("%a_%d_%b_%Y_%H_%M_%S.json", t) <NEW_LINE> with open(filename, 'w') as target: <NEW_LINE> <INDENT> dump(data, target) | Summarizes the results of the t-test performed and saves the results
out into `filename`.
Parameters
----------
filename : string, optional
The location of the file where the results will be stored. If no
filename is provided, a default filename will be generated, and the
results will be stored there. | 625941bad10714528d5ffb6f |
def identification(self, birth_date, first_name, middle_name, last_name, passport, inn=None, snils=None, oms=None): <NEW_LINE> <INDENT> result_json = apihelper.identification(self.token, self.number, birth_date, first_name, middle_name, last_name, passport, inn, snils, oms, self.proxy) <NEW_LINE> result_json['base_inn'] = inn <NEW_LINE> return types.Identity.de_json(result_json) | Идентификация пользователя
Данный запрос позволяет отправить данные для упрощенной идентификации своего QIWI кошелька.
Warnings
--------
Данный метод не тестируется, соответственно я не могу гарантировать того что он будет работать как должен.
Вы делаете это на свой страх и риск.
Parameters
----------
birth_date : str
Дата рождения пользователя (в формате “ГГГГ-ММ-ДД”)
first_name : str
Имя пользователя
middle_name : str
Отчество пользователя
last_name : str
Фамилия пользователя
passport : str
Серия и номер паспорта пользователя (только цифры)
inn : str
ИНН пользователя
snils : str
Номер СНИЛС пользователя
oms : str
Номер полиса ОМС пользователя
Returns
-------
:class:`Identity <pyqiwi.types.Identity>`
Текущая идентификация пользователя.
Параметр внутри отвечающий за подтверждение успешной идентификации: Identity.check | 625941ba96565a6dacc8f565 |
def read(*parts): <NEW_LINE> <INDENT> path = os.path.join(os.path.dirname(__file__), *parts) <NEW_LINE> with codecs.open(path, encoding='utf-8') as fobj: <NEW_LINE> <INDENT> return fobj.read() | Read file and return contents. | 625941bac432627299f04ad4 |
def maxCount(self, m, n, ops): <NEW_LINE> <INDENT> rmin = m <NEW_LINE> cmin = n <NEW_LINE> for i in ops: <NEW_LINE> <INDENT> rmin = min(i[0], rmin) <NEW_LINE> cmin = min(i[1], cmin) <NEW_LINE> <DEDENT> return rmin * cmin | :type m: int
:type n: int
:type ops: List[List[int]]
:rtype: int | 625941ba091ae35668666df5 |
def set_space(self, space): <NEW_LINE> <INDENT> self.space = space | sets the space the robot keeps between himself and the carrot
:param space: space in meters | 625941ba94891a1f4081b938 |
def upgrade_lock(self, purpose=None, retry=None): <NEW_LINE> <INDENT> if purpose is not None: <NEW_LINE> <INDENT> self._purpose = purpose <NEW_LINE> <DEDENT> if retry is not None: <NEW_LINE> <INDENT> self._retry = retry <NEW_LINE> <DEDENT> if self.shared: <NEW_LINE> <INDENT> LOG.debug('Upgrading shared lock on node %(uuid)s for %(purpose)s ' 'to an exclusive one (shared lock was held %(time).2f ' 'seconds)', {'uuid': self.node.uuid, 'purpose': self._purpose, 'time': self._debug_timer.elapsed()}) <NEW_LINE> self._lock() <NEW_LINE> self.shared = False | Upgrade a shared lock to an exclusive lock.
Also reloads node object from the database.
If lock is already exclusive only changes the lock purpose
when provided with one.
:param purpose: optionally change the purpose of the lock
:param retry: whether to retry locking if it fails, the
class-level value is used by default
:raises: NodeLocked if an exclusive lock remains on the node after
"node_locked_retry_attempts" | 625941ba293b9510aa2c3129 |
def create_information(self): <NEW_LINE> <INDENT> return AnimalInfo(origin=self, contents=None) | Create a new Info.
transmit() -> _what() -> create_information(). | 625941ba32920d7e50b2805d |
def rdkit2amberpdb(mol_pdb_txt): <NEW_LINE> <INDENT> mol_new_lines = [] <NEW_LINE> atom_counts = {} <NEW_LINE> line_format = '{0[0]}{0[1]:>7}{0[2]:>4}{0[3]:>5}{0[4]:>6}{0[5]: 12.3f}{0[6]: 8.3f}{0[7]: 8.3f}{0[8]:>6}{0[9]:>6}{0[10]:>12}' <NEW_LINE> mol_txt_lines = mol_pdb_txt.split('\n') <NEW_LINE> for line in mol_txt_lines: <NEW_LINE> <INDENT> if line.startswith('HETATM') or line.startswith('ATOM'): <NEW_LINE> <INDENT> strings = line.split() <NEW_LINE> strings[0] = 'ATOM' <NEW_LINE> atom_counts[strings[2]] = atom_counts.get(strings[2], 0) + 1 <NEW_LINE> strings[2] = strings[2] <NEW_LINE> strings[3] = 'MOL' <NEW_LINE> strings[5] = float(strings[5]) <NEW_LINE> strings[6] = float(strings[6]) <NEW_LINE> strings[7] = float(strings[7]) <NEW_LINE> new_line = line_format.format(strings) <NEW_LINE> mol_new_lines.append(new_line) <NEW_LINE> <DEDENT> <DEDENT> mol_new_lines.extend(['TER', 'END']) <NEW_LINE> return '\n'.join(mol_new_lines) | Converts a PDB block from openbabel or rdkit like format to the PDB block in rism pdb format
:param mol_pdb_txt: pdb block with openbabel or rdkit like format
:return: string with a pdb block in rism pdb comparable format | 625941bad8ef3951e32433cd |
def get_results(self, **kwargs): <NEW_LINE> <INDENT> if self.returncode is None: <NEW_LINE> <INDENT> raise self.Error("return code is None, you should call wait, communicate or poll") <NEW_LINE> <DEDENT> if self.status is None or self.status < self.S_DONE: <NEW_LINE> <INDENT> raise self.Error("Task is not completed") <NEW_LINE> <DEDENT> return self.Results.from_node(self) | Returns :class:`NodeResults` instance.
Subclasses should extend this method (if needed) by adding
specialized code that performs some kind of post-processing. | 625941bae8904600ed9f1db9 |
def test_rule(): <NEW_LINE> <INDENT> from pica.cells import Cells <NEW_LINE> from pica.conditions import Equals <NEW_LINE> from pica.rules import Rule, Result <NEW_LINE> rule = Rule('from', 'to', Equals(1, 0, 'no match'), 0.5) <NEW_LINE> cells = Cells(2, 2, 'from') <NEW_LINE> cells.update(0, 0, 'no match') <NEW_LINE> cells.update(1, 1, 'no match') <NEW_LINE> assert_is_none(rule(cells, -1, -1)) <NEW_LINE> for x in range(2): <NEW_LINE> <INDENT> for y in range(2): <NEW_LINE> <INDENT> rule.reset() <NEW_LINE> if (x, y) == (0, 1): <NEW_LINE> <INDENT> assert_equals(rule(cells, x, y), Result('to', 0.5)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert_is_none(rule(cells, x, y)) | A Rule | 625941ba498bea3a759b9941 |
def addCategory(self, entry): <NEW_LINE> <INDENT> newID = random.randint(10000, 99999) <NEW_LINE> while newID in self.idList: <NEW_LINE> <INDENT> newID = random.randint(10000, 99999) <NEW_LINE> <DEDENT> entry.insert(0, newID) <NEW_LINE> self.idList.append(newID) <NEW_LINE> self.cursor.execute("INSERT INTO CATEGORIES VALUES (?, ?, ?, ?)", entry) <NEW_LINE> return newID | Author: Alex Lambert
UW NetID: alamb25
Date: 3/7/17
Add Category to the Database | 625941ba090684286d50eb71 |
def list_user_profiles(nextToken=None, maxResults=None): <NEW_LINE> <INDENT> pass | Lists all the user profiles configured for your AWS account in AWS CodeStar.
See also: AWS API Documentation
Exceptions
:example: response = client.list_user_profiles(
nextToken='string',
maxResults=123
)
:type nextToken: string
:param nextToken: The continuation token for the next set of results, if the results cannot be returned in one response.
:type maxResults: integer
:param maxResults: The maximum number of results to return in a response.
:rtype: dict
ReturnsResponse Syntax
{
'userProfiles': [
{
'userArn': 'string',
'displayName': 'string',
'emailAddress': 'string',
'sshPublicKey': 'string'
},
],
'nextToken': 'string'
}
Response Structure
(dict) --
userProfiles (list) --
All the user profiles configured in AWS CodeStar for an AWS account.
(dict) --
Information about a user's profile in AWS CodeStar.
userArn (string) --
The Amazon Resource Name (ARN) of the user in IAM.
displayName (string) --
The display name of a user in AWS CodeStar. For example, this could be set to both first and last name ("Mary Major") or a single name ("Mary"). The display name is also used to generate the initial icon associated with the user in AWS CodeStar projects. If spaces are included in the display name, the first character that appears after the space will be used as the second character in the user initial icon. The initial icon displays a maximum of two characters, so a display name with more than one space (for example "Mary Jane Major") would generate an initial icon using the first character and the first character after the space ("MJ", not "MM").
emailAddress (string) --
The email address associated with the user.
sshPublicKey (string) --
The SSH public key associated with the user in AWS CodeStar. If a project owner allows the user remote access to project resources, this public key will be used along with the user's private key for SSH access.
nextToken (string) --
The continuation token to use when requesting the next set of results, if there are more results to be returned.
Exceptions
CodeStar.Client.exceptions.InvalidNextTokenException
CodeStar.Client.exceptions.ValidationException
:return: {
'userProfiles': [
{
'userArn': 'string',
'displayName': 'string',
'emailAddress': 'string',
'sshPublicKey': 'string'
},
],
'nextToken': 'string'
}
:returns:
CodeStar.Client.exceptions.InvalidNextTokenException
CodeStar.Client.exceptions.ValidationException
| 625941ba0a50d4780f666d1f |
def get_enclitic(self, pronoun): <NEW_LINE> <INDENT> return yaziji_const.ENCLITICS.get(pronoun,"") | Extract enclitic | 625941ba30dc7b76659017fa |
def add_artifact(self, pt_id, artifact_id, private_key, public_key, del_flag=False): <NEW_LINE> <INDENT> if del_flag: <NEW_LINE> <INDENT> response_bytes = self.retrieve_part(pt_id) <NEW_LINE> if response_bytes != None: <NEW_LINE> <INDENT> jresponse = json.loads(response_bytes.decode()) <NEW_LINE> if len(jresponse["artifact_list"]) == 0: <NEW_LINE> <INDENT> return [ None, "No {} to remove from this {}." .format("Artifact", "Part") ] <NEW_LINE> <DEDENT> if artifact_id not in jresponse["artifact_list"]: <NEW_LINE> <INDENT> return [ None, "No such {} in this {}." .format("Artifact", "Part") ] <NEW_LINE> <DEDENT> jresponse["artifact_list"].remove(artifact_id) <NEW_LINE> cur = self._get_block_num() <NEW_LINE> return self.create_part_transaction(pt_id, jresponse["name"], jresponse["checksum"], jresponse["version"], jresponse["alias"], jresponse["licensing"], jresponse["label"], jresponse["description"], "AddArtifact", private_key, public_key, jresponse["artifact_list"], jresponse["category_list"], jresponse["organization_list"], jresponse["cur_block"], cur, str(datetime.datetime.utcnow())) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response_bytes = self.retrieve_part(pt_id) <NEW_LINE> if response_bytes != None: <NEW_LINE> <INDENT> if self._validate_artifact_id(artifact_id) == None: <NEW_LINE> <INDENT> return [ None, "ArtifactException : UUID does not exist." ] <NEW_LINE> <DEDENT> jresponse = json.loads(response_bytes.decode()) <NEW_LINE> if artifact_id not in jresponse["artifact_list"]: <NEW_LINE> <INDENT> jresponse["artifact_list"].append(artifact_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [ None, "Duplicate Artifact UUID in the Part." ] <NEW_LINE> <DEDENT> cur = self._get_block_num() <NEW_LINE> return self.create_part_transaction(pt_id, jresponse["name"], jresponse["checksum"], jresponse["version"], jresponse["alias"], jresponse["licensing"], jresponse["label"], jresponse["description"], "AddArtifact", private_key, public_key, jresponse["artifact_list"], jresponse["category_list"], jresponse["organization_list"], jresponse["cur_block"], cur, str(datetime.datetime.utcnow())) <NEW_LINE> <DEDENT> return None | Constructs the batch payload for the "AddArtifact" command.
Args:
pt_id (str): The uuid of the part
artifact_id (str): The uuid of the artifact
private_key (str): The private key of the user
public_key (str): The public key of the user
del_flag (bool): The flag for "--delete" option (default False)
Returns:
type: Batch
The batch object which pertains all the data associating with the
"AddArtifact" command.
or
type: None
None object if UUID does not exist in the ledger.
or
type: list pertaining None and str
List containing None object and error message:
* If "--delete"
> If "artifact_list" is empty
> If "artifact_id" is not in "artifact_list"
* If "artifact_id" is in "artifact_list" | 625941ba377c676e9127203a |
def update_last_updated(self, commit = True): <NEW_LINE> <INDENT> assert 'person_id' in self <NEW_LINE> assert self.table_name <NEW_LINE> self.api.db.do("UPDATE %s SET last_updated = CURRENT_TIMESTAMP " % (self.table_name) + " where person_id = %d" % (self['person_id']) ) <NEW_LINE> self.sync(commit) | Update last_updated field with current time | 625941ba44b2445a33931f30 |
def mask_out(src): <NEW_LINE> <INDENT> mini = np.amin(src) <NEW_LINE> num = len(src) <NEW_LINE> for i in range(num): <NEW_LINE> <INDENT> for j in range(num): <NEW_LINE> <INDENT> if (i - num / 2) ** 2 + (j - num / 2) ** 2 > (0.3846 * num) ** 2: <NEW_LINE> <INDENT> src[i][j] = mini <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> assert (len(src) == 256 and len(src[0]) == 256) | Mask the data outside of the disk. 0.3846 is a number calculated based on the structure
of the pic. Due to -inf, this is normally done after normalize
:param src: full disk data | 625941baa79ad161976cbfd6 |
def _unwrap_maps(self, name_maps, name, analysis=None, **inner_maps): <NEW_LINE> <INDENT> name = name_maps.get('name', name) <NEW_LINE> name = name_maps.get('prefix', '') + name <NEW_LINE> analysis = name_maps.get('analysis', analysis) <NEW_LINE> maps = {} <NEW_LINE> for mtype in ('input_map', 'output_map'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> inner_map = inner_maps[mtype] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> maps[mtype] = name_maps[mtype] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> outer_map = name_maps[mtype] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> maps[mtype] = inner_map <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(outer_map, basestring): <NEW_LINE> <INDENT> if isinstance(inner_map, basestring): <NEW_LINE> <INDENT> maps[mtype] = outer_map + inner_map <NEW_LINE> <DEDENT> elif isinstance(inner_map, dict): <NEW_LINE> <INDENT> maps[mtype] = {k: outer_map + v for k, v in inner_map.items()} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ArcanaDesignError( "Unrecognised type for name map in '{}' " "pipeline can be str or dict[str,str]: {}" .format(name, inner_map)) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(outer_map, dict): <NEW_LINE> <INDENT> if isinstance(inner_map, basestring): <NEW_LINE> <INDENT> maps[mtype] = {k[len(inner_map):]: v for k, v in outer_map.items()} <NEW_LINE> <DEDENT> elif isinstance(inner_map, dict): <NEW_LINE> <INDENT> maps[mtype] = deepcopy(outer_map) <NEW_LINE> maps[mtype].update( {k: outer_map.get(v, v) for k, v in inner_map.items()}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ArcanaDesignError( "Unrecognised type for name map in '{}' " "pipeline can be str or dict[str,str]: {}" .format(name, inner_map)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ArcanaDesignError( "Unrecognised type for name map in '{}' " "pipeline can be str or dict[str,str]: {}" .format(name, outer_map)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> outer_maps = name_maps['name_maps'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name, analysis, maps = self._unwrap_maps( outer_maps, name=name, analysis=analysis, **maps) <NEW_LINE> <DEDENT> return name, analysis, maps | Unwraps potentially nested name-mapping dictionaries to get values
for name, input_map, output_map and analysis. Unsed in __init__.
Parameters
----------
name_maps : dict
A dictionary containing the name_maps to apply to the values
name : str
Name passed from inner pipeline constructor
analysis : Analysis
The analysis to bind the pipeline to. Will be overridden by any values
in the mods dict
inner_maps : dict[str, dict[str,str]]
input and output maps from inner pipeline constructors
Returns
-------
name : str
Potentially modified name of the pipeline
analysis : Analysis
Potentially modified analysis
maps : dict[str, dict[str,str]]
Potentially modifed input and output maps | 625941ba67a9b606de4a7d4d |
def sigmoid_output_to_derivative(output): <NEW_LINE> <INDENT> return output * (1-output) | Convert the sigmoid function's output to its derivative. | 625941ba4f88993c3716bf04 |
def _adaptive_step_size(f, f0=None, alpha=None, tau=2): <NEW_LINE> <INDENT> if alpha is None: <NEW_LINE> <INDENT> alpha = 1 <NEW_LINE> <DEDENT> if f0 is None: <NEW_LINE> <INDENT> f0, _ = f(0) <NEW_LINE> <DEDENT> f_alpha, x_alpha = f(alpha) <NEW_LINE> if f_alpha < f0: <NEW_LINE> <INDENT> f_alpha_up, x_alpha_up = f(alpha * tau) <NEW_LINE> if f_alpha_up < f0: <NEW_LINE> <INDENT> return f_alpha_up, x_alpha_up, alpha * tau <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f_alpha, x_alpha, alpha <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> alpha /= tau <NEW_LINE> f_alpha, x_alpha = f(alpha) <NEW_LINE> while f0 <= f_alpha and alpha > MIN_STEP_SIZE: <NEW_LINE> <INDENT> alpha /= tau <NEW_LINE> f_alpha, x_alpha = f(alpha) <NEW_LINE> <DEDENT> return f_alpha, x_alpha, alpha | Parameters
----------
f : callable
Optimized function, take only the step size as argument
f0 : float
value of f at current point, i.e. step size = 0
alpha : float
Initial step size
tau : float
Multiplication factor of the step size during the adaptation | 625941bad7e4931a7ee9ddac |
def test_get_data_from_dataset_with_multiword_dimnames(self): <NEW_LINE> <INDENT> data_frame = knoema.get('FDI_FLOW_CTRY', **{'Reporting country': 'AUS', 'Partner country/territory': 'w0', 'Measurement principle': 'DI', 'Type of FDI': 'T_FA_F', 'Type of entity': 'ALL', 'Accounting entry': 'NET', 'Level of counterpart': 'IMC', 'Currency': 'USD'}) <NEW_LINE> self.assertEqual(data_frame.shape[0], 7) <NEW_LINE> self.assertEqual(data_frame.shape[1], 1) <NEW_LINE> sname = ('Australia', 'WORLD', 'Directional principle: Inward', 'FDI financial flows - Total', 'All resident units', 'Net', 'Immediate counterpart (Immediate investor or immediate host)', 'US Dollar', 'A') <NEW_LINE> indx = data_frame.first_valid_index() <NEW_LINE> value = data_frame.at[indx, sname] <NEW_LINE> self.assertAlmostEqual(value, 31666.667, 3) <NEW_LINE> indx = data_frame.last_valid_index() <NEW_LINE> value = data_frame.at[indx, sname] <NEW_LINE> self.assertAlmostEqual(value, 22267.638, 3) | The method is testing load data from regular dataset with dimenions that have multi word names | 625941bab7558d58953c4dab |
def gen_sinc_list(a, b, n=1000): <NEW_LINE> <INDENT> dx = (b-a)/(n-1) <NEW_LINE> x = np.arange(0, n) <NEW_LINE> generatedList = [a + kx * dx for kx in x] <NEW_LINE> sincList = [np.divide(np.sin(t), t, out=None, where=t!=0) for t in generatedList] <NEW_LINE> return (generatedList, sincList) | Generates a list based on the "sinc" function. Based on the template for the Gaussian function above.
Args:
a (float): Lower bound of domain
b (float): Uper bound of domain
n (int): number of points in the domain, with a default value of 1000.
Returns:
(generatedList, sincList):
generatedList [float] : [a,...,b] A list of floats used as the inputs to the function.
sincList [float] : [sinc(a),...,sinc(b)] A list of floats produced by running the inputs through the sinc program. | 625941ba30bbd722463cbc53 |
def __init__(self, path, xlim=(0, 1), ylim=(0, 1), *args, **kwargs): <NEW_LINE> <INDENT> self.name = os.path.splitext(os.path.basename(path))[0] <NEW_LINE> self.img_data = self._read_image(path, *args, **kwargs) <NEW_LINE> self.xlim = xlim <NEW_LINE> self.ylim = ylim <NEW_LINE> self._data = None | Create a graph object from image at path. Optionally pass the x
and y limits.
Args:
path (str): The path to the image of the graph.
xlim (tuple[float]): The range of the x axis.
ylim (tuple[float]): The range of the y axis. | 625941ba6e29344779a624a6 |
def tuned_frequency_encode(self, tuned_freq): <NEW_LINE> <INDENT> return MAVLink_tuned_frequency_message(tuned_freq) | Control the tuned frequency of an SDR
tuned_freq : Tuned Frequency (float) | 625941ba26068e7796caeb6a |
def merge_user_into_another_user_accounts(request_ctx, id, destination_account_id, destination_user_id, **request_kwargs): <NEW_LINE> <INDENT> path = '/v1/users/{id}/merge_into/accounts/{destination_account_id}/users/{destination_user_id}' <NEW_LINE> url = request_ctx.base_api_url + path.format(id=id, destination_account_id=destination_account_id, destination_user_id=destination_user_id) <NEW_LINE> response = client.put(request_ctx, url, **request_kwargs) <NEW_LINE> return response | Merge a user into another user.
To merge users, the caller must have permissions to manage both users.
When finding users by SIS ids in different accounts the
destination_account_id is required.
The account can also be identified by passing the domain in destination_account_id.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param id: (required) ID
:type id: string
:param destination_account_id: (required) ID
:type destination_account_id: string
:param destination_user_id: (required) ID
:type destination_user_id: string
:return: Merge user into another user
:rtype: requests.Response (with User data) | 625941bad164cc6175782bde |
def get_power_type(self, region, namespace, power_type_id, **filters): <NEW_LINE> <INDENT> filters['namespace'] = namespace <NEW_LINE> return self.get_resource('data/wow/power-type/{0}', region, *[power_type_id], **filters) | Power Type API - get power type by id | 625941ba9c8ee82313fbb605 |
def _GetInstanceParameterFields(): <NEW_LINE> <INDENT> fields = [ (_MakeField("hvparams", "HypervisorParameters", QFT_OTHER, "Hypervisor parameters (merged)"), IQ_CONFIG, 0, lambda ctx, _: ctx.inst_hvparams), (_MakeField("beparams", "BackendParameters", QFT_OTHER, "Backend parameters (merged)"), IQ_CONFIG, 0, lambda ctx, _: ctx.inst_beparams), (_MakeField("osparams", "OpSysParameters", QFT_OTHER, "Operating system parameters (merged)"), IQ_CONFIG, 0, lambda ctx, _: ctx.inst_osparams), (_MakeField("custom_hvparams", "CustomHypervisorParameters", QFT_OTHER, "Custom hypervisor parameters"), IQ_CONFIG, 0, _GetItemAttr("hvparams")), (_MakeField("custom_beparams", "CustomBackendParameters", QFT_OTHER, "Custom backend parameters",), IQ_CONFIG, 0, _GetItemAttr("beparams")), (_MakeField("custom_osparams", "CustomOpSysParameters", QFT_OTHER, "Custom operating system parameters",), IQ_CONFIG, 0, _GetItemAttr("osparams")), (_MakeField("custom_nicparams", "CustomNicParameters", QFT_OTHER, "Custom network interface parameters"), IQ_CONFIG, 0, lambda ctx, inst: [nic.nicparams for nic in inst.nics]), ] <NEW_LINE> def _GetInstHvParam(name): <NEW_LINE> <INDENT> return lambda ctx, _: ctx.inst_hvparams.get(name, _FS_UNAVAIL) <NEW_LINE> <DEDENT> fields.extend([ (_MakeField("hv/%s" % name, constants.HVS_PARAMETER_TITLES.get(name, "hv/%s" % name), _VTToQFT[kind], "The \"%s\" hypervisor parameter" % name), IQ_CONFIG, 0, _GetInstHvParam(name)) for name, kind in constants.HVS_PARAMETER_TYPES.items() if name not in constants.HVC_GLOBALS]) <NEW_LINE> def _GetInstBeParam(name): <NEW_LINE> <INDENT> return lambda ctx, _: ctx.inst_beparams.get(name, None) <NEW_LINE> <DEDENT> fields.extend([ (_MakeField("be/%s" % name, constants.BES_PARAMETER_TITLES.get(name, "be/%s" % name), _VTToQFT[kind], "The \"%s\" backend parameter" % name), IQ_CONFIG, 0, _GetInstBeParam(name)) for name, kind in constants.BES_PARAMETER_TYPES.items()]) <NEW_LINE> return fields | Get instance fields involving parameters.
@return: List of field definitions used as input for L{_PrepareFieldList} | 625941bafff4ab517eb2f2ca |
@app.route("/objectBrowser") <NEW_LINE> @login_required <NEW_LINE> def object_browser(): <NEW_LINE> <INDENT> return render_template("dashboard/index.haml") | The object Browser page
| 625941ba50812a4eaa59c1b5 |
def update_planet_position(segment): <NEW_LINE> <INDENT> conditions = segment.state.conditions <NEW_LINE> V = conditions.freestream.velocity[:,0] <NEW_LINE> altitude = conditions.freestream.altitude[:,0] <NEW_LINE> phi = conditions.frames.body.inertial_rotations[:,0] <NEW_LINE> theta = conditions.frames.body.inertial_rotations[:,1] <NEW_LINE> psi = conditions.frames.body.inertial_rotations[:,2] <NEW_LINE> alpha = conditions.aerodynamics.angle_of_attack[:,0] <NEW_LINE> I = segment.state.numerics.time.integrate <NEW_LINE> Re = segment.analyses.planet.features.mean_radius <NEW_LINE> gamma = theta - alpha <NEW_LINE> R = altitude + Re <NEW_LINE> lamdadot = (V/R)*np.cos(gamma)*np.cos(psi) <NEW_LINE> lamda = np.dot(I,lamdadot) / Units.deg <NEW_LINE> mudot = (V/R)*np.cos(gamma)*np.sin(psi)/np.cos(lamda) <NEW_LINE> mu = np.dot(I,mudot) / Units.deg <NEW_LINE> shape = np.shape(conditions.freestream.velocity) <NEW_LINE> mu = np.reshape(mu,shape) <NEW_LINE> lamda = np.reshape(lamda,shape) <NEW_LINE> lat = conditions.frames.planet.latitude[0,0] <NEW_LINE> lon = conditions.frames.planet.longitude[0,0] <NEW_LINE> conditions.frames.planet.latitude = lat + lamda <NEW_LINE> conditions.frames.planet.longitude = lon + mu <NEW_LINE> return | Updates the location of the vehicle relative to the Planet throughout the mission
Assumptions:
This is valid for small movements and times as it does not account for the rotation of the Planet beneath the vehicle
Inputs:
segment.state.conditions:
freestream.velocity [meters/second]
freestream.altitude [meters]
frames.body.inertial_rotations [Radians]
segment.analyses.planet.features.mean_radius [meters]
segment.state.numerics.time.integrate [float]
Outputs:
segment.state.conditions:
frames.planet.latitude [Radians]
frames.planet.longitude [Radians]
Properties Used:
N/A
| 625941ba925a0f43d2549d04 |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.result = None <NEW_LINE> self.meta = None <NEW_LINE> replace_names = { "result": "result", "meta": "meta", } <NEW_LINE> if kwargs is not None: <NEW_LINE> <INDENT> for key in kwargs: <NEW_LINE> <INDENT> if key in replace_names: <NEW_LINE> <INDENT> setattr(self, replace_names[key], kwargs[key]) <NEW_LINE> <DEDENT> <DEDENT> if "result" in kwargs: <NEW_LINE> <INDENT> self.result = list() <NEW_LINE> for item in kwargs["result"]: <NEW_LINE> <INDENT> self.result.append(ProductData(**item)) <NEW_LINE> <DEDENT> <DEDENT> if "meta" in kwargs: <NEW_LINE> <INDENT> self.meta = MetaPaged(**kwargs["meta"]) | Constructor for the GetProductsWrapper class
Args:
**kwargs: Keyword Arguments in order to initialise the
object. Any of the attributes in this object are able to
be set through the **kwargs of the constructor. The values
that can be supplied and their types are as follows::
result -- list of ProductData -- Sets the attribute result
meta -- MetaPaged -- Sets the attribute meta | 625941badc8b845886cb53c5 |
def pcToToneRow(pcSet): <NEW_LINE> <INDENT> if len(pcSet) == 12: <NEW_LINE> <INDENT> a = TwelveToneRow() <NEW_LINE> for thisPc in pcSet: <NEW_LINE> <INDENT> p = music21.pitch.Pitch() <NEW_LINE> p.pitchClass = thisPc <NEW_LINE> a.append(p) <NEW_LINE> <DEDENT> return a <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a = ToneRow() <NEW_LINE> for thisPc in pcSet: <NEW_LINE> <INDENT> p = music21.pitch.Pitch() <NEW_LINE> p.pitchClass = thisPc <NEW_LINE> a.append(p) <NEW_LINE> <DEDENT> return a | A convenience function that, given a list of pitch classes represented as integers
and turns it in to a serial.ToneRow object.
>>> from music21 import *
>>> a = serial.pcToToneRow(range(12))
>>> matrixObj = a.matrix()
>>> print matrixObj
0 1 2 3 4 5 6 7 8 9 A B
B 0 1 2 3 4 5 6 7 8 9 A
...
>>> a = serial.pcToToneRow([4,5,0,6,7,2,'a',8,9,1,'b',3])
>>> matrixObj = a.matrix()
>>> print matrixObj
0 1 8 2 3 A 6 4 5 9 7 B
B 0 7 1 2 9 5 3 4 8 6 A
...
__OMIT_FROM_DOCS__
>>> a = serial.pcToToneRow([1,1,1,1,1,1,1,1,1,1,1,1])
...
>>> a = serial.pcToToneRow([3, 4])
... | 625941ba3346ee7daa2b2bfa |
def _handle_chat_event(self, event: events.ChatMessageWasReceived) -> None: <NEW_LINE> <INDENT> for subscriber in self._chat_subscribers: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subscriber(event) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOG.exception(self._prefix_log_message( f"failed to send chat event {event} to " f"subscriber {subscriber}" )) | Not thread-safe. | 625941ba66656f66f7cbc03b |
def GetFeatureImage(self): <NEW_LINE> <INDENT> return _itkBinaryStatisticsKeepNObjectsImageFilterPython.itkBinaryStatisticsKeepNObjectsImageFilterIUL3ID3_GetFeatureImage(self) | GetFeatureImage(self) -> itkImageD3 | 625941ba15fb5d323cde099b |
def read_wav(filename): <NEW_LINE> <INDENT> wave_read = wave.open(filename, 'r') <NEW_LINE> n_samples = wave_read.getnframes() <NEW_LINE> byte_data = wave_read.readframes(n_samples) <NEW_LINE> x = np.frombuffer(byte_data, dtype=np.short) <NEW_LINE> return x | Read a 16-bit wav file as an numpy array of shorts | 625941bad6c5a10208143ed8 |
def test_empty_info(self) -> None: <NEW_LINE> <INDENT> sample_gen = Foundset(i for i in [1, 2]) <NEW_LINE> self.assertEqual(sample_gen.info, {}) | Test that a foundset without 'dataInfo' section returns an empty info dictionary | 625941bafff4ab517eb2f2cb |
def ScrollPageLeft(self): <NEW_LINE> <INDENT> pass | ScrollPageLeft(self: DocumentViewer)
Scrolls left one viewport. | 625941bac432627299f04ad5 |
def resourcesPoissonPP(self, Nres, ri = 40.): <NEW_LINE> <INDENT> rmax = min(self.Lx, self.Ly)/2 <NEW_LINE> N = self.Lx * self.Ly <NEW_LINE> self.Resx = np.zeros((Nres)) <NEW_LINE> self.Resy = np.zeros((Nres)) <NEW_LINE> for j in range(Nres): <NEW_LINE> <INDENT> r = (rmax - ri)*random.random() + ri <NEW_LINE> theta = 2*3.1415*random.random() <NEW_LINE> self.Resx[j] = r*sin(theta) + self.Lx/2 <NEW_LINE> self.Resy[j] = r*cos(theta) + self.Ly/2 <NEW_LINE> self.Area[self.Resx[j], self.Resy[j]] = int( 5*random.random() ) <NEW_LINE> <DEDENT> return | Spreads resources around the area for the bees to look for. It is
implemented as a Poisson Point process. | 625941ba16aa5153ce362309 |
def test_projector(): <NEW_LINE> <INDENT> gmm1 = GMM(number_of_gaussians=2) <NEW_LINE> gmm1.ubm = GMMMachine.from_hdf5( pkg_resources.resource_filename("bob.bio.gmm.test", "data/gmm_ubm.hdf5") ) <NEW_LINE> feature = utils.random_array((20, 45), -5.0, 5.0, seed=seed_value) <NEW_LINE> projected = gmm1.project(feature) <NEW_LINE> assert isinstance(projected, GMMStats) <NEW_LINE> reference_file = pkg_resources.resource_filename( "bob.bio.gmm.test", "data/gmm_projected.hdf5" ) <NEW_LINE> if regenerate_refs: <NEW_LINE> <INDENT> projected.save(reference_file) <NEW_LINE> <DEDENT> reference = GMMStats.from_hdf5(reference_file) <NEW_LINE> assert projected.is_similar_to(reference) | Tests the projector. | 625941ba91f36d47f21ac387 |
def network_add_cl(self, nb_filter, filter_size, activation='relu', padding='same'): <NEW_LINE> <INDENT> if self.network is None: <NEW_LINE> <INDENT> print("Network not initialized. Initialize network first using the 'init_network' method!") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.network = conv_2d(self.network, nb_filter, filter_size, activation=activation, padding=padding) <NEW_LINE> self.layer_overview = self.layer_overview.append( [0, nb_filter, filter_size, activation, padding] ) | Adds a convolutional layer to the specified network.
:param nb_filter: (int) Specifying the number of convolution filters
:param filter_size: (int or list(int)) Specifying the size of the filters
:param activation: (str) Specifying which type of activation function should be applied to the weights in the
given layer. Default is set to 'rely' (Rectified Linear Unit).
:param padding: (str) Specifying padding algorithm ('same' or 'valid')
:return: An added convolutional layer to the network attribute in the CNN class. | 625941ba3317a56b86939afa |
def test_tc10(self): <NEW_LINE> <INDENT> tc = LargestWord(file_path="tests/input_files/data_tc10.txt") <NEW_LINE> self.assertEqual("File is corrupted", tc.load_file()) | Validate program against a corrupted file
Note:
Generated file using command: dd if=/dev/urandom of=data_tc10.txt bs=5000 count=1 | 625941bab57a9660fec33712 |
def weight(self, S_bar, psi, outlier): <NEW_LINE> <INDENT> psi_inliers = psi[np.invert(outlier), :] <NEW_LINE> psi_max = psi[np.argmax(np.sum(psi, 1)), :].reshape( (1, S_bar.shape[1])) <NEW_LINE> psi_inliers = psi_max <NEW_LINE> nx = S_bar.shape[0] - 1 <NEW_LINE> if psi_inliers.size > 0: <NEW_LINE> <INDENT> weights = np.prod(psi_inliers, axis=0) <NEW_LINE> weights = weights / np.sum(weights) <NEW_LINE> S_bar[nx, :] = weights <NEW_LINE> <DEDENT> return S_bar | Weigh the particles according to the probabilities in psi. | 625941baa4f1c619b28afed2 |
def convert_to_csv(element: etree.Element, **kwargs) -> None: <NEW_LINE> <INDENT> row = [] <NEW_LINE> csv_file = kwargs.get('csv_file') <NEW_LINE> namespaces = kwargs.get('namespaces') <NEW_LINE> print(f'c1: {element.xpath("ns:c1/text()", namespaces=namespaces)}') <NEW_LINE> with open(csv_file, mode='a', encoding='utf-8') as file: <NEW_LINE> <INDENT> writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL) <NEW_LINE> for column in element: <NEW_LINE> <INDENT> row.append(column.text) <NEW_LINE> <DEDENT> writer.writerow(row) | Write/append row to CSV file. | 625941bacb5e8a47e48b7940 |
def set_directories(self, directories, cache_folder): <NEW_LINE> <INDENT> if jinja2 is None: <NEW_LINE> <INDENT> req_missing(['jinja2'], 'use this theme') <NEW_LINE> <DEDENT> cache_folder = os.path.join(cache_folder, 'jinja') <NEW_LINE> makedirs(cache_folder) <NEW_LINE> cache = jinja2.FileSystemBytecodeCache(cache_folder) <NEW_LINE> self.lookup = jinja2.Environment(bytecode_cache=cache) <NEW_LINE> self.lookup.trim_blocks = True <NEW_LINE> self.lookup.lstrip_blocks = True <NEW_LINE> self.lookup.filters['tojson'] = json.dumps <NEW_LINE> self.lookup.filters['sort_posts'] = sort_posts <NEW_LINE> self.lookup.filters['smartjoin'] = _smartjoin_filter <NEW_LINE> self.lookup.filters['slugify'] = slugify <NEW_LINE> self.lookup.globals['enumerate'] = enumerate <NEW_LINE> self.lookup.globals['isinstance'] = isinstance <NEW_LINE> self.lookup.globals['tuple'] = tuple <NEW_LINE> self.directories = directories <NEW_LINE> self.create_lookup() | Create a new template lookup with set directories. | 625941bab7558d58953c4dac |
@prof.log_call(trace_logger) <NEW_LINE> def dot_product_normalized(new_vector_set_1, new_vector_set_2, ord=2): <NEW_LINE> <INDENT> assert ord > 0 <NEW_LINE> if not issubclass(new_vector_set_1.dtype.type, numpy.floating): <NEW_LINE> <INDENT> new_vector_set_1 = new_vector_set_1.astype(numpy.float64) <NEW_LINE> <DEDENT> if not issubclass(new_vector_set_2.dtype.type, numpy.floating): <NEW_LINE> <INDENT> new_vector_set_2 = new_vector_set_2.astype(numpy.float64) <NEW_LINE> <DEDENT> new_vector_set_1_norms = norm(new_vector_set_1, ord=ord) <NEW_LINE> new_vector_set_2_norms = norm(new_vector_set_2, ord=ord) <NEW_LINE> norm_products = all_permutations_operation( operator.mul, new_vector_set_1_norms, new_vector_set_2_norms ) <NEW_LINE> vector_pairs_dot_product = numpy.dot( new_vector_set_1, new_vector_set_2.T ) <NEW_LINE> vector_pairs_dot_product_normalized = vector_pairs_dot_product / norm_products <NEW_LINE> return(vector_pairs_dot_product_normalized) | Determines the dot product between a pair of vectors from each set and
divides them by the norm of the two.
Args:
new_vector_set_1(numpy.ndarray): first set of vectors.
new_vector_set_2(numpy.ndarray): second set of vectors.
ord(optional): basically the same arguments
as numpy.linalg.norm.
Returns:
(numpy.ndarray): an array with the normalized
distances between each pair
of vectors.
Examples:
>>> (dot_product_normalized(numpy.eye(2), numpy.eye(2), 2) == numpy.eye(2)).all()
True
>>> (dot_product_normalized(numpy.eye(10), numpy.eye(10), 2) == numpy.eye(10)).all()
True
>>> dot_product_normalized(
... numpy.array([[ 1, 0]]),
... numpy.array([[ 1, 0]]),
... 2
... )
array([[ 1.]])
>>> dot_product_normalized(
... numpy.array([[ 1, 0]]),
... numpy.array([[ 0, 1]]),
... 2
... )
array([[ 0.]])
>>> dot_product_normalized(
... numpy.array([[ 1, 0]]),
... numpy.array([[-1, 0]]),
... 2
... )
array([[-1.]])
>>> dot_product_normalized(
... numpy.array([[ 1, 0]]),
... numpy.array([[ 0, -1]]),
... 2
... )
array([[ 0.]])
>>> dot_product_normalized(
... numpy.array([[ 1, 0]]),
... numpy.array([[ 1, 1]]),
... 2
... )
array([[ 0.70710678]])
>>> dot_product_normalized(
... numpy.array([[ 1, 0]]),
... numpy.array([[ 1, 1]]),
... 1
... )
array([[ 0.5]])
>>> dot_product_normalized(
... numpy.array([[ True, False]]),
... numpy.array([[ True, True]]),
... 2
... )
array([[ 0.70710678]])
>>> dot_product_normalized(
... numpy.array([[ True, False]]),
... numpy.array([[ True, True]]),
... 1
... )
array([[ 0.5]])
>>> dot_product_normalized(
... numpy.arange(6).reshape((2,3)),
... numpy.arange(5, 17).reshape((4,3)),
... 2
... )
array([[ 0.85280287, 0.82857143, 0.8157437 , 0.80782729],
[ 0.9978158 , 0.99385869, 0.99111258, 0.98921809]]) | 625941ba627d3e7fe0d68ce0 |
def copy(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> bounds = [x for x in self.boundingbox] <NEW_LINE> return TextBlock(self.text,bounds) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise Exception("Unable to copy textbox") | Return a deep copy of TextBlock
Returns:
Copy TextBlock (TextBlock): New Copied TextBlock | 625941baec188e330fd5a637 |
def find_le(self, a, x): <NEW_LINE> <INDENT> i = bisect_right(a, x) <NEW_LINE> if i: <NEW_LINE> <INDENT> return a[i-1] <NEW_LINE> <DEDENT> raise ValueError | Find rightmost value less than or equal to x | 625941ba462c4b4f79d1d562 |
def __init__(self, images, labels, seed=None): <NEW_LINE> <INDENT> seed1, seed2 = random_seed.get_seed(seed) <NEW_LINE> np.random.seed(seed1 if seed is None else seed2) <NEW_LINE> assert images.shape[0] == labels.shape[0], ( 'images.shape: %s labels.shape: %s' % (images.shape, labels.shape)) <NEW_LINE> self._num_examples = images.shape[0] <NEW_LINE> images = images.reshape(images.shape[0], images.shape[1] * images.shape[2]) <NEW_LINE> images = images.astype(np.float32) <NEW_LINE> self._images = images <NEW_LINE> self._labels = labels <NEW_LINE> self._epochs_completed = 0 <NEW_LINE> self._index_in_epoch = 0 | Construct a DataSet.
one_hot arg is used only if fake_data is true. `dtype` can be either
`uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
`[0, 1]`. Seed arg provides for convenient deterministic testing. | 625941bad99f1b3c44c67427 |
@login_required <NEW_LINE> def change_profile(request): <NEW_LINE> <INDENT> profile = UserProfile.get_or_create_profile(request.user) <NEW_LINE> if request.method == "GET": <NEW_LINE> <INDENT> user_form = UserForm(instance=request.user) <NEW_LINE> pass_change_form = PasswordChangeForm(request.user) <NEW_LINE> if profile.is_net_admin: <NEW_LINE> <INDENT> admin_form = AdminProfileForm(instance=request.user.get_profile()) <NEW_LINE> <DEDENT> <DEDENT> elif request.method == "POST": <NEW_LINE> <INDENT> user_form = UserForm(request.POST, instance=request.user) <NEW_LINE> valid1 = user_form.is_valid() <NEW_LINE> if profile.is_net_admin: <NEW_LINE> <INDENT> admin_form = AdminProfileForm(request.POST, instance=request.user.get_profile()) <NEW_LINE> valid3 = admin_form.is_valid() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> valid3 = True <NEW_LINE> <DEDENT> if (request.POST['old_password']!=""): <NEW_LINE> <INDENT> pass_change_form = PasswordChangeForm(request.user, request.POST) <NEW_LINE> valid2 = pass_change_form.is_valid() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass_change_form = PasswordChangeForm(request.user) <NEW_LINE> valid2 = True <NEW_LINE> <DEDENT> if (valid1 and valid2 and valid3): <NEW_LINE> <INDENT> user_form.save() <NEW_LINE> if (request.POST['old_password']!=""): <NEW_LINE> <INDENT> pass_change_form.save() <NEW_LINE> <DEDENT> if profile.is_net_admin: <NEW_LINE> <INDENT> admin_form.save() <NEW_LINE> <DEDENT> return HttpResponseRedirect("/dashboard") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return HttpResponseNotAllowed("GET", "POST") <NEW_LINE> <DEDENT> if (profile.is_net_admin): <NEW_LINE> <INDENT> return simple.direct_to_template(request, template = 'openflow/optin_manager/users/change_profile_admin.html', extra_context = { 'user_form':user_form, 'pass_form':pass_change_form, 'admin_form':admin_form } ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return simple.direct_to_template(request, template = 'openflow/optin_manager/users/change_profile_user.html', extra_context = { 'user_form':user_form, 'pass_form':pass_change_form, } ) | The view function to change profile information for a user or admin. | 625941ba090684286d50eb72 |
def merge(*iterables, **kwargs): <NEW_LINE> <INDENT> key = kwargs.pop('key', lambda a: a) <NEW_LINE> reverse = kwargs.pop('reverse', False) <NEW_LINE> min_or_max = max if reverse else min <NEW_LINE> peekables = [peekable(it) for it in iterables] <NEW_LINE> peekables = [p for p in peekables if p] <NEW_LINE> while peekables: <NEW_LINE> <INDENT> _, p = min_or_max((key(p.peek()), p) for p in peekables) <NEW_LINE> yield p.next() <NEW_LINE> peekables = [p for p in peekables if p] | Return an iterable ordered merge of the already-sorted items
from each of `iterables`, compared by kwarg `key`.
If reverse=True is passed, iterables must return their results in
descending order rather than ascending. | 625941bab830903b967e97a8 |
def test_empty_with_metadata(): <NEW_LINE> <INDENT> dict_undict_loops({ 'contents': {}, 'metadata': 'Fake metadata', }) | Test empty tree with metadata. | 625941bae1aae11d1e749b46 |
def get_table_ovs_ports(self): <NEW_LINE> <INDENT> raise UIException("Method isn't implemented") | Get OvsPorts table.
Returns:
list[dict]: table (list of dictionaries))
Examples::
env.switch[1].ui.get_table_ovs_ports() | 625941ba0c0af96317bb807b |
def blink(self, device_uuid=None, app_id=None): <NEW_LINE> <INDENT> return self._do_command( '{0}/blink'.format(self.SUPERVISOR_API_VERSION), device_uuid=device_uuid, app_id=app_id, method='POST' ) | Start a blink pattern on a LED for 15 seconds. This is the same with `balena.models.device.identify()`.
No need to set device_uuid and app_id if command is sent to the API on device.
Args:
device_uuid (Optional[str]): device uuid.
app_id (Optional[str]): application id.
Raises:
InvalidOption: if the endpoint is balena API proxy endpoint and device_uuid or app_id is not specified.
Examples:
>>> balena.models.supervisor.blink(device_uuid='8f66ec7335267e7cc7999ca9eec029a01ea7d823214c742ace5cfffaa21be3', app_id='9020')
'OK' | 625941ba7b25080760e392ec |
def save(self): <NEW_LINE> <INDENT> if self.id is None: <NEW_LINE> <INDENT> raise ObjectHasNoId <NEW_LINE> <DEDENT> self._commit() <NEW_LINE> return self | Сохранить изменения | 625941ba1b99ca400220a942 |
def exception(self, msg, *args, exc_info=True, **kwargs): <NEW_LINE> <INDENT> self.error(msg, *args, exc_info=exc_info, **kwargs) | Convenience method for logging an ERROR with exception information. | 625941ba82261d6c526ab334 |
def execute(self): <NEW_LINE> <INDENT> configurator = get_configurator(self.params.config, storage_path=self.params.storage, include_config_dirs=True) <NEW_LINE> cluster_name = self.params.cluster <NEW_LINE> try: <NEW_LINE> <INDENT> cluster = configurator.load_cluster(cluster_name) <NEW_LINE> if self.params.update: <NEW_LINE> <INDENT> cluster.update() <NEW_LINE> <DEDENT> <DEDENT> except (ClusterNotFound, ConfigurationError) as ex: <NEW_LINE> <INDENT> log.error("Listing nodes from cluster %s: %s\n" % (cluster_name, ex)) <NEW_LINE> return <NEW_LINE> <DEDENT> if self.params.pretty_json: <NEW_LINE> <INDENT> print(json.dumps(cluster, default=dict, indent=4)) <NEW_LINE> <DEDENT> elif self.params.json: <NEW_LINE> <INDENT> print(json.dumps(cluster, default=dict)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(cluster_summary(cluster)) <NEW_LINE> for cls in cluster.nodes: <NEW_LINE> <INDENT> print("%s nodes:" % cls) <NEW_LINE> print("") <NEW_LINE> for node in cluster.nodes[cls]: <NEW_LINE> <INDENT> txt = [" " + i for i in node.pprint().splitlines()] <NEW_LINE> print(' - ' + str.join("\n", txt)[4:]) <NEW_LINE> print("") | Lists all nodes within the specified cluster with certain
information like id and ip. | 625941ba5e10d32532c5edc0 |
def _get_provider_for_router(self, context, router_id): <NEW_LINE> <INDENT> driver_name = self._stm.get_provider_names_by_resource_ids( context, [router_id]).get(router_id) <NEW_LINE> if not driver_name: <NEW_LINE> <INDENT> router = self.l3_plugin.get_router(context, router_id) <NEW_LINE> driver = self._attrs_to_driver(router) <NEW_LINE> driver_name = driver.name <NEW_LINE> self._stm.add_resource_association(context, 'L3_ROUTER_NAT', driver_name, router_id) <NEW_LINE> <DEDENT> return self.drivers[driver_name] | Return the provider driver handle for a router id. | 625941ba21bff66bcd6847e7 |
def SleepUntilHistogramHasEntry(self, histogram_name, sleep_intervals=10): <NEW_LINE> <INDENT> histogram = {} <NEW_LINE> while(not histogram and sleep_intervals > 0): <NEW_LINE> <INDENT> histogram = self.GetHistogram(histogram_name, 5) <NEW_LINE> if (not histogram): <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> sleep_intervals -= 1 <NEW_LINE> <DEDENT> <DEDENT> return bool(histogram) | Polls if a histogram exists in 1-6 second intervals for 10 intervals.
Allows script to run with a timeout of 5 seconds, so the default behavior
allows up to 60 seconds until timeout.
Args:
histogram_name: The name of the histogram to wait for
sleep_intervals: The number of polling intervals, each polling cycle takes
no more than 6 seconds.
Returns:
Whether the histogram exists | 625941ba3539df3088e2e1dd |
def _build_class(class_name, classes): <NEW_LINE> <INDENT> if not isinstance(classes, (list, tuple)): <NEW_LINE> <INDENT> classes = (classes, ) <NEW_LINE> <DEDENT> return type(class_name, tuple(import_obj(c) for c in classes), {}) | Import all classes from the parameter and then build a new class with
the given name.
:param class_name: the name for the new class
:param classes: one ore more Classes to build the new class out of | 625941bafbf16365ca6f604f |
def resco_12_hrs(read_sheet, dummy1, row, col): <NEW_LINE> <INDENT> data = read_sheet.cell_value(row, col) <NEW_LINE> return data | This function returns an integer which aligns with the number of hours worked associated with the call.
:param read_sheet: The active .xlsx sheet defined by xlrd.
:type read_sheet: object
:param dummy1: Unused variable.
:type dummy1: null
:param row: The data row that is being scraped.
:type row: integer
:param col: The data column that is being scraped.
:type col: integer
:return: The number of hours worked in the call.
:rtype: integer | 625941ba9b70327d1c4e0c66 |
def gainFocus(self, previous, previous_name, text="", *args, **kwargs): <NEW_LINE> <INDENT> self.old_state = previous <NEW_LINE> self.old_state_name = previous_name <NEW_LINE> self.ui = ui.UI(96, 208) <NEW_LINE> self.txtbox = ui.ScrollText(16, 8, 256, 33, text, 0.15) <NEW_LINE> self.ui.add(self.txtbox) <NEW_LINE> self.ui.add(ui.Button(287, 37, "", self.scroll)) | What should be done when the state gets focus. Previous is the state that had focus before this one. | 625941bab545ff76a8913cb0 |
def get_all_conversations(self,messages_dir): <NEW_LINE> <INDENT> conversations=[] <NEW_LINE> dirs=[convo for convo in os.listdir(messages_dir) if os.path.isdir(messages_dir+"/"+convo)==True] <NEW_LINE> for d in dirs: <NEW_LINE> <INDENT> files=[x for x in os.listdir(messages_dir+"/"+d) if os.path.isfile(messages_dir+"/"+d+"/"+x)==True] <NEW_LINE> try: <NEW_LINE> <INDENT> if re.search(r'message(_\d+)?\.json', files[0]): <NEW_LINE> <INDENT> self.message_filename = files[0] <NEW_LINE> conversations.append(d) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return conversations | :params message_dir: The location of the directory
:returns: a list of all the directory i.e conversations
Returns a list of all the converstaion that has taken place. | 625941ba8a349b6b435e8006 |
def forward(self, x, mask_matrix): <NEW_LINE> <INDENT> B, L, C = x.shape <NEW_LINE> H, W = self.H, self.W <NEW_LINE> assert L == H * W, "input feature has wrong size" <NEW_LINE> shortcut = x <NEW_LINE> x = self.norm1(x) <NEW_LINE> x = x.view(B, H, W, C) <NEW_LINE> pad_l = pad_t = 0 <NEW_LINE> pad_r = (self.window_size - W % self.window_size) % self.window_size <NEW_LINE> pad_b = (self.window_size - H % self.window_size) % self.window_size <NEW_LINE> x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) <NEW_LINE> _, Hp, Wp, _ = x.shape <NEW_LINE> if self.shift_size > 0: <NEW_LINE> <INDENT> shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) <NEW_LINE> attn_mask = mask_matrix <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shifted_x = x <NEW_LINE> attn_mask = None <NEW_LINE> <DEDENT> x_windows = window_partition(shifted_x, self.window_size) <NEW_LINE> x_windows = x_windows.view(-1, self.window_size * self.window_size, C) <NEW_LINE> attn_windows = self.attn(x_windows, mask=attn_mask) <NEW_LINE> attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) <NEW_LINE> shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) <NEW_LINE> if self.shift_size > 0: <NEW_LINE> <INDENT> x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = shifted_x <NEW_LINE> <DEDENT> if pad_r > 0 or pad_b > 0: <NEW_LINE> <INDENT> x = x[:, :H, :W, :].contiguous() <NEW_LINE> <DEDENT> x = x.view(B, H * W, C) <NEW_LINE> x = shortcut + self.drop_path(x) <NEW_LINE> x = x + self.drop_path(self.mlp(self.norm2(x))) <NEW_LINE> return x | Forward function.
Args:
x: Input feature, tensor size (B, H*W, C).
H, W: Spatial resolution of the input feature.
mask_matrix: Attention mask for cyclic shift. | 625941ba66656f66f7cbc03c |
def numJewelsInStones(J, S): <NEW_LINE> <INDENT> d = Counter(J) <NEW_LINE> count = 0 <NEW_LINE> for char in S: <NEW_LINE> <INDENT> if char in d: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> return count | :type J: str
:type S: str
:rtype: int | 625941ba4a966d76dd550e9e |
def download_photo(): <NEW_LINE> <INDENT> return response.download(request, db) | This action downloads a photo to be shown on screen. | 625941ba57b8e32f52483332 |
def get_euclid_distance_to(self, atom): <NEW_LINE> <INDENT> return linalg.norm(self.get_coords() - atom.get_coords()) | Gets the euclid distance from this atom to the given atom.
Returns
-------
distance : float
the distance from this atom to the diven atom | 625941bad10714528d5ffb72 |
def test_norm_vector(self): <NEW_LINE> <INDENT> desc = CoulombMatrix(n_atoms_max=5, permutation="random", sigma=100, flatten=False) <NEW_LINE> cm = desc.create(H2O) <NEW_LINE> self.assertEqual(len(cm), 5) <NEW_LINE> self.assertEqual(len(desc._norm_vector), 3) <NEW_LINE> cm = desc.create(H2O) <NEW_LINE> self.assertEqual(len(cm), 5) | Tests if the attribute _norm_vector is written and used correctly
| 625941baa4f1c619b28afed3 |
def export_getOverallStatus( self ): <NEW_LINE> <INDENT> return InstallTools.getOverallStatus( getCSExtensions() ) | Get the complete status information for the components in the
given list | 625941ba293b9510aa2c312b |
def get_registry_value(self, registry_path): <NEW_LINE> <INDENT> self.ready_event.wait() <NEW_LINE> ret = self.__post_and_wait("reg query value", registry_path) <NEW_LINE> return ret.get('value', None) | Retrieve the data from a registry value. | 625941bad8ef3951e32433cf |
def test_exp_then_log_right(self): <NEW_LINE> <INDENT> for metric in [self.metrics['right_canonical'], self.metrics['right_diag']]: <NEW_LINE> <INDENT> for base_point_type in self.elements: <NEW_LINE> <INDENT> base_point = self.elements[base_point_type] <NEW_LINE> for element_type in self.elements: <NEW_LINE> <INDENT> if element_type in self.angles_close_to_pi: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> tangent_vec = self.elements[element_type] <NEW_LINE> result = helper.exp_then_log( metric=metric, tangent_vec=tangent_vec, base_point=base_point) <NEW_LINE> expected = self.group.regularize_tangent_vec( tangent_vec=tangent_vec, base_point=base_point, metric=metric) | Test that the riemannian left exponential and the
riemannian left logarithm are inverse.
Expect their composition to give the identity function. | 625941ba498bea3a759b9943 |
def GetFriendlyName(self): <NEW_LINE> <INDENT> if hasattr(self, 'NAME'): <NEW_LINE> <INDENT> return self.NAME <NEW_LINE> <DEDENT> return 'unknown thread' | Returns a human-friendly description of the thread. | 625941ba0a50d4780f666d21 |
def _initialize(self, resource = None, id_query = False, reset = False, **keywargs): <NEW_LINE> <INDENT> super(toellner8840_50, self)._initialize(resource, id_query, reset, **keywargs) <NEW_LINE> if self._interface is not None: <NEW_LINE> <INDENT> if 'xonxoff' in self._interface.__dict__: <NEW_LINE> <INDENT> self._interface.xonxoff = True <NEW_LINE> self._interface.update_settings() <NEW_LINE> <DEDENT> <DEDENT> if id_query and not self._driver_operation_simulate: <NEW_LINE> <INDENT> id = self.identity.instrument_model <NEW_LINE> id_check = self._instrument_id <NEW_LINE> id_short = id[:len(id_check)] <NEW_LINE> if id_short != id_check: <NEW_LINE> <INDENT> raise Exception("Instrument ID mismatch, expecting %s, got %s", id_check, id_short) <NEW_LINE> <DEDENT> <DEDENT> if reset: <NEW_LINE> <INDENT> self.utility_reset() <NEW_LINE> <DEDENT> result = self._write('system:remote') | Opens an I/O session to the instrument. | 625941ba4428ac0f6e5ba684 |
def unsqueeze(input, axes, name=None): <NEW_LINE> <INDENT> helper = LayerHelper("unsqueeze", **locals()) <NEW_LINE> out = helper.create_variable_for_type_inference(dtype=input.dtype) <NEW_LINE> x_shape = helper.create_variable_for_type_inference(dtype=input.dtype) <NEW_LINE> helper.append_op( type="unsqueeze2", inputs={"X": input}, attrs={"axes": axes}, outputs={"Out": out, "XShape": x_shape}) <NEW_LINE> return out | Insert single-dimensional entries to the shape of a tensor. Takes one
required argument axes, a list of dimensions that will be inserted.
Dimension indices in axes are as seen in the output tensor.
For example:
.. code-block:: text
Given a tensor such that tensor with shape [3, 4, 5],
then Unsqueezed tensor with axes=[0, 4] has shape [1, 3, 4, 5, 1].
Args:
input (Variable): The input variable to be unsqueezed.
axes (list): List of integers, indicating the dimensions to be inserted.
name (str|None): Name for this layer.
Returns:
Variable: Output unsqueezed variable.
Examples:
.. code-block:: python
import paddle.fluid as fluid
x = fluid.layers.data(name='x', shape=[5, 10])
y = fluid.layers.unsqueeze(input=x, axes=[1]) | 625941ba0fa83653e4656e4f |
def _do_delete(self, subject_id=None, object_id=None, predicate=None): <NEW_LINE> <INDENT> affected_rels = self._get_relationships_from_criteria(subject_id, object_id, predicate).all() <NEW_LINE> tables = [schema.ObjectFromSubject, schema.SubjectFromObject] <NEW_LINE> with BatchQuery() as batch: <NEW_LINE> <INDENT> for affected_rel in affected_rels: <NEW_LINE> <INDENT> for table in tables: <NEW_LINE> <INDENT> table.objects(subject_id=affected_rel.subject_id, object_id=affected_rel.object_id, predicate=affected_rel.predicate).batch(batch).delete() | Given one or more criteria, delete all matching Relationships from the DAO's backend.
This does not affect records, data, etc. Only Relationships.
:raise ValueError: if no criteria are specified. | 625941baad47b63b2c509e1b |
def test_partial(partial_author): <NEW_LINE> <INDENT> assert partial_author.name == "John Doe" <NEW_LINE> assert partial_author.user.username == "[email protected]" | Test fixture partial specialization. | 625941ba30c21e258bdfa32d |
def default(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, trans.app.model.HistoryDatasetAssociation): <NEW_LINE> <INDENT> rval = { "__HistoryDatasetAssociation__": True, "create_time": obj.create_time.__str__(), "update_time": obj.update_time.__str__(), "hid": obj.hid, "name": to_unicode(obj.name), "info": to_unicode(obj.info), "blurb": obj.blurb, "peek": obj.peek, "extension": obj.extension, "metadata": prepare_metadata(dict(obj.metadata.items())), "parent_id": obj.parent_id, "designation": obj.designation, "deleted": obj.deleted, "visible": obj.visible, "file_name": obj.file_name, "uuid": (lambda uuid: str(uuid) if uuid else None)(obj.dataset.uuid), "annotation": to_unicode(getattr(obj, 'annotation', '')), "tags": get_item_tag_dict(obj), "extra_files_path": obj.extra_files_path } <NEW_LINE> if not obj.visible and not include_hidden: <NEW_LINE> <INDENT> rval['exported'] = False <NEW_LINE> <DEDENT> elif obj.deleted and not include_deleted: <NEW_LINE> <INDENT> rval['exported'] = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rval['exported'] = True <NEW_LINE> <DEDENT> return rval <NEW_LINE> <DEDENT> return json.JSONEncoder.default(self, obj) | Encode an HDA, default encoding for everything else. | 625941ba8c0ade5d55d3e852 |
def iter_headers(self): <NEW_LINE> <INDENT> return self.headerlist | Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. | 625941bab5575c28eb68de90 |
def test_resources_attribute_is_not_list(self): <NEW_LINE> <INDENT> new_task = Task(**self.kwargs) <NEW_LINE> with pytest.raises(TypeError) as cm: <NEW_LINE> <INDENT> new_task.resources = "a resource" <NEW_LINE> <DEDENT> assert str(cm.value) == 'Incompatible collection type: str is not list-like' | testing if a TypeError will be raised when the resources attribute
is set to any other value then a list | 625941ba377c676e9127203d |
def load_config_from_file(self, config_path): <NEW_LINE> <INDENT> self._config_path = config_path <NEW_LINE> with open(r'{}'.format(self._config_path)) as file: <NEW_LINE> <INDENT> self._config = yaml.load(file, Loader=yaml.FullLoader) <NEW_LINE> <DEDENT> self._parse_params() <NEW_LINE> self._create_output_dirs() | Loads configuration from a file | 625941ba4f88993c3716bf06 |
def version_setter(self, new_version): <NEW_LINE> <INDENT> pass | You must implement this method in your class | 625941ba30bbd722463cbc55 |
def players_turn(): <NEW_LINE> <INDENT> return _gamestate.players_turn | This function returns True if it is the player's turn, Flase if its not. | 625941ba38b623060ff0ac81 |
def _import_record(self, record_id, **kwargs): <NEW_LINE> <INDENT> return super(SaleOrderBatchImport, self)._import_record( record_id, max_retries=0, priority=5) | Import the record directly | 625941baab23a570cc250012 |
def max(values): <NEW_LINE> <INDENT> return builtins.max(values) | Given a sequence of values, returns the greatest value in the
sequence, also known as the "max" value.
Returns NaN (Not a Number) if passed an empty sequence.
Args:
values: A Sequence of numerical values. Accepts both Integers
and Floats. The sequence may not contain None type values.
However, passing a None type object instead of a Sequence of
numerical values will return NaN.
Returns:
The maximum value contained in the values parameter, or NaN if
the input was empty or null. | 625941ba8e7ae83300e4ae5e |
def findDuplicate3(self, nums): <NEW_LINE> <INDENT> slow = nums[0] <NEW_LINE> fast = nums[slow] <NEW_LINE> while fast != slow: <NEW_LINE> <INDENT> slow = nums[slow] <NEW_LINE> fast = nums[nums[fast]] <NEW_LINE> <DEDENT> fast = 0 <NEW_LINE> while fast != slow: <NEW_LINE> <INDENT> fast = nums[fast] <NEW_LINE> slow = nums[slow] <NEW_LINE> <DEDENT> return slow | :type nums: List[int]
:rtype: int | 625941ba6e29344779a624a8 |
def get_value(self, pos): <NEW_LINE> <INDENT> x, y = pos <NEW_LINE> return self.matrix[x][y] | 给出矩阵特定位置的值
:param pos: [x, y]
:return: [a, b, cn],其中,a表示格子产出,b表示各自是否有个体占据,cn定义同上 | 625941ba26068e7796caeb6c |
def create(self, transaction, prec, succs=(), flag=0, parents=None, date=None, metadata=None): <NEW_LINE> <INDENT> if metadata is None: <NEW_LINE> <INDENT> metadata = {} <NEW_LINE> <DEDENT> if date is None: <NEW_LINE> <INDENT> if 'date' in metadata: <NEW_LINE> <INDENT> date = util.parsedate(metadata.pop('date')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> date = util.makedate() <NEW_LINE> <DEDENT> <DEDENT> if len(prec) != 20: <NEW_LINE> <INDENT> raise ValueError(prec) <NEW_LINE> <DEDENT> for succ in succs: <NEW_LINE> <INDENT> if len(succ) != 20: <NEW_LINE> <INDENT> raise ValueError(succ) <NEW_LINE> <DEDENT> <DEDENT> if prec in succs: <NEW_LINE> <INDENT> raise ValueError(_('in-marker cycle with %s') % node.hex(prec)) <NEW_LINE> <DEDENT> metadata = tuple(sorted(metadata.iteritems())) <NEW_LINE> marker = (str(prec), tuple(succs), int(flag), metadata, date, parents) <NEW_LINE> return bool(self.add(transaction, [marker])) | obsolete: add a new obsolete marker
* ensuring it is hashable
* check mandatory metadata
* encode metadata
If you are a human writing code creating marker you want to use the
`createmarkers` function in this module instead.
return True if a new marker have been added, False if the markers
already existed (no op). | 625941bafff4ab517eb2f2cc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.